Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Services and RPC Types

Implementing a gRPC Server

Implement the server side of a gRPC service: handler signatures, thread-safe state, validation, graceful shutdown and server options, with runnable Go stand-ins.

Generating code from a contract gives you an interface; implementing the server means filling that interface with real behavior. This lesson walks through a complete catalog server in Go: the handler signature, safe shared state, input validation, server options and graceful shutdown. The real gRPC code is read-only, because the library cannot run on this site. Go stand-ins model the parts that matter and are fully runnable.

If you have not designed the service yet, read defining services and unary RPCs first.

What the generator gives you

For the Catalog service, the Go generator produces (simplified):

Go
type CatalogServer interface {
	GetProduct(context.Context, *GetProductRequest) (*Product, error)
	CreateProduct(context.Context, *CreateProductRequest) (*Product, error)
	// ...one method per rpc...
	mustEmbedUnimplementedCatalogServer()
}

The unexported method forces you to embed UnimplementedCatalogServer, which provides default implementations that return an UNIMPLEMENTED status. That keeps old servers compiling when the contract gains new methods.

A complete server (read-only)

Go
package main

import (
	"context"
	"log"
	"net"
	"sync"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	pb "example.com/shop/gen/shop/v1"
)

type catalogServer struct {
	pb.UnimplementedCatalogServer

	mu       sync.RWMutex
	products map[int64]*pb.Product
	nextID   int64
}

func newCatalogServer() *catalogServer {
	return &catalogServer{products: map[int64]*pb.Product{}, nextID: 1}
}

func (s *catalogServer) CreateProduct(ctx context.Context, req *pb.CreateProductRequest) (*pb.Product, error) {
	if req.GetName() == "" {
		return nil, status.Error(codes.InvalidArgument, "name is required")
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	p := &pb.Product{Id: s.nextID, Name: req.GetName(), Price: req.GetPrice()}
	s.products[p.Id] = p
	s.nextID++
	return p, nil
}

func (s *catalogServer) GetProduct(ctx context.Context, req *pb.GetProductRequest) (*pb.Product, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	p, ok := s.products[req.GetId()]
	if !ok {
		return nil, status.Errorf(codes.NotFound, "product %d not found", req.GetId())
	}
	return p, nil
}

func main() {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatal(err)
	}
	srv := grpc.NewServer(
		grpc.MaxRecvMsgSize(4<<20),
		grpc.MaxConcurrentStreams(100),
	)
	pb.RegisterCatalogServer(srv, newCatalogServer())
	log.Fatal(srv.Serve(lis))
}

Things worth noticing:

  1. Each call runs in its own goroutine. The gRPC library calls your handler concurrently, so shared state needs a mutex (or another synchronization tool). A forgotten lock is the classic server bug.
  2. Errors are statuses. status.Error(codes.NotFound, ...) becomes the grpc-status trailer. Returning a plain error yields UNKNOWN. Status codes are the subject of a later chapter, listed on the track page.
  3. Getters are nil-safe. req.GetName() never panics, even if req has no value for it.
  4. Respect the context. For slow work, check ctx.Err() or pass ctx along, so cancelled calls stop doing work. More in deadlines and cancellation.

Stand-in 1: concurrent handlers sharing a store

This runnable program mimics the server above. A Catalog struct with a mutex serves many concurrent "calls". If you remove the lock, running it with the race detector would show a data race; with the lock, the final count is always exact.

Go Stand-in: thread-safe server state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The ids are exactly 1 to 100 regardless of how the goroutines interleave, because nextID is only touched under the lock.

Validation belongs in the handler

Protobuf only checks that bytes decode into the right types. It does not know that a price must be positive or an email must contain @. Validate in the handler and return INVALID_ARGUMENT with a clear message. For large contracts, generate validation code with a rules plugin (such as protovalidate), which you annotate in the .proto file; those annotations are read-only here.

Graceful shutdown

When you deploy a new version, you do not want to cut in-flight calls. GracefulStop() stops accepting new connections and calls, waits for running ones to finish, and then returns. Stop() cuts everything immediately. Production servers usually call GracefulStop on SIGTERM, with a timeout after which they fall back to Stop.

Go
go func() {
	<-sigCh // SIGTERM from the orchestrator
	done := make(chan struct{})
	go func() { srv.GracefulStop(); close(done) }()
	select {
	case <-done:
	case <-time.After(20 * time.Second):
		srv.Stop()
	}
}()

Stand-in 2: draining in-flight work

The stand-in server below accepts jobs, then drains: new jobs are refused while running ones finish. This is the behavior GracefulStop gives you.

Go Stand-in: graceful drain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Server options worth knowing

Option Purpose
grpc.MaxRecvMsgSize, MaxSendMsgSize Limit message size (default receive limit is 4 MB)
grpc.MaxConcurrentStreams Calls per connection
grpc.Creds TLS credentials (see the security chapter on the track page)
grpc.UnaryInterceptor Cross-cutting logic such as logging and auth
grpc.KeepaliveParams Detect dead connections

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a gRPC server need synchronization for shared state?

    Each call is handled concurrently, so shared maps and counters must be protected.
  2. 2. What status does a plain Go error returned from a handler produce?

    Only status.Error values carry specific codes; other errors become UNKNOWN.
  3. 3. How does GracefulStop differ from Stop?

    Stop cuts everything immediately; GracefulStop drains first.
  4. 4. Who validates business rules such as 'price must be positive'?

    The wire format only checks types. Business validation is your job.

Summary

  • Implement the generated server interface and embed the Unimplemented...Server type.
  • Handlers run concurrently, so protect shared state.
  • Return status errors with proper codes; validate input in the handler.
  • Use GracefulStop on shutdown, with a fallback Stop.
  • Tune message size, concurrency and keepalive with server options.

Next: Clients, Channels and Stubs