My account

gRPC in Go

gRPC lets services call each other with typed messages over HTTP/2. A specialist writes a proto file that can change safely, picks the right one of the four RPC kinds, passes deadlines and returns real status codes, adds interceptors for logs and auth, reuses one client connection, and knows why one HTTP/2 connection can send all traffic to one pod.

Not reviewedWritten with AI helpReading time: 20 minOnline shop exampleGo 1.25

Author: bezzad

Contents

The problem: internal calls that are slow and hard to debug

The shop’s order service calls the inventory service to reserve items. Today it is JSON over HTTP, and the team has these problems:

  1. Field names change and nobody notices until production breaks.
  2. When inventory is slow, the order service waits much longer than the user does.
  3. Every error looks the same: “500 internal error”.

The team moves to gRPC. It gives a typed contract, deadlines, real error codes and streaming. But after the move, one inventory pod gets almost all the traffic. Let us see why, step by step.

The contract: a proto file

syntax = "proto3";
package shop.inventory.v1;
option go_package = "shop/gen/inventory/v1;inventoryv1";

service Inventory {
  rpc Reserve(ReserveRequest) returns (ReserveResponse);
  rpc WatchStock(WatchStockRequest) returns (stream StockEvent);
}

message ReserveRequest {
  string order_id = 1;
  repeated Item items = 2;
}

message Item {
  string sku = 1;
  int32 quantity = 2;
}

message ReserveResponse { string reservation_id = 1; }
message WatchStockRequest { repeated string skus = 1; }
message StockEvent { string sku = 1; int32 available = 2; }
  1. The field number (= 1, = 2) is what goes on the wire, not the name. You can rename a field, but never change or reuse a number.
  2. To remove a field, delete it and mark its number and name as reserved, so nobody uses them again by mistake.
  3. Adding a new field is safe. Old clients ignore it, and new code sees the zero value when an old client does not send it.
  4. In proto3, a missing number is 0 and a missing string is “”. If you must know “not set” vs “set to 0”, use the optional keyword.
  5. Put a version in the package name (v1). A breaking change gets a new package, v2, next to the old one.

Generate the Go code with protoc and the protoc-gen-go and protoc-gen-go-grpc plugins, or with the buf tool. buf can also check every change for breaking rules in CI.

Four kinds of RPC

Four kinds of RPCUnaryClientServerServer streamingClientServerClient streamingClientServerBidirectionalClientServerBlue: requests, green: responses
Unary: one request, one response. Server streaming: one request, many responses. Client streaming: many requests, one response. Bidirectional: both sides send many messages at the same time on one stream.
  1. Unary is the normal case, like Reserve.
  2. Server streaming fits “keep me updated”, like WatchStock for the product page.
  3. Client streaming fits uploads, like sending 10,000 price changes and getting one summary.
  4. Bidirectional fits chat-like flows, like a warehouse scanner that sends scans and gets commands back.

Streams are long. They need deadlines or cancellation too, and a load balancer only sees them as one long request.

The server

type server struct {
	inventoryv1.UnimplementedInventoryServer
	store *Store
}

func (s *server) Reserve(ctx context.Context,
	req *inventoryv1.ReserveRequest,
) (*inventoryv1.ReserveResponse, error) {
	if len(req.GetItems()) == 0 {
		return nil, status.Error(codes.InvalidArgument,
			"no items")
	}
	id, err := s.store.Reserve(ctx, req.GetOrderId(),
		req.GetItems())
	switch {
	case errors.Is(err, ErrOutOfStock):
		return nil, status.Error(codes.FailedPrecondition,
			"out of stock")
	case err != nil:
		return nil, status.Error(codes.Internal, "reserve")
	}
	return &inventoryv1.ReserveResponse{ReservationId: id}, nil
}
  1. Embed UnimplementedInventoryServer by value. When a new method is added to the proto, old servers still compile and answer “Unimplemented”.
  2. Return status errors. A plain Go error reaches the client as codes.Unknown. The code tells the client what to do: InvalidArgument means “do not retry”, Unavailable means “you may retry”.
  3. Do not put internal error text (SQL, stack traces) in the message. Log it on the server.
  4. Pass ctx down to the store. When the client gives up, the work stops too.

The client: one connection, always a deadline

conn, err := grpc.NewClient("dns:///inventory:9090",
	grpc.WithTransportCredentials(creds),
)
if err != nil {
	return err
}
defer conn.Close()
inv := inventoryv1.NewInventoryClient(conn)

// In each order request:
ctx, cancel := context.WithTimeout(r.Context(),
	300*time.Millisecond)
