Skip to content

gRPC & Protobuf in Go: proto files, codegen, streaming, metadata, interceptors, TLS, validation, gRPC-gateway ​

"In gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object, making it easier for you to create distributed applications and services." — gRPC documentation, "Introduction to gRPC", grpc.io

Summary: In Go, gRPC is three things you assemble yourself: a .proto contract compiled by buf (or protoc) with protoc-gen-go and protoc-gen-go-grpc into typed messages, a client stub and a server interface; the google.golang.org/grpc runtime (grpc.NewServer, RegisterXxxServer, grpc.NewClient) that carries those messages over HTTP/2 with deadlines, metadata and status codes; and an ecosystem around it (go-grpc-middleware v2 interceptors, protovalidate, grpc-gateway, health, reflection, grpcurl, bufconn) that turns a working RPC into a service you can run, debug and expose. Focus: proto3 messages, scalar types, enums, oneof, map, repeated, optional, the well-known types (Timestamp, Duration, Empty, Any, FieldMask), field numbers, reserved, package and go_package; protoc vs buf (buf.yaml, buf.gen.yaml, buf lint, buf breaking) and the generated code shape; unary, server streaming, client streaming and bidirectional streaming in Go; context deadlines and codes.DeadlineExceeded; status codes, status.Error/status.FromError and error details; metadata, headers and trailers; interceptors and chaining; TLS, mTLS and per-RPC credentials; protovalidate; grpc-gateway and OpenAPI; health, reflection, keepalive, load balancing, message size limits; testing with bufconn; connect-go and gRPC-Web as alternatives; the versioning compat rules. Learning goal: Write a .proto file that lints clean and can evolve without breaking old readers, generate and commit the Go code, implement every RPC shape with a deadline on every call and a precise status code on every failure, wire auth, logging, recovery and validation as interceptors, serve it over mTLS with health and reflection, expose it as REST when a non-gRPC caller needs it, and test all of it in-process with bufconn.

This page owns gRPC and Protocol Buffers as a Go developer meets them: the Go APIs, the code generators and the Go ecosystem packages. It does not re-teach its neighbours. The protocol itself (wire types, varints, the HTTP/2 framing, REST vs GraphQL vs gRPC as a system decision) is in gRPC & Protocol Buffers; serialization formats in general (JSON, Avro, MessagePack, CBOR) in Serialization Formats; HTTP/2 and TLS in Go, certificates and crypto/tls in HTTP/2, HTTPS, TLS & mTLS in Go; context itself in context; HTTP middleware (the net/http cousin of interceptors) in Middlewares; API evolution policy in API Versioning & Evolution; choosing sync vs async communication between services in Service Communication; and a full multi-service build in Project: Microservices.

Facts below were checked against protobuf.dev (proto3 language guide, Go generated code guide, field presence, editions), buf.build docs (buf.yaml v2, buf.gen.yaml v2, lint and breaking rules), grpc.io guides (core concepts, deadlines, metadata, status codes, error handling, interceptors, keepalive, health checking, reflection, performance, retry, auth), the grpc/grpc protocol documents (PROTOCOL-HTTP2.md, statuscodes.md, load-balancing.md, health-checking.md), the grpc-go source and Documentation/ folder at tag v1.80.0 and on master, the go-grpc-middleware v2.3.4, grpc-gateway v2.28.0 and protovalidate-go v1.2.0 sources in the module cache, the protovalidate, protoc-gen-validate, grpcurl, grpc-health-probe, connect-go and grpc-web READMEs, and the Kubernetes probe docs. The snippet module declares go 1.24.0 and pins google.golang.org/grpc v1.80.0 (the last release whose go.mod says 1.24; v1.81 needs 1.25), google.golang.org/protobuf v1.36.11, github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0, github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.4 and buf.build/go/protovalidate v1.2.0. The Go code under gen/ was generated with buf 1.75.0, protoc-gen-go v1.36.11, protoc-gen-go-grpc v1.6.2, protoc-gen-grpc-gateway and protoc-gen-openapiv2 v2.28.0 and is committed, so go test needs no compiler. Everything was vetted and tested with -race on Go 1.27.4 (macOS); lab outputs marked "real" are from that run.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why a typed RPC contract at allWhy it exists
Stubby, protobuf 2008, gRPC 2015, APIv2 2020, NewClient 2024Where it comes from
A before/after service and clientGo
Messages, scalar types, field numbersproto3 messages
enum, oneof, optional, presenceEnums, oneof, optional
repeated, map, Timestamp, Duration, Empty, Any, FieldMaskCollections and well-known types
package, go_package, what the generator writesGenerated code shape
buf.yaml, buf.gen.yaml, buf lint, buf breaking, protocprotoc vs buf
grpc.NewServer, RegisterXxxServer, Unimplemented embeddingServer
grpc.NewClient, targets, dns:///, passthrough:///Client
Unary, server, client and bidirectional streamingThe four RPC shapes
Deadlines, codes.DeadlineExceeded, cancellationDeadlines
codes.NotFound, status.Error, status.FromError, errdetailsStatus codes and error details
Incoming/outgoing metadata, headers, trailersMetadata
Unary/stream interceptors, chaining, go-grpc-middleware v2Interceptors
credentials.NewTLS, insecure.NewCredentials, mTLS, tokensTLS and mTLS
buf.validate rules, protovalidate, protoc-gen-validateValidation
REST transcoding, google.api.http, OpenAPIgrpc-gateway
Health service, grpc-health-probe, reflection, grpcurlHealth, reflection, grpcurl
Keepalive, MaxConnectionAge, round_robin, resolversKeepalive and load balancing
HTTP/2 multiplexing, message size limits, compressionPerformance
In-process testsTesting with bufconn
connect-go and gRPC-Webconnect-go and gRPC-Web
What you may change in a .proto fileVersioning compat rules
What is on the wire, exact error textsMechanics
The classic bugs and their fixesSolving the classic problems
What to use whenChoosing
Monolith to distributed systemIn architecture
Reproduce it on your machineLab
Calling gRPC from LaravelFor PHP/Laravel developers

Everything in one minute ​

The pieces and who makes them. Each row is unpacked in the concept catalogue.

PieceComes fromYou writeYou get
.proto fileYouMessages, enums, service with rpcsOne contract for every language
protoc-gen-gogoogle.golang.org/protobufNothingorders.pb.go: structs, enums, getters, descriptors
protoc-gen-go-grpcgoogle.golang.org/grpc/cmd/protoc-gen-go-grpcNothingorders_grpc.pb.go: OrderServiceClient, OrderServiceServer, RegisterOrderServiceServer
buf (or protoc)Buf (or Google)buf.yaml, buf.gen.yamlLint, breaking-change check, code generation
grpc.NewServergoogle.golang.org/grpc server and client runtimeYour Service structAn HTTP/2 server that dispatches to it
grpc.NewClient (1.63+)google.golang.org/grpcA target and credentialsA ClientConn: a pool of connections that reconnects itself
InterceptorsYou, or go-grpc-middleware v2Logging, auth, recovery, validationCross-cutting code around every call
grpc-gatewaygrpc-ecosystem/grpc-gateway/v2google.api.http annotationsJSON/REST in front of the same service, plus OpenAPI

The four RPC shapes.

ShapeIn .protoServer method in GoClient gets
Unaryrpc Get(Req) returns (Res)Get(ctx, *Req) (*Res, error)*Res, error
Server streamingreturns (stream Res)List(*Req, grpc.ServerStreamingServer[Res]) errorRecv() until io.EOF
Client streamingrpc Import(stream Req)Import(grpc.ClientStreamingServer[Req, Res]) errorSend many, CloseAndRecv() once
Bidirectional streamingstream Req and stream ResChat(grpc.BidiStreamingServer[Req, Res]) errorSend/Recv independently, CloseSend()

The status codes you will see most. Full list of 17 in Status codes.

CodeNumberPlain wordsTypical Go causeRetry?
codes.OK0Successreturn resp, niln/a
codes.Canceled1Caller gave upClient ctx canceledNo
codes.Unknown2Server returned a non-status errorreturn nil, errors.New(...)No (fix the server)
codes.InvalidArgument3Bad request regardless of stateValidation failedNo
codes.DeadlineExceeded4Time ran outClient deadline passedOnly if idempotent and budget remains
codes.NotFound5No such entityLookup missedNo
codes.ResourceExhausted8Quota or size limitMessage larger than 4 MiBIdempotent calls after backoff; or fix the size
codes.Unimplemented12Method not thereUnimplemented embedding answeredNo
codes.Internal13Invariant brokenRecovered panicNo
codes.Unavailable14Try again laterConnection refused, TLS failure, drainingOnly idempotent calls (or with an idempotency key), with backoff
codes.Unauthenticated16Who are you?Missing or bad tokenNo (get a token)

Why it exists ​

Two services that talk JSON over HTTP agree on a URL, a method, a body shape and an error convention, and each of those agreements lives in prose, in a Postman collection or in somebody's head. When the orders service renames customer_id, the billing service finds out in production. gRPC moves the agreement into a file the compiler reads: the .proto file names every method, every field, its type and its number, and both sides are generated from it. Add a field and old clients keep working; remove one without reserving its number and buf breaking fails the pull request.

The second reason is the transport. gRPC runs on HTTP/2, so one TCP connection carries many concurrent calls, a call can stream in both directions, the remaining deadline travels with the request (grpc-timeout), and the outcome travels as a status code and optional details in trailers. Go programs get all of that through one context.Context and one error per call.

JSON over HTTP/1.1 (typical REST)gRPC with Protocol Buffers
Contract in docs or OpenAPI written after the factContract is the source; code is generated from it
Text encoding, field names on the wireBinary encoding, field numbers on the wire
One request per connection at a time (HTTP/1.1)Many concurrent streams per connection (HTTP/2 multiplexing)
Streaming via SSE or WebSockets, separate stacksServer, client and bidirectional streaming built in
Status in the HTTP code, details by convention17 status codes plus typed error details
Every browser and curl speaks itBrowsers need gRPC-Web or Connect; curl needs grpcurl
Easy to cache at HTTP layerPOST-only, not cacheable by CDNs
Readable on the wireNeeds the schema (or reflection) to read

An everyday picture. A restaurant chain's order form. Every branch uses the same printed form: box 1 is the table number, box 2 the dish, box 5 the allergies. The kitchen reads boxes by number, not by handwriting; a new box 7 ("loyalty card") can be printed on new forms and old kitchens simply ignore it; box 4 was "coupon" until last year and is now crossed out on every form so nobody reuses it for something else. The .proto file is the master copy of that form, buf breaking is the manager who refuses a new print run that reuses box 4, and the generated Go code is the stack of pre-printed forms in every branch.

Three common misunderstandings, up front ​

  1. "gRPC is faster, so use it everywhere." It saves bytes and connections between services you control; for a public API used by browsers and partners, REST/JSON is usually the better contract, and grpc-gateway lets you have both from one .proto.
  2. "Returning an error from a handler sends that error to the client." Only a status error does. A plain errors.New("not found") arrives as codes.Unknown with the text as its message, which is the exact bug the Before snippet shows.
  3. "The field name is what matters on the wire." The field number is. Renaming a field is safe for binary clients, while changing its number or reusing an old number silently corrupts data, as the compat test proves.

Where it comes from ​

Protocol Buffers started inside Google and, per protobuf.dev, "Protobuf was open sourced in 2008". gRPC's own history page says Google had used "a single general-purpose RPC infrastructure called Stubby" for over a decade and that "In March 2015, Google decided to build the next version of Stubby and make it open source"; the September 2015 "gRPC Motivation and Design Principles" post explains that Stubby was "too tightly coupled to our internal infrastructure" and that HTTP/2 now offered the same features as a public standard.

On the Go side the story has three steps. The original github.com/golang/protobuf module (APIv1) generated both messages and gRPC code from one plugin. On 2 March 2020 the Go team released google.golang.org/protobuf (APIv2) with first-class reflection, and the gRPC code generator moved into its own plugin, protoc-gen-go-grpc, whose README notes that service implementations "must embed the corresponding Unimplemented<ServiceName>Server for future compatibility". On 16 December 2024 the Go blog announced the Opaque API for generated code, tied to Protobuf Editions (edition = "2023", the successor to syntax = "proto3"). In grpc-go, v1.63 introduced grpc.NewClient, "to allow users to create new clients in idle mode and with "dns" as the default resolver", and grpc.Dial became deprecated ("use NewClient instead. Will be supported throughout 1.x."). Validation moved from protoc-gen-validate, which "has reached a stable state and is in maintenance mode", to protovalidate. This page uses proto3 syntax and the Open Struct API, which is still what protoc-gen-go emits for proto3 files.

Go ​

Before ​

A service and client that pass every happy-path demo: the server returns plain Go errors, sleeps without looking at ctx, and the client calls with context.Background() and decides "not found" by searching the error text.

go
// Package before is a gRPC service and client that work on a quiet day but
// are badly designed: plain Go errors, no deadline, string matching on error
// text.
package before

import (
	"context"
	"fmt"
	"strings"
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
)

// Server returns plain Go errors. grpc-go turns any non-status error into
// codes.Unknown, so the client cannot tell "missing" from "broken".
type Server struct {
	ordersv1.UnimplementedOrderServiceServer
	Orders map[string]*ordersv1.Order
	// Delay simulates a slow dependency.
	Delay time.Duration
}

// GetOrder looks the order up after an uninterruptible sleep.
func (s *Server) GetOrder(_ context.Context, req *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	time.Sleep(s.Delay) // ignores ctx: keeps working after the caller left
	o, ok := s.Orders[req.GetId()]
	if !ok {
		return nil, fmt.Errorf("order %s not found", req.GetId())
	}
	return &ordersv1.GetOrderResponse{Order: o}, nil
}

// Lookup calls GetOrder with context.Background(): no deadline, no
// cancellation, and it decides "not found" by searching the error text.
func Lookup(c ordersv1.OrderServiceClient, id string) (*ordersv1.Order, bool, error) {
	res, err := c.GetOrder(context.Background(), &ordersv1.GetOrderRequest{Id: id})
	if err != nil {
		if strings.Contains(err.Error(), "not found") {
			return nil, false, nil
		}
		return nil, false, err
	}
	return res.GetOrder(), true, nil
}

The test pins both problems: the plain error arrives as codes.Unknown, and with no deadline the caller waits for the whole 300 ms of a slow server.

go
package before_test

import (
	"testing"
	"time"

	"academy/grpc-protobuf-in-go/before"
	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/testsrv"

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

func TestPlainErrorBecomesUnknown(t *testing.T) {
	srv := testsrv.Start(t, func(s *grpc.Server) {
		ordersv1.RegisterOrderServiceServer(s, &before.Server{Orders: map[string]*ordersv1.Order{}})
	})
	c := ordersv1.NewOrderServiceClient(srv.Dial(t))

	_, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "o-1"})
	if status.Code(err) != codes.Unknown {
		t.Fatalf("plain error should arrive as Unknown, got %v", err)
	}
	if err.Error() != "rpc error: code = Unknown desc = order o-1 not found" {
		t.Fatalf("text: %q", err.Error())
	}
	// String matching "works" until someone rewords the message.
	if _, found, err := before.Lookup(c, "o-1"); found || err != nil {
		t.Fatalf("found=%v err=%v", found, err)
	}
}

func TestNoDeadlineWaitsForTheSlowServer(t *testing.T) {
	srv := testsrv.Start(t, func(s *grpc.Server) {
		ordersv1.RegisterOrderServiceServer(s, &before.Server{
			Orders: map[string]*ordersv1.Order{"o-1": {Id: "o-1"}},
			Delay:  300 * time.Millisecond,
		})
	})
	c := ordersv1.NewOrderServiceClient(srv.Dial(t))
	start := time.Now()
	if _, _, err := before.Lookup(c, "o-1"); err != nil {
		t.Fatal(err)
	}
	if took := time.Since(start); took < 300*time.Millisecond {
		t.Fatalf("expected the caller to wait the full delay, took %v", took)
	}
}

After ​

The server answers status.Errorf(codes.NotFound, ...) and stops when the caller's context ends; the client derives a per-call deadline from the caller's context and maps codes, not strings, to domain errors.

go
// Package after fixes the before package: status codes on the server, a
// deadline on every call, and classification by code instead of by text.
package after