defer cancel()
res, err := inv.Reserve(ctx, req)
if status.Code(err) == codes.FailedPrecondition {
	// tell the user the item is sold out
}
  1. Create the connection once at startup and share it. It is safe for many goroutines, and it keeps one HTTP/2 connection open with many requests on it. A new connection per request costs a TCP and TLS handshake every time.
  2. Always set a deadline. gRPC sends it in the grpc-timeout header. The server’s ctx gets the same deadline, and if the server calls another service with that ctx, the deadline goes on. So the whole chain stops when the user would stop waiting.
  3. Start from the incoming request’s context, not context.Background(), so cancel and deadline flow through.
  4. Retries can be set in the service config, only for codes like Unavailable, and only for calls that are safe to repeat. Reserve is safe only if the server uses order_id as an idempotency key.

Interceptors and metadata

Interceptors are middleware for gRPC. Use them for logs, metrics, tracing and auth, so handlers stay clean.

func logCalls(ctx context.Context, req any,
	info *grpc.UnaryServerInfo, next grpc.UnaryHandler,
) (any, error) {
	start := time.Now()
	res, err := next(ctx, req)
	slog.InfoContext(ctx, "rpc",
		"method", info.FullMethod,
		"code", status.Code(err),
		"ms", time.Since(start).Milliseconds())
	return res, err
}

srv := grpc.NewServer(grpc.ChainUnaryInterceptor(logCalls, auth))
  1. Metadata is like HTTP headers. The client adds it with metadata.AppendToOutgoingContext, and the server reads it with metadata.FromIncomingContext. Use it for things like auth tokens and request ids.
  2. For streams there are stream interceptors too. Most tracing libraries (OpenTelemetry) give you a ready stats handler.
  3. Add the standard health service (grpc.health.v1), so Kubernetes and load balancers can check the server.

Load balancing: one connection, one pod

ClusterIP Service: balances connectionsOrdersClusterIP1 HTTP/2 connectionPod 1: 95%Pod 2: idlePod 3: idleHeadless Service + round_robin: balances callsOrdersPod 1: 33%Pod 2: 33%Pod 3: 33%One connection to each pod, calls spread in turn
A normal Kubernetes Service balances connections, not requests. One long HTTP/2 connection sends every call to the same pod. With client-side balancing over a headless Service, the client opens a connection to every pod and spreads the calls.

This is the problem from the start. A normal ClusterIP Service works at the connection level (L4). The order service opened one HTTP/2 connection, so the Service picked one pod once, and every call went there. New pods after scaling got nothing.

Ways to fix it:

  1. Client-side balancing: use a headless Service (clusterIP: None), so DNS returns every pod IP. Then use the dns:/// target and the round_robin policy:
conn, err := grpc.NewClient("dns:///inventory-headless:9090",
	grpc.WithTransportCredentials(creds),
	grpc.WithDefaultServiceConfig(
		`{"loadBalancingConfig": [{"round_robin":{}}]}`),
)
  1. A proxy that understands HTTP/2 (Envoy, a service mesh, or a gRPC-aware ingress) balances each request.
  2. On the server, MaxConnectionAge in keepalive.ServerParameters closes connections after some time, so clients reconnect and find new pods.

When not to use gRPC

  1. Browsers cannot call gRPC directly. They need gRPC-Web or the Connect protocol, or a REST gateway.
  2. Public APIs for many outside developers are often easier as REST with JSON.
  3. gRPC shines between your own services: typed contracts, deadlines, streaming and good speed.

Common mistakes

Mistake Result Better way
Changing or reusing a field number Old and new services read wrong data. Add new numbers. Mark removed ones as reserved.
Returning plain Go errors The client only sees Unknown. Return status.Error with the right code.
No deadline, or context.Background() Calls hang and the chain does not stop. Use the request ctx with a timeout.
A new connection per request Slow handshakes, many sockets. Create one client connection and share it.
ClusterIP Service with long connections One pod gets all the calls. Headless Service with round_robin, or an HTTP/2 proxy.
Retrying every error Duplicate side effects. Retry only safe codes on idempotent calls.

Summary in 7 lines

  1. The proto file is the contract. Field numbers must never change or be reused.
  2. Pick unary, server, client or bidirectional streaming by the flow of data.
  3. Embed the Unimplemented server and return status errors with real codes.
  4. Create one client connection and share it in the whole service.
  5. Always set a deadline from the request ctx. It flows through the whole chain.
  6. Interceptors handle logs, metrics, tracing and auth. Metadata carries headers.
  7. HTTP/2 keeps one connection, so balance per request: round_robin, a proxy, or MaxConnectionAge.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.