import (
	"context"
	"errors"
	"fmt"
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

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

// Domain errors the rest of the application understands.
var (
	ErrNotFound = errors.New("order not found")
	ErrTimeout  = errors.New("orders service did not answer in time")
)

// Server answers with status errors and stops when the caller gives up.
type Server struct {
	ordersv1.UnimplementedOrderServiceServer
	Orders map[string]*ordersv1.Order
	Delay  time.Duration
}

// GetOrder waits for its dependency or for ctx, whichever comes first.
func (s *Server) GetOrder(ctx context.Context, req *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	select {
	case <-time.After(s.Delay):
	case <-ctx.Done():
		// Canceled or DeadlineExceeded, as a gRPC status.
		return nil, status.FromContextError(ctx.Err()).Err()
	}
	o, ok := s.Orders[req.GetId()]
	if !ok {
		return nil, status.Errorf(codes.NotFound, "order %q not found", req.GetId())
	}
	return &ordersv1.GetOrderResponse{Order: o}, nil
}

// Client wraps the generated stub with a per-call budget.
type Client struct {
	Stub    ordersv1.OrderServiceClient
	Timeout time.Duration
}

// Lookup derives a deadline from the caller's ctx (it can only shorten it)
// and maps gRPC codes to domain errors.
func (c *Client) Lookup(ctx context.Context, id string) (*ordersv1.Order, error) {
	ctx, cancel := context.WithTimeout(ctx, c.Timeout)
	defer cancel()
	res, err := c.Stub.GetOrder(ctx, &ordersv1.GetOrderRequest{Id: id})
	switch status.Code(err) {
	case codes.OK:
		return res.GetOrder(), nil
	case codes.NotFound:
		return nil, ErrNotFound
	case codes.DeadlineExceeded:
		return nil, fmt.Errorf("%w: %v", ErrTimeout, err)
	default:
		return nil, fmt.Errorf("orders.GetOrder: %w", err)
	}
}
go
package after_test

import (
	"errors"
	"testing"
	"time"

	"academy/grpc-protobuf-in-go/after"
	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/testsrv"

	"google.golang.org/grpc"
)

func start(t *testing.T, delay time.Duration) *after.Client {
	srv := testsrv.Start(t, func(s *grpc.Server) {
		ordersv1.RegisterOrderServiceServer(s, &after.Server{
			Orders: map[string]*ordersv1.Order{"o-1": {Id: "o-1"}},
			Delay:  delay,
		})
	})
	return &after.Client{Stub: ordersv1.NewOrderServiceClient(srv.Dial(t)), Timeout: 50 * time.Millisecond}
}

func TestNotFoundIsACode(t *testing.T) {
	c := start(t, 0)
	if _, err := c.Lookup(t.Context(), "o-2"); !errors.Is(err, after.ErrNotFound) {
		t.Fatalf("want ErrNotFound, got %v", err)
	}
	if o, err := c.Lookup(t.Context(), "o-1"); err != nil || o.GetId() != "o-1" {
		t.Fatalf("got %v, %v", o, err)
	}
}

func TestDeadlineCutsTheSlowCall(t *testing.T) {
	c := start(t, 300*time.Millisecond)
	begin := time.Now()
	_, err := c.Lookup(t.Context(), "o-1")
	if !errors.Is(err, after.ErrTimeout) {
		t.Fatalf("want ErrTimeout, got %v", err)
	}
	if took := time.Since(begin); took > 250*time.Millisecond {
		t.Fatalf("deadline did not cut the call: %v", took)
	}
	t.Log(err) // orders service did not answer in time: rpc error: code = DeadlineExceeded desc = context deadline exceeded
}

The Go angle ​

Go's gRPC is deliberately plain Go. The generated server interface is an ordinary interface you satisfy with a struct; every method takes context.Context first, so deadlines, cancellation and metadata use the same mechanism as net/http and database/sql; every failure is an ordinary error that the status package can convert to and from a code. Streams are generic types by default since protoc-gen-go-grpc v1.5.0 (grpc.ServerStreamingServer[T] and five siblings; v1.4.0 had them behind an experimental flag), and the tooling is Go too: buf, grpcurl, grpc-health-probe and every protoc-gen-* plugin install with go install. The cost of that plainness is that nothing is automatic: no default deadline, no default auth, no validation, no REST, no retries beyond transparent retry. Each one is a choice this page shows.

The concept catalogue ​

All snippets share one contract, academy.orders.v1.OrderService. Here it is in full; every block below points back to a part of it.

proto
// Orders API used by every snippet in this chapter.
syntax = "proto3";

package academy.orders.v1;

import "buf/validate/validate.proto";
import "google/api/annotations.proto";
import "google/protobuf/duration.proto";
import "google/protobuf/field_mask.proto";
import "google/protobuf/timestamp.proto";

option go_package = "academy/grpc-protobuf-in-go/gen/academy/orders/v1;ordersv1";

// OrderService shows all four RPC shapes.
service OrderService {
  // Unary: one request, one response.
  rpc GetOrder(GetOrderRequest) returns (GetOrderResponse) {
    option (google.api.http) = {get: "/v1/orders/{id}"};
  }
  rpc CreateOrder(CreateOrderRequest) returns (CreateOrderResponse) {
    option (google.api.http) = {
      post: "/v1/orders"
      body: "*"
    };
  }
  // Partial update driven by a FieldMask.
  rpc UpdateOrder(UpdateOrderRequest) returns (UpdateOrderResponse) {
    option (google.api.http) = {
      patch: "/v1/orders/{order.id}"
      body: "order"
    };
  }
  rpc DeleteOrder(DeleteOrderRequest) returns (DeleteOrderResponse) {
    option (google.api.http) = {delete: "/v1/orders/{id}"};
  }
  // Server streaming: one request, many responses.
  rpc ListOrders(ListOrdersRequest) returns (stream ListOrdersResponse) {
    option (google.api.http) = {get: "/v1/orders"};
  }
  // Client streaming: many requests, one response.
  rpc ImportOrders(stream ImportOrdersRequest) returns (ImportOrdersResponse);
  // Bidirectional streaming: both sides send independently.
  rpc ReserveStock(stream ReserveStockRequest) returns (stream ReserveStockResponse);
  // Echo returns the payload size; used to show message size limits.
  rpc Echo(EchoRequest) returns (EchoResponse);
}

enum OrderStatus {
  ORDER_STATUS_UNSPECIFIED = 0;
  ORDER_STATUS_PENDING = 1;
  ORDER_STATUS_PAID = 2;
  ORDER_STATUS_SHIPPED = 3;
  ORDER_STATUS_CANCELLED = 4;
}

message LineItem {
  string sku = 1 [(buf.validate.field).string = {
    min_len: 1
    max_len: 32
  }];
  int32 quantity = 2 [(buf.validate.field).int32 = {
    gt: 0
    lte: 1000
  }];
  int64 unit_price_minor = 3 [(buf.validate.field).int64.gte = 0];
}

message CardPayment {
  string brand = 1;
  string last4 = 2 [(buf.validate.field).string.len = 4];
}

message Order {
  // Field 4 was "coupon" (string) in an earlier version: never reuse it.
  reserved 4;
  reserved "coupon";

  string id = 1;
  string customer_id = 2;
  OrderStatus status = 3;
  repeated LineItem items = 5;
  map<string, string> labels = 6;
  google.protobuf.Timestamp create_time = 7;
  // optional gives explicit presence: unset and "" are different.
  optional string note = 8;
  oneof payment {
    CardPayment card = 9;
    string wallet_id = 10;
  }
  google.protobuf.Duration delivery_window = 11;
  int64 total_minor = 12;
  string currency_code = 13;
}

message GetOrderRequest {
  string id = 1 [(buf.validate.field).string.min_len = 1];
}

message GetOrderResponse {
  Order order = 1;
}

message CreateOrderRequest {
  string customer_id = 1 [(buf.validate.field).string.pattern = "^c-[0-9]+$"];
  repeated LineItem items = 2 [(buf.validate.field).repeated = {
    min_items: 1
    max_items: 100
  }];
  string currency_code = 3 [(buf.validate.field).string.len = 3];
  optional string note = 4 [(buf.validate.field).string.max_len = 200];
  map<string, string> labels = 5 [(buf.validate.field).map.max_pairs = 10];
}

message CreateOrderResponse {
  Order order = 1;
}

message UpdateOrderRequest {
  Order order = 1 [(buf.validate.field).required = true];
  google.protobuf.FieldMask update_mask = 2;
}

message UpdateOrderResponse {
  Order order = 1;
}

message DeleteOrderRequest {
  string id = 1 [(buf.validate.field).string.min_len = 1];
}

// DeleteOrderResponse is empty today; a named message (rather than
// google.protobuf.Empty) leaves room to add fields later.
message DeleteOrderResponse {}

message ListOrdersRequest {
  string customer_id = 1;
  int32 page_size = 2 [(buf.validate.field).int32 = {
    gte: 0
    lte: 1000
  }];
}

message ListOrdersResponse {
  Order order = 1;
}

message ImportOrdersRequest {
  CreateOrderRequest order = 1;
}

message ImportOrdersResponse {
  int32 imported = 1;
  int32 rejected = 2;
  int64 total_minor = 3;
}

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

message ReserveStockResponse {
  string sku = 1;
  bool reserved = 2;
  int32 remaining = 3;
}

// Echo messages are used by the message-size-limit snippet.
message EchoRequest {
  bytes payload = 1;
}

message EchoResponse {
  int32 size = 1;
}

proto3 messages, scalar types and field numbers Must-know ​

In plain words: A message is a struct whose every field has a type and a number. The number, not the name, is what goes on the wire, so it is the field's real identity forever.

Common misunderstanding: "Field numbers are just ordering." They are the key in the binary encoding. The proto3 guide: "This number cannot be changed once your message type is in use because it identifies the field in the message wire format", and "Field numbers should never be reused." Another one: "an unset int64 is absent". In proto3 a plain scalar field set to its zero value is not serialised at all, so on the reader side "zero" and "not sent" look identical.

Definition: Field numbers run from 1 to 536,870,911; "Field numbers 19,000 to 19,999 are reserved for the Protobuf implementation"; "field numbers in the range 1 through 15 take one byte to encode. Field numbers in the range 16 through 2047 take two bytes" (the snippet test asserts this with protowire.SizeTag). Scalar types are double, float, int32, int64, uint32, uint64, sint32, sint64 (zig-zag, good for negatives), fixed32, fixed64, sfixed32, sfixed64, bool, string (must be valid UTF-8) and bytes. In Go, int64/uint64 map to int64/uint64, string to string, bytes to []byte, a message to a pointer, repeated to a slice and map to a Go map. reserved 4; reserved "coupon"; stops anyone reusing a deleted field's number or name.

     writer (CustomerV2)                         wire bytes                      reader (CustomerV1)
1    Id: "c-1"           field 1, LEN  ──▶  0a 03 63 2d 31                ──▶   Id = "c-1"
2    Name: "Sara"        field 2, LEN  ──▶  12 04 53 61 72 61             ──▶   Name = "Sara"
3    Email: "sara@..."   field 3, LEN  ──▶  1a 11 ...                     ──▶   unknown field 3 (kept)
4    LoyaltyPoints: 120  field 4, VARINT ─▶ 20 78                         ──▶   unknown field 4 (kept)
5                                                                              re-marshal: fields 3 and 4 still there

Real scenario: an order total stored as int64 total_minor in cents rather than double so 0.1 + 0.2 never appears on an invoice; a sint32 temperature for a sensor that reports negative values; a bytes signature field for an HMAC; the hot fields of a high-volume event (id, type, timestamp) given numbers 1 to 15.

TypeGo typeZero value on the wireUse for
stringstringNot sentText; must be UTF-8 (proto.Marshal fails with string field contains invalid UTF-8)
bytes[]byteNot sentBinary, hashes, nested encoded data
int32, int64int32, int64Not sentCounts, money in minor units
sint32, sint64int32, int64Not sentValues that are often negative
uint32, uint64uint32, uint64Not sentIds that are never negative
fixed64, sfixed64uint64, int64Not sentLarge values, hashes (always 8 bytes)
double, floatfloat64, float32Not sentMeasurements, never money
boolboolNot sentFlags (prefer an enum if a third state may come)

Fix / how to use it: choose numbers once, put the frequent fields in 1 to 15, use integer minor units for money, and when you delete a field add both its number and its name to reserved in the same commit. The protobasics tests below assert the tag sizes, UTF-8 rule and unknown-field behaviour.

go
package protobasics_test

import (
	"strings"
	"testing"
	"time"

	"academy/grpc-protobuf-in-go/protobasics"

	compatv1 "academy/grpc-protobuf-in-go/gen/academy/compat/v1"
	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/encoding/protowire"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/emptypb"
)

var at = time.Date(2026, 11, 28, 10, 0, 0, 0, time.UTC)

func TestOneofAndPresence(t *testing.T) {
	o := protobasics.SampleOrder(at)
	if got := protobasics.PaymentKind(o); got != "card visa" {
		t.Fatal(got)
	}
	o.Payment = &ordersv1.Order_WalletId{WalletId: "w-9"} // setting one member replaces the other
	if o.GetCard() != nil || protobasics.PaymentKind(o) != "wallet w-9" {
		t.Fatal("oneof should hold one member")
	}

	empty := &ordersv1.Order{}
	if set, note, cur := protobasics.Presence(empty); set || note != "" || cur != "" {
		t.Fatal("unset fields read as zero values")
	}
	zero := &ordersv1.Order{Note: proto.String("")}
	if set, _, _ := protobasics.Presence(zero); !set {
		t.Fatal("optional field set to \"\" must report presence")
	}
	// The difference survives the wire: a present empty string is encoded.
	a, _ := proto.Marshal(empty)
	b, _ := proto.Marshal(zero)
	if len(a) != 0 || len(b) != 2 {
		t.Fatalf("len(unset)=%d len(present empty)=%d", len(a), len(b))
	}
}

func TestJSONMapping(t *testing.T) {
	s, err := protobasics.JSON(protobasics.SampleOrder(at))
	if err != nil {
		t.Fatal(err)
	}
	for _, want := range []string{`"customerId":"c-7"`, `"status":"ORDER_STATUS_PAID"`, `"createTime":"2026-11-28T10:00:00Z"`, `"deliveryWindow":"172800s"`, `"totalMinor":"2500"`, `"last4":"4242"`} {
		if !strings.Contains(strings.ReplaceAll(s, " ", ""), want) {
			t.Errorf("JSON %s lacks %s", s, want)
		}
	}
}

func TestAnyRoundTrip(t *testing.T) {
	a, err := protobasics.PackAny(protobasics.SampleOrder(at))
	if err != nil {
		t.Fatal(err)
	}
	if a.GetTypeUrl() != "type.googleapis.com/academy.orders.v1.Order" {
		t.Fatal(a.GetTypeUrl())
	}
	o, err := protobasics.UnpackOrder(a)
	if err != nil || o.GetId() != "o-1" {
		t.Fatalf("%v %v", o, err)
	}
	e, _ := protobasics.PackAny(&emptypb.Empty{})
	if _, err := protobasics.UnpackOrder(e); err == nil {
		t.Fatal("unpacking Empty into Order must fail")
	}
}

func TestFieldNumberCost(t *testing.T) {
	// The tag is (field_number << 3 | wire_type) as a varint.
	cases := map[protowire.Number]int{1: 1, 15: 1, 16: 2, 2047: 2, 2048: 3}
	for n, want := range cases {
		if got := protowire.SizeTag(n); got != want {
			t.Errorf("field %d: tag size %d, want %d", n, got, want)
		}
	}
}

func TestNewFieldIsUnknownToOldReader(t *testing.T) {
	v2 := &compatv1.CustomerV2{Id: "c-1", Name: "Sara", Email: "sara@example.test", LoyaltyPoints: 120}
	wire, err := proto.Marshal(v2)
	if err != nil {
		t.Fatal(err)
	}
	// An old binary parses the new message: fields 3 and 4 become unknown fields.
	var v1 compatv1.CustomerV1
	if err := proto.Unmarshal(wire, &v1); err != nil {
		t.Fatal(err)
	}
	if v1.GetName() != "Sara" || len(v1.ProtoReflect().GetUnknown()) == 0 {
		t.Fatal("old reader should keep known fields and retain unknown ones")
	}
	// Re-marshalling the old message keeps the unknown bytes: a v2 reader downstream still sees email.
	again, _ := proto.Marshal(&v1)
	var back compatv1.CustomerV2
	if err := proto.Unmarshal(again, &back); err != nil || back.GetEmail() != "sara@example.test" {
		t.Fatalf("unknown field lost in binary pass-through: %v %v", back.GetEmail(), err)
	}
	// JSON has no place for unknown fields: they are dropped.
	js, _ := protojson.Marshal(&v1)
	var viaJSON compatv1.CustomerV1
	_ = protojson.Unmarshal(js, &viaJSON)
	if len(viaJSON.ProtoReflect().GetUnknown()) != 0 {
		t.Fatal("JSON round trip should drop unknown fields")
	}
}

func TestReusedNumberWithOtherTypeBreaks(t *testing.T) {
	wire, _ := proto.Marshal(&compatv1.CustomerV1{Id: "c-1", Name: "Sara"})
	var broken compatv1.CustomerBroken
	err := proto.Unmarshal(wire, &broken)
	// Field 2 arrives as length-delimited bytes but is declared int64 (varint):
	// the parser cannot use it, so it is kept as an unknown field and Name is 0.
	if err != nil {
		t.Logf("unmarshal error: %v", err)
	}
	if broken.GetName() != 0 {
		t.Fatalf("name = %d", broken.GetName())
	}
	if len(broken.ProtoReflect().GetUnknown()) == 0 {
		t.Fatal("mismatched wire type should land in unknown fields")
	}
}

func TestStringFieldsMustBeUTF8(t *testing.T) {
	_, err := proto.Marshal(&ordersv1.Order{Id: "\xff"})
	if err == nil || !strings.Contains(err.Error(), "invalid UTF-8") {
		t.Fatalf("got %v", err)
	}
	t.Log(err) // string field contains invalid UTF-8; bytes fields have no such rule
}

Enums, oneof, optional and field presence Must-know ​

In plain words: An enum is a named list of integers whose first value must be 0 and should mean "unspecified". A oneof is "at most one of these fields"; it may also have none set. optional on a scalar gives it a "was it set?" bit, which plain proto3 scalars do not have.

Common misunderstanding: "Plain proto3 fields cannot tell 'not set' from 'set to zero', so I need wrapper types everywhere." Since protobuf 3.15 optional brings back explicit presence for scalars, and in Go it simply becomes a pointer (Note *string); message fields always had presence. The opposite mistake: making every field optional "just in case", which turns every read into a nil check without a reason.

Definition: "In proto3, the first value defined in an enum definition must have the value zero", and "The zero value needs to be the first element". buf's STANDARD lint enforces the TYPE_NAME_UNSPECIFIED zero value and the type-name prefix (ORDER_STATUS_PAID), because enum values share one scope per package. Go generates type OrderStatus int32 with constants OrderStatus_ORDER_STATUS_PAID and String(). "Oneof fields are like optional fields except all the fields in a oneof share memory, and at most one field can be set at the same time"; Go generates an unexported interface field (Payment isOrder_Payment) and one wrapper struct per member (*Order_Card, *Order_WalletId), read with a type switch or the GetCard() getter. optional string note = 8 generates Note *string, set with proto.String("...").

1  o := &Order{}                          Note == nil, GetNote() == ""     proto.Marshal -> 0 bytes
2  o.Note = proto.String("")              Note != nil, GetNote() == ""     proto.Marshal -> 2 bytes (42 00)
3  o.Payment = &Order_Card{Card: card}    GetCard() != nil
4  o.Payment = &Order_WalletId{"w-9"}     GetCard() == nil: setting one member clears the other
5  switch p := o.GetPayment().(type) { case *Order_Card: ... case *Order_WalletId: ... case nil: ... }

Real scenario: an order status enum where ORDER_STATUS_UNSPECIFIED catches a client that forgot to set it; a payment oneof of card, wallet or bank transfer; a PATCH-like update where optional string note distinguishes "clear the note" ("") from "do not touch it" (unset); a feature flag as optional bool so "not configured" falls back to the default.

NeedUseGo shapePresence
Fixed set of statesenum with _UNSPECIFIED = 0type X int32 + constantsNo (0 means unspecified)
At most one of severaloneofInterface field + wrapper structsYes (nil means none)
Exactly one of several (a required choice)oneof + option (buf.validate.oneof).required = true;Same; enforced by protovalidateUnset is rejected
Scalar where unset mattersoptionalPointer (*string, *int64)Yes
Plain scalarno labelValue (string, int64)No
Nested messagemessage typePointerYes, always
Nullable scalar (pre-3.15 style)google.protobuf.StringValue*wrapperspb.StringValueYes (prefer optional now)

Fix / how to use it: give every enum an _UNSPECIFIED = 0 value and reject it in validation, use oneof for mutually exclusive choices (and add (buf.validate.oneof).required = true when one member is mandatory, because the oneof itself allows none), and use optional only where "unset" is a real business state.

go
// Package protobasics shows how the generated Go types behave: presence,
// oneof, maps, well-known types, binary vs JSON encoding and Any.
package protobasics

import (
	"fmt"
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// SampleOrder fills every kind of field the schema has.
func SampleOrder(at time.Time) *ordersv1.Order {
	return &ordersv1.Order{
		Id:         "o-1",
		CustomerId: "c-7",
		Status:     ordersv1.OrderStatus_ORDER_STATUS_PAID, // enum
		Items: []*ordersv1.LineItem{ // repeated message
			{Sku: "SKU-1", Quantity: 2, UnitPriceMinor: 1250},
		},
		Labels:     map[string]string{"channel": "web"}, // map
		CreateTime: timestamppb.New(at),                 // google.protobuf.Timestamp
		Note:       proto.String("leave at door"),       // optional: *string
		// oneof: exactly one wrapper type is assigned to the interface field.
		Payment:        &ordersv1.Order_Card{Card: &ordersv1.CardPayment{Brand: "visa", Last4: "4242"}},
		DeliveryWindow: durationpb.New(48 * time.Hour), // google.protobuf.Duration
		TotalMinor:     2500,
		CurrencyCode:   "EUR",
	}
}

// PaymentKind switches on the oneof wrapper types.
func PaymentKind(o *ordersv1.Order) string {
	switch p := o.GetPayment().(type) {
	case *ordersv1.Order_Card:
		return "card " + p.Card.GetBrand()
	case *ordersv1.Order_WalletId:
		return "wallet " + p.WalletId
	case nil:
		return "none"
	default:
		return fmt.Sprintf("unknown %T", p)
	}
}

// Presence reports how an optional field and a plain field look when unset,
// set to the zero value, and set to a real value.
func Presence(o *ordersv1.Order) (noteSet bool, note string, currency string) {
	return o.Note != nil, o.GetNote(), o.GetCurrencyCode()
}

// JSON renders the canonical ProtoJSON form (lowerCamelCase names, enums as
// strings, Timestamp as RFC 3339, Duration as "172800s", int64 as a string).
func JSON(m proto.Message) (string, error) {
	b, err := protojson.MarshalOptions{}.Marshal(m)
	return string(b), err
}

// PackAny wraps a message in google.protobuf.Any and unwraps it again.
func PackAny(m proto.Message) (*anypb.Any, error) {
	return anypb.New(m)
}

// UnpackOrder is the receiving side of PackAny.
func UnpackOrder(a *anypb.Any) (*ordersv1.Order, error) {
	var o ordersv1.Order
	if err := a.UnmarshalTo(&o); err != nil {
		return nil, err
	}
	return &o, nil
}

repeated, map and the well-known types Must-know ​

In plain words: repeated is a list, map<K, V> is a dictionary, and the well-known types are Google's shared messages for things every API needs: a point in time (Timestamp), a length of time (Duration), nothing (Empty), anything (Any) and "which fields" (FieldMask).

Common misunderstanding: "Timestamp is a string." It is a message with seconds and nanos; only its JSON form is an RFC 3339 string. Another: "map order is stable". Go maps are unordered, and so is the wire order of map entries; never sign or hash a marshalled message that contains a map unless you use deterministic marshalling, and even then only within one binary version.

Definition: "repeated: this field type can be repeated zero or more times in a well-formed message. The order of the repeated values will be preserved", and repeated scalar numerics are packed by default. map<key_type, value_type> keys may be any integral or string type; a map cannot be repeated. In Go: timestamppb.New(t)/ts.AsTime(), durationpb.New(d)/d.AsDuration(), emptypb.Empty{}, anypb.New(msg)/a.UnmarshalTo(&dst) with a type URL like type.googleapis.com/academy.orders.v1.Order, and fieldmaskpb.New(&Order{}, "status") with IsValid and Normalize.

1  UpdateOrder(order{id:"o-1", status:PAID, labels:{}}, update_mask{paths:["status"]})
2  server: mask.IsValid(order)               -> true ("status" is a field of Order)
3  for path in mask: "status" -> cur.Status = PAID
4  labels in the request is ignored: it is not in the mask
5  update_mask{paths:["no_such_field"]}      -> IsValid false -> codes.InvalidArgument

Real scenario: create_time as Timestamp so every language gets a native time; a delivery window as Duration instead of an ambiguous int32 hours; a PATCH endpoint driven by FieldMask so clients send only what changes (AIP-134); Any inside error details (google.rpc.Status.details is repeated Any); Empty for a Ping RPC in an internal API.

Well-known typeGo packageConstructor / accessorJSON form
google.protobuf.Timestamptypes/known/timestamppbtimestamppb.New(t), AsTime()"2026-11-28T10:00:00Z"
google.protobuf.Durationtypes/known/durationpbdurationpb.New(d), AsDuration()"172800s"
google.protobuf.Emptytypes/known/emptypb&emptypb.Empty{}{}
google.protobuf.Anytypes/known/anypbanypb.New(m), UnmarshalTo, MessageIs{"@type": "...", ...}
google.protobuf.FieldMasktypes/known/fieldmaskpbfieldmaskpb.New(m, paths...), IsValid"status,note" (lowerCamel, comma-joined)
google.protobuf.Struct / Valuetypes/known/structpbstructpb.NewStruct(map)Any JSON object
google.protobuf.StringValue etc.types/known/wrapperspbwrapperspb.String(s)The bare value or null

Fix / how to use it: use Timestamp and Duration for time, FieldMask for partial updates, Any only where the set of types is truly open (error details, plugin payloads), and a named empty message (DeleteOrderResponse {}) instead of Empty for public RPCs so you can add fields later; buf's STANDARD lint enforces that last rule with RPC_REQUEST_STANDARD_NAME/RPC_RESPONSE_STANDARD_NAME (see the lint lab). The server's UpdateOrder applies a mask:

go
// Package server implements academy.orders.v1.OrderService with an in-memory
// store. It shows the four RPC shapes, status codes with details, FieldMask
// updates and cooperative cancellation in streams.
package server

import (
	"context"
	"errors"
	"fmt"
	"io"
	"sort"
	"sync"
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// Service is the OrderService implementation. Embedding the Unimplemented
// struct by value keeps the type compiling when new RPCs are added to the
// .proto file: they answer codes.Unimplemented until written.
type Service struct {
	ordersv1.UnimplementedOrderServiceServer

	mu     sync.Mutex
	orders map[string]*ordersv1.Order
	stock  map[string]int32
	nextID int
	now    func() time.Time
	// StreamDelay slows ListOrders down so tests can watch deadlines fire.
	StreamDelay time.Duration
}

// New returns a service with an empty store and some stock.
func New() *Service {
	return &Service{
		orders: map[string]*ordersv1.Order{},
		stock:  map[string]int32{"SKU-1": 5, "SKU-2": 1},
		now:    time.Now,
	}
}

// Seed stores an order as-is (used by tests and the demo binary).
func (s *Service) Seed(o *ordersv1.Order) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.orders[o.GetId()] = proto.Clone(o).(*ordersv1.Order)
}

// GetOrder is a unary RPC. A missing order is codes.NotFound with a
// ResourceInfo detail, never a plain Go error (that would be codes.Unknown).
func (s *Service) GetOrder(ctx context.Context, req *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	o, ok := s.orders[req.GetId()]
	if !ok {
		return nil, notFound(req.GetId())
	}
	// Clone under the lock: UpdateOrder mutates stored orders in place.
	return &ordersv1.GetOrderResponse{Order: proto.Clone(o).(*ordersv1.Order)}, nil
}

// CreateOrder computes the total and stores a PENDING order.
func (s *Service) CreateOrder(ctx context.Context, req *ordersv1.CreateOrderRequest) (*ordersv1.CreateOrderResponse, error) {
	o, err := s.create(req)
	if err != nil {
		return nil, err
	}
	return &ordersv1.CreateOrderResponse{Order: o}, nil
}

func (s *Service) create(req *ordersv1.CreateOrderRequest) (*ordersv1.Order, error) {
	if len(req.GetItems()) == 0 {
		// Validation normally happens in the protovalidate interceptor; the
		// service still refuses to store an empty order.
		st, _ := status.New(codes.InvalidArgument, "order has no items").WithDetails(&errdetails.BadRequest{
			FieldViolations: []*errdetails.BadRequest_FieldViolation{{Field: "items", Description: "at least one item is required"}},
		})
		return nil, st.Err()
	}
	var total int64
	for _, it := range req.GetItems() {
		total += int64(it.GetQuantity()) * it.GetUnitPriceMinor()
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	id := ""
	for id == "" || s.orders[id] != nil { // skip ids taken by seeded orders
		s.nextID++
		id = fmt.Sprintf("o-%d", s.nextID)
	}
	o := &ordersv1.Order{
		Id:             id,
		CustomerId:     req.GetCustomerId(),
		Status:         ordersv1.OrderStatus_ORDER_STATUS_PENDING,
		Items:          req.GetItems(),
		Labels:         req.GetLabels(),
		CreateTime:     timestamppb.New(s.now()),
		Note:           req.Note, // pointer copy keeps "unset" distinct from ""
		DeliveryWindow: durationpb.New(48 * time.Hour),
		TotalMinor:     total,
		CurrencyCode:   req.GetCurrencyCode(),
	}
	s.orders[o.Id] = o
	return proto.Clone(o).(*ordersv1.Order), nil
}

// UpdateOrder applies only the paths named in update_mask (AIP-134 style).
func (s *Service) UpdateOrder(ctx context.Context, req *ordersv1.UpdateOrderRequest) (*ordersv1.UpdateOrderResponse, error) {
	in := req.GetOrder()
	mask := req.GetUpdateMask()
	if !mask.IsValid(in) {
		return nil, status.Errorf(codes.InvalidArgument, "invalid update_mask %v", mask.GetPaths())
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	stored, ok := s.orders[in.GetId()]
	if !ok {
		return nil, notFound(in.GetId())
	}
	// Apply the mask to a copy and store it only if every path was accepted,
	// so a rejected request never leaves a half-applied update behind.
	next := proto.Clone(stored).(*ordersv1.Order)
	for _, p := range mask.GetPaths() {
		switch p {
		case "status":
			next.Status = in.GetStatus()
		case "note":
			next.Note = in.Note
		case "labels":
			next.Labels = in.GetLabels()
		default:
			return nil, status.Errorf(codes.InvalidArgument, "field %q is not updatable", p)
		}
	}
	s.orders[in.GetId()] = next
	return &ordersv1.UpdateOrderResponse{Order: proto.Clone(next).(*ordersv1.Order)}, nil
}

// DeleteOrder is idempotent: deleting a missing order is still OK.
func (s *Service) DeleteOrder(ctx context.Context, req *ordersv1.DeleteOrderRequest) (*ordersv1.DeleteOrderResponse, error) {
	s.mu.Lock()
	delete(s.orders, req.GetId())
	s.mu.Unlock()
	return &ordersv1.DeleteOrderResponse{}, nil
}

// ListOrders is server streaming. It checks the stream context between
// messages so a client deadline or cancel stops the work.
func (s *Service) ListOrders(req *ordersv1.ListOrdersRequest, stream ordersv1.OrderService_ListOrdersServer) error {
	ctx := stream.Context()
	s.mu.Lock()
	ids := make([]string, 0, len(s.orders))
	for id, o := range s.orders {
		if req.GetCustomerId() == "" || o.GetCustomerId() == req.GetCustomerId() {
			ids = append(ids, id)
		}
	}
	s.mu.Unlock()
	sort.Strings(ids)
	if n := int(req.GetPageSize()); n > 0 && n < len(ids) {
		ids = ids[:n]
	}
	for _, id := range ids {
		if s.StreamDelay > 0 {
			select {
			case <-ctx.Done():
				return status.FromContextError(ctx.Err()).Err()
			case <-time.After(s.StreamDelay):
			}
		}
		s.mu.Lock()
		o, ok := s.orders[id]
		var msg *ordersv1.Order
		if ok {
			msg = proto.Clone(o).(*ordersv1.Order)
		}
		s.mu.Unlock()
		if !ok {
			continue
		}
		if err := stream.Send(&ordersv1.ListOrdersResponse{Order: msg}); err != nil {
			return err
		}
	}
	return nil
}

// ImportOrders is client streaming: read until io.EOF, then answer once.
func (s *Service) ImportOrders(stream ordersv1.OrderService_ImportOrdersServer) error {
	sum := &ordersv1.ImportOrdersResponse{}
	for {
		req, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			return stream.SendAndClose(sum)
		}
		if err != nil {
			return err
		}
		o, err := s.create(req.GetOrder())
		if err != nil {
			sum.Rejected++
			continue
		}
		sum.Imported++
		sum.TotalMinor += o.GetTotalMinor()
	}
}

// ReserveStock is bidirectional streaming: one answer per request, in order,
// while the client may keep sending.
func (s *Service) ReserveStock(stream ordersv1.OrderService_ReserveStockServer) error {
	for {
		req, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			return nil
		}
		if err != nil {
			return err
		}
		s.mu.Lock()
		left := s.stock[req.GetSku()]
		ok := req.GetQuantity() > 0 && req.GetQuantity() <= left
		if ok {
			left -= req.GetQuantity()
			s.stock[req.GetSku()] = left
		}
		s.mu.Unlock()
		if err := stream.Send(&ordersv1.ReserveStockResponse{Sku: req.GetSku(), Reserved: ok, Remaining: left}); err != nil {
			return err
		}
	}
}

// Echo reports the payload size (used by the message-size snippet).
func (s *Service) Echo(ctx context.Context, req *ordersv1.EchoRequest) (*ordersv1.EchoResponse, error) {
	return &ordersv1.EchoResponse{Size: int32(len(req.GetPayload()))}, nil
}

func notFound(id string) error {
	st, err := status.New(codes.NotFound, fmt.Sprintf("order %q not found", id)).WithDetails(&errdetails.ResourceInfo{
		ResourceType: "academy.orders.v1.Order",
		ResourceName: id,
		Description:  "no order with this id",
	})
	if err != nil {
		return status.Errorf(codes.NotFound, "order %q not found", id)
	}
	return st.Err()
}

package, go_package and the generated code shape Must-know ​

In plain words: package academy.orders.v1; is the protobuf namespace (it appears in method names on the wire); option go_package is the Go import path and package name of the generated code. The two are independent, and you need both.

Common misunderstanding: "The protobuf package becomes the Go package." It does not; protoc-gen-go needs a Go import path, "In order to generate Go code, the Go package's import path must be provided for every .proto file". Without go_package (or an M flag, or buf managed mode) generation fails. Another: "generated code is a build artefact, do not commit it". In Go it is normally committed, because go get and go test must work without a protobuf compiler.

Definition: option go_package = "academy/grpc-protobuf-in-go/gen/academy/orders/v1;ordersv1"; gives the import path before the ; and the package name after it. With paths=source_relative the output mirrors the .proto path under gen/. protoc-gen-go writes orders.pb.go (one struct per message with state, sizeCache, unknownFields and struct tags such as protobuf:"bytes,2,opt,name=customer_id,json=customerId,proto3", getters like GetCustomerId() that are nil-safe, enum types and the file descriptor). protoc-gen-go-grpc writes orders_grpc.pb.go: OrderService_GetOrder_FullMethodName = "/academy.orders.v1.OrderService/GetOrder", the OrderServiceClient interface and NewOrderServiceClient(cc grpc.ClientConnInterface), the OrderServiceServer interface, UnimplementedOrderServiceServer, RegisterOrderServiceServer(s grpc.ServiceRegistrar, srv OrderServiceServer) (the RegisterXxxServer of every service), the OrderService_ServiceDesc and const _ = grpc.SupportPackageIsVersion9 ("Requires gRPC-Go v1.64.0 or later").

go
// Excerpt of gen/academy/orders/v1/orders_grpc.pb.go (protoc-gen-go-grpc v1.6.2).
type OrderServiceServer interface {
	GetOrder(context.Context, *GetOrderRequest) (*GetOrderResponse, error)
	ListOrders(*ListOrdersRequest, grpc.ServerStreamingServer[ListOrdersResponse]) error
	ImportOrders(grpc.ClientStreamingServer[ImportOrdersRequest, ImportOrdersResponse]) error
	ReserveStock(grpc.BidiStreamingServer[ReserveStockRequest, ReserveStockResponse]) error
	// ... CreateOrder, UpdateOrder, DeleteOrder, Echo
	mustEmbedUnimplementedOrderServiceServer()
}

func RegisterOrderServiceServer(s grpc.ServiceRegistrar, srv OrderServiceServer) {
	// If the following call panics, it indicates UnimplementedOrderServiceServer was
	// embedded by pointer and is nil.
	if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
		t.testEmbeddedByValue()
	}
	s.RegisterService(&OrderService_ServiceDesc, srv)
}
From one .proto file to Go code: buf drives the compiler, plugins write the filesorders.protopackage academy.orders.v1option go_package = ...service OrderServicemessages, enumsdeps (buf.lock)buf.build/googleapis/googleapisbuf.build/bufbuild/protovalidatebuf CLIbuf lint (STANDARD rules)buf breaking --against mainbuf generatecompiles to descriptors,then calls each plugin(protoc does the same with--go_out / --go-grpc_out)protoc-gen-gomessages, enums, oneofsprotoc-gen-go-grpcclient stub, server interfaceprotoc-gen-grpc-gatewayREST reverse proxyprotoc-gen-openapiv2OpenAPI v2 (Swagger)orders.pb.goorders_grpc.pb.goorders.pb.gw.goorders.swagger.jsonYour code imports academy/grpc-protobuf-in-go/gen/academy/orders/v1 (package ordersv1)type Service struct { ordersv1.UnimplementedOrderServiceServer } // embed by value: new RPCs answer Unimplementedordersv1.RegisterOrderServiceServer(grpcServer, svc) // RegisterXxxServerconn, _ := grpc.NewClient("dns:///orders:50051", creds); c := ordersv1.NewOrderServiceClient(conn)ordersv1.RegisterOrderServiceHandlerClient(ctx, gatewayMux, c) // REST transcoding

Real scenario: a monorepo proto/ directory generating into gen/ and committed; a shared contracts module that several Go services import; a client-only consumer that imports just ordersv1 and uses NewOrderServiceClient; a team that adds a rpc and finds every server still compiles because of the Unimplemented embedding.

FilePluginContainsImported by
orders.pb.goprotoc-gen-goMessages, enums, oneof wrappers, getters, descriptorEveryone
orders_grpc.pb.goprotoc-gen-go-grpcClient interface + constructor, server interface, Unimplemented struct, RegisterOrderServiceServer, method name constantsClients and servers
orders.pb.gw.goprotoc-gen-grpc-gatewayRegisterOrderServiceHandlerClient, ...HandlerServer, ...HandlerFromEndpointThe REST gateway
orders.swagger.jsonprotoc-gen-openapiv2OpenAPI v2 documentAPI docs, client generators
validate.pb.gonot generated by youbuf.validate optionsComes from buf.build/gen/go/bufbuild/protovalidate/...

Fix / how to use it: set go_package explicitly in every file, generate with paths=source_relative into a gen/ tree, commit the output, and add a CI step that regenerates and fails on a diff.

protoc vs buf: buf.yaml, buf.gen.yaml, buf lint, buf breaking Must-know ​

In plain words: protoc is Google's compiler; you call it with include paths and one --xxx_out flag per plugin. buf is a newer CLI with its own compiler that reads two small YAML files, fetches dependencies like googleapis from the Buf Schema Registry, and adds a linter and a breaking-change checker.

Common misunderstanding: "buf is a different format." It compiles the same .proto files and runs the same protoc-gen-* plugins; you can switch either way. And "lint is cosmetic": STANDARD lint enforces versioned packages, _UNSPECIFIED enum zero values and unique request/response messages per RPC, the rules that make later evolution possible.

Definition: buf.yaml v2 declares modules (directories that hold .proto files), deps (BSR modules such as buf.build/googleapis/googleapis and buf.build/bufbuild/protovalidate, pinned in buf.lock by buf dep update), and the lint and breaking rule sets. buf.gen.yaml v2 lists plugins (local: binaries on PATH or remote: BSR plugins), their out directory and opt. buf lint checks style rules; buf breaking --against <ref> compares against a git branch, tag, directory or BSR module with categories FILE (strictest), PACKAGE, WIRE_JSON and WIRE; buf generate runs the plugins. The protoc equivalent of this chapter's generation is protoc -I proto -I <googleapis> -I <protovalidate> --go_out=gen --go_opt=paths=source_relative --go-grpc_out=gen --go-grpc_opt=paths=source_relative ..., where you download the include directories yourself.

yaml
# buf.yaml v2: one module (the proto/ directory) plus two BSR dependencies.
version: v2
modules:
  - path: proto
deps:
  - buf.build/googleapis/googleapis
  - buf.build/bufbuild/protovalidate
lint:
  use:
    - STANDARD
breaking:
  use:
    - FILE
yaml
# buf.gen.yaml v2: local plugins found on PATH, output under gen/.
# No managed mode: every .proto file sets its own go_package.
version: v2
plugins:
  - local: protoc-gen-go
    out: gen
    opt: paths=source_relative
  - local: protoc-gen-go-grpc
    out: gen
    opt: paths=source_relative
  - local: protoc-gen-grpc-gateway
    out: gen
    opt: paths=source_relative
  - local: protoc-gen-openapiv2
    out: gen/openapiv2
1  developer edits proto/academy/orders/v1/orders.proto
2  buf lint                        -> naming, packages, enum zero values
3  buf breaking --against '.git#branch=main'   -> deleted fields, changed types, renamed fields
4  buf generate                    -> gen/**.pb.go, *_grpc.pb.go, *.pb.gw.go, swagger.json
5  go build ./... && go test ./... -> generated code compiles against pinned grpc
6  CI: regenerate, git diff --exit-code gen/   -> nobody hand-edited generated files

Real scenario: a pull request that renames customer_id to customer fails buf breaking with changed option "json_name" before review; a new hire's .proto with enum Status { PENDING = 0; } fails lint; a repository that drops a 40-line Makefile of protoc flags for an eight-line buf.gen.yaml; a team that publishes its module to the BSR so other teams depend on buf.build/acme/orders instead of copying files.

Taskprotocbuf
Compileprotoc -I ... --go_out=...buf build / buf generate
Third-party protos (googleapis, protovalidate)Download and -I them yourselfdeps: in buf.yaml, pinned in buf.lock
Plugin configFlags per invocationbuf.gen.yaml
LintNone built inbuf lint (MINIMAL, BASIC, STANDARD)
Breaking changesNone built inbuf breaking (FILE, PACKAGE, WIRE_JSON, WIRE)
Go import paths for depsM flags or go_packageSame, or managed mode
FormatNonebuf format -w

Fix / how to use it: keep buf.yaml, buf.gen.yaml and buf.lock next to go.mod, run buf lint and buf breaking --against the main branch in CI, and install plugins at pinned versions (go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.11). Real lint and breaking output is in the Lab.

Server: grpc.NewServer, RegisterXxxServer and Unimplemented embedding Must-know ​

In plain words: You write a struct with one method per RPC, embed the generated UnimplementedOrderServiceServer in it, create a grpc.NewServer(opts...), register your struct with RegisterOrderServiceServer and call Serve(listener).

Common misunderstanding: "Embedding Unimplemented is optional boilerplate." It is what keeps your server compiling when someone adds an rpc to the .proto file: the new method answers codes.Unimplemented until you write it. It must be embedded by value; protoc-gen-go-grpc's README warns that a nil pointer embedding "will lead to a panic in Register<ServiceName>Server". A second one: "one service per server". One grpc.Server can host many services (yours, health, reflection) on one port.

Definition: grpc.NewServer(opt ...grpc.ServerOption) *grpc.Server; options include grpc.Creds, grpc.ChainUnaryInterceptor, grpc.ChainStreamInterceptor, grpc.KeepaliveParams, grpc.KeepaliveEnforcementPolicy, grpc.MaxRecvMsgSize ("If this is not set, gRPC uses the default 4MB"), grpc.MaxSendMsgSize (default math.MaxInt32) and grpc.MaxConcurrentStreams. Each handler runs in its own goroutine, so the struct must be safe for concurrent use (the snippet guards its maps with a sync.Mutex). Stop closes everything at once; GracefulStop stops accepting, waits for running RPCs and then closes.

1  lis, _ := net.Listen("tcp", ":50051")
2  s := grpc.NewServer(grpc.Creds(tlsCreds), grpc.ChainUnaryInterceptor(...))
3  ordersv1.RegisterOrderServiceServer(s, server.New())      // your service
4  healthpb.RegisterHealthServer(s, health.NewServer()); reflection.Register(s)
5  go s.Serve(lis)                     -> one goroutine per connection, one per RPC
6  SIGTERM: health NOT_SERVING -> s.GracefulStop()   -> in-flight RPCs finish

Real scenario: an orders service that adds rpc CancelOrder in the .proto file while the implementation lands a week later; a binary that serves the business service, health and reflection on one port; a server that drains on SIGTERM so a Kubernetes rolling update drops no calls.

MethodWhat it doesUse when
Serve(lis)Accepts connections until stoppedAlways (blocks)
Stop()Closes listeners and connections, cancels RPCsTests, hard shutdown
GracefulStop()Stops accepting, waits for active RPCsNormal shutdown (add your own timeout)
RegisterService(desc, impl)Low-level registrationOnly via the generated RegisterXxxServer
GetServiceInfo()Map of registered services and methodsDebug endpoints, tests

Fix / how to use it: embed Unimplemented by value, register every service before Serve, and drain with health first, GracefulStop second (the ops snippet's Drain). The tests below start the full service on bufconn and exercise every RPC shape.

go
package server_test

import (
	"context"
	"errors"
	"io"
	"testing"
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/server"
	"academy/grpc-protobuf-in-go/testsrv"

	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

func newClient(t *testing.T, svc *server.Service) ordersv1.OrderServiceClient {
	t.Helper()
	srv := testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, svc) })
	return ordersv1.NewOrderServiceClient(srv.Dial(t))
}

func item(sku string, qty int32, price int64) *ordersv1.LineItem {
	return &ordersv1.LineItem{Sku: sku, Quantity: qty, UnitPriceMinor: price}
}

func TestUnaryCreateGetNotFound(t *testing.T) {
	c := newClient(t, server.New())
	ctx, cancel := context.WithTimeout(t.Context(), time.Second)
	defer cancel()

	created, err := c.CreateOrder(ctx, &ordersv1.CreateOrderRequest{
		CustomerId: "c-7", CurrencyCode: "EUR", Note: proto.String(""),
		Items: []*ordersv1.LineItem{item("SKU-1", 2, 1250), item("SKU-2", 1, 500)},
	})
	if err != nil {
		t.Fatal(err)
	}
	o := created.GetOrder()
	if o.GetTotalMinor() != 3000 || o.GetStatus() != ordersv1.OrderStatus_ORDER_STATUS_PENDING {
		t.Fatalf("total=%d status=%v", o.GetTotalMinor(), o.GetStatus())
	}
	if o.Note == nil {
		t.Fatal("optional note set to \"\" must stay present")
	}

	got, err := c.GetOrder(ctx, &ordersv1.GetOrderRequest{Id: o.GetId()})
	if err != nil || !proto.Equal(got.GetOrder(), o) {
		t.Fatalf("GetOrder = %v, %v", got, err)
	}

	_, err = c.GetOrder(ctx, &ordersv1.GetOrderRequest{Id: "o-404"})
	st, ok := status.FromError(err)
	if !ok || st.Code() != codes.NotFound {
		t.Fatalf("want NotFound, got %v", err)
	}
	var info *errdetails.ResourceInfo
	for _, d := range st.Details() {
		if ri, ok := d.(*errdetails.ResourceInfo); ok {
			info = ri
		}
	}
	if info.GetResourceName() != "o-404" {
		t.Fatalf("missing ResourceInfo detail: %v", st.Details())
	}
	if err.Error() != `rpc error: code = NotFound desc = order "o-404" not found` {
		t.Fatalf("error text: %q", err.Error())
	}
}

func TestUpdateWithFieldMask(t *testing.T) {
	svc := server.New()
	svc.Seed(&ordersv1.Order{Id: "o-1", CustomerId: "c-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PENDING, Labels: map[string]string{"channel": "web"}})
	c := newClient(t, svc)

	mask, err := fieldmaskpb.New(&ordersv1.Order{}, "status")
	if err != nil {
		t.Fatal(err)
	}
	// labels is in the request but not in the mask: it must not be touched.
	res, err := c.UpdateOrder(t.Context(), &ordersv1.UpdateOrderRequest{
		Order:      &ordersv1.Order{Id: "o-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PAID, Labels: map[string]string{}},
		UpdateMask: mask,
	})
	if err != nil {
		t.Fatal(err)
	}
	if res.GetOrder().GetStatus() != ordersv1.OrderStatus_ORDER_STATUS_PAID || res.GetOrder().GetLabels()["channel"] != "web" {
		t.Fatalf("got %v", res.GetOrder())
	}

	_, err = c.UpdateOrder(t.Context(), &ordersv1.UpdateOrderRequest{
		Order:      &ordersv1.Order{Id: "o-1"},
		UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"no_such_field"}},
	})
	if status.Code(err) != codes.InvalidArgument {
		t.Fatalf("want InvalidArgument, got %v", err)
	}
}

func TestServerStreaming(t *testing.T) {
	svc := server.New()
	for _, id := range []string{"o-1", "o-2", "o-3"} {
		svc.Seed(&ordersv1.Order{Id: id, CustomerId: "c-1"})
	}
	svc.Seed(&ordersv1.Order{Id: "o-9", CustomerId: "c-2"})
	c := newClient(t, svc)

	stream, err := c.ListOrders(t.Context(), &ordersv1.ListOrdersRequest{CustomerId: "c-1"})
	if err != nil {
		t.Fatal(err)
	}
	var ids []string
	for {
		msg, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			break // the server returned nil: status OK in the trailers
		}
		if err != nil {
			t.Fatal(err)
		}
		ids = append(ids, msg.GetOrder().GetId())
	}
	if len(ids) != 3 || ids[0] != "o-1" || ids[2] != "o-3" {
		t.Fatalf("ids = %v", ids)
	}
}

func TestServerStreamingDeadline(t *testing.T) {
	svc := server.New()
	svc.StreamDelay = 40 * time.Millisecond
	for _, id := range []string{"o-1", "o-2", "o-3", "o-4", "o-5"} {
		svc.Seed(&ordersv1.Order{Id: id})
	}
	c := newClient(t, svc)

	ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond)
	defer cancel()
	stream, err := c.ListOrders(ctx, &ordersv1.ListOrdersRequest{})
	if err != nil {
		t.Fatal(err)
	}
	got := 0
	for {
		_, err = stream.Recv()
		if err != nil {
			break
		}
		got++
	}
	if status.Code(err) != codes.DeadlineExceeded {
		t.Fatalf("want DeadlineExceeded, got %v", err)
	}
	if got == 0 || got >= 5 {
		t.Fatalf("received %d messages before the deadline, want 1..4", got)
	}
}

func TestClientStreaming(t *testing.T) {
	c := newClient(t, server.New())
	stream, err := c.ImportOrders(t.Context())
	if err != nil {
		t.Fatal(err)
	}
	reqs := []*ordersv1.CreateOrderRequest{
		{CustomerId: "c-1", CurrencyCode: "EUR", Items: []*ordersv1.LineItem{item("SKU-1", 1, 1000)}},
		{CustomerId: "c-2", CurrencyCode: "EUR"}, // no items: rejected
		{CustomerId: "c-3", CurrencyCode: "EUR", Items: []*ordersv1.LineItem{item("SKU-2", 3, 200)}},
	}
	for _, r := range reqs {
		if err := stream.Send(&ordersv1.ImportOrdersRequest{Order: r}); err != nil {
			t.Fatal(err)
		}
	}
	sum, err := stream.CloseAndRecv()
	if err != nil {
		t.Fatal(err)
	}
	if sum.GetImported() != 2 || sum.GetRejected() != 1 || sum.GetTotalMinor() != 1600 {
		t.Fatalf("summary = %v", sum)
	}
}

func TestBidiStreaming(t *testing.T) {
	c := newClient(t, server.New())
	stream, err := c.ReserveStock(t.Context())
	if err != nil {
		t.Fatal(err)
	}
	// Send in a goroutine while the test goroutine receives: the two
	// directions are independent.
	reqs := []*ordersv1.ReserveStockRequest{{Sku: "SKU-1", Quantity: 3}, {Sku: "SKU-1", Quantity: 3}, {Sku: "SKU-2", Quantity: 1}}
	go func() {
		for _, r := range reqs {
			if err := stream.Send(r); err != nil {
				return
			}
		}
		_ = stream.CloseSend()
	}()
	var got []bool
	for {
		res, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			t.Fatal(err)
		}
		got = append(got, res.GetReserved())
	}
	want := []bool{true, false, true}
	if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] || got[2] != want[2] {
		t.Fatalf("reserved = %v, want %v", got, want)
	}
}

func TestUnimplementedEmbedding(t *testing.T) {
	// A server that implements nothing still registers and answers Unimplemented.
	type empty struct {
		ordersv1.UnimplementedOrderServiceServer
	}
	srv := testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, empty{}) })
	c := ordersv1.NewOrderServiceClient(srv.Dial(t))
	_, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
	if status.Code(err) != codes.Unimplemented {
		t.Fatalf("want Unimplemented, got %v", err)
	}
}

func TestConcurrentGetAndUpdate(t *testing.T) {
	svc := server.New()
	svc.Seed(&ordersv1.Order{Id: "o-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PENDING})
	mask := &fieldmaskpb.FieldMask{Paths: []string{"status", "note", "labels"}}
	done := make(chan struct{})
	go func() {
		defer close(done)
		for i := 0; i < 200; i++ {
			_, _ = svc.UpdateOrder(t.Context(), &ordersv1.UpdateOrderRequest{
				Order:      &ordersv1.Order{Id: "o-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PAID, Note: proto.String("n"), Labels: map[string]string{"k": "v"}},
				UpdateMask: mask,
			})
		}
	}()
	for i := 0; i < 200; i++ {
		if _, err := svc.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "o-1"}); err != nil {
			t.Fatal(err)
		}
	}
	<-done
}

func TestRejectedMaskChangesNothing(t *testing.T) {
	svc := server.New()
	svc.Seed(&ordersv1.Order{Id: "o-1", CustomerId: "c-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PENDING})
	_, err := svc.UpdateOrder(t.Context(), &ordersv1.UpdateOrderRequest{
		Order:      &ordersv1.Order{Id: "o-1", CustomerId: "c-2", Status: ordersv1.OrderStatus_ORDER_STATUS_PAID},
		UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"status", "customer_id"}},
	})
	if status.Code(err) != codes.InvalidArgument {
		t.Fatalf("want InvalidArgument, got %v", err)
	}
	got, _ := svc.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "o-1"})
	if got.GetOrder().GetStatus() != ordersv1.OrderStatus_ORDER_STATUS_PENDING || got.GetOrder().GetCustomerId() != "c-1" {
		t.Fatalf("failed update modified the order: %v", got.GetOrder())
	}
}

Client: grpc.NewClient (1.63+), targets and resolvers Must-know ​

In plain words: grpc.NewClient(target, opts...) returns a *grpc.ClientConn without connecting; the first RPC connects. You create it once at startup, share it across goroutines, and wrap it with the generated NewOrderServiceClient(conn).

Common misunderstanding: "grpc.Dial with WithBlock tells me the server is up." grpc-go's anti-patterns doc says knowing you are connected "does not tell you much in this regard", because the server could go away a second later; RPCs on an idle or connecting ClientConn simply wait until their deadline. Dial is deprecated; its WithBlock, WithTimeout, WithReturnConnectionError and FailOnNonTempDialError options "are ignored by" NewClient. Second trap: NewClient uses the dns resolver by default while Dial used passthrough, so a custom dialer test that passed with Dial("bufnet") fails with NewClient("bufnet"); write passthrough:///bufnet.

Definition: "NewClient creates a new gRPC "channel" for the target URI provided. No I/O is performed." Target syntax follows grpc's naming.md: host:port and dns:///host:port (DNS, re-resolved), passthrough:///addr (hand the string to the dialer), unix:///path, or a custom scheme registered with grpc.WithResolvers or resolver.Register. Transport security is mandatory to choose: grpc.WithTransportCredentials(insecure.NewCredentials()) for plaintext or credentials.NewTLS(cfg). A ClientConn holds zero or more HTTP/2 connections ("subchannels"), reconnects with backoff and is safe for concurrent use. Close it once on shutdown.

1  conn, err := grpc.NewClient("dns:///orders.internal:50051", grpc.WithTransportCredentials(creds))
2                                       state IDLE, no DNS lookup, no TCP yet
3  c := ordersv1.NewOrderServiceClient(conn)
4  c.GetOrder(ctx, req)                 IDLE -> CONNECTING: resolve, dial, TLS, HTTP/2 preface
5                                       READY: RPC sent; later RPCs reuse the connection
6  server restarts                      TRANSIENT_FAILURE -> reconnect with backoff; RPCs fail Unavailable
7  ctx deadline passes while waiting    rpc error: code = DeadlineExceeded

Real scenario: a service that builds one ClientConn per dependency in main and injects the stubs; a Kubernetes client using dns:///orders-headless:50051 with round_robin; a test that uses passthrough:///bufnet plus grpc.WithContextDialer; a batch job that sets grpc.WaitForReady(true) so calls queue during a short restart instead of failing.

OptionPurposeNote
grpc.WithTransportCredentials(...)TLS, mTLS or insecure.NewCredentials()Required
grpc.WithPerRPCCredentials(...)Token per callRefuses insecure transport if it says so
grpc.WithChainUnaryInterceptor(...)Client interceptorsRun in list order
grpc.WithDefaultServiceConfig(json)LB policy, retry policy, timeoutsResolver-provided config overrides it
grpc.WithKeepaliveParams(...)Client pingsMust respect server enforcement
grpc.WithDefaultCallOptions(...)MaxCallRecvMsgSize, WaitForReadyPer call too
grpc.WithContextDialer(...)Custom dialer (bufconn, SSH)Pair with passthrough:///

Fix / how to use it: one NewClient per target at startup, never per request; always set credentials explicitly; give every call a deadline; close on shutdown. The bufconn helper used by every test shows the passthrough:/// rule:

go
// Package testsrv starts a real gRPC server on an in-memory bufconn listener,
// so tests exercise the full HTTP/2 stack, interceptors and codecs without a
// TCP port.
package testsrv

import (
	"context"
	"net"
	"testing"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/test/bufconn"
)

// bufSize is the in-memory buffer per connection direction.
const bufSize = 1 << 20

// Server is a running in-memory gRPC server.
type Server struct {
	Listener *bufconn.Listener
	GRPC     *grpc.Server
}

// Start creates a grpc.Server with opts, lets register add services, serves
// it on a bufconn listener and stops it when the test ends.
func Start(t testing.TB, register func(*grpc.Server), opts ...grpc.ServerOption) *Server {
	t.Helper()
	lis := bufconn.Listen(bufSize)
	s := grpc.NewServer(opts...)
	register(s)
	go func() { _ = s.Serve(lis) }()
	t.Cleanup(s.Stop)
	return &Server{Listener: lis, GRPC: s}
}

// Dial returns a client connection to the in-memory server. The target uses
// the passthrough resolver because grpc.NewClient defaults to "dns", which
// would try to resolve the made-up name "bufnet".
func (s *Server) Dial(t testing.TB, opts ...grpc.DialOption) *grpc.ClientConn {
	t.Helper()
	base := []grpc.DialOption{
		grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
			return s.Listener.DialContext(ctx)
		}),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	}
	conn, err := grpc.NewClient("passthrough:///bufnet", append(base, opts...)...)
	if err != nil {
		t.Fatalf("NewClient: %v", err)
	}
	t.Cleanup(func() { _ = conn.Close() })
	return conn
}

The four RPC shapes: unary, server streaming, client streaming, bidirectional streaming Must-know ​

In plain words: Unary is a function call. Server streaming is "ask once, get many answers". Client streaming is "send many, get one summary". Bidirectional streaming is two independent pipes on one call.

Common misunderstanding: "A stream ends when the server stops sending." A server stream ends when the handler returns; the client sees that as io.EOF from Recv, and the status (OK or an error) arrives in the trailers. A second one: "streams are always faster". grpc.io's performance guide says streams "cannot be load balanced once they have started and can be hard to debug", and "Use streams to optimize the application, not gRPC."

Definition: In .proto, stream before the request type makes the client stream, before the response type makes the server stream. Since protoc-gen-go-grpc v1.5.0 the Go types are six generics: grpc.ServerStreamingServer[Res] (Send), grpc.ServerStreamingClient[Res] (Recv), grpc.ClientStreamingServer[Req, Res] (Recv, SendAndClose), grpc.ClientStreamingClient[Req, Res] (Send, CloseAndRecv), and the two BidiStreaming types (Send, Recv, plus CloseSend on the client). Every stream has Context(), which is canceled when the call ends; one goroutine may Send while another Recvs, but two goroutines must not Send on the same stream at once.

     client                                   server (ReserveStock, bidi)
1    stream := c.ReserveStock(ctx)            handler starts
2    go: Send(SKU-1 x3)  ─────────────────▶   Recv -> reserve -> Send(reserved=true, left=2)
3        Send(SKU-1 x3)  ─────────────────▶   Recv -> not enough -> Send(reserved=false)
4        Send(SKU-2 x1); CloseSend()  ─────▶  Recv -> Send(reserved=true); Recv -> io.EOF -> return nil
5    Recv x3, then io.EOF  ◀──────────────    trailers: grpc-status 0
Four RPC shapes, one HTTP/2 stream each: who sends how many messagesUnaryclientserverreturn resp, err;status in trailersGetOrder(ctx, *GetOrderRequest) (*GetOrderResponse, error)Server streamingclientserverclient Recvuntil io.EOFListOrders(*ListOrdersRequest, grpc.ServerStreamingServer[ListOrdersResponse]) errorClient streamingclientserverserver Recv untilio.EOF, SendAndCloseImportOrders(grpc.ClientStreamingServer[ImportOrdersRequest, ImportOrdersResponse]) errorBidirectionalclientserverhalves independent;CloseSend ends clientReserveStock(grpc.BidiStreamingServer[ReserveStockRequest, ReserveStockResponse]) error

Real scenario: server streaming for a large export or a price feed; client streaming for a bulk import whose answer is a count of accepted and rejected rows; bidi for stock reservation, chat or a game session; unary for everything else (most RPCs).

ShapeServer ends byClient ends byBack-pressure
Unaryreturn resp, errCall returnsn/a
Server streamingReturning from the handlerRecv returns io.EOF or a status errorSend blocks when the HTTP/2 window is full
Client streamingSendAndClose(resp) after Recv gives io.EOFCloseAndRecv()Client Send blocks
BidirectionalReturning (client sees io.EOF)CloseSend(), then Recv until io.EOFBoth directions

Fix / how to use it: check stream.Context() between messages (the snippet's ListOrders returns status.FromContextError(ctx.Err())), always drain Recv to io.EOF on the client, call CloseSend when done sending, and keep unary as the default.

Context deadlines → DeadlineExceeded, and cancellation Must-know ​

In plain words: The client puts a deadline on its ctx; grpc-go sends the remaining time as grpc-timeout, the server's handler gets a ctx with that deadline, and when it passes the client gets codes.DeadlineExceeded.

Common misunderstanding: "gRPC has a default timeout." grpc.io: "By default, gRPC does not set a deadline", so a call with context.Background() can wait forever, as the Before test shows. And "DeadlineExceeded means the server did nothing". The status code doc says this code "may be returned even if the operation has completed successfully".

Definition: ctx, cancel := context.WithTimeout(parent, 50*time.Millisecond); defer cancel() bounds one call. The server sees the same deadline in ctx.Deadline(); passing that ctx to the next client call propagates the remaining budget automatically. When the client cancels (or the deadline passes), grpc-go resets the HTTP/2 stream and the server's ctx is canceled; work continues only if your handler ignores ctx. status.FromContextError(err) maps context.DeadlineExceeded to codes.DeadlineExceeded and context.Canceled to codes.Canceled. Context itself is taught in context; system timeout policy in Timeouts, Retries & Jitter.

t=0ms    client: WithTimeout(ctx, 100ms); ListOrders(ctx)    grpc-timeout: 99m (approx)
t=40ms   server: Send(o-1)          client Recv -> o-1
t=80ms   server: Send(o-2)          client Recv -> o-2
t=100ms  client deadline: RST_STREAM   client Recv -> rpc error: code = DeadlineExceeded
t=100ms  server: <-ctx.Done() in the select -> return status.FromContextError -> stops at once

Real scenario: a checkout that gives inventory 300 ms of its 2 s budget; a streaming export the user abandons; a BFF that propagates the mobile app's 3 s budget to four backends; a server that keeps a database query running for a client that left because the handler ignored ctx.

WhereKnobDefaultError
Clientcontext.WithTimeout / WithDeadline per callNonecodes.DeadlineExceeded
ClientInterceptor that adds a defaultNoneSame
Wiregrpc-timeout headerAbsent without a deadlinen/a
ServerIncoming ctx.Deadline()Client's valuectx.Err()
ServerPass ctx to DB/HTTP callsYour codeThose calls stop

Fix / how to use it: every call gets a deadline (the interceptors package has a DefaultTimeout client interceptor for callers that forget), every handler passes ctx down and selects on ctx.Done() where it waits, and a timed-out write is treated as "unknown outcome" and resolved with an idempotency key.

Status codes, status.Error / status.FromError and error details (errdetails) Must-know ​

In plain words: Every gRPC call ends with one of 17 codes plus a message. A server returns status.Error(codes.NotFound, "..."); a client reads it with status.FromError(err) or status.Code(err). When a code and a string are not enough, attach typed details such as BadRequest or RetryInfo.

Common misunderstanding: "errors.Is(err, myErr) works across the network." Nothing but the code, the message and the details crosses the wire; domain errors must be mapped to codes at the edge and back on the other side. And "codes.Unknown is fine". grpc-go turns any non-status error into Unknown, which tells the caller nothing.

Definition: codes.Code is a uint32 with OK 0, Canceled 1, Unknown 2, InvalidArgument 3, DeadlineExceeded 4, NotFound 5, AlreadyExists 6, PermissionDenied 7, ResourceExhausted 8, FailedPrecondition 9, Aborted 10, OutOfRange 11, Unimplemented 12, Internal 13, Unavailable 14, DataLoss 15, Unauthenticated 16. status.Error(c, msg)/status.Errorf build an error; status.New(c, msg).WithDetails(msgs...) adds details; status.FromError(err) returns (*Status, ok) (ok is false for a non-status error, whose code is Unknown); status.Convert and status.Code are shortcuts. Details travel as google.rpc.Status in the grpc-status-details-bin trailer; the standard detail types live in google.golang.org/genproto/googleapis/rpc/errdetails (BadRequest, ErrorInfo, RetryInfo, ResourceInfo, QuotaFailure, PreconditionFailure, DebugInfo, Help, LocalizedMessage). The error text format is rpc error: code = NotFound desc = order "o-404" not found (real, from the server test).

1  server: st := status.New(codes.Unavailable, "inventory down")
2          st, _ = st.WithDetails(&errdetails.RetryInfo{RetryDelay: durationpb.New(2*time.Second)})
3          return nil, st.Err()
4  wire:   trailers grpc-status: 14, grpc-message: inventory down, grpc-status-details-bin: <base64 google.rpc.Status>
5  client: st, ok := status.FromError(err)   -> Code() == Unavailable, ok == true
6          for _, d := range st.Details() { case *errdetails.RetryInfo: wait d.RetryDelay }

Real scenario: a create call that returns InvalidArgument with one BadRequest field violation per bad field, rendered next to each form input; Unavailable plus RetryInfo from a dependency that is being failed over; NotFound with ResourceInfo; FailedPrecondition when an order cannot be cancelled after shipping; Aborted on an optimistic-lock conflict the client should redo from the read.

SituationCodeWhy not the neighbourDetail type
Malformed inputInvalidArgumentNot FailedPrecondition: wrong regardless of stateBadRequest
Entity missingNotFoundNot InvalidArgument: input is well-formedResourceInfo
Duplicate createAlreadyExistsNot AbortedResourceInfo
State forbids it (shipped order)FailedPreconditionDo not retry until state changesPreconditionFailure
Version conflictAbortedRetry the whole read-modify-writeErrorInfo
Quota or rate limitResourceExhaustedNot PermissionDenied (status code doc)QuotaFailure, RetryInfo
No or bad credentialsUnauthenticatedNot PermissionDenied (caller unknown)ErrorInfo
Authenticated but not allowedPermissionDeniedCaller is knownErrorInfo
Dependency down, transientUnavailableNot Internal; retry only if idempotentRetryInfo
Bug, invariant brokenInternalDo not leak detailsnone (log it)

Fix / how to use it: map domain errors to codes in one function at the service edge, attach details when the client can act on them, never put internal error text in the message, and retry only the codes your policy allows, and only for idempotent calls: the status code doc warns for UNAVAILABLE that "it is not always safe to retry non-idempotent operations", so statuserr.Retryable returns false for every code when idempotent is false.

go
// Package statuserr builds gRPC status errors with rich details on the
// server and reads them back on the client.
package statuserr

import (
	"context"
	"errors"
	"time"

	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/durationpb"
)

// InvalidArgument returns codes.InvalidArgument with one BadRequest field
// violation per entry in fields (field path -> description).
func InvalidArgument(msg string, fields map[string]string) error {
	br := &errdetails.BadRequest{}
	for f, d := range fields {
		br.FieldViolations = append(br.FieldViolations, &errdetails.BadRequest_FieldViolation{Field: f, Description: d})
	}
	st, err := status.New(codes.InvalidArgument, msg).WithDetails(br)
	if err != nil {
		return status.Error(codes.InvalidArgument, msg)
	}
	return st.Err()
}

// Unavailable tells the client to come back after retryAfter.
func Unavailable(msg string, retryAfter time.Duration) error {
	st, err := status.New(codes.Unavailable, msg).WithDetails(
		&errdetails.RetryInfo{RetryDelay: durationpb.New(retryAfter)},
		&errdetails.ErrorInfo{Reason: "INVENTORY_DOWN", Domain: "orders.academy.test"},
	)
	if err != nil {
		return status.Error(codes.Unavailable, msg)
	}
	return st.Err()
}

// FromDomain maps application errors to status errors at the edge of the
// service: the only place that knows about both worlds.
func FromDomain(err error) error {
	var notFound *NotFoundError
	switch {
	case err == nil:
		return nil
	case errors.As(err, &notFound):
		return status.Errorf(codes.NotFound, "%s %q not found", notFound.Kind, notFound.ID)
	case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
		return status.FromContextError(err).Err()
	default:
		// Do not leak internals: log err, return a generic message.
		return status.Error(codes.Internal, "internal error")
	}
}

// NotFoundError is an example domain error.
type NotFoundError struct{ Kind, ID string }

func (e *NotFoundError) Error() string { return e.Kind + " " + e.ID + " not found" }

// Report is what a client extracts from any error returned by a stub.
type Report struct {
	Code       codes.Code
	Message    string
	Fields     map[string]string
	RetryAfter time.Duration
	Reason     string
	IsStatus   bool
}

// Inspect uses status.FromError and walks the details.
func Inspect(err error) Report {
	st, ok := status.FromError(err)
	r := Report{Code: st.Code(), Message: st.Message(), IsStatus: ok, Fields: map[string]string{}}
	for _, d := range st.Details() {
		switch v := d.(type) {
		case *errdetails.BadRequest:
			for _, f := range v.GetFieldViolations() {
				r.Fields[f.GetField()] = f.GetDescription()
			}
		case *errdetails.RetryInfo:
			r.RetryAfter = v.GetRetryDelay().AsDuration()
		case *errdetails.ErrorInfo:
			r.Reason = v.GetReason()
		}
	}
	return r
}

// Retryable is a conservative client policy: only transient codes are
// retried, and only for idempotent calls (or calls made idempotent with an
// idempotency key). A non-idempotent write that failed with Unavailable may
// already have been applied, so it is never retried blindly.
func Retryable(c codes.Code, idempotent bool) bool {
	if !idempotent {
		return false
	}
	switch c {
	case codes.Unavailable, codes.ResourceExhausted, codes.Aborted, codes.DeadlineExceeded:
		return true
	default:
		return false
	}
}
go
package statuserr_test

import (
	"context"
	"errors"
	"fmt"
	"testing"
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/statuserr"
	"academy/grpc-protobuf-in-go/testsrv"

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

type failing struct {
	ordersv1.UnimplementedOrderServiceServer
	err error
}

func (f failing) GetOrder(context.Context, *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	return nil, f.err
}

func call(t *testing.T, err error) error {
	srv := testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, failing{err: err}) })
	_, got := ordersv1.NewOrderServiceClient(srv.Dial(t)).GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
	return got
}

func TestDetailsCrossTheWire(t *testing.T) {
	err := call(t, statuserr.InvalidArgument("bad order", map[string]string{"items[0].quantity": "must be > 0"}))
	r := statuserr.Inspect(err)
	if r.Code != codes.InvalidArgument || r.Fields["items[0].quantity"] != "must be > 0" {
		t.Fatalf("%+v", r)
	}

	err = call(t, statuserr.Unavailable("inventory down", 2*time.Second))
	r = statuserr.Inspect(err)
	if r.Code != codes.Unavailable || r.RetryAfter != 2*time.Second || r.Reason != "INVENTORY_DOWN" {
		t.Fatalf("%+v", r)
	}
}

func TestDomainMapping(t *testing.T) {
	cases := []struct {
		in   error
		want codes.Code
	}{
		{&statuserr.NotFoundError{Kind: "order", ID: "o-1"}, codes.NotFound},
		{fmt.Errorf("repo: %w", &statuserr.NotFoundError{Kind: "order", ID: "o-2"}), codes.NotFound},
		{context.DeadlineExceeded, codes.DeadlineExceeded},
		{context.Canceled, codes.Canceled},
		{errors.New("pq: connection refused"), codes.Internal},
	}
	for _, c := range cases {
		err := call(t, statuserr.FromDomain(c.in))
		if got := status.Code(err); got != c.want {
			t.Errorf("%v -> %v, want %v", c.in, got, c.want)
		}
	}
	// The internal message is not leaked.
	err := call(t, statuserr.FromDomain(errors.New("pq: password authentication failed")))
	if status.Convert(err).Message() != "internal error" {
		t.Fatal(err)
	}
}

func TestFromErrorOnNonStatus(t *testing.T) {
	r := statuserr.Inspect(errors.New("boom"))
	if r.IsStatus || r.Code != codes.Unknown {
		t.Fatalf("%+v", r)
	}
	if statuserr.Inspect(nil).Code != codes.OK {
		t.Fatal("nil error is OK")
	}
}

func TestRetryable(t *testing.T) {
	cases := []struct {
		code       codes.Code
		idempotent bool
		want       bool
	}{
		{codes.Unavailable, true, true},
		{codes.Unavailable, false, false}, // a non-idempotent write may already have happened
		{codes.ResourceExhausted, true, true},
		{codes.ResourceExhausted, false, false},
		{codes.Aborted, true, true},
		{codes.DeadlineExceeded, false, false},
		{codes.DeadlineExceeded, true, true},
		{codes.InvalidArgument, true, false},
	}
	for _, c := range cases {
		if got := statuserr.Retryable(c.code, c.idempotent); got != c.want {
			t.Errorf("Retryable(%v, idempotent=%v) = %v, want %v", c.code, c.idempotent, got, c.want)
		}
	}
}

Metadata: incoming/outgoing, headers and trailers Important ​

In plain words: Metadata is gRPC's name for HTTP/2 headers: key/value pairs next to the messages. The client sends request metadata; the server answers with response headers (before the first message) and trailers (after the last one, together with the status).

Common misunderstanding: "Metadata set on the incoming context is forwarded to the next call." Incoming and outgoing metadata are different context keys; a server that calls another service must copy what it wants with metadata.AppendToOutgoingContext. Also: "metadata keys keep their case". The grpc-go doc: "all the keys will be automatically converted to lowercase".

Definition: grpc.io: keys are ASCII and "must not start with the prefix grpc-, which is reserved for gRPC itself"; a key ending in -bin carries binary data, which grpc-go base64-encodes. Client: metadata.AppendToOutgoingContext(ctx, k, v, ...) or metadata.NewOutgoingContext(ctx, md); capture the response with the call options grpc.Header(&md) and grpc.Trailer(&md), or stream.Header() and (after io.EOF) stream.Trailer(). Server: metadata.FromIncomingContext(ctx); grpc.SetHeader/grpc.SendHeader/grpc.SetTrailer for unary, stream.SetHeader/SendHeader/SetTrailer for streams. grpc.io warns servers "may limit the size of Request-Headers, with a default of 8 KiB suggested".

1  client: ctx = AppendToOutgoingContext(ctx, "x-request-id", "r-42", "x-tenant-bin", "\x00\xffA")
2  wire:   HEADERS :path /academy.orders.v1.OrderService/GetOrder, x-request-id: r-42, x-tenant-bin: AP9B
3  server: md := FromIncomingContext(ctx)    md["x-tenant-bin"] == ["\x00\xffA"] (decoded)
4  server: SetHeader(x-request-id, x-served-by) -> HEADERS before DATA
5  server: SetTrailer(x-cost-units: 3)          -> trailers with grpc-status: 0
6  client: grpc.Header(&h), grpc.Trailer(&t)    -> h["x-served-by"], t["x-cost-units"]

Real scenario: a request id propagated to every service and log line; authorization: Bearer ... checked by an auth interceptor; a tenant id for a multi-tenant backend; a trailer with query cost or server-side timing; OpenTelemetry's traceparent header (its gRPC instrumentation uses metadata).

APISideDirectionWhen it is sent
metadata.AppendToOutgoingContextClientRequestWith the request headers
metadata.FromIncomingContextServerRequestRead at any time
grpc.SetHeader / stream.SetHeaderServerResponseWith the first message or SendHeader
grpc.SendHeader / stream.SendHeaderServerResponseImmediately
grpc.SetTrailer / stream.SetTrailerServerResponseWhen the RPC ends
grpc.Header(&md) / stream.Header()ClientResponseBlocks until headers arrive
grpc.Trailer(&md) / stream.Trailer()ClientResponseValid after the call or io.EOF

Fix / how to use it: lowercase keys, a -bin suffix for bytes, copy only the keys you mean to forward, and put request-scoped ids in metadata, never in every request message. The snippet also hit a real rule while being written: a -bin value pushed into a proto3 string field failed with grpc: error while marshaling: string field contains invalid UTF-8, so it is hex-encoded first.

go
// Package headers shows gRPC metadata: incoming and outgoing, response
// headers and trailers, in unary and streaming calls.
package headers

import (
	"context"
	"fmt"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

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

// Server echoes request metadata back as response headers and trailers.
type Server struct {
	ordersv1.UnimplementedOrderServiceServer
}

// GetOrder reads incoming metadata, sends a header and sets a trailer.
func (Server) GetOrder(ctx context.Context, req *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	md, _ := metadata.FromIncomingContext(ctx) // keys are lowercased
	rid := first(md, "x-request-id")
	if rid == "" {
		return nil, status.Error(codes.InvalidArgument, "x-request-id is required")
	}
	// Headers go out before the first response message.
	if err := grpc.SetHeader(ctx, metadata.Pairs("x-request-id", rid, "x-served-by", "orders-1")); err != nil {
		return nil, err
	}
	// Trailers go out after the last message, together with the status.
	grpc.SetTrailer(ctx, metadata.Pairs("x-cost-units", "3"))
	// The -bin value arrives decoded as raw bytes. It is hex-encoded here
	// because a proto3 string field must hold valid UTF-8.
	tenant := fmt.Sprintf("%x", first(md, "x-tenant-bin"))
	return &ordersv1.GetOrderResponse{Order: &ordersv1.Order{Id: req.GetId(), CustomerId: tenant}}, nil
}

// ListOrders does the same on a stream with SendHeader and SetTrailer.
func (Server) ListOrders(req *ordersv1.ListOrdersRequest, stream ordersv1.OrderService_ListOrdersServer) error {
	md, _ := metadata.FromIncomingContext(stream.Context())
	if err := stream.SendHeader(metadata.Pairs("x-request-id", first(md, "x-request-id"))); err != nil {
		return err
	}
	for i := 1; i <= 2; i++ {
		if err := stream.Send(&ordersv1.ListOrdersResponse{Order: &ordersv1.Order{Id: fmt.Sprintf("o-%d", i)}}); err != nil {
			return err
		}
	}
	stream.SetTrailer(metadata.Pairs("x-total", "2"))
	return nil
}

func first(md metadata.MD, key string) string {
	if v := md.Get(key); len(v) > 0 {
		return v[0]
	}
	return ""
}

// Result is what the client collected from one unary call.
type Result struct {
	Order            *ordersv1.Order
	Header, Trailer  metadata.MD
	RequestIDEchoed  string
	CostUnitsTrailer string
}

// Call attaches outgoing metadata and captures header and trailer with the
// grpc.Header and grpc.Trailer call options.
func Call(ctx context.Context, c ordersv1.OrderServiceClient, requestID string, tenant []byte) (Result, error) {
	// AppendToOutgoingContext adds to whatever metadata ctx already carries.
	// A "-bin" key holds raw bytes; grpc-go base64-encodes it on the wire.
	ctx = metadata.AppendToOutgoingContext(ctx, "x-request-id", requestID, "x-tenant-bin", string(tenant))
	var header, trailer metadata.MD
	res, err := c.GetOrder(ctx, &ordersv1.GetOrderRequest{Id: "o-1"}, grpc.Header(&header), grpc.Trailer(&trailer))
	r := Result{Header: header, Trailer: trailer}
	if err != nil {
		return r, err
	}
	r.Order = res.GetOrder()
	r.RequestIDEchoed = first(header, "x-request-id")
	r.CostUnitsTrailer = first(trailer, "x-cost-units")
	return r, nil
}
go
package headers_test

import (
	"errors"
	"io"
	"testing"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/headers"
	"academy/grpc-protobuf-in-go/testsrv"

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

func client(t *testing.T) ordersv1.OrderServiceClient {
	srv := testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, headers.Server{}) })
	return ordersv1.NewOrderServiceClient(srv.Dial(t))
}

func TestUnaryHeadersAndTrailers(t *testing.T) {
	r, err := headers.Call(t.Context(), client(t), "r-42", []byte{0x00, 0xff, 'A'})
	if err != nil {
		t.Fatal(err)
	}
	if r.RequestIDEchoed != "r-42" || r.CostUnitsTrailer != "3" || r.Header.Get("x-served-by")[0] != "orders-1" {
		t.Fatalf("header=%v trailer=%v", r.Header, r.Trailer)
	}
	if r.Order.GetCustomerId() != "00ff41" {
		t.Fatalf("binary metadata not round-tripped: %q", r.Order.GetCustomerId())
	}
	// grpc-go adds its own response header: the content type.
	if ct := r.Header.Get("content-type"); len(ct) == 0 || ct[0] != "application/grpc" {
		t.Fatalf("content-type = %v", ct)
	}
}

func TestMissingMetadataIsInvalidArgument(t *testing.T) {
	_, err := client(t).GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "o-1"})
	if status.Code(err) != codes.InvalidArgument {
		t.Fatal(err)
	}
}

func TestOutgoingKeysAreLowercased(t *testing.T) {
	md := metadata.Pairs("X-Request-ID", "r-1")
	if _, ok := md["x-request-id"]; !ok {
		t.Fatalf("Pairs should lowercase keys: %v", md)
	}
}

func TestStreamHeaderAndTrailer(t *testing.T) {
	ctx := metadata.AppendToOutgoingContext(t.Context(), "x-request-id", "r-7")
	stream, err := client(t).ListOrders(ctx, &ordersv1.ListOrdersRequest{})
	if err != nil {
		t.Fatal(err)
	}
	h, err := stream.Header() // blocks until the server sent headers
	if err != nil || h.Get("x-request-id")[0] != "r-7" {
		t.Fatalf("header %v %v", h, err)
	}
	n := 0
	for {
		_, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			t.Fatal(err)
		}
		n++
	}
	// Trailer is only valid after Recv returned io.EOF (or an error).
	if tr := stream.Trailer(); n != 2 || tr.Get("x-total")[0] != "2" {
		t.Fatalf("n=%d trailer=%v", n, tr)
	}
}

Interceptors: unary/stream, chaining, logging, auth, recovery via go-grpc-middleware v2 Must-know ​

In plain words: An interceptor is gRPC's middleware: a function that runs around every call, sees the method name, the request and the result, and can stop the call with a status. There are four kinds (unary/stream × server/client), and you chain them.

Common misunderstanding: "grpc.UnaryInterceptor twice adds two interceptors." The second call panics ("The unary server interceptor was already set and may not be reset"); use grpc.ChainUnaryInterceptor. Another: "a stream interceptor runs per message". It runs once around the whole stream; to act per message you wrap the grpc.ServerStream and override RecvMsg/SendMsg, as the protovalidate interceptor does.

Definition: grpc.UnaryServerInterceptor is func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error); grpc.StreamServerInterceptor is func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error; client versions get an invoker or streamer. With ChainUnaryInterceptor(a, b, c) "the first interceptor will be the outer most, while the last interceptor will be the inner most wrapper around the real call" (the chain test asserts A> B> <B <A). go-grpc-middleware v2 (github.com/grpc-ecosystem/go-grpc-middleware/v2) provides interceptors/logging (adapter for slog, fields grpc.service, grpc.method, grpc.code, grpc.time_ms; default events StartCall and FinishCall; DefaultServerCodeToLevel logs NotFound at INFO and Internal at ERROR), interceptors/auth (AuthFunc, AuthFromMD(ctx, "bearer")), interceptors/recovery (panic to error), interceptors/protovalidate, retry, ratelimit, timeout, selector and realip.

     client chain                         server chain (ChainUnaryInterceptor order)
1    RequestID -> DefaultTimeout  ──────▶ logging        start timer
2                                         auth           AuthFromMD -> no token -> return Unauthenticated
3                                         protovalidate  bad request -> return InvalidArgument
4                                         recovery       defer recover()
5                                         handler        panics -> recovery returns Internal
6                                ◀──────  logging        logs grpc.code=Internal grpc.time_ms=...
One unary call through the client and server interceptor chainscallerstub.GetOrder(ctx)RequestIDDefaultTimeout(client interceptors)HTTP/2 streamheaders + DATAgrpc-timeoutloggingsees final codeauthUnauthenticatedprotovalidateInvalidArgumentrecoverypanic -> InternalhandlerGetOrder(ctx, req)response / statusOrder is the list ordergrpc.ChainUnaryInterceptor( logging.UnaryServerInterceptor(log), // outermost auth.UnaryServerInterceptor(authFn), protovalidate.UnaryServerInterceptor(v), recovery.UnaryServerInterceptor(rec), // innermost)first in the list = first to run, last to see the resultstream interceptors wrap the whole stream, not each message

Real scenario: one structured log line per call with method, code and duration; bearer-token auth that skips the health service (with selector); a nil-map panic in one handler that returns Internal instead of killing the process; a client interceptor that stamps a request id and a default deadline on every call; metrics with the Prometheus provider of go-grpc-middleware.

ConcernPackageServer code on failurePosition
Logginginterceptors/loggingNever fails a callOutermost: sees the final code
Metrics / tracingproviders/prometheus, OpenTelemetry otelgrpc stats handlerNever failsOutermost
Authinterceptors/authUnauthenticatedBefore business logic
Rate limitinterceptors/ratelimitResourceExhaustedEarly
Validationinterceptors/protovalidateInvalidArgumentAfter auth
Recoveryinterceptors/recoveryInternalInnermost, next to the handler

Fix / how to use it: one ChainUnaryInterceptor and one ChainStreamInterceptor with the same order, recovery innermost so logging records the converted code, and the principal stored in ctx under an unexported key. HTTP middleware is the same idea for net/http (Middlewares).

go
// Package interceptors wires server and client interceptors: hand-written
// ones to show the shape, and go-grpc-middleware v2 for logging, auth and
// recovery.
package interceptors

import (
	"context"
	"log/slog"
	"runtime/debug"
	"time"

	"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
	"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
	"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
)

// Timing is a hand-written unary server interceptor: it runs around the
// handler and sees the method name, the request, the response and the error.
func Timing(record func(method string, code codes.Code, d time.Duration)) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
		start := time.Now()
		resp, err := handler(ctx, req)
		record(info.FullMethod, status.Code(err), time.Since(start))
		return resp, err
	}
}

// StreamTiming is the stream variant: it wraps the whole stream, not each message.
func StreamTiming(record func(method string, code codes.Code, d time.Duration)) grpc.StreamServerInterceptor {
	return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		start := time.Now()
		err := handler(srv, ss)
		record(info.FullMethod, status.Code(err), time.Since(start))
		return err
	}
}

// SlogLogger adapts *slog.Logger to the go-grpc-middleware logging.Logger.
func SlogLogger(l *slog.Logger) logging.Logger {
	return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) {
		l.Log(ctx, slog.Level(lvl), msg, fields...)
	})
}

type principalKey struct{}

// Principal returns the caller set by the auth interceptor.
func Principal(ctx context.Context) string {
	p, _ := ctx.Value(principalKey{}).(string)
	return p
}

// BearerAuth checks "authorization: bearer <token>" against a token table
// and stores the principal in ctx.
func BearerAuth(tokens map[string]string) auth.AuthFunc {
	return func(ctx context.Context) (context.Context, error) {
		tok, err := auth.AuthFromMD(ctx, "bearer")
		if err != nil {
			return nil, err // already codes.Unauthenticated
		}
		who, ok := tokens[tok]
		if !ok {
			return nil, status.Error(codes.Unauthenticated, "invalid token")
		}
		return context.WithValue(ctx, principalKey{}, who), nil
	}
}

// ServerOptions returns the chained interceptors in the order they run:
// logging (outermost, sees the final code), auth, recovery (innermost, turns
// a handler panic into codes.Internal before logging sees it).
func ServerOptions(l *slog.Logger, tokens map[string]string) []grpc.ServerOption {
	logOpts := []logging.Option{logging.WithLogOnEvents(logging.FinishCall)}
	rec := recovery.WithRecoveryHandlerContext(func(ctx context.Context, p any) error {
		l.ErrorContext(ctx, "panic in handler", "panic", p, "stack", string(debug.Stack()))
		return status.Error(codes.Internal, "internal error")
	})
	return []grpc.ServerOption{
		grpc.ChainUnaryInterceptor(
			logging.UnaryServerInterceptor(SlogLogger(l), logOpts...),
			auth.UnaryServerInterceptor(BearerAuth(tokens)),
			recovery.UnaryServerInterceptor(rec),
		),
		grpc.ChainStreamInterceptor(
			logging.StreamServerInterceptor(SlogLogger(l), logOpts...),
			auth.StreamServerInterceptor(BearerAuth(tokens)),
			recovery.StreamServerInterceptor(rec),
		),
	}
}

// RequestID is a unary client interceptor that adds x-request-id when the
// caller did not set one.
func RequestID(newID func() string) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		if md, ok := metadata.FromOutgoingContext(ctx); !ok || len(md.Get("x-request-id")) == 0 {
			ctx = metadata.AppendToOutgoingContext(ctx, "x-request-id", newID())
		}
		return invoker(ctx, method, req, reply, cc, opts...)
	}
}

// DefaultTimeout is a client interceptor that gives every call a deadline
// unless the caller already set a shorter one.
func DefaultTimeout(d time.Duration) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		if _, ok := ctx.Deadline(); !ok {
			var cancel context.CancelFunc
			ctx, cancel = context.WithTimeout(ctx, d)
			defer cancel()
		}
		return invoker(ctx, method, req, reply, cc, opts...)
	}
}
go
package interceptors_test

import (
	"bytes"
	"context"
	"log/slog"
	"strings"
	"sync"
	"testing"
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/interceptors"
	"academy/grpc-protobuf-in-go/testsrv"

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

type svc struct {
	ordersv1.UnimplementedOrderServiceServer
	mu       sync.Mutex
	seenRID  string
	seenUser string
}

func (s *svc) GetOrder(ctx context.Context, req *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	if req.GetId() == "panic" {
		panic("nil map write in handler")
	}
	md, _ := metadata.FromIncomingContext(ctx)
	s.mu.Lock()
	s.seenUser = interceptors.Principal(ctx)
	if v := md.Get("x-request-id"); len(v) > 0 {
		s.seenRID = v[0]
	}
	s.mu.Unlock()
	return &ordersv1.GetOrderResponse{Order: &ordersv1.Order{Id: req.GetId()}}, nil
}

type syncBuf struct {
	mu sync.Mutex
	b  bytes.Buffer
}

func (w *syncBuf) Write(p []byte) (int, error) { w.mu.Lock(); defer w.mu.Unlock(); return w.b.Write(p) }
func (w *syncBuf) String() string              { w.mu.Lock(); defer w.mu.Unlock(); return w.b.String() }

func setup(t *testing.T, copts ...grpc.DialOption) (ordersv1.OrderServiceClient, *svc, *syncBuf) {
	logs := &syncBuf{}
	l := slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
	s := &svc{}
	srv := testsrv.Start(t, func(g *grpc.Server) { ordersv1.RegisterOrderServiceServer(g, s) },
		interceptors.ServerOptions(l, map[string]string{"t-alice": "user:alice"})...)
	return ordersv1.NewOrderServiceClient(srv.Dial(t, copts...)), s, logs
}

func withToken(ctx context.Context, tok string) context.Context {
	return metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+tok)
}

func TestAuth(t *testing.T) {
	c, s, logs := setup(t)
	_, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "o-1"})
	if status.Code(err) != codes.Unauthenticated {
		t.Fatalf("no token: %v", err)
	}
	_, err = c.GetOrder(withToken(t.Context(), "wrong"), &ordersv1.GetOrderRequest{Id: "o-1"})
	if status.Code(err) != codes.Unauthenticated {
		t.Fatalf("bad token: %v", err)
	}
	if _, err := c.GetOrder(withToken(t.Context(), "t-alice"), &ordersv1.GetOrderRequest{Id: "o-1"}); err != nil {
		t.Fatal(err)
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.seenUser != "user:alice" {
		t.Fatalf("principal = %q", s.seenUser)
	}
	out := logs.String()
	for _, want := range []string{"grpc.code=Unauthenticated", "grpc.code=OK", "grpc.method=GetOrder", "grpc.service=academy.orders.v1.OrderService"} {
		if !strings.Contains(out, want) {
			t.Errorf("logs lack %s:\n%s", want, out)
		}
	}
}

func TestRecoveryTurnsPanicIntoInternal(t *testing.T) {
	c, _, logs := setup(t)
	_, err := c.GetOrder(withToken(t.Context(), "t-alice"), &ordersv1.GetOrderRequest{Id: "panic"})
	if status.Code(err) != codes.Internal || status.Convert(err).Message() != "internal error" {
		t.Fatalf("got %v", err)
	}
	out := logs.String()
	if !strings.Contains(out, "panic in handler") || !strings.Contains(out, "grpc.code=Internal") {
		t.Fatalf("logs:\n%s", out)
	}
	// The server is still alive after the panic.
	if _, err := c.GetOrder(withToken(t.Context(), "t-alice"), &ordersv1.GetOrderRequest{Id: "o-2"}); err != nil {
		t.Fatal(err)
	}
}

func TestClientInterceptors(t *testing.T) {
	c, s, _ := setup(t, grpc.WithChainUnaryInterceptor(
		interceptors.RequestID(func() string { return "r-generated" }),
		interceptors.DefaultTimeout(time.Second),
	))
	if _, err := c.GetOrder(withToken(t.Context(), "t-alice"), &ordersv1.GetOrderRequest{Id: "o-1"}); err != nil {
		t.Fatal(err)
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.seenRID != "r-generated" {
		t.Fatalf("request id = %q", s.seenRID)
	}
}

func TestChainOrder(t *testing.T) {
	var mu sync.Mutex
	var order []string
	mk := func(name string) grpc.UnaryServerInterceptor {
		return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) {
			mu.Lock()
			order = append(order, name+">")
			mu.Unlock()
			resp, err := h(ctx, req)
			mu.Lock()
			order = append(order, "<"+name)
			mu.Unlock()
			return resp, err
		}
	}
	var timed []string
	srv := testsrv.Start(t, func(g *grpc.Server) { ordersv1.RegisterOrderServiceServer(g, &svc{}) },
		grpc.ChainUnaryInterceptor(mk("A"), mk("B"), interceptors.Timing(func(m string, c codes.Code, _ time.Duration) {
			mu.Lock()
			timed = append(timed, m+" "+c.String())
			mu.Unlock()
		})))
	c := ordersv1.NewOrderServiceClient(srv.Dial(t))
	if _, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "o-1"}); err != nil {
		t.Fatal(err)
	}
	mu.Lock()
	defer mu.Unlock()
	if got := strings.Join(order, " "); got != "A> B> <B <A" {
		t.Fatalf("order = %s", got)
	}
	if len(timed) != 1 || timed[0] != "/academy.orders.v1.OrderService/GetOrder OK" {
		t.Fatalf("timed = %v", timed)
	}
}

TLS and mTLS: credentials.NewTLS, insecure.NewCredentials, per-RPC credentials Must-know ​

In plain words: Transport credentials decide how the connection is protected: insecure.NewCredentials() for plaintext (local tests only), credentials.NewTLS(cfg) for TLS, and the same with a client certificate for mutual TLS. Per-RPC credentials add a token to every call on top.

Common misunderstanding: "TLS inside the cluster is optional." Without it, a bearer token in metadata travels in clear text; grpc-go refuses exactly that combination: grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set) (real output from the test). Another: "mTLS replaces authorization." It proves which workload is calling; whether that workload may cancel an order is still your code.

Definition: credentials.NewTLS(*tls.Config) wraps crypto/tls and sets the ALPN protocol to h2; servers pass it with grpc.Creds(...), clients with grpc.WithTransportCredentials(...). mTLS on the server is ClientAuth: tls.RequireAndVerifyClientCert plus ClientCAs; on the client, Certificates plus RootCAs and ServerName. In a handler, peer.FromContext(ctx) gives p.AuthInfo.(credentials.TLSInfo), whose State.VerifiedChains[0][0].Subject is the verified client identity. credentials.PerRPCCredentials has GetRequestMetadata and RequireTransportSecurity; credentials/oauth provides token sources. Certificates, rotation and crypto/tls details are in HTTP/2, HTTPS, TLS & mTLS in Go; mTLS as a service-to-service design in mTLS & Service Security.

1  client (cert CN=billing-service)          server (RequireAndVerifyClientCert, ClientCAs = academy CA)
2  ClientHello, ALPN h2  ──────────────────▶  ServerHello, server cert (orders.internal), CertificateRequest
3  verify server cert vs RootCAs + ServerName  ok
4  client cert  ───────────────────────────▶  verify vs ClientCAs: ok
5  HTTP/2 preface, GetOrder  ──────────────▶  peer.FromContext -> TLSInfo -> CN "billing-service"
   wrong ServerName: x509: certificate is valid for orders.internal, not payments.internal -> Unavailable

Real scenario: the billing service identified by its client certificate CN or SPIFFE URI SAN; a mesh sidecar terminating mTLS so the Go process listens on plaintext localhost; a public gRPC API with server TLS and OAuth tokens per call; a test PKI generated in memory so no key file is ever committed.

SetupServer optionClient optionFailure looks like
Plaintextnone (default)insecure.NewCredentials()n/a
TLSgrpc.Creds(credentials.NewTLS(cfg))credentials.NewTLS(&tls.Config{RootCAs, ServerName})Unavailable, authentication handshake failed
mTLSplus ClientAuth, ClientCAsplus CertificatesUnavailable on the client
Token per callauth interceptorgrpc.WithPerRPCCredentials(t)NewClient error if transport is insecure
Insecure client, TLS serverTLSinsecureUnavailable

Fix / how to use it: TLS 1.3 minimum, mTLS between services (or a mesh that does it), tokens only over TLS, and identity read from the verified chain.

go
package tlsauth

import (
	"context"
	"crypto/tls"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/peer"
	"google.golang.org/grpc/status"
)

// ServerCreds returns TLS 1.3 server credentials. With mutual set, the
// server demands a client certificate signed by the PKI's CA.
func ServerCreds(p *PKI, mutual bool) credentials.TransportCredentials {
	cfg := &tls.Config{
		Certificates: []tls.Certificate{p.Server},
		MinVersion:   tls.VersionTLS13,
	}
	if mutual {
		cfg.ClientAuth = tls.RequireAndVerifyClientCert
		cfg.ClientCAs = p.Pool
	}
	return credentials.NewTLS(cfg) // sets NextProtos to "h2" for gRPC
}

// ClientCreds trusts the PKI's CA for serverName; withCert adds the client
// certificate for mTLS.
func ClientCreds(p *PKI, serverName string, withCert bool) credentials.TransportCredentials {
	cfg := &tls.Config{RootCAs: p.Pool, ServerName: serverName, MinVersion: tls.VersionTLS13}
	if withCert {
		cfg.Certificates = []tls.Certificate{p.Client}
	}
	return credentials.NewTLS(cfg)
}

// WhoAmI answers with the CommonName of the verified client certificate.
type WhoAmI struct {
	ordersv1.UnimplementedOrderServiceServer
}

// GetOrder uses peer.FromContext to reach the TLS connection state.
func (WhoAmI) GetOrder(ctx context.Context, _ *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	p, ok := peer.FromContext(ctx)
	if !ok {
		return nil, status.Error(codes.Internal, "no peer")
	}
	info, ok := p.AuthInfo.(credentials.TLSInfo)
	if !ok || len(info.State.VerifiedChains) == 0 {
		return nil, status.Error(codes.Unauthenticated, "no verified client certificate")
	}
	cn := info.State.VerifiedChains[0][0].Subject.CommonName
	return &ordersv1.GetOrderResponse{Order: &ordersv1.Order{CustomerId: cn}}, nil
}

// Token is per-RPC credentials: an "authorization" header added to every
// call. RequireTransportSecurity makes grpc-go refuse to send it over an
// insecure connection.
type Token string

// GetRequestMetadata implements credentials.PerRPCCredentials.
func (t Token) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {
	return map[string]string{"authorization": "Bearer " + string(t)}, nil
}

// RequireTransportSecurity implements credentials.PerRPCCredentials.
func (Token) RequireTransportSecurity() bool { return true }
go
package tlsauth_test

import (
	"strings"
	"testing"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/testsrv"
	"academy/grpc-protobuf-in-go/tlsauth"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
)

const name = "orders.internal"

func start(t *testing.T, p *tlsauth.PKI, mutual bool) *testsrv.Server {
	return testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, tlsauth.WhoAmI{}) },
		grpc.Creds(tlsauth.ServerCreds(p, mutual)))
}

func pki(t *testing.T) *tlsauth.PKI {
	p, err := tlsauth.NewPKI(name, "billing-service")
	if err != nil {
		t.Fatal(err)
	}
	return p
}

func TestMutualTLS(t *testing.T) {
	p := pki(t)
	srv := start(t, p, true)
	// Later options win: the TLS credentials replace testsrv's insecure default.
	c := ordersv1.NewOrderServiceClient(srv.Dial(t, grpc.WithTransportCredentials(tlsauth.ClientCreds(p, name, true))))
	res, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
	if err != nil {
		t.Fatal(err)
	}
	if res.GetOrder().GetCustomerId() != "billing-service" {
		t.Fatalf("CN = %q", res.GetOrder().GetCustomerId())
	}
}

func TestClientWithoutCertificateIsRejected(t *testing.T) {
	p := pki(t)
	srv := start(t, p, true)
	c := ordersv1.NewOrderServiceClient(srv.Dial(t, grpc.WithTransportCredentials(tlsauth.ClientCreds(p, name, false))))
	_, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
	if status.Code(err) != codes.Unavailable {
		t.Fatalf("want Unavailable (handshake failed), got %v", err)
	}
	t.Log(err)
}

func TestInsecureClientAgainstTLSServer(t *testing.T) {
	p := pki(t)
	srv := start(t, p, false)
	c := ordersv1.NewOrderServiceClient(srv.Dial(t, grpc.WithTransportCredentials(insecure.NewCredentials())))
	_, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
	if status.Code(err) != codes.Unavailable {
		t.Fatalf("want Unavailable, got %v", err)
	}
}

func TestWrongServerNameFails(t *testing.T) {
	p := pki(t)
	srv := start(t, p, false)
	c := ordersv1.NewOrderServiceClient(srv.Dial(t, grpc.WithTransportCredentials(tlsauth.ClientCreds(p, "payments.internal", false))))
	_, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
	if status.Code(err) != codes.Unavailable || !strings.Contains(err.Error(), "certificate") {
		t.Fatalf("got %v", err)
	}
	t.Log(err)
}

func TestTokenRefusesInsecureTransport(t *testing.T) {
	p := pki(t)
	srv := start(t, p, false)
	// grpc.NewClient itself refuses: the token must not travel in clear text.
	_, err := grpc.NewClient("passthrough:///bufnet",
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithPerRPCCredentials(tlsauth.Token("t-1")))
	if err == nil || !strings.Contains(err.Error(), "require transport level security") {
		t.Fatalf("got %v", err)
	}
	t.Log(err)
	// Over TLS the same credentials are accepted.
	c := ordersv1.NewOrderServiceClient(srv.Dial(t,
		grpc.WithTransportCredentials(tlsauth.ClientCreds(p, name, false)),
		grpc.WithPerRPCCredentials(tlsauth.Token("t-1"))))
	_, err = c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
	// WhoAmI demands a client certificate, so Unauthenticated proves the call got through.
	if status.Code(err) != codes.Unauthenticated {
		t.Fatalf("got %v", err)
	}
}

Validation with protovalidate (replaces protoc-gen-validate) Important ​

In plain words: Write the rules ("sku is 1 to 32 characters", "quantity is 1 to 1000") as options in the .proto file and let one interceptor enforce them before any handler runs.

Common misunderstanding: "protoc-gen-validate is the standard." Its README now says "protoc-gen-validate (PGV) has reached a stable state and is in maintenance mode" and recommends protovalidate. The difference matters in Go: PGV generated Validate() methods; protovalidate generates nothing and evaluates the rules at runtime from the descriptors, with CEL for custom rules.

Definition: Import buf/validate/validate.proto (BSR dep buf.build/bufbuild/protovalidate) and annotate fields: (buf.validate.field).string = {min_len: 1, max_len: 32}, .int32 = {gt: 0, lte: 1000}, .string.pattern, .repeated.min_items, .map.max_pairs, .required = true, and message-level (buf.validate.message).cel. In Go, buf.build/go/protovalidate offers protovalidate.New() (a validator that caches compiled rules) and protovalidate.Validate(msg); errors are *protovalidate.ValidationError with ToProto() returning buf.validate.Violations. go-grpc-middleware v2's interceptors/protovalidate returns codes.InvalidArgument with that Violations message as a status detail, and for streams validates each received message.

1  CreateOrder{customer_id:"7", currency_code:"EURO", items:[{sku:"", quantity:0}]}
2  interceptor: v.Validate(req)
3    customer_id: does not match regex pattern `^c-[0-9]+$`    rule string.pattern
4    items[0].sku: must be at least 1 characters               rule string.min_len
5    items[0].quantity: must be greater than 0 and less than or equal to 1000
6    currency_code: must be 3 characters                       rule string.len
7  -> InvalidArgument + buf.validate.Violations detail; handler never called

Real scenario: the same rules enforced for gRPC callers and for REST callers through grpc-gateway (the gateway forwards to the same server and interceptor); a TypeScript client using protovalidate-es on the same .proto for form validation; a CEL rule "if first_name is set, last_name must be"; a bulk import stream that rejects the second message without killing the first.

ToolStatusHow rules runGo
protovalidateCurrentRuntime, from descriptors, CELbuf.build/go/protovalidate
protoc-gen-validate (PGV)Maintenance modeGenerated Validate() methods*.pb.validate.go
Hand-written checksAlways possibleYour handlerDuplicated per language
go-grpc-middleware interceptors/validatorFor PGV-style Validate()Calls the methodLegacy

Fix / how to use it: rules in the .proto, one protovalidate interceptor for unary and stream, business rules that need the database still in the service (the snippet's server still refuses an empty order).

go
// Package validation enforces the buf.validate rules written in the .proto
// file, with protovalidate (the successor of protoc-gen-validate) running as
// a gRPC interceptor.
package validation

import (
	"buf.build/go/protovalidate"
	pvmw "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/protovalidate"
	"google.golang.org/grpc"
)

// ServerOptions builds one validator (it caches compiled CEL rules per
// message type) and installs it for unary and streaming calls. Invalid
// requests never reach the handler: they fail with codes.InvalidArgument and
// a buf.validate.Violations detail.
func ServerOptions() ([]grpc.ServerOption, error) {
	v, err := protovalidate.New()
	if err != nil {
		return nil, err
	}
	return []grpc.ServerOption{
		grpc.ChainUnaryInterceptor(pvmw.UnaryServerInterceptor(v)),
		grpc.ChainStreamInterceptor(pvmw.StreamServerInterceptor(v)),
	}, nil
}
go
package validation_test

import (
	"errors"
	"sort"
	"testing"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/server"
	"academy/grpc-protobuf-in-go/testsrv"
	"academy/grpc-protobuf-in-go/validation"

	"buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go/buf/validate"
	"buf.build/go/protovalidate"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func invalid() *ordersv1.CreateOrderRequest {
	return &ordersv1.CreateOrderRequest{
		CustomerId:   "7",    // pattern ^c-[0-9]+$
		CurrencyCode: "EURO", // len 3
		Items:        []*ordersv1.LineItem{{Sku: "", Quantity: 0}},
	}
}

func TestValidateDirectly(t *testing.T) {
	err := protovalidate.Validate(invalid())
	var verr *protovalidate.ValidationError
	if !errors.As(err, &verr) {
		t.Fatalf("want ValidationError, got %v", err)
	}
	var paths []string
	for _, v := range verr.ToProto().GetViolations() {
		paths = append(paths, protovalidate.FieldPathString(v.GetField())+" "+v.GetRuleId())
	}
	sort.Strings(paths)
	want := []string{"currency_code string.len", "customer_id string.pattern", "items[0].quantity int32.gt_lte", "items[0].sku string.min_len"}
	if len(paths) != len(want) {
		t.Fatalf("violations = %v", paths)
	}
	for i := range want {
		if paths[i] != want[i] {
			t.Fatalf("violations = %v, want %v", paths, want)
		}
	}
	t.Log(err)
}

func TestInterceptorRejectsBeforeHandler(t *testing.T) {
	opts, err := validation.ServerOptions()
	if err != nil {
		t.Fatal(err)
	}
	srv := testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, server.New()) }, opts...)
	c := ordersv1.NewOrderServiceClient(srv.Dial(t))

	_, err = c.CreateOrder(t.Context(), invalid())
	st := status.Convert(err)
	if st.Code() != codes.InvalidArgument {
		t.Fatalf("got %v", err)
	}
	var found *validate.Violations
	for _, d := range st.Details() {
		if v, ok := d.(*validate.Violations); ok {
			found = v
		}
	}
	if len(found.GetViolations()) != 4 {
		t.Fatalf("details = %v", st.Details())
	}

	ok := &ordersv1.CreateOrderRequest{CustomerId: "c-7", CurrencyCode: "EUR",
		Items: []*ordersv1.LineItem{{Sku: "SKU-1", Quantity: 1, UnitPriceMinor: 100}}}
	if _, err := c.CreateOrder(t.Context(), ok); err != nil {
		t.Fatal(err)
	}

	// Streams are validated message by message.
	stream, err := c.ImportOrders(t.Context())
	if err != nil {
		t.Fatal(err)
	}
	_ = stream.Send(&ordersv1.ImportOrdersRequest{Order: ok})
	_ = stream.Send(&ordersv1.ImportOrdersRequest{Order: invalid()})
	_, err = stream.CloseAndRecv()
	if status.Code(err) != codes.InvalidArgument {
		t.Fatalf("stream: %v", err)
	}
}

grpc-gateway: REST transcoding, annotations, OpenAPI Important ​

In plain words: grpc-gateway generates an http.Handler that accepts JSON over HTTP, calls your gRPC service, and turns the answer back into JSON. You choose the URLs with google.api.http annotations in the .proto file.

Common misunderstanding: "The gateway is a second implementation." It holds no business logic: its README says it "reads protobuf service definitions and generates a reverse-proxy server which translates a RESTful HTTP API into gRPC". Another: "every RPC becomes REST". Only annotated ones are routed; client and bidi streaming are not usable from a plain HTTP client, and the in-process RegisterXxxHandlerServer variant does not support streaming at all.

Definition: option (google.api.http) = { get: "/v1/orders/{id}" } binds the path variable to the request field id; post: "/v1/orders" body: "*" maps the whole JSON body; patch: "/v1/orders/{order.id}" body: "order" maps the body to one field, and with the generator flag allow_patch_feature (default true) the gateway fills a FieldMask named update_mask from the JSON keys present. Query parameters fill remaining fields (?customerId=c-1). runtime.NewServeMux(opts...) plus RegisterOrderServiceHandlerClient (forward over a ClientConn) or RegisterOrderServiceHandlerFromEndpoint (dial for you). The JSON is ProtoJSON (lowerCamelCase, enums as strings, int64 as strings). Errors map codes to HTTP: NotFound 404, InvalidArgument 400, Unauthenticated 401, PermissionDenied 403, ResourceExhausted 429, FailedPrecondition 400, Unavailable 503, DeadlineExceeded 504, Canceled 499, with a body like {"code":5, "message":"...", "details":[...]} (real, from the test). protoc-gen-openapiv2 writes an OpenAPI v2 (Swagger) document from the same annotations.

1  curl GET /v1/orders/o-404        ──▶ runtime.ServeMux: route GetOrder, id = "o-404"
2  gateway ──▶ GetOrder(ctx, {id:"o-404"}) over gRPC (metadata from matched headers)
3  server  ──▶ status NotFound + ResourceInfo
4  gateway: HTTPStatusFromCode(NotFound) = 404
5  body {"code":5, "message":"order \"o-404\" not found", "details":[{"@type":"type.googleapis.com/google.rpc.ResourceInfo", ...}]}
One Go gRPC server, five kinds of callersgrpc.Server (Go)academy.orders.v1.OrderServicegrpc.health.v1.Healthgrpc.reflection.v1.ServerReflectionHTTP/2, protobuf, TLS or mTLSGo servicegrpc.NewClient + stubbinary gRPC, mTLSREST / JSON clientcurl, mobile, partnergrpc-gateway ServeMuxBrowsergrpc-web / Connect clientEnvoy grpc_web filter or connect-gogrpcurl, grpcuilist, describe, calluses reflectionKubernetes grpc probeor grpc-health-probegrpc.health.v1.Health/CheckSame .proto, same handlers: only the edge translates (JSON <-> protobuf, HTTP/1.1 <-> HTTP/2).

Real scenario: a public REST API and an internal gRPC API from one .proto; a mobile team that consumes the OpenAPI file; a partner integration that can only send JSON; a streaming export served as newline-delimited JSON ({"result": ...} per line, real output).

HTTPgRPC codeHTTPgRPC code
200OK409AlreadyExists, Aborted
400InvalidArgument, FailedPrecondition, OutOfRange429ResourceExhausted
401Unauthenticated499Canceled
403PermissionDenied500Unknown, Internal, DataLoss
404NotFound501 / 503 / 504Unimplemented / Unavailable / DeadlineExceeded

Fix / how to use it: annotate only what external callers need, run the gateway as its own http.Server (or the same binary on another port), forward request ids with WithIncomingHeaderMatcher, and publish the generated OpenAPI. REST design itself is in A REST API in Go.

go
// Package gateway exposes the gRPC OrderService as JSON over HTTP with
// grpc-gateway v2: the google.api.http annotations in orders.proto decide the
// routes, and the generated orders.pb.gw.go does the transcoding.
package gateway

import (
	"context"
	"net/http"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/encoding/protojson"
)

// New returns an http.Handler that forwards each REST call to the gRPC
// server behind conn. Incoming HTTP headers that match the matcher become
// gRPC metadata.
func New(ctx context.Context, conn *grpc.ClientConn) (http.Handler, error) {
	mux := runtime.NewServeMux(
		runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
			MarshalOptions:   protojson.MarshalOptions{UseProtoNames: false, EmitUnpopulated: false},
			UnmarshalOptions: protojson.UnmarshalOptions{DiscardUnknown: true},
		}),
		runtime.WithIncomingHeaderMatcher(func(key string) (string, bool) {
			if key == "X-Request-Id" {
				return "x-request-id", true
			}
			return runtime.DefaultHeaderMatcher(key)
		}),
	)
	// RegisterOrderServiceHandlerClient supports server streaming;
	// RegisterOrderServiceHandlerServer (in-process, no network) does not.
	if err := ordersv1.RegisterOrderServiceHandlerClient(ctx, mux, ordersv1.NewOrderServiceClient(conn)); err != nil {
		return nil, err
	}
	return mux, nil
}
go
package gateway_test

import (
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/grpc-protobuf-in-go/gateway"
	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/server"
	"academy/grpc-protobuf-in-go/testsrv"

	"google.golang.org/grpc"
)

func setup(t *testing.T) *httptest.Server {
	svc := server.New()
	svc.Seed(&ordersv1.Order{Id: "o-1", CustomerId: "c-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PAID, TotalMinor: 2500})
	svc.Seed(&ordersv1.Order{Id: "o-2", CustomerId: "c-1"})
	srv := testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, svc) })
	h, err := gateway.New(t.Context(), srv.Dial(t))
	if err != nil {
		t.Fatal(err)
	}
	hs := httptest.NewServer(h)
	t.Cleanup(hs.Close)
	return hs
}

func do(t *testing.T, method, url, body string) (int, string) {
	req, _ := http.NewRequestWithContext(t.Context(), method, url, strings.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	b, _ := io.ReadAll(res.Body)
	return res.StatusCode, string(b)
}

func TestGetMapsPathParam(t *testing.T) {
	hs := setup(t)
	code, body := do(t, http.MethodGet, hs.URL+"/v1/orders/o-1", "")
	if code != http.StatusOK {
		t.Fatalf("%d %s", code, body)
	}
	var got struct {
		Order struct {
			ID         string `json:"id"`
			CustomerID string `json:"customerId"`
			Status     string `json:"status"`
			TotalMinor string `json:"totalMinor"` // int64 is a JSON string in ProtoJSON
		} `json:"order"`
	}
	if err := json.Unmarshal([]byte(body), &got); err != nil {
		t.Fatal(err)
	}
	if got.Order.CustomerID != "c-1" || got.Order.Status != "ORDER_STATUS_PAID" || got.Order.TotalMinor != "2500" {
		t.Fatalf("body = %s", body)
	}
}

func TestStatusCodesBecomeHTTPCodes(t *testing.T) {
	hs := setup(t)
	code, body := do(t, http.MethodGet, hs.URL+"/v1/orders/o-404", "")
	if code != http.StatusNotFound {
		t.Fatalf("%d %s", code, body)
	}
	var st struct {
		Code    int    `json:"code"`
		Message string `json:"message"`
	}
	_ = json.Unmarshal([]byte(body), &st)
	if st.Code != 5 || !strings.Contains(st.Message, "not found") {
		t.Fatalf("body = %s", body)
	}
	t.Log(body)
}

func TestPostBodyAndPatchMask(t *testing.T) {
	hs := setup(t)
	code, body := do(t, http.MethodPost, hs.URL+"/v1/orders",
		`{"customerId":"c-9","currencyCode":"EUR","items":[{"sku":"SKU-1","quantity":2,"unitPriceMinor":"700"}]}`)
	if code != http.StatusOK || !strings.Contains(body, `"totalMinor":"1400"`) {
		t.Fatalf("%d %s", code, body)
	}
	// PATCH with body "order": the gateway fills update_mask from the JSON
	// keys present when the request does not send one.
	code, body = do(t, http.MethodPatch, hs.URL+"/v1/orders/o-1", `{"status":"ORDER_STATUS_SHIPPED"}`)
	if code != http.StatusOK || !strings.Contains(body, "ORDER_STATUS_SHIPPED") || !strings.Contains(body, `"totalMinor":"2500"`) {
		t.Fatalf("%d %s", code, body)
	}
}

func TestServerStreamIsNewlineDelimited(t *testing.T) {
	hs := setup(t)
	code, body := do(t, http.MethodGet, hs.URL+"/v1/orders?customerId=c-1", "")
	if code != http.StatusOK {
		t.Fatalf("%d %s", code, body)
	}
	lines := strings.Split(strings.TrimSpace(body), "\n")
	if len(lines) != 2 || !strings.HasPrefix(lines[0], `{"result":`) {
		t.Fatalf("body = %q", body)
	}
	t.Log(lines[0])
}

Health service, grpc-health-probe, reflection service, grpcurl Important ​

In plain words: The health service is a standard RPC (grpc.health.v1.Health/Check) that answers SERVING or NOT_SERVING; load balancers, Kubernetes and grpc-health-probe call it. The reflection service lets tools such as grpcurl ask the server for its own schema, so you can call it without .proto files.

Common misunderstanding: "An open TCP port means healthy." The process may be up while it cannot reach its database; the health service lets you say so per service. And "reflection is a debug toy that is safe everywhere". It publishes your whole schema; keep it on internal listeners or behind auth on public ones.

Definition: health.NewServer() with SetServingStatus(service, status) ("" is the whole server), Shutdown() (everything NOT_SERVING) and Resume(); register with healthpb.RegisterHealthServer. The protocol has Check and the streaming Watch; an unknown service gets NotFound from Check (real: code = NotFound desc = unknown service). reflection.Register(s) adds grpc.reflection.v1.ServerReflection and v1alpha. grpcurl's README calls it "basically curl for gRPC servers": list, describe, and calls with -d JSON; on an error status it exits non-zero (69 for NotFound in the real lab run). Kubernetes has a native grpc: probe (GA in v1.27 per the Kubernetes blog) that calls the health service; grpc-health-probe is the older exec-based tool and exits 0 when SERVING.

1  kubelet: grpc probe port 50051         ──▶ Health/Check{service:""}   -> SERVING: pod ready
2  SIGTERM arrives                         hs.Shutdown()               -> NOT_SERVING
3  kubelet / LB: Check -> NOT_SERVING       stop sending new calls
4  s.GracefulStop()                         in-flight RPCs finish, connections close
5  Watch subscribers saw SERVING -> NOT_SERVING (real, ops test)

Real scenario: readiness that turns NOT_SERVING while a cache warms up; a drain step during rolling deploys; an on-call engineer running grpcurl -plaintext host:50051 list against a staging pod; Envoy or a cloud load balancer health-checking a gRPC backend.

ToolTalks toGives you
grpc.health.v1.Health/CheckHealth serviceOne status
Health/WatchHealth serviceA stream of status changes
Kubernetes grpc: probeHealth serviceLiveness/readiness without an extra binary
grpc-health-probeHealth serviceExit code 0 / non-zero for exec probes
grpcurl / grpcuiReflection (or .proto files)list, describe, invoke from JSON
buf curlReflection or BSR schemaSame idea, part of buf

Fix / how to use it: register health and reflection in every server, flip health before stopping, and gate reflection on public endpoints.

go
// Package ops assembles a production-shaped grpc.Server: the standard health
// service, server reflection, keepalive and connection-age settings, and a
// message size limit.
package ops

import (
	"time"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/keepalive"
	"google.golang.org/grpc/reflection"
)

// ServiceName is the fully qualified name health checks ask about.
const ServiceName = "academy.orders.v1.OrderService"

// ServerOptions are the transport settings most services want.
func ServerOptions() []grpc.ServerOption {
	return []grpc.ServerOption{
		grpc.KeepaliveParams(keepalive.ServerParameters{
			MaxConnectionIdle:     5 * time.Minute,  // close idle connections with GOAWAY
			MaxConnectionAge:      30 * time.Minute, // force reconnects so new pods get traffic
			MaxConnectionAgeGrace: 30 * time.Second, // let in-flight RPCs finish
			Time:                  2 * time.Minute,  // ping an idle client after this
			Timeout:               20 * time.Second, // close if the ping is not answered
		}),
		grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
			MinTime:             30 * time.Second, // clients may ping at most this often
			PermitWithoutStream: true,
		}),
		grpc.MaxRecvMsgSize(8 << 20), // default is 4 MiB
		grpc.MaxConcurrentStreams(1000),
	}
}

// NewServer registers the business service, health and reflection.
func NewServer(svc ordersv1.OrderServiceServer, extra ...grpc.ServerOption) (*grpc.Server, *health.Server) {
	s := grpc.NewServer(append(ServerOptions(), extra...)...)
	ordersv1.RegisterOrderServiceServer(s, svc)

	hs := health.NewServer()
	// "" is the overall server status; per-service entries are optional.
	hs.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)
	hs.SetServingStatus(ServiceName, healthpb.HealthCheckResponse_SERVING)
	healthpb.RegisterHealthServer(s, hs)

	// Reflection lets grpcurl and grpcui discover services without .proto files.
	reflection.Register(s)
	return s, hs
}

// Drain flips health to NOT_SERVING first, so load balancers stop sending
// new calls, then stops the server gracefully.
func Drain(s *grpc.Server, hs *health.Server) {
	hs.Shutdown() // every service reports NOT_SERVING from now on
	s.GracefulStop()
}
go
package ops_test

import (
	"context"
	"net"
	"sort"
	"testing"
	"time"

	"academy/grpc-protobuf-in-go/ops"
	"academy/grpc-protobuf-in-go/server"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	reflectionpb "google.golang.org/grpc/reflection/grpc_reflection_v1"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)

func start(t *testing.T) (*grpc.ClientConn, func()) {
	lis := bufconn.Listen(1 << 20)
	s, hs := ops.NewServer(server.New())
	go func() { _ = s.Serve(lis) }()
	conn, err := grpc.NewClient("passthrough:///bufnet",
		grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return lis.DialContext(ctx) }),
		grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = conn.Close(); s.Stop() })
	return conn, func() { ops.Drain(s, hs) }
}

func TestHealth(t *testing.T) {
	conn, drain := start(t)
	h := healthpb.NewHealthClient(conn)
	for _, svc := range []string{"", ops.ServiceName} {
		res, err := h.Check(t.Context(), &healthpb.HealthCheckRequest{Service: svc})
		if err != nil || res.GetStatus() != healthpb.HealthCheckResponse_SERVING {
			t.Fatalf("%q: %v %v", svc, res, err)
		}
	}
	_, err := h.Check(t.Context(), &healthpb.HealthCheckRequest{Service: "no.such.Service"})
	if status.Code(err) != codes.NotFound {
		t.Fatalf("unknown service: %v", err)
	}

	// Watch streams every status change; Drain must report NOT_SERVING.
	ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
	defer cancel()
	w, err := h.Watch(ctx, &healthpb.HealthCheckRequest{Service: ops.ServiceName})
	if err != nil {
		t.Fatal(err)
	}
	if first, err := w.Recv(); err != nil || first.GetStatus() != healthpb.HealthCheckResponse_SERVING {
		t.Fatalf("first watch: %v %v", first, err)
	}
	go drain()
	next, err := w.Recv()
	if err != nil || next.GetStatus() != healthpb.HealthCheckResponse_NOT_SERVING {
		t.Fatalf("after drain: %v %v", next, err)
	}
}

func TestReflectionListsServices(t *testing.T) {
	conn, _ := start(t)
	stream, err := reflectionpb.NewServerReflectionClient(conn).ServerReflectionInfo(t.Context())
	if err != nil {
		t.Fatal(err)
	}
	if err := stream.Send(&reflectionpb.ServerReflectionRequest{
		MessageRequest: &reflectionpb.ServerReflectionRequest_ListServices{ListServices: ""},
	}); err != nil {
		t.Fatal(err)
	}
	res, err := stream.Recv()
	if err != nil {
		t.Fatal(err)
	}
	var names []string
	for _, s := range res.GetListServicesResponse().GetService() {
		names = append(names, s.GetName())
	}
	sort.Strings(names)
	want := []string{"academy.orders.v1.OrderService", "grpc.health.v1.Health", "grpc.reflection.v1.ServerReflection", "grpc.reflection.v1alpha.ServerReflection"}
	if len(names) != len(want) {
		t.Fatalf("services = %v", names)
	}
	for i := range want {
		if names[i] != want[i] {
			t.Fatalf("services = %v", names)
		}
	}
}

Keepalive, connection age and load balancing (round_robin, resolver) Important ​

In plain words: One gRPC client keeps a long-lived HTTP/2 connection, so a normal L4 load balancer balances connections, not calls: every call from that client goes to the same backend. Client-side load balancing (a resolver that returns all backend addresses and a policy such as round_robin) spreads calls; keepalive and MaxConnectionAge keep connections healthy and force them to rebalance.

Common misunderstanding: "A Kubernetes ClusterIP Service balances my gRPC calls." It balances TCP connections; with one connection per client the load is uneven. Use a headless Service with dns:/// and round_robin, an L7 proxy (Envoy, a mesh), or xDS. A second one: "keepalive pings every few seconds keep things safe". Servers enforce MinTime (default 5 minutes) and answer a too-eager client with GOAWAY ENHANCE_YOUR_CALM.

Definition: A resolver turns a target into addresses (dns, passthrough, unix, xds, or manual in tests); the LB policy picks one ready subchannel per RPC. pick_first "is the default LB policy if the service config does not specify any"; round_robin connects to all addresses and rotates over the ready ones; set it with grpc.WithDefaultServiceConfig('{"loadBalancingConfig":[{"round_robin":{}}]}') (a Go string; the snippet builds it with backquotes) as the balancing snippet does. Keepalive: client keepalive.ClientParameters{Time, Timeout, PermitWithoutStream} (Time below 10 s is raised to 10 s); server keepalive.ServerParameters{MaxConnectionIdle, MaxConnectionAge, MaxConnectionAgeGrace, Time, Timeout} (defaults: infinity, infinity, infinity, 2 hours, 20 seconds) and keepalive.EnforcementPolicy{MinTime: 5m default, PermitWithoutStream: false}. MaxConnectionAge adds "A random jitter of +/-10%" so reconnects do not storm. Reaching the age is graceful: the server sends GOAWAY, new RPCs go to a new connection, and RPCs already running on the old one continue. Only after MaxConnectionAgeGrace (default infinity) is the connection closed by force, and then in-flight calls fail: grpc.io says "For streaming RPCs, if the connection is closed, any in-progress RPCs will fail". With the default grace a long-lived stream therefore never moves; with a finite grace it is cut and the client must reopen it.

1  NewClient("academy:///orders", WithResolvers(r), round_robin)   r returns [a, b, c]
2  balancer: connect to a, b, c (subchannels)
3  call 1 -> a (ready), call 2 -> b, call 3 -> c, ...                 only READY ones are picked
4  real run, 9 calls: map[backend-a:2 backend-b:3 backend-c:4]        (c became ready first)
5  pick_first, same addresses: all 9 calls to one backend (real)

Real scenario: an orders service scaled from 3 to 10 pods that sees no traffic on the new pods until clients reconnect (fixed with MaxConnectionAge of 30 minutes); a cloud NAT or L4 proxy that silently drops idle connections (fixed with client keepalive pings shorter than its idle timeout); a headless Service plus round_robin inside Kubernetes; a mesh doing L7 balancing with no client code at all.

ApproachBalancesClient codeNote
L4 LB / ClusterIPConnectionsNoneUneven for long-lived clients
dns:///headless:port + round_robinCallsService configDNS re-resolution on reconnect
L7 proxy (Envoy, nginx grpc_pass)CallsNoneExtra hop
Service mesh sidecarCallsNoneSee Service Mesh
xDS (xds:///)Calls, with control planeImport google.golang.org/grpc/xdsProxyless mesh

Fix / how to use it: pick one of the call-level options above, set MaxConnectionAge with a finite MaxConnectionAgeGrace on servers so connections (including long streams) eventually rebalance, make stream clients reopen a stream that fails with Unavailable, and keep client keepalive slower than the server's MinTime. Load balancing as a system topic is in Load Balancing.

go
// Package balancing shows client-side load balancing in grpc-go: a resolver
// produces addresses, a balancing policy (pick_first or round_robin) picks a
// connection per RPC.
package balancing

import (
	"context"
	"net"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"
	"google.golang.org/grpc/resolver/manual"
)

// Backend answers GetOrder with its own name, so the test can see who served.
type Backend struct {
	ordersv1.UnimplementedOrderServiceServer
	Name string
}

// GetOrder implements the RPC.
func (b Backend) GetOrder(context.Context, *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	return &ordersv1.GetOrderResponse{Order: &ordersv1.Order{Id: b.Name}}, nil
}

// StartBackend serves a Backend on a real localhost TCP port.
func StartBackend(name string) (addr string, stop func(), err error) {
	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return "", nil, err
	}
	s := grpc.NewServer()
	ordersv1.RegisterOrderServiceServer(s, Backend{Name: name})
	go func() { _ = s.Serve(lis) }()
	return lis.Addr().String(), s.Stop, nil
}

// Dial builds a client whose manual resolver returns addrs. policy is
// "pick_first" (the default when no service config says otherwise) or
// "round_robin". In production the resolver is usually "dns:///" against a
// headless Kubernetes Service, or xDS.
func Dial(policy string, addrs ...string) (*grpc.ClientConn, error) {
	r := manual.NewBuilderWithScheme("academy")
	state := resolver.State{}
	for _, a := range addrs {
		state.Addresses = append(state.Addresses, resolver.Address{Addr: a})
	}
	r.InitialState(state)
	return grpc.NewClient(r.Scheme()+":///orders",
		grpc.WithResolvers(r),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingConfig":[{"`+policy+`":{}}]}`),
	)
}
go
package balancing_test

import (
	"testing"

	"academy/grpc-protobuf-in-go/balancing"
	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
)

func served(t *testing.T, policy string, n int) map[string]int {
	var addrs []string
	for _, name := range []string{"backend-a", "backend-b", "backend-c"} {
		addr, stop, err := balancing.StartBackend(name)
		if err != nil {
			t.Fatal(err)
		}
		t.Cleanup(stop)
		addrs = append(addrs, addr)
	}
	conn, err := balancing.Dial(policy, addrs...)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = conn.Close() })
	c := ordersv1.NewOrderServiceClient(conn)
	count := map[string]int{}
	for i := 0; i < n; i++ {
		res, err := c.GetOrder(t.Context(), &ordersv1.GetOrderRequest{Id: "x"})
		if err != nil {
			t.Fatal(err)
		}
		count[res.GetOrder().GetId()]++
	}
	return count
}

func TestPickFirstSticksToOneBackend(t *testing.T) {
	count := served(t, "pick_first", 9)
	if len(count) != 1 {
		t.Fatalf("pick_first spread calls: %v", count)
	}
}

func TestRoundRobinSpreadsCalls(t *testing.T) {
	count := served(t, "round_robin", 9)
	if len(count) != 3 {
		t.Fatalf("round_robin used %d backends: %v", len(count), count)
	}
	t.Log(count)
}

Performance: HTTP/2 multiplexing, message size limits, compression Important ​

In plain words: Reuse one ClientConn; many calls share its HTTP/2 connection at once. Keep messages small: by default a server refuses any message over 4 MiB. Compression trades CPU for bytes and does not get you past the limit.

Common misunderstanding: "gzip lets me send a 5 MiB payload under a 4 MiB limit." The real run says no: grpc: received message after decompression larger than max 4194304. And "a new connection per call is fine". grpc.io's first rule is "Always re-use stubs and channels when possible."

Definition: HTTP/2 multiplexing runs concurrent RPCs as streams on one connection, limited by the server's MaxConcurrentStreams; above that, calls queue on the client. Size limits: server receive default 4 MiB (grpc.MaxRecvMsgSize), server send math.MaxInt32; client receive default 4 MiB (grpc.MaxCallRecvMsgSize), client send math.MaxInt32 (grpc.MaxCallSendMsgSize). Exceeding them is codes.ResourceExhausted: grpc: received message larger than max (5242885 vs. 4194304) on the server side and trying to send message larger than max (2097157 vs. 1048576) when the client limit is hit (both real; the 5 extra bytes are the protobuf tag and length). Compression: import google.golang.org/grpc/encoding/gzip and use grpc.UseCompressor(gzip.Name) per call.

1  client: Echo(5 MiB payload)                            5,242,885 bytes encoded
2  server: read length prefix 5242885 > 4194304           reject before decoding
3  client: rpc error: code = ResourceExhausted desc = grpc: received message larger than max (5242885 vs. 4194304)
4  same call with grpc.UseCompressor("gzip")              a few KiB on the wire
5  server: decompress, size check again                   ResourceExhausted ... after decompression larger than max 4194304

Real scenario: a file upload as one 50 MB message that fails in production (stream it in chunks instead); a report RPC whose response grew past 4 MiB on the client; a chatty service opening a ClientConn per request and exhausting ephemeral ports; protobuf binary vs JSON for a high-volume event bus.

KnobDefaultError when exceeded
Server MaxRecvMsgSize4 MiBResourceExhausted
Server MaxSendMsgSizemath.MaxInt32ResourceExhausted
Client MaxCallRecvMsgSize4 MiBResourceExhausted
Client MaxCallSendMsgSizemath.MaxInt32ResourceExhausted
MaxConcurrentStreamsmath.MaxUint32 in grpc-go v1.80 unless setCalls wait on the client
CompressionOffn/a

Fix / how to use it: stream large data in chunks of tens or hundreds of KiB, raise limits deliberately on both sides when a message really is large, reuse connections, and measure before turning compression on.

go
// Package limits shows the message size limits and compression knobs of
// grpc-go and the errors they produce.
package limits

import (
	"context"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"

	"google.golang.org/grpc"
	"google.golang.org/grpc/encoding/gzip" // registers the "gzip" compressor
)

// EchoSize sends n bytes and returns the size the server saw. Extra call
// options let the caller compress or raise the per-call limits.
func EchoSize(ctx context.Context, c ordersv1.OrderServiceClient, n int, opts ...grpc.CallOption) (int32, error) {
	res, err := c.Echo(ctx, &ordersv1.EchoRequest{Payload: make([]byte, n)}, opts...)
	return res.GetSize(), err
}

// Gzip is the call option that compresses the request with gzip.
func Gzip() grpc.CallOption { return grpc.UseCompressor(gzip.Name) }
go
package limits_test

import (
	"strings"
	"testing"

	ordersv1 "academy/grpc-protobuf-in-go/gen/academy/orders/v1"
	"academy/grpc-protobuf-in-go/limits"
	"academy/grpc-protobuf-in-go/server"
	"academy/grpc-protobuf-in-go/testsrv"

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

const mib = 1 << 20

func client(t *testing.T, sopts []grpc.ServerOption, copts ...grpc.DialOption) ordersv1.OrderServiceClient {
	srv := testsrv.Start(t, func(s *grpc.Server) { ordersv1.RegisterOrderServiceServer(s, server.New()) }, sopts...)
	return ordersv1.NewOrderServiceClient(srv.Dial(t, copts...))
}

func TestDefaultServerLimitIsFourMiB(t *testing.T) {
	c := client(t, nil)
	if _, err := limits.EchoSize(t.Context(), c, 3*mib); err != nil {
		t.Fatalf("3 MiB should pass: %v", err)
	}
	_, err := limits.EchoSize(t.Context(), c, 5*mib)
	if status.Code(err) != codes.ResourceExhausted || !strings.Contains(err.Error(), "larger than max") {
		t.Fatalf("got %v", err)
	}
	t.Log(err)
}

func TestRaisedServerLimit(t *testing.T) {
	c := client(t, []grpc.ServerOption{grpc.MaxRecvMsgSize(8 * mib)})
	if n, err := limits.EchoSize(t.Context(), c, 5*mib); err != nil || n != 5*mib {
		t.Fatalf("%d %v", n, err)
	}
}

func TestClientSendLimit(t *testing.T) {
	c := client(t, nil, grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(1*mib)))
	_, err := limits.EchoSize(t.Context(), c, 2*mib)
	if status.Code(err) != codes.ResourceExhausted {
		t.Fatalf("got %v", err)
	}
	t.Log(err)
}

func TestGzipDoesNotBypassTheLimit(t *testing.T) {
	// 5 MiB of zeros compresses to a few KiB, but the server checks the
	// decompressed size too.
	c := client(t, nil)
	_, err := limits.EchoSize(t.Context(), c, 5*mib, limits.Gzip())
	if status.Code(err) != codes.ResourceExhausted {
		t.Fatalf("got %v", err)
	}
	t.Log(err)
	if n, err := limits.EchoSize(t.Context(), c, 3*mib, limits.Gzip()); err != nil || n != 3*mib {
		t.Fatalf("%d %v", n, err)
	}
}

Testing with bufconn Must-know ​

In plain words: bufconn is an in-memory net.Listener. You start a real grpc.Server on it and connect a real client through it, so tests run the whole stack (HTTP/2, codecs, interceptors, TLS, metadata, status details) with no port and no flakiness from the network.

Common misunderstanding: "Test the service by calling its methods directly." That skips interceptors, serialization, status conversion and metadata, which is where most gRPC bugs live (the UTF-8 marshalling error above only appears through the stack). And "bufconn works with any target". With grpc.NewClient you need passthrough:///bufnet and grpc.WithContextDialer, because the default dns resolver would try to look up bufnet.

Definition: google.golang.org/grpc/test/bufconn: "Package bufconn provides a net.Conn implemented by a buffer and related dialing and listening functionality." bufconn.Listen(size) returns a *Listener with Accept, Close, Dial and DialContext. Every package in this chapter's module starts its server with the testsrv helper and stops it in t.Cleanup; TLS tests run real handshakes over it.

1  lis := bufconn.Listen(1 << 20)
2  s := grpc.NewServer(opts...); Register...(s, svc); go s.Serve(lis)
3  conn := grpc.NewClient("passthrough:///bufnet", WithContextDialer(lis.DialContext), creds)
4  c.GetOrder(t.Context(), req)  -> full HTTP/2 round trip in memory
5  t.Cleanup: conn.Close(); s.Stop()

Real scenario: table tests of status codes per input; interceptor order and logging asserted from captured slog output; mTLS tested with an in-memory PKI; gateway tests that go HTTP → gateway → bufconn → server.

ApproachCoversSpeedUse for
Call methods directlyBusiness logic onlyFastestPure logic
bufconnFull gRPC stack in processFastMost service tests
net.Listen("tcp", "127.0.0.1:0")Plus real sockets, resolvers, LBFastLoad balancing, keepalive
Mock client (interface)Callers of the stubFastestCode that uses OrderServiceClient
Containers / stagingReal network, proxiesSlowEnd-to-end

Fix / how to use it: one helper that starts a server on bufconn and returns a client, t.Context() as the root ctx, and real codes asserted with status.Code(err). Mocking the generated client interface is in Mocking with Interfaces; tests in general in Testing & Benchmarking.

connect-go and gRPC-Web Good to know ​

In plain words: This is the connect-go alternative and its older cousin. Browsers cannot speak raw gRPC (they cannot read HTTP/2 trailers), so either a proxy translates gRPC-Web, or you use Connect, a library that serves gRPC, gRPC-Web and its own simple HTTP protocol from a plain net/http handler.

Common misunderstanding: "gRPC-Web gives the browser full streaming." The grpc-web README lists server-side streaming (only in grpcwebtext mode) and says "Client-side and Bi-directional streaming is not currently supported". And "connect-go is a different protocol, so gRPC clients cannot call it." Connect's docs: "Any gRPC client, in any language, can call a Connect server, and Connect clients can call any gRPC server."

Definition: gRPC-Web is a protocol variant (PROTOCOL-WEB.md) that puts trailers in the body; grpc/grpc-web's JavaScript client needs Envoy's grpc_web filter or another proxy in front of a normal gRPC server. connect-go (connectrpc.com/connect, generated by protoc-gen-connect-go): "Connect servers and clients support three protocols: gRPC, gRPC-Web, and Connect's own protocol"; it works over HTTP/1.1, HTTP/2 and HTTP/3, handlers are http.Handlers, and the Connect protocol can be called with curl and JSON. Its latest release (v1.21.1) declares go 1.26 in go.mod, which is why it is not in this chapter's go 1.24 snippet module.

1  browser (grpc-web JS) ── HTTP/1.1, application/grpc-web+proto ──▶ Envoy grpc_web filter
2  Envoy ── HTTP/2 application/grpc ──▶ grpc-go server        (no change to the Go server)
   or
1  browser (connect-es) ── POST /academy.orders.v1.OrderService/GetOrder, JSON ──▶ connect-go handler
2  same handler also accepts gRPC and gRPC-Web from other clients

Real scenario: an admin SPA that calls the same services as the backend through Envoy; a new service written with connect-go so it can be called with curl and from the browser without a proxy; a team keeping grpc-go for its mature xDS and load-balancing support.

OptionBrowsergRPC clientsServer in GoStreaming from browser
grpc-go + grpc-gatewayREST/JSONYesgrpc-go + gatewayServer streaming as NDJSON
grpc-go + Envoy gRPC-Webgrpc-web JSYesgrpc-go, unchangedServer streaming only
connect-goConnect or gRPC-WebYesnet/http handlersServer streaming (fetch)
grpc-go onlyNoYesgrpc-gon/a

Fix / how to use it: grpc-go for service-to-service with advanced balancing; add grpc-gateway for JSON partners; consider connect-go when the browser is a first-class client and you want plain net/http.

Versioning compat rules Must-know ​

In plain words: Binary clients and servers built from different versions of a .proto file must keep understanding each other. Adding fields is safe; changing a number, a type or reusing an old number is not.

Common misunderstanding: "If it compiles, it is compatible." Reusing number 2 with another type compiles and runs, and the real test shows the result: the old string name = 2 arrives at a reader that declares int64 name = 2, the parser cannot use it, keeps it as an unknown field and GetName() returns 0, with no error. And "renaming is always safe". It is safe for binary, but breaks JSON (the JSON name changes) and generated code, which is why buf breaking with FILE reports it.

Definition: The proto3 guide lists wire-safe changes ("Adding new fields is safe", "Removing fields is safe" if the number is reserved, "Adding additional values to an enum is safe"), wire-unsafe ones ("Changing field numbers for any existing field is not safe", "Moving fields into an existing oneof is not safe") and conditionally compatible ones (int32, uint32, int64, uint64 and bool are compatible but may truncate; string and bytes if valid UTF-8). "Proto3 messages preserve unknown fields", but they are lost when you "Serialize a proto to JSON". JSON has a second trap: protojson's doc says only "If DiscardUnknown is set, unknown fields and enum name values are ignored", so by default an old JSON reader (for example a grpc-gateway configured with strict UnmarshalOptions) rejects a request that carries a new field or enum name; binary-safe is not the same as JSON-safe. Major versions get a new package (academy.orders.v2) served side by side. API-level policy is in API Versioning & Evolution.

1  v1 binary sends CustomerV1{id, name}
2  v2 binary reads it: email, loyalty_points = zero values           safe
3  v2 sends CustomerV2{id, name, email, points}; v1 reads it: unknown fields kept
4  v1 re-marshals: unknown fields still present; v2 downstream reads email (real test)
5  v1 converts to JSON and back: unknown fields gone                 lossy path
6  "broken" reader reuses number 2 as int64: name = 0, no error      silent corruption (real test)

Real scenario: a new email field rolled out to servers before clients; a deleted coupon field whose number 4 is reserved; a team that needed to change int32 amount to int64 and wrote only int32-sized values until every reader was upgraded; an orders.v2 package served next to v1 for a year.

ChangeBinaryJSONGenerated Gobuf FILE
Add a field with a new numberSafeSafe only for readers that discard unknown fields; a strict old ProtoJSON reader (protojson.Unmarshal default, DiscardUnknown: false) fails with unknown fieldSafeOK
Delete a field, reserve number and nameSafeOld JSON that still sends the key fails unless DiscardUnknownBreaks users of the fieldReports deletion
Rename a fieldSafeBreaksBreaksReports
Change a field numberBreaksSafe if name keptSafeReports
Reuse a deleted numberSilent corruptionVariesCompilesReports if reserved was set
int32 → int64Compatible, may truncateSafeBreaksReports
Add an enum valueSafeAn old strict ProtoJSON reader rejects the new enum name unless DiscardUnknown is setExhaustive switches miss itOK
Move a field into a oneofUnsafeUnsafeBreaksReports

Fix / how to use it: run buf breaking against the main branch on every pull request, reserve deleted numbers and names, add fields instead of changing them, and start a v2 package for incompatible redesigns. The compat messages used by the tests:

proto
// Three versions of one message, side by side, to test wire compatibility.
syntax = "proto3";

package academy.compat.v1;

option go_package = "academy/grpc-protobuf-in-go/gen/academy/compat/v1;compatv1";

// CustomerV1 is what an old binary knows.
message CustomerV1 {
  string id = 1;
  string name = 2;
}

// CustomerV2 adds a field with a new number: a safe change.
message CustomerV2 {
  string id = 1;
  string name = 2;
  string email = 3;
  int64 loyalty_points = 4;
}

// CustomerBroken reuses number 2 with another type: an unsafe change.
message CustomerBroken {
  string id = 1;
  int64 name = 2;
}

Mechanics ​

What one unary call puts on the wire Important ​

PROTOCOL-HTTP2.md defines a call as "Request-Headers *Length-Prefixed-Message EOS" and the answer as "(Response-Headers *Length-Prefixed-Message Trailers) / Trailers-Only". Each message is prefixed by a 1-byte Compressed-Flag and a 4-byte big-endian length, which is why the 5 MiB payload above was reported as 5,242,885 bytes plus 5 for the frame. The byte-level protobuf encoding (tags, varints, zig-zag) is in gRPC & Protocol Buffers.

1  HEADERS  :method POST  :path /academy.orders.v1.OrderService/GetOrder  :scheme https
2           content-type: application/grpc  te: trailers  grpc-timeout: 49m  x-request-id: r-42
3  DATA     00 | 00 00 00 05 | 0a 03 6f 2d 31            (flag | length | GetOrderRequest{id:"o-1"})
4  HEADERS  :status 200  content-type: application/grpc   (response headers, from SetHeader)
5  DATA     00 | length | GetOrderResponse
6  HEADERS  grpc-status: 0  x-cost-units: 3                (trailers, END_STREAM)
   error case: only a trailers-only HEADERS with grpc-status: 5, grpc-message, grpc-status-details-bin

The HTTP status is 200 even for a failed call; the gRPC code lives in grpc-status. The spec also says servers "SHOULD respond with HTTP status of 415 (Unsupported Media Type)" when the content type does not begin with application/grpc.

How grpc-go dispatches a call Good to know ​

Serve accepts a connection and runs the HTTP/2 transport; each new stream gets a goroutine that looks up /package.Service/Method in the registered ServiceDescs (unknown: Unimplemented), then either calls the generated _OrderService_GetOrder_Handler (which decodes into a fresh GetOrderRequest and calls your method through the chained unary interceptor) or the stream handler (which wraps the grpc.ServerStream in the generic type and calls your method through the stream interceptor chain). The returned error is converted with status.Convert: a *status.Status error keeps its code and details; anything else becomes Unknown with err.Error() as the message.

StepCode pathFailure code
Accept, TLS handshakecredentials.TransportCredentials.ServerHandshakeClient sees Unavailable
Read headers, method lookupServiceDesc.Methods / StreamsUnimplemented
Read length prefixMax receive size checkResourceExhausted
Decodecodec (proto)Internal (bad bytes)
Interceptor chainChainUnaryInterceptor orderWhatever the interceptor returns
Your handlerYour codeYour status, or Unknown
Encode responsecodec; UTF-8 checkInternal (error while marshaling)
Trailersgrpc-status, grpc-message, detailsn/a

Exact error texts Must-know ​

All from real runs of this chapter's tests and labs unless marked.

TextMeaning
rpc error: code = NotFound desc = order "o-404" not foundstatus.Error from the server, formatted by grpc-go
rpc error: code = Unknown desc = order o-1 not foundPlain Go error returned by a handler
rpc error: code = DeadlineExceeded desc = context deadline exceededClient deadline passed
rpc error: code = ResourceExhausted desc = grpc: received message larger than max (5242885 vs. 4194304)Server receive limit
trying to send message larger than max (2097157 vs. 1048576)Client send limit (ResourceExhausted)
grpc: received message after decompression larger than max 4194304Limit checked after gzip
grpc: error while marshaling: string field contains invalid UTF-8Non-UTF-8 bytes in a string field (Internal)
transport: authentication handshake failed: tls: failed to verify certificate: x509: certificate is valid for orders.internal, not payments.internalWrong ServerName (Unavailable)
grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)Per-RPC token on an insecure connection (NewClient error)
Request unauthenticated with bearergo-grpc-middleware AuthFromMD, no header (Unauthenticated)
method GetOrder not implementedUnimplemented embedding (Unimplemented)
code = NotFound desc = unknown serviceHealth Check for an unregistered service
validation errors: - customer_id: does not match regex pattern ...protovalidate (InvalidArgument through the interceptor)

Solving the classic problems ​

BugSymptomFixCost
Plain errors from handlersEvery failure is Unknownstatus.Error with the right codeOne mapping function
No deadlineCalls hang behind a slow dependencyWithTimeout per call, default-timeout interceptorOne line per call
ClientConn per requestLatency spikes, port exhaustionOne NewClient per target at startupDependency wiring
Dial("bufnet") copied to NewClientdns resolver failspassthrough:///bufnetNone
Internal text in messagesLeaks SQL, hostnamesLog it; return a generic InternalLogging discipline
Validation scattered in handlersRules differ per RPC and languageprotovalidate rules + interceptorLearn the rule syntax
Field number reusedSilent data corruptionreserved, buf breaking in CICI step
One backend gets all trafficUneven load behind L4 LBround_robin + headless DNS, or L7 proxy; MaxConnectionAgeConfig
Large messagesResourceExhaustedStream in chunks; raise limits on both sides deliberatelyProtocol change
Panic in a handlerWhole process diesRecovery interceptorNone
Token over plaintextCredentials sniffableTLS; RequireTransportSecurityCertificates
Hard shutdownDropped calls during deploysHealth NOT_SERVING, then GracefulStopShutdown hook

From plain errors to codes ​

The Before and After snippets are the whole fix: map at the edge with one function (statuserr.FromDomain), classify on the client with status.Code, never with strings.Contains.

Retrying safely ​

grpc.io: "Retries are enabled by default, but there is no default retry policy"; without a policy grpc-go still performs transparent retries: unlimited while the RPC "never leaves the client", and "a single transparent retry when RPC reaches the gRPC server library, but has never been seen by the server application logic". A policy in the service config retries listed codes with exponential backoff and ±20% jitter. Retry only idempotent methods, and only while the caller's deadline still has room (policy is in Timeouts, Retries & Jitter):

go
// Service config passed with grpc.WithDefaultServiceConfig (shape from grpc.io's retry guide).
const retryConfig = `{
  "methodConfig": [{
    "name": [{"service": "academy.orders.v1.OrderService", "method": "GetOrder"}],
    "retryPolicy": {
      "maxAttempts": 4,
      "initialBackoff": "0.1s",
      "maxBackoff": "1s",
      "backoffMultiplier": 2,
      "retryableStatusCodes": ["UNAVAILABLE"]
    }
  }]
}`

Draining without dropping calls ​

Flip health to NOT_SERVING (hs.Shutdown()), wait for load balancers to notice (a few probe periods), then GracefulStop with an outer timeout that falls back to Stop. The ops.Drain helper and its Watch test show the first and last step; cmd/ordersd wires it to SIGTERM. Signals themselves are in OS Processes, Signals & Graceful Shutdown.

Choosing ​

SituationUseExtra techniqueReason
Internal service-to-service callsgrpc-go unary RPCsDeadlines, mTLS, interceptorsTyped contract, HTTP/2, codes
Public API for partners and browsersgrpc-gateway (or plain REST)OpenAPI from the same .protoEveryone speaks JSON
Browser is the main clientconnect-go, or Envoy gRPC-WebConnect or grpc-web clientNo raw gRPC in browsers
Large exportServer streamingCheck ctx between sendsNo 4 MiB ceiling, back-pressure
Bulk uploadClient streamingPer-message validationOne summary, constant memory
Interactive both-way flowBidirectional streamingSeparate send/receive goroutinesIndependent directions
Events between services, asyncA broker, not gRPCOutbox (Event-Driven Go)Decoupling in time
Schema managementbufbuf lint + buf breaking in CICatches breaking changes
Request validationprotovalidateInterceptorOne set of rules for all languages
Load balancing in Kubernetesheadless Service + round_robin, or a meshMaxConnectionAgeL4 balances connections only
Testsbufconnt.Context(), real codesFull stack, no ports
Debugginggrpcurl + reflectionInternal listener onlyNo .proto needed

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Inside one process, gRPC is usually the wrong tool between packages: a Go interface is faster and type-checked by the compiler. A monolith meets gRPC at its edge, as a server for a mobile app or as a client of a payment provider's gRPC API. The simplest correct shape is one grpc.Server next to the http.Server, one ClientConn per external dependency built in main, and the store behind the service as plain SQL. The snippet's in-memory store stands in for this table, and ListOrders streaming maps naturally onto a keyset scan:

sql
-- the table behind OrderService (money in minor units, like the proto)
CREATE TABLE orders (
  id            text PRIMARY KEY,
  customer_id   text        NOT NULL,
  status        smallint    NOT NULL DEFAULT 1,  -- OrderStatus enum value
  total_minor   bigint      NOT NULL,
  currency_code char(3)     NOT NULL,
  note          text,                            -- NULL = optional field unset
  labels        jsonb       NOT NULL DEFAULT '{}',
  create_time   timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_id_id ON orders (customer_id, id);
-- ListOrders as a stream: one keyset page per batch of Send calls
SELECT id, customer_id, status, total_minor, currency_code, note, create_time
FROM orders
WHERE customer_id = $1 AND id > $2
ORDER BY id
LIMIT 500;

Modular monolith and multiple databases ​

When a modular monolith prepares to split, the .proto files become the module boundaries before the network does: each module owns a package (academy.orders.v1, academy.billing.v1) and its tables, and other modules call it through the generated client interface. In one process you can even register every module's service on one grpc.Server and call them through bufconn or a direct adapter, so the later split only changes the target string. With two databases (orders in PostgreSQL, sessions in Redis), nothing in gRPC makes them atomic; each module's RPC is its own transaction. Boundaries themselves are in Service Boundaries.

Microservices ​

Across services, what survives is exactly what is in the .proto and in metadata: messages, the deadline (grpc-timeout), request id and trace context (metadata), identity (mTLS certificate plus a token re-verified by each service), and the status code. What does not survive: Go error types, context values, and any guarantee that the callee stopped when you gave up. A concrete flow: the mobile app calls the REST gateway (POST /v1/orders, 3 s); the gateway calls orders.CreateOrder over mTLS with grpc-timeout: 2900m and x-request-id; orders calls inventory.ReserveStock (bidi, 800 ms) and payments.Charge (unary, 1.5 s, idempotency key in the request); payments returns Unavailable with RetryInfo; orders maps that to Unavailable, the gateway to HTTP 503, and the app retries with the same idempotency key. Communication style choices are in Service Communication; a full build is in Project: Microservices.

Distributed data: replicas, caches, multi-region ​

gRPC's guarantees end at the call. A DeadlineExceeded on a write means "unknown outcome": the server may have committed; resolve it with idempotency keys (API Idempotency) or a read-back. Retries and hedging multiply load on a struggling replica set, so retry only idempotent calls (or writes carrying an idempotency key), only on Unavailable (and ResourceExhausted after the advised delay), and only within the caller's budget. Across regions, clients prefer local backends via the resolver or xDS locality, deadlines travel as durations so clock skew does not matter, and long-lived streams pin a client to one backend: MaxConnectionAge only sends GOAWAY, an open stream keeps the old connection until MaxConnectionAgeGrace expires (infinite by default), and that forced close fails the stream, so streaming clients need resume logic (a cursor or last-seen id) to reconnect elsewhere. Caches in front of gRPC are application-level: there is no HTTP caching for POST-only RPCs.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesgRPC practice
1× (one instance)Bugs are invisibleCodes, deadlines, recovery, bufconn tests, buf lint
10× (a few replicas)One backend hot, slow dependencies pile upround_robin or L7 balancing, MaxConnectionAge, health-driven draining, size limits
100× (many services, several teams)Breaking changes and retry stormsbuf breaking in CI, BSR modules, retry policies with budgets, xDS or mesh, MaxConcurrentStreams, load shedding (Load Shedding)

Lab ​

1. Run the tests (real) ​

cd docs/snippets/go/grpc-protobuf-in-go/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok   academy/grpc-protobuf-in-go/after         1.986s
# ok   academy/grpc-protobuf-in-go/balancing     2.063s
# ok   academy/grpc-protobuf-in-go/before        2.211s
# ok   academy/grpc-protobuf-in-go/gateway       1.927s
# ok   academy/grpc-protobuf-in-go/headers       1.911s
# ok   academy/grpc-protobuf-in-go/interceptors  1.919s
# ok   academy/grpc-protobuf-in-go/limits        2.260s
# ok   academy/grpc-protobuf-in-go/ops           1.913s
# ok   academy/grpc-protobuf-in-go/protobasics   1.909s
# ok   academy/grpc-protobuf-in-go/server        2.016s
# ok   academy/grpc-protobuf-in-go/statuserr     1.918s
# ok   academy/grpc-protobuf-in-go/tlsauth       1.933s
# ok   academy/grpc-protobuf-in-go/validation    1.676s

2. Lint and breaking-change checks (real) ​

The fixtures live next to the Go module in docs/snippets/go/grpc-protobuf-in-go/buf-lab/: bad/ is a one-file buf module with STANDARD lint, old/ and new/ are two versions of one Invoice message with breaking: use: [FILE]. The bad file (unversioned package, enum without prefix, Empty as request):

proto
syntax = "proto3";

package shop;

import "google/protobuf/empty.proto";

enum Status {
  PENDING = 0;
  PAID = 1;
}

message order {
  string ID = 1;
  Status status = 2;
}

service Orders {
  rpc Get(google.protobuf.Empty) returns (order);
}

The old and the new Invoice (coupon = 4 deleted, customer_id renamed, int64 amount_minor changed to int32):

proto
syntax = "proto3";

package academy.billing.v1;

message Invoice {
  string id = 1;
  string customer_id = 2;
  int64 amount_minor = 3;
  string coupon = 4;
}
proto
syntax = "proto3";

package academy.billing.v1;

message Invoice {
  string id = 1;
  string customer = 2;
  int32 amount_minor = 3;
  string email = 5;
}

From the Go module directory used in lab 1 (docs/snippets/go/grpc-protobuf-in-go/go):

$ cd ../buf-lab/bad && buf lint
proto/shop/orders.proto:3:1:Package name "shop" should be suffixed with a correctly formed version, such as "shop.v1".
proto/shop/orders.proto:8:3:Enum value name "PENDING" should be prefixed with "STATUS_".
proto/shop/orders.proto:8:3:Enum zero value name "PENDING" should be suffixed with "_UNSPECIFIED".
proto/shop/orders.proto:9:3:Enum value name "PAID" should be prefixed with "STATUS_".
proto/shop/orders.proto:12:9:Message name "order" should be PascalCase, such as "Order".
proto/shop/orders.proto:13:10:Field name "ID" should be lower_snake_case, such as "id".
proto/shop/orders.proto:17:9:Service name "Orders" should be suffixed with "Service".
proto/shop/orders.proto:18:11:RPC request type "Empty" should be named "GetRequest" or "OrdersGetRequest".
proto/shop/orders.proto:18:43:RPC response type "order" should be named "GetResponse" or "OrdersGetResponse".
exit=100

$ cd .. && buf breaking new --against old       # now in buf-lab/
new/proto/academy/billing/v1/invoice.proto:5:1:Previously present field "4" with name "coupon" on message "Invoice" was deleted.
new/proto/academy/billing/v1/invoice.proto:7:3:Field "2" with name "customer" on message "Invoice" changed option "json_name" from "customerId" to "customer".
new/proto/academy/billing/v1/invoice.proto:7:10:Field "2" on message "Invoice" changed name from "customer_id" to "customer".
new/proto/academy/billing/v1/invoice.proto:8:3:Field "3" with name "amount_minor" on message "Invoice" changed type from "int64" to "int32".
exit=100

In a real repository the --against input is usually the main branch: buf breaking --against '.git#branch=main'.

3. Regenerate the code (real with buf; protoc expected, not run) ​

go install github.com/bufbuild/buf/cmd/buf@v1.75.0
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.11
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.6.2
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway@v2.28.0
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@v2.28.0
buf dep update && buf lint && buf generate     # real: exit 0, writes gen/
git diff --exit-code gen/                       # CI: nothing changed by hand
# protoc equivalent (expected, not run; protoc is not installed here):
# protoc -I proto -I third_party/googleapis -I third_party/protovalidate \
#   --go_out=gen --go_opt=paths=source_relative \
#   --go-grpc_out=gen --go-grpc_opt=paths=source_relative \
#   proto/academy/orders/v1/orders.proto

4. grpcurl and grpc-health-probe against a running server (real) ​

go run ./cmd/ordersd -addr 127.0.0.1:50071 in one terminal, then:

$ grpcurl -plaintext 127.0.0.1:50071 list
academy.orders.v1.OrderService
grpc.health.v1.Health
grpc.reflection.v1.ServerReflection
grpc.reflection.v1alpha.ServerReflection

$ grpcurl -plaintext -d '{"id":"o-1"}' 127.0.0.1:50071 academy.orders.v1.OrderService/GetOrder
{ "order": { "id": "o-1", "customerId": "c-1", "status": "ORDER_STATUS_PAID", "totalMinor": "2500", "currencyCode": "EUR" } }

$ grpcurl -plaintext -d '{"id":"o-404"}' 127.0.0.1:50071 academy.orders.v1.OrderService/GetOrder
ERROR:
  Code: NotFound
  Message: order "o-404" not found
  Details:
  1) { "@type": "type.googleapis.com/google.rpc.ResourceInfo", "resourceName": "o-404", ... }
exit=69

$ grpc-health-probe -addr=127.0.0.1:50071
status: SERVING
$ grpc-health-probe -addr=127.0.0.1:50071 -service=nope
error: health rpc failed: rpc error: code = NotFound desc = unknown service
exit=3

(JSON output condensed to one line here; grpcurl prints it indented.)

5. REST through the gateway (real, from the gateway test log) ​

GET  /v1/orders/o-404  -> 404 {"code":5, "message":"order \"o-404\" not found", "details":[{"@type":"type.googleapis.com/google.rpc.ResourceInfo", ...}]}
GET  /v1/orders?customerId=c-1 -> 200, one line per message: {"result":{"order":{"id":"o-1","customerId":"c-1","status":"ORDER_STATUS_PAID","totalMinor":"2500"}}}
POST /v1/orders {"customerId":"c-9",...}  -> 200 {"order":{... "totalMinor":"1400" ...}}

6. Kubernetes gRPC probe (expected, not run) ​

yaml
readinessProbe:
  grpc:
    port: 50051          # calls grpc.health.v1.Health/Check with service ""
  periodSeconds: 5
livenessProbe:
  grpc:
    port: 50051
    service: academy.orders.v1.OrderService
  initialDelaySeconds: 10
# expected: pod Ready while SERVING; after SIGTERM ops.Drain flips NOT_SERVING,
# the pod leaves the Service endpoints, then GracefulStop finishes in-flight calls

For PHP/Laravel developers ​

grpc.io's PHP guide is blunt: "currently, you can only create clients in PHP for gRPC services. Use another language to create a gRPC server." A Laravel app therefore meets gRPC as a client (the grpc PECL extension plus protoc --php_out --grpc_out), while the Go service is the server; RoadRunner-based setups that serve gRPC from PHP run a Go process in front of PHP workers. The usual Laravel pattern is still JSON over HTTP with Http::timeout(...), which is what grpc-gateway gives a Laravel caller without any extension.

php
// Laravel calling the Go service through grpc-gateway: plain JSON over HTTP.
$response = Http::timeout(2)
    ->withHeaders(['X-Request-Id' => (string) Str::uuid()])
    ->get('https://orders.internal/v1/orders/o-1');

if ($response->status() === 404) {
    // gateway mapped codes.NotFound to 404; body: {"code":5,"message":"...","details":[...]}
    abort(404);
}
$total = (int) $response->json('order.totalMinor'); // int64 arrives as a JSON string
Laravel / PHPGo gRPC
Form Request validation rulesprotovalidate rules in the .proto
HTTP middlewareInterceptors
API Resources / JSONGenerated messages, ProtoJSON at the gateway
Http::timeout(2)context.WithTimeout per call, grpc-timeout on the wire
Exceptions to HTTP codes (abort(404))status.Error(codes.NotFound, ...)
php artisan route:listgrpcurl list / describe
PHP gRPC extension: client onlygrpc-go: client and server

Common misconceptions ​

BeliefReality
Returning any error sends it to the clientNon-status errors arrive as Unknown
gRPC has a default deadlineNone; set one on every call
grpc.Dial + WithBlock proves the server is upDeprecated; connectivity changes after the check; use NewClient and deadlines
Field names are on the wireField numbers are; names matter only for JSON
Reusing a deleted field number is fine if types matchOld data is read as the new field; reserve numbers
A changed type fails loudlyIt can decode to zero values silently (compat test)
ClusterIP balances gRPC callsIt balances connections; use round_robin/L7
gzip gets around the 4 MiB limitThe limit is checked after decompression
Unimplemented embedding is boilerplateIt keeps servers compiling when RPCs are added
Metadata keys keep their caseThey are lowercased
Incoming metadata is forwarded automaticallyCopy it to the outgoing context yourself
protoc-gen-validate is the current standardIt is in maintenance mode; use protovalidate
Browsers can call gRPC directlyThey need gRPC-Web (proxy) or Connect
Generated code should not be committedIn Go it is committed so go get works

Cheat sheet ​

TopicRemember
Contractpackage x.v1;, go_package, numbers 1 to 15 for hot fields, reserved on delete
Presenceoptional → pointer; oneof → wrapper types; enums start at _UNSPECIFIED = 0
Time and updatesTimestamp, Duration, FieldMask; named empty responses over Empty
Toolingbuf lint, buf breaking --against main, buf generate, commit gen/
ServerEmbed UnimplementedXxxServer by value, RegisterXxxServer, GracefulStop
ClientOne grpc.NewClient per target; dns:/// default; passthrough:/// for bufconn
DeadlinesEvery call; codes.DeadlineExceeded; pass ctx down
Errorsstatus.Error(codes.X, msg), details via WithDetails, read with status.FromError
MetadataLowercase keys, -bin for bytes, headers before, trailers after
InterceptorsChainUnaryInterceptor + ChainStreamInterceptor, logging outer, recovery inner
Securitycredentials.NewTLS, mTLS between services, tokens only over TLS
Validationprotovalidate rules + interceptor → InvalidArgument with violations
RESTgrpc-gateway with google.api.http; OpenAPI from protoc-gen-openapiv2
OpsHealth + reflection on every server; Kubernetes grpc: probe; grpcurl
Scaleround_robin or L7, MaxConnectionAge, 4 MiB limits, stream big data
Testsbufconn, real codes, t.Context()

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A handler returns errors.New("not found"). What does the client see, and what should the handler return instead? Must-know ​

Answer

Answer: rpc error: code = Unknown desc = not found: grpc-go converts any non-status error to codes.Unknown. Return status.Errorf(codes.NotFound, "order %q not found", id), optionally with a ResourceInfo detail, so the client can branch on status.Code(err).

2 — Why must you never reuse a field number, even with the same type? Must-know ​

Answer

Answer: The number is the field's identity on the wire. Old data or old clients still send values under that number, and the new code reads them as the new field's value. Reserve deleted numbers and names with reserved, and let buf breaking catch deletions.

3 — What is the difference between grpc.NewClient and grpc.Dial, and why does a bufconn test need passthrough:///? Must-know ​

Answer

Answer: NewClient (grpc-go 1.63+) performs no I/O and connects on the first RPC; Dial is deprecated and connects immediately. NewClient uses the dns resolver by default while Dial used passthrough, so a made-up name like bufnet must be written passthrough:///bufnet to reach the custom dialer.

4 — Why embed UnimplementedOrderServiceServer, and why by value? Must-know ​

Answer

Answer: It provides every method returning codes.Unimplemented, so adding an rpc to the .proto does not break compiling servers. Embedded as a nil pointer it would panic when called, which is why the generated RegisterOrderServiceServer checks it at registration time.

5 — A client sets no deadline and the server hangs. What happens, and what is the fix on both sides? Must-know ​

Answer

Answer: The call waits forever: gRPC sets no default deadline. The client should call with context.WithTimeout; the server should pass its ctx to every blocking call and return status.FromContextError(ctx.Err()) when it ends, so the work stops when the caller gives up.

6 — In what order do ChainUnaryInterceptor(logging, auth, recovery) run, and why put recovery last? Important ​

Answer

Answer: The first is outermost: logging runs first and sees the final result, auth next, recovery innermost around the handler. With recovery innermost a panic becomes codes.Internal before logging records it, so the log line shows grpc.code=Internal and the process survives.

7 — How do headers and trailers differ, and how does a Go client read each? Important ​

Answer

Answer: Headers are sent before the first response message, trailers after the last one together with the status. A unary client passes grpc.Header(&h) and grpc.Trailer(&t) as call options; a stream client calls stream.Header() (blocks until sent) and stream.Trailer() after Recv returned io.EOF or an error.

8 — Your gRPC clients in Kubernetes all hit one pod of three. Why, and what are the fixes? Important ​

Answer

Answer: A ClusterIP Service balances TCP connections and each client holds one long-lived HTTP/2 connection. Use a headless Service with dns:/// and the round_robin policy, an L7 proxy or mesh, or xDS; set MaxConnectionAge on servers so connections rebalance after scaling.

9 — What does protovalidate do differently from protoc-gen-validate, and what does the client get on a violation? Important ​

Answer

Answer: PGV generated Validate() methods and is in maintenance mode; protovalidate evaluates the buf.validate rules at runtime from descriptors, with CEL for custom rules. Through the go-grpc-middleware interceptor the client gets codes.InvalidArgument with a buf.validate.Violations detail listing each field path and rule.

10 — A 5 MiB request fails even with gzip. Why, and what are the options? Important ​

Answer

Answer: The server's default receive limit is 4 MiB and grpc-go checks it again after decompression (received message after decompression larger than max 4194304, ResourceExhausted). Stream the data in chunks, or raise MaxRecvMsgSize on the server (and MaxCallRecvMsgSize on clients for large responses) deliberately.

11 — How does grpc-gateway map a PATCH with a partial JSON body to an RPC with a FieldMask? Good to know ​

Answer

Answer: With patch: "/v1/orders/{order.id}" body: "order" and the generator's allow_patch_feature (default true), the gateway fills update_mask from the JSON keys that were present when the client did not send a mask. The server then updates only those paths, as UpdateOrder does.

12 — When would you choose connect-go or gRPC-Web over plain grpc-go? Good to know ​

Answer

Answer: When browsers are first-class clients: they cannot read HTTP/2 trailers, so raw gRPC does not work. gRPC-Web needs a translating proxy such as Envoy and supports only unary and server streaming; connect-go serves gRPC, gRPC-Web and the Connect protocol from net/http handlers without a proxy.

Glossary ​

TermMeaning
Protocol Buffers (protobuf)Google's schema language and binary encoding, open sourced in 2008
proto3Protobuf syntax version used here; editions (edition = "2023") succeed it
MessageA structured type of numbered fields
Scalar typesint32, int64, sint*, fixed*, bool, string, bytes, double, float
Field numberA field's identity on the wire; 1 to 536,870,911 minus 19,000 to 19,999
reservedMarks deleted field numbers or names so they cannot be reused
EnumNamed integer set; the first value must be 0 (_UNSPECIFIED)
oneofAt most one of a set of fields is set; Go wrapper types
optionalExplicit presence for a scalar; a pointer in Go
Field presenceWhether a reader can tell "unset" from "zero"
repeatedList field; a slice in Go
mapKey/value field; a Go map, unordered
Well-known typesTimestamp, Duration, Empty, Any, FieldMask, Struct, wrappers
AnyA message plus its type URL
FieldMaskList of field paths for partial reads or updates
packageProtobuf namespace, part of the method path
go_packageGo import path and package name of generated code
Unknown fieldsFields a reader does not know; kept in binary, dropped in JSON
protocGoogle's protobuf compiler
bufCLI with its own compiler, linter, breaking checker and dependency management
buf.yaml / buf.gen.yaml / buf.lockModule and rule config / plugin config / pinned dependencies
buf lint / buf breakingStyle checks / compatibility checks against a previous version
BSRBuf Schema Registry, hosts modules like googleapis and protovalidate
protoc-gen-goPlugin that writes *.pb.go messages
protoc-gen-go-grpcPlugin that writes *_grpc.pb.go clients and servers
Generated code shapeThe interfaces, structs and functions the plugins emit
RegisterXxxServerGenerated function that registers an implementation on a grpc.Server
Unimplemented embeddingEmbedding UnimplementedXxxServer for forward compatibility
grpc.NewServerConstructor of the gRPC server
grpc.NewClientConstructor of a lazy ClientConn (grpc-go 1.63+)
ClientConnClient-side virtual connection: resolver, balancer, subchannels
ResolverTurns a target into addresses (dns, passthrough, manual, xds)
round_robin / pick_firstLB policies: rotate over ready backends / use the first that works
Unary RPCOne request, one response
Server / client / bidirectional streamingMany responses / many requests / both, independently
DeadlineAbsolute time by which a call must finish; sent as grpc-timeout
codes.DeadlineExceededStatus code 4: the deadline passed
Status codeOne of 17 outcomes of a call (codes.Code)
status.Error / status.FromErrorBuild a status error / read code, message and details
Error details (errdetails)Typed messages such as BadRequest and RetryInfo in a status
MetadataKey/value headers of a call; incoming and outgoing contexts
Headers / trailersMetadata before the first message / after the last, with the status
InterceptorMiddleware around unary or stream calls, client or server
ChainingRunning several interceptors in a defined order
go-grpc-middleware v2Ecosystem interceptors: logging, auth, recovery, protovalidate, retry
RecoveryInterceptor converting panics to codes.Internal
credentials.NewTLSTransport credentials from a tls.Config
insecure.NewCredentialsPlaintext transport credentials
mTLSBoth sides present certificates
Per-RPC credentialsToken added to each call's metadata
protovalidateRuntime validation of buf.validate rules with CEL
protoc-gen-validate (PGV)Older generated validation, now in maintenance mode
grpc-gatewayGenerated REST/JSON reverse proxy for gRPC services
REST transcodingMapping HTTP routes and JSON to RPCs and messages
google.api.http annotationsOptions that define the REST mapping
OpenAPIAPI description generated by protoc-gen-openapiv2
ProtoJSONCanonical JSON mapping of protobuf (lowerCamel names, int64 as string)
Health servicegrpc.health.v1.Health with Check and Watch
grpc-health-probeCLI that calls the health service, for exec probes
Reflection serviceLets clients fetch the server's schema at runtime
grpcurlcurl for gRPC, uses reflection or .proto files
KeepaliveHTTP/2 pings that detect dead connections
MaxConnectionAgeServer setting that recycles connections with GOAWAY
HTTP/2 multiplexingMany concurrent streams on one connection
Message size limits4 MiB default receive limit; ResourceExhausted when exceeded
bufconnIn-memory listener for testing with the full gRPC stack
connect-goLibrary serving gRPC, gRPC-Web and Connect from net/http
gRPC-WebBrowser-compatible variant of gRPC, usually via a proxy
Versioning compat rulesWhich .proto changes keep old and new readers compatible

References ​

Built by Morteza Negahi