Skip to content

gRPC & Protocol Buffers; REST vs GraphQL vs gRPC ​

"Field numbers should never be reused. Never take a field number out of the reserved list for reuse with a new field definition." — Protocol Buffers Language Guide (proto3), protobuf.dev

Summary: Protocol Buffers is a schema plus a compact binary encoding in which every field is identified by a number, and gRPC is an RPC protocol that carries those messages over HTTP/2 with deadlines, metadata, status codes, streaming, retries and client-side load balancing; together they are the default choice for typed service-to-service calls, while REST and GraphQL usually stay at the public and front-end edges. Focus: proto3 syntax, field numbers, wire types, varint and zigzag, length-delimited fields, field presence (optional, oneof, map, repeated), schema evolution (reserved, unknown fields), well-known types and the JSON mapping; the gRPC call model on HTTP/2 (unary, server streaming, client streaming, bidirectional streaming), deadlines and cancellation, metadata, status codes and rich error details, interceptors, retry and hedging policy in the service config, name resolution and load balancing (pick_first, round_robin, xDS), keepalive, max message size, compression, health checking, reflection, gRPC-Web, grpc-gateway and transcoding, Connect, buf (lint, breaking change detection, BSR), measured performance against JSON, and the REST vs GraphQL vs gRPC decision. Learning goal: Write a .proto contract that can evolve for years without breaking a reader, run it as a gRPC service whose every call has a deadline, a precise status code and a safe retry policy, put it behind a load-balancing setup that actually spreads HTTP/2 traffic, expose it to browsers when needed, and defend in a design review why a given boundary uses REST, GraphQL or gRPC.

This chapter sits in the Networking & Protocols group after HTTP/1.1, HTTP/2, HTTP/3 (the transport gRPC rides on), REST API Design and GraphQL, and before API Versioning & Evolution. It owns the protocol semantics and the system-level decision. Siblings own the rest: encoding families compared side by side (JSON, Protobuf, MessagePack, Avro, CBOR) in Serialization Formats; the hands-on Go deep dive (codegen layout, TLS, validation, gateway wiring) in gRPC & Protobuf in Go; the architecture-level choice between sync and async in Service Communication; retry and backoff mathematics in Timeouts, Retries & Jitter; balancer algorithms in Load Balancing; Protobuf in event streams and schema registries in Message Design & Schema Evolution; sidecars in Service Mesh; and mutual TLS in mTLS.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why a binary schema and an RPC protocol at allWhy it exists
Proto1 to editions, Stubby to gRPC, gRPC-Web, Connect, bufWhere it comes from
.proto files, protoc, protoc-gen-go, generated codeContract and codegen
Field numbers, wire types, varint, zigzag, length-delimitedWire format
optional, oneof, map, repeated, presenceField presence and shapes
reserved, unknown fields, safe and unsafe changesSchema evolution
Timestamp, Duration, Any, Struct, JSON mappingWell-known types and JSON
HTTP/2 framing, grpc-timeout, trailersgRPC on HTTP/2
Unary and the three streaming shapesRPC shapes
Deadlines, cancellation, propagationDeadlines and cancellation
Headers, trailers, -bin keysMetadata
OK to UNAUTHENTICATED, google.rpc.Status detailsStatus codes and rich errors
Middleware for RPCsInterceptors
retryPolicy, hedgingPolicy, retryThrottlingRetries, hedging, service config
Resolvers, pick_first, round_robin, xDS, KubernetesName resolution and load balancing
Keepalive, message size, compression, flow controlConnection knobs
grpc.health.v1, server reflection, grpcurlHealth checking and reflection
Browsers: gRPC-Web, grpc-gateway, Envoy transcoding, ConnectReaching browsers
buf lint, buf breaking, BSRbuf
Size and speed against JSON, with numbersPerformance
Tables of codes, headers and knobsMechanics
CodeGo, Laravel
Classic failures and fixesSolving the classic problems
REST vs GraphQL vs gRPCChoosing
Monolith to distributed systemIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Protocol Buffers in one table.

ConceptIn plain wordsTiny exampleWhat goes wrong without it
Field numberThe real name of a field on the wirestring id = 1;Renumbering silently corrupts old data
Wire typeHow many bytes follow a tag0 VARINT, 1 I64, 2 LEN, 5 I32A reader cannot skip a field it does not know
VarintSmall numbers take few bytes150 is 96 01Fixed 8-byte integers everywhere
Zigzag (sint32/sint64)Small negatives stay small-500 is 2 bytes, not 10Refunds and deltas bloat messages
Length-delimitedStrings, bytes, sub-messages, packed lists0a 03 "EUR"No nesting
optionalTells "not set" from "set to zero"optional string note = 8;0 and "missing" look the same
oneofAt most one of several fieldspickup_store_id or ship_toTwo contradictory fields set
reservedTombstone for deleted numbers and namesreserved 4; reserved "customer_email";Someone reuses 4 for another type
Unknown fieldsFields from a newer writer survive in an older readerOld binary forwards new field 12Data loss in proxies and middle tiers
Well-known typesShared messages for time, durations, anygoogle.protobuf.TimestampEvery team invents its own date format

gRPC in one table.

ConceptIn plain wordsExact knob or wire nameDefault
ChannelLong-lived virtual connection to a service namegrpc.NewClient("dns:///orders:443")Reuse it; never one per call
Unary / streamingOne or many messages per siderpc X(A) returns (stream B)Unary
DeadlineAbsolute "give up" time, sent as a timeoutgrpc-timeout: 800mNone: waits forever
MetadataKey/value headers and trailersx-request-id, authorization, trace-binEmpty
Status code17 codes, carried in trailersgrpc-status: 14 (UNAVAILABLE)OK = 0
Rich error detailsTyped details inside google.rpc.Statusgrpc-status-details-binNone
Retry policyPer-method automatic retryretryPolicy.maxAttempts (capped at 5)Only transparent retries
HedgingParallel copies to cut tail latencyhedgingPolicy.hedgingDelayOff
Load balancingPer-call choice of backendpick_first, round_robin, xDSpick_first
Max message sizeReceive limit per messageMaxRecvMsgSize, grpc.max_receive_message_length4 MiB receive
KeepaliveHTTP/2 PING to detect dead linkskeepalive.ClientParameters.TimeClient off; server ping policy 5 min
HealthStandard service grpc.health.v1.HealthCheck, WatchNot registered

REST vs GraphQL vs gRPC in one table.

AxisREST (HTTP + JSON)GraphQLgRPC (HTTP/2 + Protobuf)
Best boundaryPublic and partner APIsYour own front ends, BFFYour own services
ContractOptional (OpenAPI)Mandatory schema (SDL)Mandatory .proto
BrowserNativeNative (POST or GET)Needs gRPC-Web, Connect or transcoding
StreamingSSE, WebSocket, chunkedSubscriptions (usually WebSocket)Four native shapes
HTTP cachingNative: GET, ETag, CDNHard; persisted queries + GETNone (every call is POST)
ErrorsHTTP status + Problem Detailserrors array, HTTP 20017 status codes + typed details
Payload sizeText, verboseText, only requested fieldsBinary, field numbers
Toolingcurl, browsers, every languageGraphiQL, codegenprotoc/buf codegen, grpcurl, Postman
Client (checkout)Server (orders)HTTP/2 stream 1 (one RPC = one stream)HEADERS:method POST :path /orders.v1.OrderService/GetOrder :scheme httpscontent-type: application/grpc+proto te: trailers grpc-timeout: 800mgrpc-accept-encoding: gzip x-request-id: 9f2c... authorization: Bearer ...(custom metadata = plain HTTP/2 headers; binary keys end in -bin)DATA [END_STREAM]00 | 00 00 00 05 | 0a 03 6f 2d 31 (flag, 4-byte length, GetOrderRequest{id:"o-1"})HEADERS :status 200, content-type: application/grpc, x-served-by: orders-1(response header metadata)DATA00 | 4-byte length N | N bytes of GetOrderResponseHEADERS (trailers) [END_STREAM]grpc-status: 0 grpc-message: (percent-encoded) grpc-status-details-bin: base64The real result is HERE: :status 200 with grpc-status 5 is NOT_FOUND.

The picture is one unary call. A gRPC call is an ordinary HTTP/2 POST on one stream: request headers carry the method path, content-type: application/grpc, the deadline and your metadata; each message is a 5-byte prefix plus Protobuf bytes; and the outcome is in the trailers, not the HTTP status. Everything else on this page builds on those three frames.

Why it exists ​

Two services that call each other thousands of times per second need three things a hand-written JSON-over-HTTP API does not give for free: a machine-checked contract that both sides compile against, an encoding that is cheap to produce and parse, and a call model that knows about deadlines, cancellation, retries and per-call load balancing. Protocol Buffers supplies the first two; gRPC supplies the third on top of HTTP/2. The price is that humans and browsers lose the "open it in a tab and read it" experience that REST with JSON gives.

JSON over HTTP (REST)Protobuf over gRPC
Self-describing text: field names in every messageField numbers only; the schema is needed to read it
Contract optional; drift found in productionContract mandatory; drift found at compile time and by buf breaking
Any client, any browser, curlGenerated stubs; browsers need a bridge
HTTP caching and CDNs workNo HTTP caching; every call is POST
Streaming bolted on (SSE, WebSocket)Four streaming shapes built in
Timeouts per client library, not on the wireDeadline on the wire (grpc-timeout), propagated
Errors: HTTP status + ad hoc bodies17 canonical codes + typed details
Connection-level load balancing worksHTTP/2 multiplexing breaks L4 balancing; needs per-call LB

The analogy we reuse on this page: a numbered customs form. Two border offices share the same printed form. Each box has a number; the clerk writes only in boxes, never the labels, so the form is short. A clerk with last year's form can still process this year's: boxes he does not recognise are stapled on and passed along (unknown fields). If box 4 used to be "email" and is now "loyalty points", every old form in the archive is misread, so retired boxes are blacked out forever (reserved). gRPC is the courier service that carries the forms: every envelope has a "useless after 14:05" stamp (deadline), a sticker area anyone can read (metadata), and a receipt with one of 17 printed outcomes (status code).

Three common misunderstandings, up front ​

  1. "gRPC is fast, so it fixes slow services." The encoding is cheaper than JSON (we measure about 3.5 times smaller and 1.6 times faster to encode for one order on this page), but a database query or a fan-out to five services dwarfs microseconds of encoding. Choose gRPC for the contract, streaming and call semantics; treat speed as a bonus.
  2. "Protobuf is backward compatible automatically." It is compatible only if you follow the rules: never change or reuse a field number, never change a field's wire type, reserve what you delete. A renumbered field compiles cleanly and corrupts data at runtime.
  3. "An HTTP 200 means the call succeeded." In gRPC almost every response is HTTP 200; the result is grpc-status in the trailers. A proxy, log line or dashboard that looks only at HTTP status will report a 100 % success rate while every call returns NOT_FOUND or INTERNAL.

Where it comes from ​

Proto1 and Proto2 at Google, 2001 onward. The protobuf.dev history page: "The initial version of Protobuf ("Proto1") was developed starting in early 2001". Proto2 "was a complete rewrite, though it kept most of the design".

Open source, 2008. "Protobuf was open sourced in 2008 as a way to provide developers outside of Google with the same benefits" (protobuf.dev overview).

Proto3 and editions. Proto3 simplified the language (no required fields, implicit presence by default, later optional restored explicit presence). Editions replace the proto2/proto3 split with per-feature settings: files start with edition = "2023" or edition = "2024", and the editions overview says "The latest released edition is 2024." This page uses syntax = "proto3"; because it is still what most codebases contain; everything here carries over to editions.

Stubby to gRPC, 2015. The gRPC principles post (8 September 2015): "Google has been using a single general-purpose RPC infrastructure called Stubby to connect the large number of microservices running within and across our data centers for over a decade." Stubby was "too tightly coupled to our internal infrastructure", and HTTP/2 made a standards-based successor possible. HTTP/2 itself is now RFC 9113 (2022), see HTTP evolution.

Browsers, gateways and Connect. Browsers cannot read HTTP/2 trailers from JavaScript, so gRPC-Web moved the trailers into the body and is served through a proxy such as Envoy. grpc-gateway generates a REST-to-gRPC reverse proxy from google.api.http annotations; Envoy and Google Cloud offer the same transcoding. Connect (from Buf) implements gRPC, gRPC-Web and its own simple HTTP protocol in one library. Buf also built buf (lint, breaking-change detection, generation) and the Buf Schema Registry (BSR).

text
     Year   Event                                       What changed in practice
1    2001   Proto1 inside Google                         Numbered fields, binary encoding
2    -      Proto2 rewrite                               The design still in use today
3    2008   Protobuf open sourced                        protoc + many languages outside Google
4    -      Proto3                                       Simpler syntax; later explicit optional
5    2015   gRPC announced as Stubby's successor          RPC on HTTP/2, open source
6    -      gRPC-Web, grpc-gateway, Envoy transcoding     Browsers and REST clients reach gRPC
7    -      buf, BSR, Connect                            Lint, breaking checks, registry, simpler protocol
8    2022   RFC 9113 obsoletes RFC 7540 (HTTP/2)          Transport spec refreshed
9    2024   Edition 2024 is the latest released edition   Per-feature behaviour instead of proto2/proto3

Dates with a dash are not stated on the primary pages we read; we do not invent them.

The concept catalogue ​

Every block follows the same order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, how the products differ, and the fix. The running example is orders.v1.OrderService, called by checkout, a mobile BFF and a warehouse importer.

The .proto contract and code generation Must-know ​

In plain words: you write the messages and RPCs once in a .proto file; a compiler (protoc or buf generate) turns it into classes and client/server stubs for every language that talks to the service.

Common misunderstanding: "Generated code is a build artefact, so the .proto file is an implementation detail." The .proto file is the API. It is reviewed like a public interface, versioned in its package name (orders.v1), linted, and checked for breaking changes in CI.

Definition: a .proto file declares syntax (or edition), a package, imports, messages with typed and numbered fields, enums whose first value is zero, and service blocks of rpc methods. protoc parses it and calls plugins: protoc-gen-go writes message types (orders.pb.go), protoc-gen-go-grpc writes the client interface and server registration (orders_grpc.pb.go), grpc_php_plugin writes OrderServiceClient for PHP. buf generate runs the same plugins from a buf.gen.yaml.

text
     Developer                     buf / protoc                          Consumers
1    edits orders/v1/orders.proto
2    buf lint                      STANDARD rules: package version suffix, enum zero value, naming
3    buf breaking --against main   compares against the previous schema
4    buf generate                  protoc-gen-go -> orders.pb.go
5                                  protoc-gen-go-grpc -> orders_grpc.pb.go
6                                  grpc_php_plugin -> Orders/V1/OrderServiceClient.php
7    commit .proto + generated code; Laravel app and Go services build against the same contract

Real scenario: checkout (Go) and the admin panel (Laravel) both read orders; a renamed field shows up as a compile error in both instead of a null in production. A mobile team pulls generated Swift and Kotlin stubs from the BSR instead of hand-writing models. A data team decodes Kafka records with the same .proto the service uses.

What provides it:

ToolRoleNotes
protocReference compilerPlugins found on PATH as protoc-gen-NAME
protoc-gen-go (google.golang.org/protobuf/cmd/protoc-gen-go)Go message typesoption go_package sets the import path
protoc-gen-go-grpc (google.golang.org/grpc/cmd/protoc-gen-go-grpc)Go client and server stubsEmbeds UnimplementedXServer for forward compatibility
grpc_php_plugin + protobuf PHPPHP classes and client stubsPHP is client-only for gRPC
buf generateRuns plugins from buf.gen.yamlLocal or remote plugins (BSR)

Fix / how to use it: keep .proto files in one place (a proto/ tree or a schema repository), one package per directory with a version suffix (orders.v1), lint and breaking-check on every pull request, and commit or publish generated code so consumers never run a different compiler version. The Go deep dive is in gRPC & Protobuf in Go.

proto
// Contract for the running example: an order service called by checkout,
// the mobile BFF and a warehouse importer.
syntax = "proto3";

package orders.v1;

import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";

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

// OrderService shows all four RPC shapes.
service OrderService {
  // Unary: one request, one response.
  rpc GetOrder(GetOrderRequest) returns (GetOrderResponse);
  // Server streaming: one request, many responses.
  rpc ListOrders(ListOrdersRequest) returns (stream ListOrdersResponse);
  // Client streaming: many requests, one response.
  rpc ImportOrders(stream ImportOrdersRequest) returns (ImportOrdersResponse);
  // Bidirectional streaming: both sides send independently.
  rpc TrackOrders(stream TrackOrdersRequest) returns (stream TrackOrdersResponse);
}

enum OrderStatus {
  // Zero value must exist and means "not set".
  ORDER_STATUS_UNSPECIFIED = 0;
  ORDER_STATUS_PENDING = 1;
  ORDER_STATUS_PAID = 2;
  ORDER_STATUS_SHIPPED = 3;
  ORDER_STATUS_CANCELLED = 4;
}

message Money {
  string currency_code = 1;
  // Minor units (cents). sint64 uses zigzag so refunds (negative) stay small.
  sint64 amount_minor = 2;
}

message LineItem {
  string sku = 1;
  int32 quantity = 2;
  Money unit_price = 3;
}

message Order {
  // Field 4 was `string customer_email` in v1; removed for privacy.
  reserved 4;
  reserved "customer_email";

  string id = 1;
  string customer_id = 2;
  OrderStatus status = 3;
  repeated LineItem items = 5;
  Money total = 6;
  google.protobuf.Timestamp created_at = 7;
  // Explicit presence: "no note" differs from "empty note".
  optional string note = 8;
  map<string, string> labels = 9;
  oneof delivery {
    string pickup_store_id = 10;
    Address ship_to = 11;
  }
}

message Address {
  string line1 = 1;
  string city = 2;
  string country_code = 3;
}

message GetOrderRequest {
  string id = 1;
}

message GetOrderResponse {
  Order order = 1;
}

message ListOrdersRequest {
  string customer_id = 1;
  int32 page_size = 2;
}

message ListOrdersResponse {
  Order order = 1;
}

message ImportOrdersRequest {
  Order order = 1;
}

message ImportOrdersResponse {
  int32 accepted = 1;
  int32 rejected = 2;
  google.protobuf.Duration took = 3;
}

message TrackOrdersRequest {
  string order_id = 1;
}

message TrackOrdersResponse {
  string order_id = 1;
  OrderStatus status = 2;
  google.protobuf.Timestamp at = 3;
}

Field numbers, wire types, varint, zigzag, length-delimited Must-know ​

In plain words: on the wire a message is a list of (number, type, value) records; names never travel. Integers use as few bytes as their size needs.

Common misunderstanding: "Field order or names matter for compatibility." Neither does. Only the field number and the wire type matter; you can rename customer_id to buyer_id without breaking binary readers (you will break JSON readers and generated code, see evolution).

Definition: each record starts with a tag varint equal to (field_number << 3) | wire_type. The encoding guide lists "six wire types: VARINT, I64, LEN, SGROUP, EGROUP, and I32": 0 VARINT (int32, int64, uint32, uint64, sint32, sint64, bool, enum), 1 I64 (fixed64, sfixed64, double), 2 LEN (string, bytes, embedded messages, packed repeated fields), 3/4 groups (deprecated), 5 I32 (fixed32, sfixed32, float). A varint stores 7 bits per byte, least significant group first, with the high bit meaning "more bytes follow". intN stores negatives as two's complement, which "means that all ten bytes must be used"; sintN uses zigzag: "Positive integers p are encoded as 2 * p (the even numbers), while negative integers n are encoded as 2 * |n| - 1". LEN records carry a varint length, then the bytes; a string or bytes field can hold up to 2 GB. Field numbers range from 1 to 536,870,911; 19,000 to 19,999 are reserved for the implementation; "field numbers in the range 1 through 15 take one byte to encode".

0a0345555210e707Money { currency_code: "EUR", amount_minor: -500 } = 8 bytestaglength 3"E" "U" "R" (UTF-8)tagvarint 999 = zigzag(-500)0x0a = 0000 1010field 1 = 00001 | wire type 2 (LEN) = 010tag = (field_number << 3) | wire_type0x10 = field 2 | wire type 0 (VARINT)e7 07: low 7 bits first, MSB = "more bytes"0x67 + (0x07 << 7) = 103 + 896 = 999What is NOT on the wire: field names, types, schema versionA reader maps number -> field with ITS copy of the .proto. Reusing number 2 for another type breaks every old reader.Same -500 as int64 (two's complement) costs 10 bytes; as sint64 (zigzag) it costs 2. Numbers 1-15 have 1-byte tags.Wire types: 0 VARINT, 1 I64, 2 LEN, 3/4 groups (deprecated), 5 I32.
text
     Encoder (Money{currency_code:"EUR", amount_minor:-500})      Decoder with the same .proto
1    tag 1<<3|2 = 0x0a                                             0x0a -> field 1, LEN
2    length 3 = 0x03, then 45 55 52                                 reads 3 bytes -> "EUR"
3    tag 2<<3|0 = 0x10                                             0x10 -> field 2, VARINT
4    zigzag(-500) = 999 -> varint e7 07                            999 -> unzigzag -> -500
5    total 8 bytes; as int64 the -500 alone would need 10 bytes

Real scenario: a refunds service stores signed deltas; switching them from int64 to sint64 (a breaking change, so done in a new field) cut each negative from 10 bytes to 1 to 3. A telemetry message with 40 fields keeps the 15 hottest in numbers 1 to 15 so each tag is one byte. A debugging session reads a captured hex dump by hand with the tag formula.

What differs by type:

Proto typeWire typeNegative -1 costsUse for
int32 / int64VARINT10 bytesCounters that are almost never negative
sint32 / sint64VARINT (zigzag)1 byteValues often negative: deltas, refunds, offsets
uint32 / uint64VARINTnot allowedSizes, ids that are never negative
fixed32 / fixed64I32 / I64n/aValues usually large (hashes)
sfixed32 / sfixed64I32 / I644 / 8 bytesLarge signed values
double / floatI64 / I328 / 4 bytesMeasurements; never money
string / bytes / messageLENn/aText must be valid UTF-8 for string

Fix / how to use it: give the most frequently set fields numbers 1 to 15; use sint64 for values that go negative; store money as integer minor units plus a currency code, never double; and check the bytes yourself with protowire when in doubt (the Go section's wire package does exactly that and its test asserts 0a03455552 10e707).

go
// Package wire encodes a tiny message by hand with protowire so the bytes
// on the page can be checked against proto.Marshal.
package wire

import "google.golang.org/protobuf/encoding/protowire"

// Varint returns the base-128 varint encoding of v.
func Varint(v uint64) []byte { return protowire.AppendVarint(nil, v) }

// ZigZag maps signed to unsigned so small negatives stay short:
// 0->0, -1->1, 1->2, -2->3.
func ZigZag(v int64) uint64 { return protowire.EncodeZigZag(v) }

// Tag is (field_number << 3) | wire_type, itself a varint.
func Tag(field protowire.Number, t protowire.Type) []byte {
	return protowire.AppendTag(nil, field, t)
}

// Money encodes orders.v1.Money{currency_code, amount_minor} by hand.
func Money(currency string, amountMinor int64) []byte {
	var b []byte
	b = protowire.AppendTag(b, 1, protowire.BytesType) // LEN
	b = protowire.AppendString(b, currency)
	b = protowire.AppendTag(b, 2, protowire.VarintType) // sint64 -> zigzag varint
	b = protowire.AppendVarint(b, protowire.EncodeZigZag(amountMinor))
	return b
}

Field presence and shapes: implicit, optional, oneof, map, repeated Must-know ​

In plain words: a proto3 scalar without optional cannot tell "set to 0" from "not set"; optional adds that difference; oneof allows at most one field of a group; repeated is a list; map is a dictionary.

Common misunderstanding: "If the client did not send discount_percent, the server sees null." With implicit presence it sees 0, and "you cannot determine whether the default (zero) value was set or parsed from the wire or not provided at all" (proto3 guide). A PATCH-style update that treats 0 as "not provided" can never set a discount to zero.

Definition: proto3 singular fields are either implicit (zero values are not serialized, no "has" method) or optional ("recommended", explicit presence with a has/pointer accessor). Message-typed fields always have presence. oneof fields share presence: setting one clears the others; "Moving fields into an existing oneof is not safe." repeated scalars are packed by default (one LEN record). map<K, V> keys can be any integral or string type, values anything but another map; "Map fields cannot be repeated" and "Wire format ordering and map iteration ordering of map values is undefined".

text
     Client (mobile app)                                   Server (orders)
1    UpdateNote{note: ""} with implicit string note         sees "" -> cannot tell "clear" from "untouched"
2    switch to optional string note = 8 (same number, compatible on the wire)
3    UpdateNote{} (note unset)                              HasNote == false -> leave note alone
4    UpdateNote{note: ""}                                   HasNote == true, value "" -> clear the note
5    delivery oneof: set ship_to                            pickup_store_id automatically cleared

Real scenario: partial updates (PATCH-like RPCs) where zero is a valid value (stock 0, discount 0 %); delivery choice "pickup or shipping, never both"; product labels as map<string, string>; line items as repeated LineItem.

How languages expose presence:

Languageoptional scalaroneofmap iteration
Go (protoc-gen-go)Pointer field *string, GetNote() returns "" when nilInterface field with wrapper types (Order_PickupStoreId)Go map, random order
PHP (protobuf)hasNote(), clearNote()getDelivery() returns the set field's nameMapField, undefined order
JSON mappingField omitted when unsetOnly the set field appearsJSON object

Fix / how to use it: use optional for every scalar whose zero value is meaningful; use oneof for mutually exclusive choices from day one (moving fields into a oneof later is unsafe); for partial updates prefer a google.protobuf.FieldMask naming the fields to change; never rely on map order.

Schema evolution: reserved, unknown fields, safe and unsafe changes Must-know ​

In plain words: you can add fields forever; you must never change what an existing number means. When you delete a field, you lock its number and name so nobody can reuse them.

Common misunderstanding: "We deleted field 4 and nobody uses it, so it is free." Old messages in Kafka, caches, databases and mobile apps still contain field 4. The proto3 guide lists what reuse leads to: "A parse/merge error (best case scenario)", "Leaked PII/SPII", "Data corruption".

Definition: binary wire-safe changes: adding fields, deleting fields (with reserved), renaming fields (binary only), adding enum values (beware exhaustive switches). Wire-unsafe: "Changing field numbers for any existing field is not safe", changing a field to an incompatible wire type, "Moving fields into an existing oneof". reserved 4, 9 to 11; and reserved "customer_email"; make the compiler reject reuse; reserved names "affect only the protoc compiler behavior and not runtime". Unknown fields: "Proto3 messages preserve unknown fields and include them during parsing and in the serialized output"; they are lost when you "Serialize a proto to JSON" or copy field by field. The JSON format has different safe changes: a rename breaks JSON readers because names are on the wire there.

text
     v1 writer (old app)          broker / DB (bytes at rest)        v2 reader (new service)
1    Order{id, customer_email=4}  stored                              4 is reserved in v2: skipped as unknown
2    v2 author adds loyalty_points = 4 (int64) by mistake
3                                 old bytes: field 4 = LEN "a@x"      v2 parses 4 as VARINT -> parse error
4                                 or worse: same wire type             wrong value silently accepted
5    with "reserved 4;" step 2 fails at compile time; buf breaking also fails in CI

Real scenario: a mobile app version from two years ago still sends v1 messages; an event archive in Kafka replays years of records; a Go proxy in the middle that only knows v1 must forward v2 fields untouched (unknown fields); a team "tidies" field numbers into sequence and breaks every stored record.

Change table:

ChangeBinary wireJSON mappingGenerated codebuf breaking category that flags it
Add a field with a new numberSafeSafeSafenone
Delete a field and reserved its number + nameSafeSafe if name reservedBreaks users of the fieldFILE, PACKAGE (deletion)
Delete without reservedSafe now, unsafe laterUnsafe laterBreaks usersWIRE too ("without reserving the number")
Rename a fieldSafeBreaks (json_name changes)BreaksFILE, PACKAGE, WIRE_JSON
Change a field numberUnsafeUnsafeBreaksall four
int32 to int64Compatible (truncation risk)SafeBreaks typesFILE, PACKAGE
int64 to sint64Unsafe (encoding differs)SafeBreaks typesall
Move a field into an existing oneofUnsafeUnsafeBreaksall
Add an enum valueSafe (unknown values preserved)Old readers see the numberExhaustive switches breaknone
Remove reserved entriesUnsafeUnsafen/aall four

Fix / how to use it: never renumber; reserved every deleted number and name in the same commit; keep a field's type; run buf breaking --against '.git#branch=main' in CI; create orders.v2 only when the meaning changes, not to rename fields; keep proxies binary so unknown fields survive. Versioning strategy across API styles is in API Versioning.

Well-known types and the JSON mapping Important ​

In plain words: Google ships standard messages for common needs (Timestamp, Duration, Any, Struct, wrappers, FieldMask, Empty), and every Protobuf message has an official JSON form.

Common misunderstanding: "The JSON mapping is just json.Marshal of the generated struct." It has its own rules: field names become lowerCamelCase, 64-bit integers become strings, enums become their names, Timestamp becomes RFC 3339 text and Duration a decimal number of seconds with an s suffix. Use protojson (Go) or serializeToJsonString() (PHP), not a generic JSON library.

Definition: the JSON guide's table: message → object, "Keys are serialized as lowerCamelCase of field name"; enum → string, "The name of the enum value as specified in proto is used"; int64, fixed64, uint64 → string, "JSON value will be a decimal string"; Any → {"@type": "url", ...}; Timestamp → "1972-01-01T10:00:20.021Z" ("Uses RFC 3339", Z-normalized); Duration → "1.000340012s", "1s"; Struct → "Any JSON object". Any packs an arbitrary message with its type URL; Struct/Value hold schemaless JSON inside a typed message.

text
     Go service                                         JSON consumer (browser via transcoding)
1    Order{created_at: Timestamp(2026-11-26T09:00Z), total.amount_minor: 4999 (sint64)}
2    protojson.Marshal                                  {"createdAt":"2026-11-26T09:00:00Z",
3                                                        "total":{"amountMinor":"4999",...}}
4                                                       JavaScript parses "4999" as a string: no 2^53 precision loss
5    a client sends {"amountMinor": 4999}               protojson accepts numbers or strings on input

Real scenario: a transcoded REST endpoint for a partner shows "amountMinor":"4999" and the partner asks why money is a string (answer: 64-bit precision in JavaScript); an audit service stores google.protobuf.Struct for free-form attributes; an event envelope uses Any to carry differently typed payloads.

Common well-known types:

TypeUseJSON form
google.protobuf.TimestampA point in time (seconds + nanos since epoch, UTC)RFC 3339 string
google.protobuf.DurationA span of time"1.5s"
google.protobuf.AnyAny message plus its type URLObject with @type
google.protobuf.Struct / Value / ListValueSchemaless JSONPlain JSON
google.protobuf.FieldMaskWhich fields a partial update touches"note,labels"
google.protobuf.EmptyNo request or response data{}
Wrappers (StringValue, Int64Value, ...)Presence before proto3 optional existedThe bare value

Fix / how to use it: use Timestamp and Duration instead of strings or epoch integers; prefer typed fields over Struct and Any (they defeat the contract); prefer optional over wrapper types in new schemas; serialize with protojson and remember that JSON drops unknown fields.

go
package wire

import (
	"bytes"
	"encoding/hex"
	"testing"

	ordersv1 "academy/grpc-protobuf/gen/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/timestamppb"
)

func TestVarintAndZigZag(t *testing.T) {
	cases := map[uint64]string{1: "01", 127: "7f", 128: "8001", 150: "9601", 300: "ac02"}
	for v, want := range cases {
		if got := hex.EncodeToString(Varint(v)); got != want {
			t.Errorf("varint(%d)=%s want %s", v, got, want)
		}
	}
	for v, want := range map[int64]uint64{0: 0, -1: 1, 1: 2, -2: 3, -500: 999} {
		if got := ZigZag(v); got != want {
			t.Errorf("zigzag(%d)=%d want %d", v, got, want)
		}
	}
	if got := hex.EncodeToString(Tag(1, protowire.VarintType)); got != "08" {
		t.Errorf("tag 1 varint=%s", got)
	}
	if got := hex.EncodeToString(Tag(2, protowire.BytesType)); got != "12" {
		t.Errorf("tag 2 LEN=%s", got)
	}
}

func TestHandEncodingMatchesMarshal(t *testing.T) {
	want, err := proto.MarshalOptions{Deterministic: true}.Marshal(&ordersv1.Money{CurrencyCode: "EUR", AmountMinor: -500})
	if err != nil {
		t.Fatal(err)
	}
	got := Money("EUR", -500)
	if !bytes.Equal(got, want) {
		t.Fatalf("hand %x marshal %x", got, want)
	}
	if hex.EncodeToString(got) != "0a03455552"+"10e707" {
		t.Fatalf("unexpected bytes %x", got)
	}
}

// Fields a reader does not know survive a round trip (unknown fields).
func TestUnknownFieldsArePreserved(t *testing.T) {
	newer := Money("EUR", 100)
	newer = protowire.AppendTag(newer, 3, protowire.VarintType) // field 3 added by a newer writer
	newer = protowire.AppendVarint(newer, 1)
	var older ordersv1.Money
	if err := proto.Unmarshal(newer, &older); err != nil {
		t.Fatal(err)
	}
	if len(older.ProtoReflect().GetUnknown()) == 0 {
		t.Fatal("unknown field dropped")
	}
	again, _ := proto.Marshal(&older)
	if !bytes.Equal(again, newer) {
		t.Fatalf("round trip lost data: %x vs %x", again, newer)
	}
}

func TestJSONMapping(t *testing.T) {
	o := &ordersv1.Order{
		Id:        "o-1",
		Status:    ordersv1.OrderStatus_ORDER_STATUS_PAID,
		Total:     &ordersv1.Money{CurrencyCode: "EUR", AmountMinor: 4999},
		CreatedAt: timestamppb.New(timestamppb.Now().AsTime().Truncate(0)),
	}
	b, err := protojson.Marshal(o)
	if err != nil {
		t.Fatal(err)
	}
	// lowerCamelCase names, enum as string, int64 as a JSON string.
	for _, frag := range []string{`"createdAt"`, `"ORDER_STATUS_PAID"`, `"amountMinor":"4999"`} {
		if !bytes.Contains(bytes.ReplaceAll(b, []byte(" "), nil), []byte(frag)) {
			t.Errorf("json %s missing %s", b, frag)
		}
	}
}

gRPC on HTTP/2: channels, streams and framing Must-know ​

In plain words: a gRPC client keeps one or a few HTTP/2 connections open to each backend and runs every call as one HTTP/2 stream on them; many calls share one connection at the same time.

Common misunderstanding: "Opening a gRPC connection per request is fine, HTTP/2 is cheap." Each new channel pays DNS resolution, TCP and TLS handshakes and HTTP/2 setup, and loses load-balancing state. The performance guide's first rule: "Always re-use stubs and channels when possible."

Definition: a channel (*grpc.ClientConn in Go) is a virtual connection to a target name; it owns a resolver, a load-balancing policy and subchannels (one HTTP/2 connection per backend address). Each RPC is one HTTP/2 stream: request headers (:method POST, :path /orders.v1.OrderService/GetOrder, te: trailers, content-type: application/grpc, optional grpc-timeout, grpc-encoding, custom metadata), zero or more length-prefixed messages (1-byte compressed flag, 4-byte big-endian length, message), then the response headers, messages and trailers (grpc-status, grpc-message, grpc-status-details-bin). A Trailers-Only response sends just the status. Servers that get a non-gRPC content type "SHOULD respond with HTTP status of 415".

text
     Client channel (one TCP+TLS connection to orders-1)
1    stream 1: GetOrder        HEADERS -> DATA(END_STREAM)    <- HEADERS, DATA, trailers grpc-status 0
2    stream 3: ListOrders      HEADERS -> DATA                <- DATA, DATA, DATA, trailers
3    stream 5: GetOrder        interleaved with 1 and 3 on the same connection (multiplexing)
4    stream N+1 over the limit  waits in the client (limit = peer SETTINGS_MAX_CONCURRENT_STREAMS, e.g. 100)
5    GOAWAY from server        new streams go to a new connection; in-flight ones finish

Real scenario: a checkout pod with 400 concurrent RPCs to the pricing service hits the per-connection stream limit and queues in the client (the performance guide's "Special topic"); an AWS ALB or NGINX proxy that does not support end-to-end HTTP/2 and trailers breaks gRPC; a server deploy sends GOAWAY and clients migrate without errors.

Which proxies carry gRPC:

ProductgRPC supportNotes
Envoy (and Istio, which uses it)Native HTTP/2, per-stream balancing, gRPC-Web filter, JSON transcoderThe reference gRPC proxy
NGINXgrpc_pass moduleNeeds HTTP/2 on the listener
HAProxyHTTP/2 end-to-end modeConfigure proto h2 to the backend
AWS ALBgRPC target groupsL7; NLB is L4 and balances connections only
Google Cloud Load BalancingHTTP/2 backendsTraffic Director adds xDS
LinkerdTransparent per-request gRPC balancingSidecar proxy

Fix / how to use it: create one channel per target at startup and share it; let the server's MaxConnectionAge rotate connections; if one connection's stream limit is the bottleneck, use separate channels per hot area; put only HTTP/2-capable L7 proxies in the path. The HTTP/2 framing itself (streams, HPACK, flow control) is explained in HTTP evolution.

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

In plain words: one request and one response (unary); one request, many responses (server streaming); many requests, one response (client streaming); both sides send whenever they like (bidirectional streaming).

Common misunderstanding: "Streaming is always faster, so use it everywhere." The performance guide warns that streams "cannot be load balanced once they have started and can be hard to debug", and "might increase performance at a small scale but can reduce scalability". Use streams for flows that are naturally long-lived, not to shave per-call overhead.

Definition: declared with the stream keyword: rpc GetOrder(A) returns (B), rpc ListOrders(A) returns (stream B), rpc ImportOrders(stream A) returns (B), rpc TrackOrders(stream A) returns (stream B). In a bidirectional call "the two streams operate independently, so clients and servers can read and write in whatever order they like" (core concepts). Order is preserved within each direction of a stream. The whole stream shares one deadline and one final status.

text
     Unary          C: GetOrder{id}            -> S: Order + status OK
     Server stream  C: ListOrders{customer}    -> S: Order, Order, Order ... + status OK (trailers)
     Client stream  C: Import, Import, Import, CloseSend  -> S: ImportSummary{accepted:2, rejected:1}
     Bidi           C: Track{o-1}  S: Event{o-1 PAID}
                    C: Track{o-2}  S: Event{o-2 SHIPPED}
                    C: CloseSend   S: status OK

Real scenario: unary for GetOrder, ReserveStock, Authorize; server streaming for exporting a customer's order history or pushing price ticks; client streaming for a warehouse uploading scanned parcels in batches; bidirectional streaming for chat, live tracking, or a long-lived control channel (xDS itself is a bidi stream).

Support by platform:

PlatformUnaryServer streamingClient streamingBidi
gRPC over HTTP/2 (Go, Java, C++, ...)YesYesYesYes
gRPC PHP extension (client only)YesYesYesYes
gRPC-Web in browsersYesYes (grpcwebtext mode)NoNo
Connect protocolYes (also GET)YesNeeds HTTP/2Needs HTTP/2
grpc-gateway / Envoy JSON transcodingYesYes (newline-delimited JSON)LimitedNo

Fix / how to use it: start every method as unary; choose a stream when the data is a sequence in time or too big for one message; always check the stream context in server loops so a cancelled client stops the work; keep stream lifetimes bounded (reconnect every few minutes) so load balancing still happens. The Go server implements all four.

Deadlines and cancellation Must-know ​

In plain words: every call carries "I stop caring at time T"; when T passes or the caller hangs up, everybody working on the call, on every hop, should stop.

Common misunderstanding: "gRPC has a sensible default timeout." It has none: "By default, gRPC does not set a deadline which means it is possible for a client to end up waiting for a response effectively forever." A second misunderstanding: "When the deadline passes, the server stops my handler." The server library marks the call cancelled, but "the server application is responsible for stopping any activity it has spawned".

Definition: a deadline is an absolute point in time; on the wire it travels as a relative grpc-timeout header (value up to 8 digits plus a unit H, M, S, m, u, n), so clock skew does not matter: gRPC "converts the deadline to a timeout from which the already elapsed time is already deducted". When it expires the client fails with DEADLINE_EXCEEDED and the server sees a cancelled context (CANCELLED). Deadline propagation is automatic in Go and Java when you pass the incoming context to outgoing calls. Cancellation by the client (closing the context) is sent to the server as an HTTP/2 RST_STREAM. DEADLINE_EXCEEDED "may be returned even if the operation has completed successfully".

text
     Mobile BFF (budget 800 ms)     Checkout                     Orders                  PostgreSQL
1    ctx deadline t+800ms
2    -> Checkout grpc-timeout 795m
3                                   work 100 ms
4                                   -> Orders grpc-timeout 690m  (same ctx: propagated)
5                                                                query with ctx
6    user closes the app at t+300   RST_STREAM                    ctx.Done() fires          query cancelled
7    nobody keeps working for a user who left; with no deadline steps 3-5 would run to completion

Real scenario: a payment provider hangs; without deadlines checkout goroutines pile up until the pod is OOM-killed; with an 800 ms budget they fail fast and a fallback renders. A report RPC keeps scanning the database after the browser tab is closed because the handler ignores ctx.Done(). A retry after DEADLINE_EXCEEDED on CreateOrder produces a duplicate order because the first attempt actually succeeded.

Per stack:

StackSet a deadlinePropagationWhat the handler must do
Go (grpc-go)context.WithTimeout(ctx, d)Automatic when you pass the incoming ctxselect on ctx.Done(), pass ctx to SQL and HTTP
Javastub.withDeadlineAfter(...)Automatic via ContextCheck Context.current().isCancelled()
C++ClientContext::set_deadlineMust be enabled explicitlyCheck ServerContext::IsCancelled()
PHP extension['timeout' => microseconds] call optionManual (PHP is client-only)n/a
Service configmethodConfig.timeoutDefault per method when the caller sets nonen/a

Fix / how to use it: derive every outgoing deadline from the user's budget (Latency budgets); pass the incoming context downstream; check ctx.Err() in loops and pass ctx to every I/O call; treat DEADLINE_EXCEEDED on writes as "unknown outcome" and retry only with an idempotency key (API Idempotency). Budget arithmetic per hop is in Service Communication.

Metadata: headers, trailers and binary keys Important ​

In plain words: metadata is the gRPC name for HTTP/2 headers: key/value pairs sent before the first message (headers) or with the final status (trailers).

Common misunderstanding: "Put the user id or tenant in metadata and the server will validate it." Metadata is caller-controlled input exactly like HTTP headers; trust it only after authentication (mTLS identity or a verified token).

Definition: "gRPC metadata is implemented using HTTP/2 headers. The keys are ASCII strings, while the values can be either ASCII strings or binary data." Keys are case-insensitive, "must not start with the prefix grpc-", and binary values use keys ending in -bin (base64 on the wire). Headers go before the first message in each direction; "Trailers are sent by the server when it closes an RPC." Servers "may limit the size of Request-Headers, with a default of 8 KiB suggested."

text
     Client                                    Server
1    headers: authorization, x-request-id, traceparent
2                                              interceptor reads x-request-id, verifies token
3                                              grpc.SetHeader(x-served-by: orders-1)
4    <- response headers (x-served-by)
5    <- messages
6                                              stream.SetTrailer(x-total: done)
7    <- trailers: grpc-status 0, x-total

Real scenario: a bearer token in authorization; W3C traceparent for tracing; x-request-id for log correlation; a server returning x-served-by or rate-limit counters in trailers; grpc-retry-pushback-ms from the server telling clients when to retry.

Metadata APIs:

StackSend (client)Read (server)Send header / trailer (server)
Gometadata.AppendToOutgoingContext(ctx, k, v)metadata.FromIncomingContext(ctx)grpc.SetHeader, grpc.SetTrailer / stream.SetTrailer
PHPSecond argument of the stub method: ['k' => ['v']]n/a (client only)Client reads $call->getMetadata(), trailers in $status->metadata
Envoyrequest_headers_to_addHeader matching in routesresponse_headers_to_add

Fix / how to use it: keep metadata small and for cross-cutting data (auth, tracing, correlation, tenancy after verification); put business data in the message; add standard keys in an interceptor rather than in every call.

Status codes and rich error details Must-know ​

In plain words: every gRPC call ends with one of 17 numbered codes plus a message, and optionally a list of typed details such as "field id is empty" or "retry after 2 s".

Common misunderstanding: "Use UNKNOWN or INTERNAL for everything and put the reason in the message." Callers cannot branch on prose. Another one: "NOT_FOUND, INVALID_ARGUMENT may come from the library." The status-code page is explicit: these "are never generated by the library, only by user code": INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS, FAILED_PRECONDITION, ABORTED, OUT_OF_RANGE, DATA_LOSS. If you see one, your application (or the server's) produced it.

Definition: codes 0 to 16 (full table in Mechanics): OK 0, CANCELLED 1, UNKNOWN 2, INVALID_ARGUMENT 3, DEADLINE_EXCEEDED 4, NOT_FOUND 5, ALREADY_EXISTS 6, PERMISSION_DENIED 7, RESOURCE_EXHAUSTED 8, FAILED_PRECONDITION 9, ABORTED 10, OUT_OF_RANGE 11, UNIMPLEMENTED 12, INTERNAL 13, UNAVAILABLE 14, DATA_LOSS 15, UNAUTHENTICATED 16. The guidance for the three retry-related codes: "(a) Use UNAVAILABLE if the client can retry just the failing call. (b) Use ABORTED if the client should retry at a higher level ... (c) Use FAILED_PRECONDITION if the client should not retry until the system state has been explicitly fixed." Rich error details (the "richer error model") serialize a google.rpc.Status with details (an array of Any: BadRequest, ErrorInfo, RetryInfo, QuotaFailure, ResourceInfo, PreconditionFailure, DebugInfo, Help, LocalizedMessage) into the grpc-status-details-bin trailer. Google's AIP-193 requires that "All error responses must include an ErrorInfo within details".

text
     Client                                      Orders server
1    GetOrder{id:""}
2                                                status INVALID_ARGUMENT "id is required"
3                                                + BadRequest{field_violations:[{field:"id", ...}]}
4    Explain(err): code=InvalidArgument, retry=false, detail="id: must be a non-empty order id"
5    GetOrder{id:"o-404"}                        NOT_FOUND + ResourceInfo{orders.v1.Order/o-404}
6    GetOrder{id:"o-1"} during deploy            UNAVAILABLE -> retry policy retries -> OK

Real scenario: the BFF maps INVALID_ARGUMENT + BadRequest to a 400 with per-field form errors; a rate-limited caller gets RESOURCE_EXHAUSTED + RetryInfo and backs off exactly as told; an optimistic-locking conflict returns ABORTED so the caller re-reads and retries the whole read-modify-write; dashboards alert on the rate of INTERNAL and UNKNOWN, not on HTTP 5xx.

HTTP mapping used by grpc-gateway (runtime.HTTPStatusFromCode):

gRPC codeHTTP (grpc-gateway / Google APIs mapping)Retry?
OK200n/a
INVALID_ARGUMENT, FAILED_PRECONDITION, OUT_OF_RANGE400No
UNAUTHENTICATED401After refreshing credentials
PERMISSION_DENIED403No
NOT_FOUND404No
ALREADY_EXISTS, ABORTED409ABORTED: retry the whole transaction
RESOURCE_EXHAUSTED429With backoff, honour RetryInfo
CANCELLED499 (non-standard "client closed")No (the caller gave up)
UNIMPLEMENTED501No
UNAVAILABLE503Yes, with backoff (idempotent only)
DEADLINE_EXCEEDED504Only if idempotent; outcome unknown
INTERNAL, UNKNOWN, DATA_LOSS500No

Fix / how to use it: return the most specific code; attach BadRequest for validation, ResourceInfo for missing resources, RetryInfo for throttling, ErrorInfo with a stable reason for machine handling; never leak stack traces (use DebugInfo only internally); branch on codes and details in clients, never on message text. The Go client's Explain is the pattern.

Interceptors Important ​

In plain words: interceptors are middleware for RPCs: code that runs around every call on the client or the server.

Common misunderstanding: "Interceptors are only for logging." They are the place for authentication, metadata injection, deadline defaults, metrics, tracing, retries in languages without service-config retries, panic recovery and fault injection. The guide calls them "filters" or "middleware" by another name.

Definition: gRPC-Go has four kinds: grpc.UnaryServerInterceptor, grpc.StreamServerInterceptor, grpc.UnaryClientInterceptor, grpc.StreamClientInterceptor, chained with grpc.ChainUnaryInterceptor / grpc.WithChainUnaryInterceptor. A unary interceptor gets the context, request, method info and the next handler; a stream interceptor wraps the ServerStream and must wrap RecvMsg/SendMsg to see individual messages.

text
     Client call                Client chain              wire        Server chain                  Handler
1    o.Get(ctx,"o-1")           RequestID adds x-request-id
2                               otel adds traceparent      ----->     auth checks token
3                                                                     RequestIDUnary logs start
4                                                                                                   GetOrder
5                                                          <-----     RequestIDUnary logs code=OK took=0.3ms

Real scenario: an auth interceptor rejects missing tokens with UNAUTHENTICATED before any handler runs; OpenTelemetry's gRPC instrumentation records grpc.server.call.duration; a recovery interceptor turns a panic into INTERNAL instead of crashing the process; a chaos interceptor injects UNAVAILABLE for 1 % of calls in staging.

Ecosystem:

StackMechanismReady-made examples
GoUnary/stream, client/server interceptorsgo-grpc-middleware (auth, logging, recovery, ratelimit), OpenTelemetry otelgrpc stats handler
JavaClientInterceptor, ServerInterceptorBuilt-in deadline and metadata utilities
PHPGrpc\Interceptor + Interceptor::intercept($channel, ...)Custom metadata and logging
Envoy / meshHTTP filters in the proxyRetries, mTLS, rate limiting outside the app

Fix / how to use it: keep interceptors small and ordered (auth before logging of user data, recovery outermost); put defaults (deadline, request id) in client interceptors; do not do business logic there.

Retries, hedging and the service config Must-know ​

In plain words: the client can be told, per method, "retry these codes up to N times with backoff" or "send a second copy if the first is slow"; that policy lives in a JSON document called the service config.

Common misunderstanding: "Retries are off unless I configure them." "Retries are enabled by default, but there is no default retry policy": gRPC still does transparent retries when it is sure the server application never saw the request. Another: "I can retry anything." A retry policy on a non-idempotent write duplicates side effects.

Definition: the service config is "a mechanism that allows service owners to publish parameters to be automatically used by all clients of their service", provided by the resolver (for example DNS TXT records) or as a client default (grpc.WithDefaultServiceConfig). methodConfig entries match service/method names and hold timeout, waitForReady, maxRequestMessageBytes, maxResponseMessageBytes, and either a retryPolicy or a hedgingPolicy. retryPolicy: maxAttempts ("Values greater than 5 are treated as 5"), initialBackoff, maxBackoff, backoffMultiplier, retryableStatusCodes; "Jitter of plus or minus 20% is applied". Once response headers arrive "the RPC is committed. No further retries will be attempted". hedgingPolicy: maxAttempts, hedgingDelay, nonFatalStatusCodes; "gRPC call deadlines apply to the entire chain of hedged requests". retryThrottling (maxTokens, tokenRatio): failures cost 1 token, successes add tokenRatio, and when the count falls below half of maxTokens retries pause. Servers can push back with the grpc-retry-pushback-ms trailer.

text
     Client (retryPolicy maxAttempts 4, initialBackoff 50ms, UNAVAILABLE)     Orders pods
1    attempt 1 -> orders-1                                                  UNAVAILABLE (warming up)
2    wait ~50ms (+/-20%)
3    attempt 2 -> orders-2 (round_robin)                                    UNAVAILABLE
4    wait ~100ms
5    attempt 3 -> orders-3                                                  headers received -> committed
6    application sees OK; the test TestRetryPolicyHidesTransientUnavailable takes ~0.15 s for this

Real scenario: rolling deploys produce brief UNAVAILABLE that a retry policy hides; a search fan-out uses hedging with hedgingDelay near p95 to cut the tail (Dean and Barroso's idea, see Tail latency); a payment Capture method gets no retry policy at all and relies on an idempotency key.

Retry options compared:

WhereConfigurationGood forWatch out
gRPC client service configretryPolicy per methodTransient UNAVAILABLE on idempotent methodsMultiplies with retries in other layers
gRPC hedginghedgingPolicy per methodTail latency on readsExtra load; only idempotent methods
Envoy / Istio routeretry_policy with retry_on: unavailable,resource-exhaustedLanguage-independentDouble retries with the client
Application loop (PHP retry())CodeLanguages without service-config retriesMust respect the deadline

Fix / how to use it: retry only idempotent methods, only on UNAVAILABLE (and RESOURCE_EXHAUSTED with RetryInfo), with retryThrottling on; pick one layer for retries (client or mesh, not both); keep maxAttempts small (3 to 4); never put retry policies on writes without idempotency keys. Backoff and budget theory lives in Timeouts, Retries & Jitter.

Name resolution and load balancing: pick_first, round_robin, xDS Must-know ​

In plain words: the client turns a name into a list of addresses (name resolver), then a load-balancing policy picks a backend for each call. With HTTP/2 this has to happen in the client or in an L7 proxy, because a classic L4 balancer only sees one long connection.

Common misunderstanding: "Kubernetes Services load balance my gRPC traffic." A ClusterIP Service is L4: it balances connections, and the Kubernetes blog notes that gRPC "also breaks the standard connection-level load balancing" because "HTTP/2 is designed to have a single long-lived TCP connection". Scale from 3 to 10 pods and the 7 new pods get no traffic until clients reconnect.

Definition: targets are URIs; "If no scheme prefix is specified or the scheme is unknown, the dns scheme is used by default" (dns:///orders.internal:443, unix:///path, xds:///orders). Go's grpc.NewClient also defaults to dns. The resolver returns addresses plus a service config. "Load-balancing within gRPC happens on a per-call basis, not a per-connection basis." Policies: pick_first ("the default LB policy if the service config does not specify any LB policy"; connects to the first reachable address and sends everything there), round_robin (a subchannel to every address, calls rotate), grpclb ("deprecated"; replaced by xDS), and xDS: the client speaks Envoy's xDS APIs to a control plane (Istio's istiod, Google Traffic Director) and receives endpoints, weights and policies without a sidecar ("proxyless"). A gRPC xDS client "will simply ignore the configuration of a feature it does not support".

1. L4 (connection)2. Client-side3. L7 proxy4. Proxyless xDSClusterIP, AWS NLBdns:/// + round_robinEnvoy, Linkerd, Istioxds:/// + istiod / TDclientclientclientclientL4 LBproxycontrol planeABCABCABCABCone HTTP/2 connall RPCs on Anew pods idleheadless Servicesubchannel per podper-RPC spreadper-stream spreadone extra hopany client languageEDS endpoints +policy via ADSno sidecar hopFix for 1 without changing clients: server MaxConnectionAge (Go) / max_connection_age_ms (core) forces GOAWAY and reconnect,so connections re-spread over time. pick_first is the default policy; round_robin must be chosen in the service config.
text
     Checkout pod (dns:///orders-headless:50051, round_robin)          Kubernetes
1    resolver: DNS A records of the headless Service                    192.0.2.4, 192.0.2.5, 192.0.2.6
2    LB policy creates 3 subchannels, all READY
3    calls 1,2,3,4 -> .4, .5, .6, .4
4    HPA adds 192.0.2.7; DNS re-resolution (on reconnect or periodically) adds a 4th subchannel
5    a pod is deleted: its subchannel goes TRANSIENT_FAILURE, calls skip it; server MaxConnectionAge
     also forces reconnects so pick_first clients rebalance over time

Real scenario: a team migrates from REST to gRPC and one pod per deployment runs at 90 % CPU while the others idle; the fix is a headless Service plus round_robin, or Linkerd/Istio, or server MaxConnectionAge. A multi-region deployment uses xDS weights to send 10 % of traffic to a canary. AWS NLB in front of gRPC shows the same pinning; an ALB with a gRPC target group balances per request.

Options:

OptionWhere balancing happensProsCons
L4 balancer (ClusterIP, AWS NLB, HAProxy TCP mode)Per connectionSimple, no client changePinning; new backends idle
Client round_robin over DNS (headless Service)Per call in the clientNo extra hopDNS TTL and re-resolution lag; each client sees all pods
L7 proxy (Envoy, Linkerd, Istio sidecar, NGINX grpc_pass, AWS ALB)Per stream in the proxyAny language, retries and mTLS centrallyExtra hop, proxy CPU
Proxyless xDS (istiod, Traffic Director)Per call in the client, configured centrallyNo sidecar hop, weights, localityClient feature support varies by language
Server MaxConnectionAgeForces reconnectWorks with any clientCoarse; rebalances only over minutes

Fix / how to use it: never rely on an L4 balancer alone for gRPC; inside Kubernetes use a headless Service + round_robin, or a mesh; set MaxConnectionAge on servers anyway; read Load Balancing for algorithms and Service Mesh for sidecars.

Connection knobs: keepalive, max message size, compression, flow control Important ​

In plain words: a handful of settings decide whether idle connections survive, how big a message may be, whether messages are compressed and how fast a sender may push data.

Common misunderstanding: "Set the client keepalive to 5 seconds so dead connections are found fast." The server enforces a minimum ping interval (Go: EnforcementPolicy.MinTime, default 5 minutes); faster pings get the connection closed with GOAWAY ENHANCE_YOUR_CALM and debug data too_many_pings. Client and server keepalive "should also be in agreement".

Definition: keepalive sends HTTP/2 PING frames after Time of inactivity and closes the transport if no ack arrives within Timeout. Core defaults: client GRPC_ARG_KEEPALIVE_TIME_MS "INT_MAX (disabled)", server 2 hours; timeout 20 s; server GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS 5 minutes; GRPC_ARG_HTTP2_MAX_PING_STRIKES 2. In Go, a client Time "below 10s" is raised to 10 s. Max message size: Go clients and servers receive at most 4 MB by default (MaxCallRecvMsgSize, MaxRecvMsgSize), send up to math.MaxInt32; exceeding it gives RESOURCE_EXHAUSTED "grpc: received message larger than max (N vs. 4194304)". Compression: per message, negotiated with grpc-encoding and grpc-accept-encoding (gzip is standard); an unsupported algorithm yields UNIMPLEMENTED, and disabling compression for sensitive messages helps against "BEAST and CRIME attacks". Flow control: HTTP/2 windows per stream and connection; gRPC adjusts them (BDP estimation in Go) so a slow reader pushes back on a fast streaming sender.

text
     Client keepalive Time=30s, PermitWithoutStream   AWS NLB / firewall (idle timeout)   Server MinTime=10s
1    idle 30 s -> PING                                 sees traffic, keeps the flow open   ack
2    network partition; PING sent                      -                                   -
3    no ack within Timeout=10s -> transport closed, channel reconnects to another backend
4    misconfig: client Time=5s (raised to 10s in Go) and server MinTime=5min
5    server counts ping strikes > 2 -> GOAWAY ENHANCE_YOUR_CALM "too_many_pings"

Real scenario: a cloud firewall drops idle flows and the first call after a quiet night hangs until its deadline; keepalive fixes it. An export RPC returns a 9 MB page and fails with RESOURCE_EXHAUSTED; the fix is pagination or streaming, not raising the limit to 1 GB. Gzip on large JSON-like string payloads saves bandwidth across regions and costs CPU in the same zone.

Knob names per stack:

KnobGo (grpc-go)gRPC core (C++, PHP, Python, Ruby) channel argDefault
Client ping intervalkeepalive.ClientParameters.Timegrpc.keepalive_time_msOff
Ping ack timeoutClientParameters.Timeoutgrpc.keepalive_timeout_ms20 s
Ping with no callsPermitWithoutStreamgrpc.keepalive_permit_without_callsfalse
Server minimum ping intervalEnforcementPolicy.MinTimegrpc.http2.min_ping_interval_without_data_ms5 min
Connection ageServerParameters.MaxConnectionAgegrpc.max_connection_age_msInfinite
Receive limitMaxRecvMsgSize, MaxCallRecvMsgSizegrpc.max_receive_message_length4 MiB
Send limitMaxCallSendMsgSizegrpc.max_send_message_lengthUnlimited in Go
Compressiongrpc.UseCompressor(gzip.Name)grpc.default_compression_algorithmNone

Fix / how to use it: set client keepalive Time above the server's MinTime and below the shortest idle timeout in the path; set MaxConnectionAge with a grace period on servers; keep messages small and paginate or stream big results; enable gzip only where bandwidth costs more than CPU.

Health checking and server reflection Good to know ​

In plain words: health checking is a standard gRPC service that answers "can you serve orders.v1.OrderService right now?"; reflection is a standard service that tells tools like grpcurl which services and message types the server has.

Common misunderstanding: "A TCP check on port 50051 is a health check." It proves only that the socket accepts connections. Another: "Reflection is harmless, leave it on in production." It publishes your whole API surface to anyone who can connect; enable it where tooling needs it and protect it like any other endpoint.

Definition: grpc.health.v1.Health has Check(HealthCheckRequest) returns (HealthCheckResponse) and Watch(...) returns (stream ...); status values UNKNOWN, SERVING, NOT_SERVING, SERVICE_UNKNOWN. "A client can query the server's health status by calling the Check method, and a deadline should be set on the rpc." An unknown service name returns NOT_FOUND. Kubernetes has built-in gRPC probes (grpc: with port and optional service) that call this protocol. Server reflection lets clients "encode requests and decode responses in a human-readable manner"; "Reflection is used heavily by debugging tools such as grpcurl and Postman."

text
     kubelet (readinessProbe grpc port 50051 service orders.v1.OrderService)     Orders pod
1    Check{service:"orders.v1.OrderService"} with a 1 s deadline
2                                                                               SERVING -> pod Ready
3    pod receives SIGTERM: server sets NOT_SERVING, then GracefulStop()
4    Check -> NOT_SERVING -> endpoint removed; in-flight calls finish
5    grpcurl -plaintext localhost:50051 list   (reflection) -> grpc.health.v1.Health, orders.v1.OrderService, ...

Real scenario: graceful shutdown flips health to NOT_SERVING before draining so clients and Kubernetes stop sending new calls; client-side health checking (healthCheckConfig.serviceName in the service config) makes round_robin skip unhealthy backends; an on-call engineer uses grpcurl with reflection to call GetOrder during an incident.

ProductHealth integration
KubernetesNative grpc liveness/readiness probes
Envoygrpc_health_check in cluster health checking
AWS ALBgRPC health checks with expected gRPC codes
grpc_health_probeCLI for older Kubernetes or scripts

Fix / how to use it: register the health service in every server and set per-service status; flip to NOT_SERVING on shutdown; give probes a deadline; restrict reflection to internal networks or authenticated callers.

Reaching browsers and REST clients: gRPC-Web, grpc-gateway, transcoding, Connect Important ​

In plain words: browsers cannot speak native gRPC, so you either use a browser-friendly variant (gRPC-Web, Connect) or put a translator in front that turns REST/JSON into gRPC (grpc-gateway, Envoy or Google Cloud transcoding).

Common misunderstanding: "HTTP/2 is in every browser, so browsers can call gRPC." The browser fetch API gives JavaScript no access to HTTP/2 trailers or frame-level control, and gRPC puts its status in trailers. gRPC-Web therefore encodes trailers in the body: "8th (MSB) bit of the 1st gRPC frame byte ... 1: trailers".

Definition: gRPC-Web uses application/grpc-web or application/grpc-web-text (base64), works over HTTP/1.1 and HTTP/2, and needs a proxy such as Envoy's envoy.filters.http.grpc_web filter to translate to native gRPC; the grpc-web client supports unary and server streaming (server streaming: "Only when grpcwebtext mode is used."), "Client-side and Bi-directional streaming is not currently supported". grpc-gateway "is a plugin of protoc. It reads a gRPC service definition and generates a reverse-proxy server which translates a RESTful JSON API into gRPC", driven by option (google.api.http) = { get: "/v1/orders/{id}" };. Envoy's gRPC-JSON transcoder does the same in the proxy from a descriptor set. Connect: "Connect servers and clients support three protocols: gRPC, gRPC-Web, and Connect's own protocol"; the Connect protocol is plain HTTP (POST /orders.v1.OrderService/GetOrder with application/json or application/proto, deadline in connect-timeout-ms), and methods marked idempotency_level = NO_SIDE_EFFECTS can use GET, which makes HTTP caching possible.

text
     Browser                         Edge                                   Orders (gRPC)
1    fetch POST /orders.v1.OrderService/GetOrder
     content-type: application/grpc-web+proto
2                                    Envoy grpc_web filter -> HTTP/2 application/grpc
3                                                                           OK + trailers
4                                    Envoy puts trailers in the body (flag 0x80)
5    grpc-web client reads status from the body
     --- or ---
6    GET /v1/orders/o-1 (JSON)        grpc-gateway / Envoy transcoder -> GetOrder{id:"o-1"}
7    200 {"order":{"id":"o-1",...}}   status mapped: NOT_FOUND -> 404

Real scenario: an internal admin SPA calls services through Envoy with gRPC-Web; a partner API is generated with grpc-gateway from the same .proto and gets OpenAPI docs via protoc-gen-openapiv2; a new product uses Connect so the browser, curl and Go services all call the same handler.

ApproachBrowser streamingProxy neededHuman-readableHTTP caching
gRPC-Web (grpc-web JS)Server streaming onlyYes (Envoy, or in-process in some servers)No (binary or base64)No
Connect protocolUnary + server streaming over fetchNo (server speaks it)Yes with JSONYes for GET on side-effect-free methods
grpc-gatewayREST semanticsYes (generated Go proxy)Yes (JSON)Yes for GET routes
Envoy gRPC-JSON transcoderREST semanticsYes (Envoy)YesYes for GET routes
Google Cloud Endpoints / API Gateway transcodingREST semanticsManagedYesYes

Fix / how to use it: keep one .proto as the source of truth; add google.api.http annotations for the methods that need REST; use Connect or gRPC-Web for first-party browsers; never hand-maintain a parallel REST API that drifts. Browser real-time alternatives (SSE, WebSocket) are compared in Real-time communication.

buf: lint, breaking change detection and the BSR Important ​

In plain words: buf is a Protobuf toolchain: it lints .proto files, compares a schema against an older version to catch breaking changes, generates code, and publishes modules to a registry.

Common misunderstanding: "Code review catches breaking schema changes." Reviewers miss a removed reserved line or a renumbered field; a machine does not. Another: "buf replaces protoc." It replaces the workflow (configuration, includes, plugin invocation); the same plugins run.

Definition: buf lint "checks .proto files against style and structural rules"; categories MINIMAL, BASIC, STANDARD ("Buf's recommended baseline", the default), with STANDARD adding package version suffixes, service-name suffixes, request/response naming and zero-value enum naming. buf breaking --against '.git#branch=main' groups rules into four categories "from strictest to most lenient": FILE (the default), PACKAGE, WIRE_JSON, WIRE. The Buf Schema Registry (BSR) "is a Protobuf-aware registry for Buf modules"; buf push publishes, and consumers install generated SDKs with go get, npm install and friends. buf generate runs local or remote plugins from buf.gen.yaml.

text
     Pull request: reuse field 4 as int64 loyalty_points, renumber created_at 7 -> 12, rename customer_id
1    buf lint                                   OK (style is fine)
2    buf breaking --against main (FILE)         5 failures, including:
3      Previously present field "7" with name "created_at" on message "Order" was deleted.
4      Previously present reserved range "[4]" on message "Order" is missing values: [4] were removed.
5      Field "2" on message "Order" changed name from "customer_id" to "buyer_id".
6    with WIRE only                             3 failures: the rename disappears (wire-safe),
7      the deleted number is reported "without reserving the number "7""

The messages above are real output from buf 1.75.0 on this page's schema (see the Lab).

Real scenario: a platform team runs buf breaking with FILE on public packages and WIRE_JSON on internal ones that only care about bytes and JSON; mobile teams consume generated SDKs from the BSR; a monorepo runs buf lint as a pre-commit hook.

CategoryProtectsTypical use
FILEGenerated source per file (C++, Python imports)Default; public APIs
PACKAGEGenerated source per packageGo, Java codebases
WIRE_JSONBinary and JSON encodingServices exposed through transcoding
WIREBinary encoding onlyPure internal binary traffic, stored blobs

Fix / how to use it: commit buf.yaml with lint: STANDARD and breaking: FILE (or WIRE_JSON for internal), run both in CI against the main branch, and publish modules to the BSR or a schema repository so every consumer builds from the same version.

yaml
version: v2
modules:
  - path: proto
lint:
  use:
    - STANDARD
breaking:
  use:
    - FILE
yaml
version: v2
plugins:
  - local: protoc-gen-go
    out: gen
    opt: paths=source_relative
  - local: protoc-gen-go-grpc
    out: gen
    opt: paths=source_relative

Performance against JSON and REST Good to know ​

In plain words: Protobuf messages are smaller and cheaper to encode and decode than the same data in JSON, and HTTP/2 multiplexing avoids per-request connections, but the difference is microseconds per message.

Common misunderstanding: "gRPC is 10 times faster than REST." No primary source we read publishes such a number. The gRPC project runs continuous benchmarks ("Multi-language performance tests run every few hours against the master branch") and publishes a dashboard, not a headline ratio. Any ratio depends on payload, language, library and network.

Definition: what we measured on this page (Go 1.27, Apple M4 Pro, go test -bench in the Lab, one Order with two line items): Protobuf 113 bytes vs 398 bytes for encoding/json of an equivalent struct (about 3.5 times smaller); proto.Marshal about 520 ns/op vs json.Marshal about 840 ns/op (about 1.6 times faster); proto.Unmarshal about 670 ns/op vs json.Unmarshal about 1,580 ns/op (about 2.4 times faster); protojson.Marshal about 2,500 ns/op, slower than plain encoding/json. These are single-machine micro-benchmarks, labelled as such.

text
     Request path for GetOrder (illustrative budget, not measured end to end)
1    encode request            ~0.5 us   (measured: proto.Marshal of a full Order)
2    network same zone         ~hundreds of us
3    database query            ~1-5 ms
4    decode response           ~0.7 us   (measured: proto.Unmarshal)
5    encoding is three orders of magnitude below the I/O; it matters at very high QPS or for large payloads

Real scenario: a high-QPS internal pricing service saves CPU on encoding; a mobile app on a slow network benefits from 3.5 times smaller payloads; a CRUD admin API sees no measurable difference and keeps REST.

Measurement (this page's lab)ProtobufJSONRatio
Size of one Order113 B398 B (encoding/json)3.5x smaller
Marshal~520 ns/op, 5 allocs~840 ns/op, 5 allocs1.6x faster
Unmarshal~670 ns/op, 28 allocs~1,580 ns/op, 11 allocs2.4x faster
protojson.Marshal (official JSON mapping)~2,500 ns/opn/aSlower than both

Fix / how to use it: decide on contract, streaming and call semantics first; measure your own payloads with your own stack before quoting speed; if you must transcode to JSON at the edge, remember that protojson costs more than either binary Protobuf or plain JSON.

go
package wire

import (
	"encoding/json"
	"testing"
	"time"

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

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

// sample is the same Order the lab prints.
func sample() *ordersv1.Order {
	note := "leave at door"
	return &ordersv1.Order{
		Id: "o-1", CustomerId: "c-42", Status: ordersv1.OrderStatus_ORDER_STATUS_PAID,
		Items: []*ordersv1.LineItem{
			{Sku: "SKU-1", Quantity: 2, UnitPrice: &ordersv1.Money{CurrencyCode: "EUR", AmountMinor: 1250}},
			{Sku: "SKU-2", Quantity: 1, UnitPrice: &ordersv1.Money{CurrencyCode: "EUR", AmountMinor: 2499}},
		},
		Total:     &ordersv1.Money{CurrencyCode: "EUR", AmountMinor: 4999},
		CreatedAt: timestamppb.New(time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)),
		Note:      &note,
		Labels:    map[string]string{"channel": "web"},
		Delivery:  &ordersv1.Order_PickupStoreId{PickupStoreId: "store-7"},
	}
}

// plain is a hand-written struct, the typical REST/JSON DTO.
type plain struct {
	ID         string            `json:"id"`
	CustomerID string            `json:"customerId"`
	Status     string            `json:"status"`
	Items      []plainItem       `json:"items"`
	Total      plainMoney        `json:"total"`
	CreatedAt  time.Time         `json:"createdAt"`
	Note       string            `json:"note"`
	Labels     map[string]string `json:"labels"`
	PickupID   string            `json:"pickupStoreId"`
}
type plainItem struct {
	Sku       string     `json:"sku"`
	Quantity  int32      `json:"quantity"`
	UnitPrice plainMoney `json:"unitPrice"`
}
type plainMoney struct {
	CurrencyCode string `json:"currencyCode"`
	AmountMinor  int64  `json:"amountMinor"`
}

func samplePlain() plain {
	return plain{ID: "o-1", CustomerID: "c-42", Status: "ORDER_STATUS_PAID",
		Items: []plainItem{{"SKU-1", 2, plainMoney{"EUR", 1250}}, {"SKU-2", 1, plainMoney{"EUR", 2499}}},
		Total: plainMoney{"EUR", 4999}, CreatedAt: time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC),
		Note: "leave at door", Labels: map[string]string{"channel": "web"}, PickupID: "store-7"}
}

func BenchmarkProtoMarshal(b *testing.B) {
	m := sample()
	for i := 0; i < b.N; i++ {
		_, _ = proto.Marshal(m)
	}
}

func BenchmarkProtoUnmarshal(b *testing.B) {
	data, _ := proto.Marshal(sample())
	for i := 0; i < b.N; i++ {
		var o ordersv1.Order
		_ = proto.Unmarshal(data, &o)
	}
}

func BenchmarkProtoJSONMarshal(b *testing.B) {
	m := sample()
	for i := 0; i < b.N; i++ {
		_, _ = protojson.Marshal(m)
	}
}

func BenchmarkStdJSONMarshal(b *testing.B) {
	p := samplePlain()
	for i := 0; i < b.N; i++ {
		_, _ = json.Marshal(p)
	}
}

func BenchmarkStdJSONUnmarshal(b *testing.B) {
	data, _ := json.Marshal(samplePlain())
	for i := 0; i < b.N; i++ {
		var p plain
		_ = json.Unmarshal(data, &p)
	}
}

func TestSizes(t *testing.T) {
	pb, _ := proto.Marshal(sample())
	js, _ := json.Marshal(samplePlain())
	t.Logf("protobuf=%d bytes, encoding/json=%d bytes", len(pb), len(js))
	if len(pb) >= len(js) {
		t.Fatal("protobuf should be smaller for this message")
	}
}

Mechanics ​

Wire types and scalar encodings ​

Wire type idNameUsed forPayload
0VARINTint32, int64, uint32, uint64, sint32, sint64, bool, enumBase-128 varint (zigzag for sint*)
1I64fixed64, sfixed64, double8 bytes little-endian
2LENstring, bytes, messages, packed repeatedVarint length + bytes
3 / 4SGROUP / EGROUPproto2 groupsDeprecated
5I32fixed32, sfixed32, float4 bytes little-endian

Rules worth memorising: tag = (field_number << 3) | wire_type; numbers 1 to 15 have 1-byte tags, 16 to 2047 two bytes; for a non-repeated field that appears twice "Last One Wins" (the last value is used, sub-messages are merged); maps are encoded as repeated key/value entry messages; packed repeated scalars are one LEN record.

HTTP/2 mapping ​

ElementWire formNotes
Method:method POSTAlways POST in gRPC (Connect allows GET for side-effect-free methods)
Path:path /orders.v1.OrderService/GetOrderPackage.Service/Method
Content typecontent-type: application/grpc or application/grpc+protoOther types get HTTP 415
Proxy detectionte: trailersRequired; detects proxies that drop trailers
Deadlinegrpc-timeout: 800mAt most 8 digits; units H, M, S, m, u, n
Compressiongrpc-encoding, grpc-accept-encodingPer message, flag byte = 1
Message framing1 byte flag + 4 byte big-endian length + bytesLength-Prefixed-Message
Statusgrpc-status trailerDecimal code 0-16
Messagegrpc-message trailerPercent-encoded UTF-8
Detailsgrpc-status-details-bin trailerBase64 google.rpc.Status
Binary metadatakey ending in -binBase64 on the wire
Pushbackgrpc-retry-pushback-ms trailerServer tells client when (or not) to retry

Status codes and what the caller does ​

CodeNameGenerated by library?Typical causeCaller action
0OKYesSuccessUse the response
1CANCELLEDYesCaller cancelled, or server saw the deadline passStop; nothing to retry
2UNKNOWNYesUnknown error space, handler panic convertedAlert; do not retry blindly
3INVALID_ARGUMENTNoBad request regardless of stateFix the request
4DEADLINE_EXCEEDEDYesDeadline expired; operation may have completedRetry only if idempotent
5NOT_FOUNDNoEntity missingTreat as absent
6ALREADY_EXISTSNoCreate of an existing entityTreat as success if idempotent create
7PERMISSION_DENIEDNo (except auth plugins)Caller identified but not allowedDo not retry
8RESOURCE_EXHAUSTEDYes (message too large, flow control)Quota, rate limit, message sizeBack off; honour RetryInfo
9FAILED_PRECONDITIONNoState not suitable (non-empty dir)Fix state first
10ABORTEDNoConcurrency conflictRetry the whole read-modify-write
11OUT_OF_RANGENoPast the end (pagination, file offset)Stop iterating
12UNIMPLEMENTEDYesMethod not registered, unsupported compressionDo not retry; check versions
13INTERNALYesInvariant broken, protocol errorAlert
14UNAVAILABLEYesConnection failure, server shutting downRetry with backoff (idempotent)
15DATA_LOSSNoUnrecoverable corruptionPage someone
16UNAUTHENTICATEDYes (credentials plugins)Missing or invalid credentialsRefresh token, then retry once

Service config fields ​

FieldMeaningExample
loadBalancingConfigOrdered list of LB policies; first supported wins[{"round_robin": {}}]
methodConfig[].nameWhich service/method the entry applies to{"service": "orders.v1.OrderService", "method": "GetOrder"}
methodConfig[].timeoutDefault deadline when the caller sets none"2s"
methodConfig[].waitForReadyQueue the call while the channel connects instead of failing fast with UNAVAILABLEtrue
methodConfig[].maxRequestMessageBytes / maxResponseMessageBytesPer-method message limits1048576
retryPolicymaxAttempts, initialBackoff, maxBackoff, backoffMultiplier, retryableStatusCodesSee Go
hedgingPolicymaxAttempts, hedgingDelay, nonFatalStatusCodes"hedgingDelay": "0.05s"
retryThrottlingmaxTokens, tokenRatio{"maxTokens": 10, "tokenRatio": 0.1}
healthCheckConfig.serviceNameClient-side health checking per subchannel"orders.v1.OrderService"

Error messages you will actually see ​

Message (verbatim or format)SourceMeaning
rpc error: code = DeadlineExceeded desc = context deadline exceededgrpc-go status.Error string format rpc error: code = %s desc = %sClient deadline passed
rpc error: code = Unavailable desc = connection error: ...grpc-go transportNo ready subchannel, dial failed
grpc: received message larger than max (N vs. 4194304)grpc-go rpc_util.go, code RESOURCE_EXHAUSTEDReceive limit (4 MiB default)
GOAWAY ENHANCE_YOUR_CALM, debug data too_many_pingsgrpc-go / core server keepalive enforcementClient pings faster than server MinTime
HTTP 415 Unsupported Media TypeServer got a non-gRPC content typeA REST client or a misrouted request
Previously present field "7" with name "created_at" on message "Order" was deleted.buf breakingA field number disappeared
Previously present reserved range "[4]" on message "Order" is missing values: [4] were removed.buf breakingSomeone un-reserved a number
missing x-request-id metadata (INVALID_ARGUMENT)This page's server interceptorRequired metadata absent

Go ​

The Go module (academy/grpc-protobuf, go 1.24, google.golang.org/grpc v1.80.0, google.golang.org/protobuf v1.36.11) contains the .proto above, the code generated by buf generate with protoc-gen-go and protoc-gen-go-grpc (committed under gen/), a client, a server and tests that run both over bufconn, an in-memory listener.

Before ​

A client that works in a demo and fails in production: a new channel per call, no deadline, no metadata, the default pick_first policy, and error handling by string matching.

go
// Package before shows a gRPC client that compiles, works in a demo and
// fails in production: a new channel per call, no deadline, no metadata,
// no retry policy and error strings compared by text.
package before

import (
	"context"
	"strings"

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

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

// GetOrder dials on every call. Each call pays a TCP (and TLS) handshake,
// gets a fresh HTTP/2 connection and, with pick_first, sticks to whichever
// backend the resolver listed first.
func GetOrder(target, id string) (*ordersv1.Order, error) {
	conn, err := grpc.NewClient(target, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	// context.Background(): no deadline, so a stuck server holds this
	// goroutine forever.
	resp, err := ordersv1.NewOrderServiceClient(conn).GetOrder(context.Background(), &ordersv1.GetOrderRequest{Id: id})
	if err != nil {
		// Matching on message text breaks when the server rewords it.
		if strings.Contains(err.Error(), "not found") {
			return nil, nil
		}
		return nil, err
	}
	return resp.GetOrder(), nil
}

After ​

The client: one channel built with a service config (round_robin, per-method timeout, retryPolicy on UNAVAILABLE, retryThrottling), keepalive above the server's MinTime, a 4 MiB receive limit, an interceptor that adds x-request-id, a per-call deadline, header metadata read back, and Explain that turns status codes and rich details into decisions.

go
// Package client builds an OrderService client the way production callers
// should: one long-lived channel, a service config with round_robin and a
// retry policy, keepalive, a per-call deadline and request metadata.
package client

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"time"

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

	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/keepalive"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
)

// ServiceConfig is the JSON service config. Retries apply only to the
// listed codes; GetOrder is a read, so retrying it is safe.
const ServiceConfig = `{
  "loadBalancingConfig": [{"round_robin": {}}],
  "methodConfig": [{
    "name": [{"service": "orders.v1.OrderService", "method": "GetOrder"}],
    "timeout": "2s",
    "retryPolicy": {
      "maxAttempts": 4,
      "initialBackoff": "0.05s",
      "maxBackoff": "1s",
      "backoffMultiplier": 2,
      "retryableStatusCodes": ["UNAVAILABLE"]
    }
  }],
  "retryThrottling": {"maxTokens": 10, "tokenRatio": 0.1}
}`

// Options returns the dial options. creds is TLS in production
// (credentials.NewTLS) and insecure.NewCredentials() only in tests.
func Options(creds credentials.TransportCredentials) []grpc.DialOption {
	return []grpc.DialOption{
		grpc.WithTransportCredentials(creds),
		grpc.WithDefaultServiceConfig(ServiceConfig),
		grpc.WithKeepaliveParams(keepalive.ClientParameters{
			Time:                30 * time.Second, // must be >= server MinTime
			Timeout:             10 * time.Second,
			PermitWithoutStream: true,
		}),
		grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(4 << 20)),
		grpc.WithChainUnaryInterceptor(RequestID()),
	}
}

// Dial creates the channel once. target is "dns:///orders.internal:443"
// so the dns resolver returns every address and round_robin spreads calls.
func Dial(target string, creds credentials.TransportCredentials, extra ...grpc.DialOption) (*grpc.ClientConn, error) {
	return grpc.NewClient(target, append(Options(creds), extra...)...)
}

// RequestID adds x-request-id unless the caller already set one.
func RequestID() grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, inv grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		md, _ := metadata.FromOutgoingContext(ctx)
		if len(md.Get("x-request-id")) == 0 {
			b := make([]byte, 8)
			_, _ = rand.Read(b)
			ctx = metadata.AppendToOutgoingContext(ctx, "x-request-id", hex.EncodeToString(b))
		}
		return inv(ctx, method, req, reply, cc, opts...)
	}
}

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

// Get fetches an order. The deadline is the smaller of the caller's
// remaining budget and o.Timeout; gRPC sends it as grpc-timeout.
func (o Orders) Get(ctx context.Context, id string) (*ordersv1.Order, string, error) {
	ctx, cancel := context.WithTimeout(ctx, o.Timeout)
	defer cancel()
	var header metadata.MD
	resp, err := o.Stub.GetOrder(ctx, &ordersv1.GetOrderRequest{Id: id}, grpc.Header(&header))
	if err != nil {
		return nil, "", err
	}
	served := ""
	if v := header.Get("x-served-by"); len(v) > 0 {
		served = v[0]
	}
	return resp.GetOrder(), served, nil
}

// Explain turns a status into a decision the caller can act on.
func Explain(err error) (code codes.Code, retry bool, detail string) {
	st := status.Convert(err)
	for _, d := range st.Details() {
		switch v := d.(type) {
		case *errdetails.BadRequest:
			for _, f := range v.GetFieldViolations() {
				detail = f.GetField() + ": " + f.GetDescription()
			}
		case *errdetails.ResourceInfo:
			detail = v.GetResourceType() + "/" + v.GetResourceName()
		}
	}
	switch st.Code() {
	case codes.Unavailable, codes.ResourceExhausted, codes.Aborted:
		return st.Code(), true, detail
	default:
		return st.Code(), false, detail
	}
}

The server: all four RPC shapes, ctx.Done() honoured in the slow path and in stream loops, INVALID_ARGUMENT with BadRequest and NOT_FOUND with ResourceInfo, header and trailer metadata, unary and stream interceptors, keepalive enforcement, MaxConnectionAge, the health service and reflection.

go
// Package server implements orders.v1.OrderService with the production
// habits the chapter teaches: honour the caller's deadline, read and write
// metadata, return precise status codes with rich error details, and stop
// streaming when the client cancels.
package server

import (
	"context"
	"errors"
	"io"
	"log/slog"
	"sync"
	"time"

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

	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/keepalive"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/reflection"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// Store is the data the service reads. A real service backs it with SQL.
type Store interface {
	Get(ctx context.Context, id string) (*ordersv1.Order, bool)
	ByCustomer(ctx context.Context, customerID string) []*ordersv1.Order
	Put(ctx context.Context, o *ordersv1.Order) error
}

// Service implements ordersv1.OrderServiceServer.
type Service struct {
	ordersv1.UnimplementedOrderServiceServer
	Store Store
	// SlowFor makes GetOrder sleep, so tests can see DEADLINE_EXCEEDED.
	SlowFor time.Duration
	// FailFirst returns UNAVAILABLE for the first N GetOrder calls, so tests
	// can see the client's retry policy at work.
	FailFirst int

	mu    sync.Mutex
	calls int
}

func (s *Service) GetOrder(ctx context.Context, req *ordersv1.GetOrderRequest) (*ordersv1.GetOrderResponse, error) {
	if req.GetId() == "" {
		st := status.New(codes.InvalidArgument, "id is required")
		st, _ = st.WithDetails(&errdetails.BadRequest{
			FieldViolations: []*errdetails.BadRequest_FieldViolation{
				{Field: "id", Description: "must be a non-empty order id"},
			},
		})
		return nil, st.Err()
	}
	s.mu.Lock()
	s.calls++
	n := s.calls
	s.mu.Unlock()
	if n <= s.FailFirst {
		return nil, status.Error(codes.Unavailable, "warming up")
	}
	if s.SlowFor > 0 {
		select {
		case <-time.After(s.SlowFor):
		case <-ctx.Done():
			// The caller gave up or its deadline passed: stop the work.
			return nil, status.FromContextError(ctx.Err()).Err()
		}
	}
	o, ok := s.Store.Get(ctx, req.GetId())
	if !ok {
		st := status.New(codes.NotFound, "order not found")
		st, _ = st.WithDetails(&errdetails.ResourceInfo{
			ResourceType: "orders.v1.Order",
			ResourceName: req.GetId(),
			Description:  "no order with this id",
		})
		return nil, st.Err()
	}
	// Response header metadata, sent before the message.
	_ = grpc.SetHeader(ctx, metadata.Pairs("x-served-by", "orders-1"))
	return &ordersv1.GetOrderResponse{Order: o}, nil
}

func (s *Service) ListOrders(req *ordersv1.ListOrdersRequest, stream grpc.ServerStreamingServer[ordersv1.ListOrdersResponse]) error {
	for _, o := range s.Store.ByCustomer(stream.Context(), req.GetCustomerId()) {
		if err := stream.Context().Err(); err != nil {
			return status.FromContextError(err).Err()
		}
		if err := stream.Send(&ordersv1.ListOrdersResponse{Order: o}); err != nil {
			return err
		}
	}
	// Trailer metadata travels with the final status.
	stream.SetTrailer(metadata.Pairs("x-total", "done"))
	return nil
}

func (s *Service) ImportOrders(stream grpc.ClientStreamingServer[ordersv1.ImportOrdersRequest, ordersv1.ImportOrdersResponse]) error {
	start := time.Now()
	var accepted, rejected int32
	for {
		req, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			return stream.SendAndClose(&ordersv1.ImportOrdersResponse{
				Accepted: accepted, Rejected: rejected,
				Took: durationpb.New(time.Since(start)),
			})
		}
		if err != nil {
			return err
		}
		if req.GetOrder().GetId() == "" {
			rejected++
			continue
		}
		if err := s.Store.Put(stream.Context(), req.GetOrder()); err != nil {
			return status.Errorf(codes.Internal, "store: %v", err)
		}
		accepted++
	}
}

func (s *Service) TrackOrders(stream grpc.BidiStreamingServer[ordersv1.TrackOrdersRequest, ordersv1.TrackOrdersResponse]) error {
	for {
		req, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			return nil
		}
		if err != nil {
			return err
		}
		o, ok := s.Store.Get(stream.Context(), req.GetOrderId())
		st := ordersv1.OrderStatus_ORDER_STATUS_UNSPECIFIED
		if ok {
			st = o.GetStatus()
		}
		if err := stream.Send(&ordersv1.TrackOrdersResponse{
			OrderId: req.GetOrderId(), Status: st, At: timestamppb.Now(),
		}); err != nil {
			return err
		}
	}
}

// RequestIDUnary rejects calls without x-request-id and logs code + latency.
func RequestIDUnary(log *slog.Logger) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (any, error) {
		md, _ := metadata.FromIncomingContext(ctx)
		ids := md.Get("x-request-id")
		if len(ids) == 0 {
			return nil, status.Error(codes.InvalidArgument, "missing x-request-id metadata")
		}
		start := time.Now()
		resp, err := h(ctx, req)
		log.Info("rpc", "method", info.FullMethod, "request_id", ids[0],
			"code", status.Code(err).String(), "took", time.Since(start))
		return resp, err
	}
}

// LogStream logs streaming RPCs.
func LogStream(log *slog.Logger) grpc.StreamServerInterceptor {
	return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, h grpc.StreamHandler) error {
		err := h(srv, ss)
		log.Info("stream", "method", info.FullMethod, "code", status.Code(err).String())
		return err
	}
}

// New builds a server with keepalive enforcement, a message size limit,
// the standard health service and server reflection.
func New(svc *Service, log *slog.Logger) (*grpc.Server, *health.Server) {
	gs := grpc.NewServer(
		grpc.ChainUnaryInterceptor(RequestIDUnary(log)),
		grpc.ChainStreamInterceptor(LogStream(log)),
		grpc.MaxRecvMsgSize(4<<20), // the default, written out
		grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
			MinTime:             10 * time.Second, // pings more often get GOAWAY "too_many_pings"
			PermitWithoutStream: true,
		}),
		grpc.KeepaliveParams(keepalive.ServerParameters{
			MaxConnectionAge:      5 * time.Minute, // forces clients to re-resolve and rebalance
			MaxConnectionAgeGrace: 30 * time.Second,
		}),
	)
	ordersv1.RegisterOrderServiceServer(gs, svc)
	hs := health.NewServer()
	hs.SetServingStatus("orders.v1.OrderService", healthpb.HealthCheckResponse_SERVING)
	healthpb.RegisterHealthServer(gs, hs)
	reflection.Register(gs)
	return gs, hs
}

// MemStore is an in-memory Store for tests and the lab.
type MemStore struct {
	mu sync.Mutex
	m  map[string]*ordersv1.Order
}

func NewMemStore(orders ...*ordersv1.Order) *MemStore {
	s := &MemStore{m: map[string]*ordersv1.Order{}}
	for _, o := range orders {
		s.m[o.GetId()] = o
	}
	return s
}

func (s *MemStore) Get(_ context.Context, id string) (*ordersv1.Order, bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	o, ok := s.m[id]
	return o, ok
}

func (s *MemStore) ByCustomer(_ context.Context, c string) []*ordersv1.Order {
	s.mu.Lock()
	defer s.mu.Unlock()
	var out []*ordersv1.Order
	for _, o := range s.m {
		if o.GetCustomerId() == c {
			out = append(out, o)
		}
	}
	return out
}

func (s *MemStore) Put(_ context.Context, o *ordersv1.Order) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.m[o.GetId()] = o
	return nil
}

The tests prove each claim on this page: header metadata, rich details, DEADLINE_EXCEEDED within the budget, CANCELLED on client cancel, the retry policy absorbing two UNAVAILABLE, the interceptor rejecting missing metadata, server streaming with a trailer, client streaming, bidirectional streaming, and health SERVING / NOT_FOUND.

go
package server_test

import (
	"context"
	"errors"
	"io"
	"log/slog"
	"net"
	"testing"
	"time"

	"academy/grpc-protobuf/client"
	ordersv1 "academy/grpc-protobuf/gen/orders/v1"
	"academy/grpc-protobuf/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"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)

func seed() *server.MemStore {
	return server.NewMemStore(
		&ordersv1.Order{Id: "o-1", CustomerId: "c-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PAID},
		&ordersv1.Order{Id: "o-2", CustomerId: "c-1", Status: ordersv1.OrderStatus_ORDER_STATUS_SHIPPED},
	)
}

// start runs the server on an in-memory listener and returns a client
// channel built with the production options from package client.
func start(t *testing.T, svc *server.Service) *grpc.ClientConn {
	t.Helper()
	lis := bufconn.Listen(1 << 20)
	gs, _ := server.New(svc, slog.New(slog.NewTextHandler(io.Discard, nil)))
	go func() { _ = gs.Serve(lis) }()
	t.Cleanup(gs.Stop)
	conn, err := client.Dial("passthrough:///bufnet", insecure.NewCredentials(),
		grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return lis.DialContext(ctx) }))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { _ = conn.Close() })
	return conn
}

func TestUnaryWithHeaderMetadata(t *testing.T) {
	conn := start(t, &server.Service{Store: seed()})
	o := client.Orders{Stub: ordersv1.NewOrderServiceClient(conn), Timeout: time.Second}
	got, servedBy, err := o.Get(context.Background(), "o-1")
	if err != nil {
		t.Fatal(err)
	}
	if got.GetStatus() != ordersv1.OrderStatus_ORDER_STATUS_PAID || servedBy != "orders-1" {
		t.Fatalf("got %v served by %q", got.GetStatus(), servedBy)
	}
}

func TestNotFoundCarriesResourceInfo(t *testing.T) {
	conn := start(t, &server.Service{Store: seed()})
	o := client.Orders{Stub: ordersv1.NewOrderServiceClient(conn), Timeout: time.Second}
	_, _, err := o.Get(context.Background(), "o-404")
	code, retry, detail := client.Explain(err)
	if code != codes.NotFound || retry || detail != "orders.v1.Order/o-404" {
		t.Fatalf("code=%v retry=%v detail=%q", code, retry, detail)
	}
}

func TestInvalidArgumentCarriesBadRequest(t *testing.T) {
	conn := start(t, &server.Service{Store: seed()})
	o := client.Orders{Stub: ordersv1.NewOrderServiceClient(conn), Timeout: time.Second}
	_, _, err := o.Get(context.Background(), "")
	code, _, detail := client.Explain(err)
	if code != codes.InvalidArgument || detail != "id: must be a non-empty order id" {
		t.Fatalf("code=%v detail=%q", code, detail)
	}
}

func TestDeadlineExceeded(t *testing.T) {
	conn := start(t, &server.Service{Store: seed(), SlowFor: 2 * time.Second})
	o := client.Orders{Stub: ordersv1.NewOrderServiceClient(conn), Timeout: 50 * time.Millisecond}
	startAt := time.Now()
	_, _, err := o.Get(context.Background(), "o-1")
	if status.Code(err) != codes.DeadlineExceeded {
		t.Fatalf("want DEADLINE_EXCEEDED, got %v", err)
	}
	if time.Since(startAt) > time.Second {
		t.Fatal("client waited past its deadline")
	}
}

func TestCancellation(t *testing.T) {
	conn := start(t, &server.Service{Store: seed(), SlowFor: 2 * time.Second})
	o := client.Orders{Stub: ordersv1.NewOrderServiceClient(conn), Timeout: 5 * time.Second}
	ctx, cancel := context.WithCancel(context.Background())
	time.AfterFunc(30*time.Millisecond, cancel)
	_, _, err := o.Get(ctx, "o-1")
	if status.Code(err) != codes.Canceled {
		t.Fatalf("want CANCELLED, got %v", err)
	}
}

func TestRetryPolicyHidesTransientUnavailable(t *testing.T) {
	conn := start(t, &server.Service{Store: seed(), FailFirst: 2})
	o := client.Orders{Stub: ordersv1.NewOrderServiceClient(conn), Timeout: 2 * time.Second}
	if _, _, err := o.Get(context.Background(), "o-1"); err != nil {
		t.Fatalf("retry policy should have absorbed two UNAVAILABLE: %v", err)
	}
}

func TestMissingRequestIDRejectedByInterceptor(t *testing.T) {
	// A raw stub on a channel without the client interceptor.
	lis := bufconn.Listen(1 << 20)
	gs, _ := server.New(&server.Service{Store: seed()}, slog.New(slog.NewTextHandler(io.Discard, nil)))
	go func() { _ = gs.Serve(lis) }()
	defer gs.Stop()
	conn, err := grpc.NewClient("passthrough:///bufnet",
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return lis.DialContext(ctx) }))
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	_, err = ordersv1.NewOrderServiceClient(conn).GetOrder(ctx, &ordersv1.GetOrderRequest{Id: "o-1"})
	if status.Code(err) != codes.InvalidArgument {
		t.Fatalf("want INVALID_ARGUMENT, got %v", err)
	}
}

func TestServerStreamingAndTrailer(t *testing.T) {
	conn := start(t, &server.Service{Store: seed()})
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	stream, err := ordersv1.NewOrderServiceClient(conn).ListOrders(ctx, &ordersv1.ListOrdersRequest{CustomerId: "c-1"})
	if err != nil {
		t.Fatal(err)
	}
	n := 0
	for {
		_, err := stream.Recv()
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			t.Fatal(err)
		}
		n++
	}
	if n != 2 || stream.Trailer().Get("x-total")[0] != "done" {
		t.Fatalf("n=%d trailer=%v", n, stream.Trailer())
	}
}

func TestClientStreaming(t *testing.T) {
	conn := start(t, &server.Service{Store: seed()})
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	stream, err := ordersv1.NewOrderServiceClient(conn).ImportOrders(ctx)
	if err != nil {
		t.Fatal(err)
	}
	for _, id := range []string{"o-10", "", "o-11"} {
		if err := stream.Send(&ordersv1.ImportOrdersRequest{Order: &ordersv1.Order{Id: id}}); err != nil {
			t.Fatal(err)
		}
	}
	sum, err := stream.CloseAndRecv()
	if err != nil {
		t.Fatal(err)
	}
	if sum.GetAccepted() != 2 || sum.GetRejected() != 1 || sum.GetTook() == nil {
		t.Fatalf("summary %v", sum)
	}
}

func TestBidiStreaming(t *testing.T) {
	conn := start(t, &server.Service{Store: seed()})
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	ctx = metadata.AppendToOutgoingContext(ctx, "x-request-id", "bidi-1")
	stream, err := ordersv1.NewOrderServiceClient(conn).TrackOrders(ctx)
	if err != nil {
		t.Fatal(err)
	}
	for _, id := range []string{"o-1", "o-2"} {
		if err := stream.Send(&ordersv1.TrackOrdersRequest{OrderId: id}); err != nil {
			t.Fatal(err)
		}
		ev, err := stream.Recv()
		if err != nil {
			t.Fatal(err)
		}
		if ev.GetOrderId() != id || ev.GetAt() == nil {
			t.Fatalf("event %v", ev)
		}
	}
	if err := stream.CloseSend(); err != nil {
		t.Fatal(err)
	}
	if _, err := stream.Recv(); !errors.Is(err, io.EOF) {
		t.Fatalf("want EOF after CloseSend, got %v", err)
	}
}

func TestHealthCheck(t *testing.T) {
	conn := start(t, &server.Service{Store: seed()})
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	resp, err := healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{Service: "orders.v1.OrderService"})
	if err != nil || resp.GetStatus() != healthpb.HealthCheckResponse_SERVING {
		t.Fatalf("health %v %v", resp, err)
	}
	_, err = healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{Service: "unknown"})
	if status.Code(err) != codes.NotFound {
		t.Fatalf("unknown service should be NOT_FOUND, got %v", err)
	}
}

The Go angle ​

  • grpc.NewClient (since v1.63) replaces grpc.Dial; it does no I/O, defaults to the dns resolver and connects on first use. WithBlock and WithTimeout are ignored by it; use a per-call deadline or WaitForReady instead.
  • Deadlines are context.Context deadlines. Pass the incoming ctx to outgoing calls and propagation is automatic; status.FromContextError(ctx.Err()) maps context.DeadlineExceeded and context.Canceled to the right codes.
  • google.golang.org/grpc/status and codes build errors; status.Convert(err).Details() returns typed details from google.golang.org/genproto/googleapis/rpc/errdetails.
  • Generated servers embed UnimplementedOrderServiceServer, so adding an RPC to the .proto does not break existing implementations (unimplemented methods return UNIMPLEMENTED).
  • Generic stream types (grpc.ServerStreamingServer[T], grpc.BidiStreamingServer[Req, Res]) are what current protoc-gen-go-grpc emits (this module was generated with v1.6.2).
  • google.golang.org/grpc/test/bufconn gives in-process tests with the real HTTP/2 transport; google.golang.org/grpc/health and reflection register the standard services in one line each.
  • protojson is the only correct JSON encoder for Protobuf messages; encoding/json on generated structs ignores the mapping rules.
  • Connect for Go (connectrpc.com/connect) serves gRPC, gRPC-Web and Connect from a plain net/http handler when you need browsers without a proxy.
  • The full Go treatment (project layout, TLS credentials, protovalidate, grpc-gateway wiring) is in gRPC & Protobuf in Go.

Laravel ​

PHP is a gRPC client language: the grpc.io PHP guide says "you can only create clients in PHP for gRPC services. Use another language to create a gRPC server." A Laravel app needs the grpc PECL extension, the grpc/grpc and google/protobuf Composer packages (optionally the protobuf C extension for speed), and classes generated by protoc --php_out plus grpc_php_plugin, or by buf generate with remote plugins. Package orders.v1 becomes the namespace Orders\V1, so the stub is Orders\V1\OrderServiceClient and messages are Orders\V1\GetOrderRequest with setters and getters (setId(), getOrder()).

Before ​

A controller helper that builds a channel per request, sets no deadline (the PHP AbstractCall then uses Timeval::infFuture()) and drops the status.

php
<?php

// Before: a controller action that builds a new channel on every request,
// sets no deadline and ignores the status object.

use Orders\V1\GetOrderRequest;
use Orders\V1\OrderServiceClient;

function showOrder(string $id): array
{
    $client = new OrderServiceClient('orders.internal:443', [
        'credentials' => Grpc\ChannelCredentials::createInsecure(),
    ]);

    // No 'timeout' option: the deadline is infinite (Timeval::infFuture()).
    [$response] = $client->GetOrder((new GetOrderRequest())->setId($id))->wait();

    // $response is null on any error; the code and details are lost.
    return ['id' => $response?->getOrder()?->getId()];
}

After ​

Configuration with the same service config JSON the Go client uses:

php
<?php

// config/grpc.php: one entry per upstream gRPC service.
return [
    'orders' => [
        // dns:/// makes gRPC core resolve every A/AAAA record so round_robin has targets.
        'target' => env('ORDERS_GRPC_TARGET', 'dns:///orders.internal:443'),
        'tls' => env('ORDERS_GRPC_TLS', true),
        // Per-call deadline in milliseconds; the client converts it to microseconds.
        'deadline_ms' => (int) env('ORDERS_GRPC_DEADLINE_MS', 800),
        // Same JSON service config the Go client uses: round_robin + retry on UNAVAILABLE.
        'service_config' => json_encode([
            'loadBalancingConfig' => [['round_robin' => new stdClass()]],
            'methodConfig' => [[
                'name' => [['service' => 'orders.v1.OrderService', 'method' => 'GetOrder']],
                'retryPolicy' => [
                    'maxAttempts' => 3,
                    'initialBackoff' => '0.05s',
                    'maxBackoff' => '0.5s',
                    'backoffMultiplier' => 2,
                    'retryableStatusCodes' => ['UNAVAILABLE'],
                ],
            ]],
        ]),
    ],
];

A deferred service provider that builds one stub per worker with TLS credentials and gRPC core channel arguments (grpc.service_config, grpc.enable_retries, grpc.keepalive_time_ms, grpc.max_receive_message_length):

php
<?php

namespace App\Providers;

use App\Services\Orders\OrdersClient;
use Grpc\ChannelCredentials;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\ServiceProvider;
use Orders\V1\OrderServiceClient;

/**
 * Builds ONE generated gRPC stub per PHP worker and shares it.
 * Under PHP-FPM that means one channel per request process; under
 * Laravel Octane the singleton lives as long as the worker, which is
 * what gRPC wants (a long-lived HTTP/2 connection).
 */
class OrdersGrpcServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register(): void
    {
        $this->app->singleton(OrderServiceClient::class, function (Application $app) {
            $cfg = $app['config']->get('grpc.orders');

            return new OrderServiceClient($cfg['target'], [
                'credentials' => $cfg['tls']
                    ? ChannelCredentials::createSsl()
                    : ChannelCredentials::createInsecure(),
                // gRPC core channel args (GRPC_ARG_* names).
                'grpc.service_config' => $cfg['service_config'],
                'grpc.enable_retries' => 1,
                'grpc.keepalive_time_ms' => 30000,
                'grpc.max_receive_message_length' => 4 * 1024 * 1024,
            ]);
        });

        $this->app->singleton(OrdersClient::class, fn (Application $app) => new OrdersClient(
            $app->make(OrderServiceClient::class),
            (int) $app['config']->get('grpc.orders.deadline_ms'),
        ));
    }

    /** @return array<int, class-string> */
    public function provides(): array
    {
        return [OrderServiceClient::class, OrdersClient::class];
    }
}

A service class that sets a deadline on every call ('timeout' in microseconds), adds x-request-id metadata, maps status codes with match, and wraps the call in Laravel's retry() helper only for UNAVAILABLE:

php
<?php

namespace App\Services\Orders;

use Illuminate\Support\Str;
use Orders\V1\GetOrderRequest;
use Orders\V1\Order;
use Orders\V1\OrderServiceClient;
use RuntimeException;

/**
 * Thin wrapper over the generated stub: deadline on every call,
 * x-request-id metadata, status codes mapped to decisions.
 */
final class OrdersClient
{
    public function __construct(
        private readonly OrderServiceClient $stub,
        private readonly int $deadlineMs,
    ) {}

    public function find(string $orderId, ?string $requestId = null): ?Order
    {
        // Application-level retry only for UNAVAILABLE, on top of the
        // channel's retryPolicy, with a short budget: 2 tries, 100 ms apart.
        return retry(2, function () use ($orderId, $requestId) {
            $request = (new GetOrderRequest())->setId($orderId);
            $metadata = ['x-request-id' => [$requestId ?? (string) Str::uuid()]];
            // 'timeout' is in MICROseconds; gRPC sends it as grpc-timeout.
            $options = ['timeout' => $this->deadlineMs * 1000];

            [$response, $status] = $this->stub->GetOrder($request, $metadata, $options)->wait();

            return match ($status->code) {
                \Grpc\STATUS_OK => $response->getOrder(),
                \Grpc\STATUS_NOT_FOUND => null,
                \Grpc\STATUS_UNAVAILABLE => throw new OrdersUnavailable($status->details),
                \Grpc\STATUS_DEADLINE_EXCEEDED => throw new RuntimeException('orders: deadline exceeded'),
                default => throw new RuntimeException("orders: code {$status->code}: {$status->details}"),
            };
        }, 100, fn ($e) => $e instanceof OrdersUnavailable);
    }
}
php
<?php

namespace App\Services\Orders;

use RuntimeException;

/** Raised for gRPC UNAVAILABLE (14): the only code this client retries. */
final class OrdersUnavailable extends RuntimeException {}

Code generation for the Laravel app with buf remote plugins:

yaml
# buf.gen.yaml for the Laravel app: PHP messages plus the gRPC client stub.
# Remote plugins run on the Buf Schema Registry; no local protoc needed.
version: v2
plugins:
  - remote: buf.build/protocolbuffers/php
    out: generated
  - remote: buf.build/grpc/php
    out: generated

The Laravel angle ​

  • Register the provider in bootstrap/providers.php (Laravel 13 does this automatically for php artisan make:provider). Implementing DeferrableProvider with provides() means the stub is built only when a request actually needs it.
  • $this->app->singleton() gives one channel per PHP-FPM process per request lifecycle, and under Laravel Octane one per long-lived worker, which is what gRPC wants. Do not use scoped() here: it would rebuild the channel every request under Octane.
  • The stub call returns a call object; ->wait() returns [$response, $status] where $status->code is compared with \Grpc\STATUS_OK, \Grpc\STATUS_NOT_FOUND, \Grpc\STATUS_UNAVAILABLE and so on, $status->details is the message, and $status->metadata holds the trailers.
  • Deadlines: pass ['timeout' => $microseconds] as the third argument; without it the call has no deadline. Metadata: the second argument, ['key' => ['value']].
  • Retries: gRPC core honours retryPolicy from grpc.service_config (with grpc.enable_retries); the retry(2, ..., 100, fn ($e) => ...) helper adds an application-level retry for UNAVAILABLE only. Keep the total under the request's own budget.
  • PHP cannot host gRPC servers with the official extension; for a Laravel-owned service exposed to gRPC callers, put a Go/Envoy front or use Connect-compatible HTTP. For browsers, the Laravel app usually stays a REST/JSON or GraphQL edge in front of gRPC services.
  • Queue workers (php artisan queue:work) are long-lived like Octane: a singleton channel is reused across jobs, which is good, but set keepalive so idle channels are not silently dropped by firewalls.

Solving the classic problems ​

All traffic lands on one pod after scaling out ​

SolutionHowAdvantageCost / limitation
Client-side round_robinHeadless Service + dns:/// target + service configPer-call spread, no proxyRe-resolution lag; client config in every language
Service meshLinkerd or Istio sidecarPer-request spread, mTLS, retriesExtra hop and proxy CPU
Proxyless xDSxds:/// target + istiod or Traffic DirectorCentral policy, no sidecarLanguage support varies
Server MaxConnectionAgekeepalive.ServerParameters{MaxConnectionAge: 5 * time.Minute}Works with any client, even pick_firstCoarse; minutes to rebalance
L7 load balancerAWS ALB gRPC target group, Envoy edgePer-request at the edgeOnly for edge traffic

Calls hang and goroutines pile up ​

SolutionHowAdvantageCost / limitation
Deadline on every callcontext.WithTimeout, PHP timeout optionBounded waitMust be derived from the budget
Default per-method timeoutmethodConfig.timeout in service configSafety net for forgotten deadlinesHidden from callers
Honour cancellation in handlersctx.Done(), pass ctx to SQLStops wasted workDiscipline in every handler
KeepaliveClientParameters{Time, Timeout}Detects dead connectionsMust match server enforcement

A deleted field number was reused ​

SolutionHowAdvantageCost / limitation
reserved numbers and namesreserved 4; reserved "customer_email";Compiler refuses reuseMust be done in the deleting commit
buf breaking in CIbuf breaking --against '.git#branch=main'Catches removal of reserved, renumberingNeeds a baseline branch or BSR
New field for new meaningint64 loyalty_points = 12;Old data stays readableField numbers grow
New package for new semanticsorders.v2Clean breakTwo versions to run

Browsers and partners need the API ​

SolutionHowAdvantageCost / limitation
gRPC-Web + Envoyenvoy.filters.http.grpc_webTyped browser clientNo client or bidi streaming
ConnectServe gRPC + gRPC-Web + Connect from one handlerNo proxy, curl-friendly, GET cachingServer must use Connect libraries
grpc-gatewaygoogle.api.http annotations + generated proxyReal REST + OpenAPIExtra process; mapping to maintain
Envoy JSON transcoderDescriptor set in EnvoyNo codeProxy config per service

Duplicate side effects after retries ​

A DEADLINE_EXCEEDED or UNAVAILABLE after the server committed means "unknown outcome". Retrying CreateOrder without protection creates two orders. Carry an idempotency key in the request message (better than metadata: it is part of the contract and survives transcoding) and store it with the result.

sql
-- Idempotency store used by the CreateOrder handler (PostgreSQL)
CREATE TABLE grpc_idempotency (
    method        text        NOT NULL,           -- '/orders.v1.OrderService/CreateOrder'
    idem_key      text        NOT NULL,           -- CreateOrderRequest.request_id
    request_hash  bytea       NOT NULL,           -- sha256 of the deterministic proto bytes
    status_code   smallint,                       -- gRPC code once finished, NULL while running
    response      bytea,                          -- serialized CreateOrderResponse
    created_at    timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (method, idem_key)
);
-- First attempt claims the key; a retry finds the stored response.
INSERT INTO grpc_idempotency (method, idem_key, request_hash)
VALUES ($1, $2, $3)
ON CONFLICT (method, idem_key) DO NOTHING
RETURNING idem_key;
SolutionHowAdvantageCost / limitation
Idempotency key in the requeststring request_id = 1; + table aboveSafe retries end to endStorage and TTL
No retry policy on writesOmit retryPolicy for the methodNo duplicates from gRPC itselfCallers see transient errors
ALREADY_EXISTS as successClient treats it as done for creates with client-chosen idsNatural idempotencyNeeds client-generated ids

The full design (TTL, fingerprint mismatch, concurrent duplicates) is in API Idempotency.

Large responses fail with RESOURCE_EXHAUSTED ​

SolutionHowAdvantageCost / limitation
Paginationpage_size, page_token fieldsBounded messagesMore round trips
Server streamingreturns (stream Order)Constant memoryHarder to load-balance and retry
Raise the limitMaxCallRecvMsgSize(16 << 20)QuickMemory spikes; hides design issues
Claim checkStore blob in object storage, send a URLTiny messagesTwo systems

Errors cannot be told apart ​

SolutionHowAdvantageCost / limitation
Precise codesNOT_FOUND vs FAILED_PRECONDITION vs ABORTEDCallers branch correctlyNeeds a code review checklist
Rich detailsBadRequest, ErrorInfo{reason}, RetryInfoMachine-readableClients must decode details
Dashboards on grpc-statusOpenTelemetry rpc.grpc.status_codeTrue error rateHTTP-only dashboards must change

Choosing ​

Who calls this API?public / partnersown front endsown servicesREST + OpenAPIany client, curl, browsersHTTP caching: ETag, CDN, GETJSON; schema optionalstreaming: SSE / WebSocketGraphQL (BFF / federation)client picks fields per screenone round trip, many servicestyped schema, introspectioncaching: persisted queriesgRPC + Protobuftyped contract, codegen4 streaming shapes on HTTP/2deadlines, status, retriesper-call LB, small payloadsBrowser must call it?gRPC-Web via Envoy, Connect,or JSON transcoding (gateway)Common real answer: all three, one per boundaryREST at the public edge, GraphQL for the app BFF, gRPC between services,one .proto as the source of truth, transcoded where JSON is needed.Not the deciding factor: raw speed. Measured here, protobuf is ~3.5x smaller and ~1.6x faster to encode than JSONfor one order; network, database and fan-out usually dominate. Decide on boundary, tooling, streaming and caching.

REST vs GraphQL vs gRPC ​

This is the decision table for REST vs gRPC and GraphQL vs gRPC on every axis that comes up in a design review.

AxisRESTGraphQLgRPC
AudiencePublic, partners, unknown clientsFirst-party UIs with many screensFirst-party services
Browser supportNativeNativegRPC-Web, Connect or transcoding
Contract and schemaOpenAPI, optionalSDL, mandatory, introspection.proto, mandatory, reflection
Code generationOptional (OpenAPI generators)Common (typed queries)Standard (protoc, buf)
Over/under-fetchingFixed resource shapesClient chooses fieldsFixed message shapes
StreamingSSE, WebSocket, chunkedSubscriptions (WebSocket, SSE)Server, client, bidi built in
HTTP caching / CDNExcellent (GET, ETag, Cache-Control)Poor without persisted queriesNone (Connect GET is the exception)
Error modelHTTP status + RFC 9457 Problem Detailserrors array, usually HTTP 20017 codes + google.rpc.Status details
Deadlines on the wireNo standardNo standardgrpc-timeout, propagated
Load balancingAny L4/L7 balancerAny L7 balancerPer-call LB needed (client, mesh, xDS)
PayloadJSON textJSON text, only requested fieldsBinary Protobuf
VersioningURL or header versionsAdditive schema, @deprecatedAdditive fields, reserved, package v2
Debuggingcurl, browser devtoolsGraphiQL, devtoolsgrpcurl, Postman, reflection
Gateway / edge productsEvery API gatewayApollo Router, GraphQL gatewaysEnvoy, Istio, Linkerd, NGINX grpc_pass, AWS ALB

By workload ​

WorkloadRecommendationExtra techniqueReason
Public API for third partiesREST + OpenAPIOptionally generated from .proto via grpc-gatewayEveryone can call it; caching works
Mobile app talking to many backendsGraphQL BFF or REST BFFgRPC from the BFF inwardOne round trip, shape per screen
Internal service-to-service callsgRPCDeadlines, round_robin/mesh, buf breakingTyped contracts, call semantics
High-fan-out low-latency readsgRPCHedging near p95, small messagesTail latency control
Real-time feed to browsersSSE or WebSocket, or Connect server streamingReconnect with resume tokensBrowsers lack bidi gRPC
Bulk upload from devices or warehousesgRPC client streamingBatching, idempotent idsOne stream, one summary
Event streams between servicesKafka/RabbitMQ with Protobuf payloadsSchema registryAsync is a different decision (messaging)
Admin CRUD in LaravelREST or Inertia/LivewiregRPC client to internal servicesSimplicity wins
Polyglot platform with many teamsgRPC + BSRGenerated SDKs per languageOne contract, many languages

Which gRPC feature to turn on ​

SituationFeatureSetting
Every callDeadlineDerived from the user budget
Idempotent reads during deploysretryPolicyUNAVAILABLE, maxAttempts 3-4, throttling on
Tail latency on fan-out readshedgingPolicyhedgingDelay near p95, maxAttempts 2-3
Kubernetes without meshround_robin + headless ServicePlus server MaxConnectionAge
Idle connections through firewallsKeepaliveClient Time above server MinTime
Large resultsStreaming or paginationKeep 4 MiB default
Cross-region bandwidthgzip compressionMeasure CPU cost
Graceful deploysHealth serviceNOT_SERVING before GracefulStop()

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

gRPC and Protobuf change shape as the system grows: first a contract inside one codebase, then a boundary between teams, then the backbone of service-to-service traffic, and finally a schema that outlives every deployment because it is stored in logs, caches and archives.

Monolith: one process, one database ​

A Laravel monolith has no network boundary, so it needs neither gRPC nor Protobuf internally. The first appearance is usually outbound: the monolith calls an external gRPC API (Google Cloud APIs, a payment or search vendor) through a generated PHP client, exactly like the OrdersClient above, with a deadline and a status mapping. Example: the checkout controller calls a fraud-scoring service over gRPC with a 300 ms deadline and falls back to manual review on DEADLINE_EXCEEDED or UNAVAILABLE.

Modular monolith: boundaries without the network ​

Modules can share Protobuf messages as their in-process contract (Go services sometimes do this) or keep PHP interfaces and DTOs. The useful step is to write the .proto for the module boundary before you extract it: lint it, run buf breaking on it, and generate types the module uses internally. When the module becomes a service, the contract is already reviewed and versioned. Example: the Orders module in a Go modular monolith exposes an OrderService interface generated from orders.v1; extraction changes the wiring from a direct call to a channel, not the callers.

Microservices: every arrow is a channel ​

Here gRPC is typically the default for synchronous internal calls. The concrete flow for the running example:

text
     Mobile app        BFF (GraphQL or REST)        Checkout (Go)             Orders (Go)           Payments
1    POST /checkout -> resolves query, budget 800 ms
2                     gRPC Checkout.PlaceOrder (grpc-timeout 790m, traceparent, authorization)
3                                                   Orders.CreateOrder{request_id} (deadline propagated)
4                                                                             INSERT ... idempotency
5                                                   Payments.Authorize (no retryPolicy, idempotency key)
6                                                   <- OK / ABORTED / UNAVAILABLE mapped to user messages
7    <- 201 JSON with order id; HTTP status from grpc-gateway-style mapping

What survives across services: the .proto contract, deadlines (propagated through ctx), metadata (tracing, auth), status codes and details. What does not: transactions (use sagas and the outbox), and "exactly once" (use idempotency keys). Async events between the same services still use Protobuf payloads on Kafka or RabbitMQ, and the same evolution rules apply. Contract ownership, consumer-driven tests and sync-vs-async choices are in Service Communication.

Distributed data: replicas, caches, regions ​

Protobuf bytes end up at rest: in Redis caches, in Kafka topics with weeks of retention, in database bytea columns, in object-storage archives. That is where schema evolution stops being theoretical: a reader in 2028 must decode a message written in 2026, so reserved and "never change a number" are data-durability rules, not style. Middle tiers (caches, proxies, replication pipelines) must handle unknown fields in binary form; converting to JSON on the way drops them. Across regions, gRPC calls should prefer local backends (xDS locality-aware balancing), use hedging only on reads, and carry deadlines that include the extra round trip. Read-your-writes across replicas is not something gRPC provides; a GetOrder right after CreateOrder may hit a replica that has not caught up (Replication).

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

ScaleWhat changesgRPC / Protobuf decisions
1x (a few services, one cluster)Hand-run protoc or buf generate, client round_robinDeadlines everywhere, health service, buf lint
10x (dozens of services, several teams)Schema repository or BSR, buf breaking in CI, a mesh or xDSRetry policies per method, throttling, OpenTelemetry interceptors, MaxConnectionAge
100x (hundreds of services, multi-region)Proxyless xDS or mesh with locality, generated SDKs per language, schema governanceHedging on fan-out reads, per-method message limits, error budgets on grpc-status, API review for every .proto change

Lab ​

Steps 1 to 4 were run on the author's machine (Go 1.27.4, macOS arm64, buf 1.75.0); their output is real. Steps 5 and 6 start a server and use external CLIs: expected, not run.

1. Generate code and run the test suite.

bash
cd docs/snippets/system-design/grpc-protobuf/go
buf lint && buf generate          # protoc-gen-go and protoc-gen-go-grpc on PATH
go vet ./... && go test ./... -v -count=1
# --- PASS: TestUnaryWithHeaderMetadata (0.00s)
# --- PASS: TestNotFoundCarriesResourceInfo (0.00s)
# --- PASS: TestInvalidArgumentCarriesBadRequest (0.00s)
# --- PASS: TestDeadlineExceeded (0.05s)
# --- PASS: TestCancellation (0.03s)
# --- PASS: TestRetryPolicyHidesTransientUnavailable (0.15s)
# --- PASS: TestMissingRequestIDRejectedByInterceptor (0.00s)
# --- PASS: TestServerStreamingAndTrailer (0.00s)
# --- PASS: TestClientStreaming (0.00s)
# --- PASS: TestBidiStreaming (0.00s)
# --- PASS: TestHealthCheck (0.00s)
# ok   academy/grpc-protobuf/server

2. Look at the bytes.

go
// Command lab prints the wire bytes of one Order, its JSON mapping and the
// two sizes, so the encoding section of the chapter can be checked locally.
package main

import (
	"encoding/json"
	"fmt"
	"time"

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

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

func main() {
	note := "leave at door"
	o := &ordersv1.Order{
		Id:         "o-1",
		CustomerId: "c-42",
		Status:     ordersv1.OrderStatus_ORDER_STATUS_PAID,
		Items: []*ordersv1.LineItem{
			{Sku: "SKU-1", Quantity: 2, UnitPrice: &ordersv1.Money{CurrencyCode: "EUR", AmountMinor: 1250}},
			{Sku: "SKU-2", Quantity: 1, UnitPrice: &ordersv1.Money{CurrencyCode: "EUR", AmountMinor: 2499}},
		},
		Total:     &ordersv1.Money{CurrencyCode: "EUR", AmountMinor: 4999},
		CreatedAt: timestamppb.New(time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)),
		Note:      &note,
		Labels:    map[string]string{"channel": "web"},
		Delivery:  &ordersv1.Order_PickupStoreId{PickupStoreId: "store-7"},
	}
	pb, err := proto.MarshalOptions{Deterministic: true}.Marshal(o)
	if err != nil {
		panic(err)
	}
	js, err := protojson.Marshal(o)
	if err != nil {
		panic(err)
	}
	var compact map[string]any
	_ = json.Unmarshal(js, &compact)
	cj, _ := json.Marshal(compact)
	fmt.Printf("protobuf bytes: %d\n", len(pb))
	fmt.Printf("json bytes:     %d\n", len(cj))
	fmt.Printf("first 16 bytes: % x\n", pb[:16])
	fmt.Printf("json: %s\n", cj)
}
bash
go run ./lab
# protobuf bytes: 113
# json bytes:     404          (protojson mapping; int64 amounts are quoted strings)
# first 16 bytes: 0a 03 6f 2d 31 12 04 63 2d 34 32 18 02 2a 13 0a
#   0a = field 1 LEN, 03 = length, "o-1"; 12 = field 2 LEN, 04, "c-42"; 18 = field 3 VARINT, 02 = PAID
#   2a = field 5 LEN (first LineItem), 13 = 19 bytes, 0a = its field 1 (sku)

3. Benchmark encoding.

bash
go test ./wire -run '^$' -bench . -benchmem
# BenchmarkProtoMarshal-12        ~520 ns/op   192 B/op    5 allocs/op
# BenchmarkProtoUnmarshal-12      ~670 ns/op  1096 B/op   28 allocs/op
# BenchmarkProtoJSONMarshal-12   ~2500 ns/op  3054 B/op   67 allocs/op
# BenchmarkStdJSONMarshal-12      ~840 ns/op   768 B/op    5 allocs/op
# BenchmarkStdJSONUnmarshal-12   ~1580 ns/op   704 B/op   11 allocs/op
go test ./wire -run TestSizes -v
# protobuf=113 bytes, encoding/json=398 bytes

4. Break the schema on purpose. Copy proto/ to old/proto, then in the new copy delete reserved 4; reserved "customer_email";, add int64 loyalty_points = 4;, renumber created_at from 7 to 12 and rename customer_id to buyer_id.

bash
buf breaking proto --against old/proto            # breaking: FILE
# proto/orders/v1/orders.proto:45:1:Previously present field "7" with name "created_at" on message "Order" was deleted.
# proto/orders/v1/orders.proto:45:1:Previously present reserved name "customer_email" on message "Order" was deleted.
# proto/orders/v1/orders.proto:45:1:Previously present reserved range "[4]" on message "Order" is missing values: [4] were removed.
# proto/orders/v1/orders.proto:49:3:Field "2" with name "buyer_id" on message "Order" changed option "json_name" from "customerId" to "buyerId".
# proto/orders/v1/orders.proto:49:10:Field "2" on message "Order" changed name from "customer_id" to "buyer_id".
# with breaking: WIRE in buf.yaml the two rename lines disappear and line 1 ends "... was deleted without reserving the number "7"."

5. Call the running server with grpcurl (expected, not run).

go
// Command orders-server runs the chapter's OrderService on 127.0.0.1:50051
// (plaintext, for the lab only) with health and reflection enabled, so
// grpcurl and grpc_health_probe can talk to it.
package main

import (
	"log/slog"
	"net"
	"os"

	ordersv1 "academy/grpc-protobuf/gen/orders/v1"
	"academy/grpc-protobuf/server"
)

func main() {
	log := slog.New(slog.NewTextHandler(os.Stdout, nil))
	store := server.NewMemStore(
		&ordersv1.Order{Id: "o-1", CustomerId: "c-1", Status: ordersv1.OrderStatus_ORDER_STATUS_PAID},
		&ordersv1.Order{Id: "o-2", CustomerId: "c-1", Status: ordersv1.OrderStatus_ORDER_STATUS_SHIPPED},
	)
	gs, _ := server.New(&server.Service{Store: store}, log)
	lis, err := net.Listen("tcp", "127.0.0.1:50051")
	if err != nil {
		log.Error("listen", "err", err)
		os.Exit(1)
	}
	log.Info("serving", "addr", lis.Addr().String())
	if err := gs.Serve(lis); err != nil {
		log.Error("serve", "err", err)
		os.Exit(1)
	}
}
bash
go run ./cmd/orders-server &
grpcurl -plaintext 127.0.0.1:50051 list
# grpc.health.v1.Health
# grpc.reflection.v1.ServerReflection
# grpc.reflection.v1alpha.ServerReflection
# orders.v1.OrderService
grpcurl -plaintext -H 'x-request-id: lab-1' -d '{"id":"o-1"}' 127.0.0.1:50051 orders.v1.OrderService/GetOrder
# {"order": {"id": "o-1", "customerId": "c-1", "status": "ORDER_STATUS_PAID"}}
grpcurl -plaintext -H 'x-request-id: lab-2' -d '{"id":"o-404"}' 127.0.0.1:50051 orders.v1.OrderService/GetOrder
# ERROR:
#   Code: NotFound
#   Message: order not found
#   Details:
#   1)  {"@type": "type.googleapis.com/google.rpc.ResourceInfo", "resourceName": "o-404", ...}
grpcurl -plaintext -d '{"id":"o-1"}' 127.0.0.1:50051 orders.v1.OrderService/GetOrder
# ERROR: Code: InvalidArgument  Message: missing x-request-id metadata
grpcurl -plaintext -d '{"service":"orders.v1.OrderService"}' 127.0.0.1:50051 grpc.health.v1.Health/Check
# {"status": "SERVING"}

6. Keepalive misconfiguration (expected, not run). Change the client's keepalive.ClientParameters.Time to 1 * time.Second (raised to 10 s by grpc-go) and the server's EnforcementPolicy.MinTime to 1 * time.Minute, idle for a minute: the server logs a ping strike, sends GOAWAY ENHANCE_YOUR_CALM with too_many_pings, and the client logs Client received GoAway with error code ENHANCE_YOUR_CALM and debug data equal to ASCII "too_many_pings" and reconnects.

Common misconceptions ​

BeliefReality
gRPC is always much faster than RESTEncoding is cheaper (we measured ~1.6x to 2.4x for one message), but I/O dominates most calls
Protobuf is automatically backward compatibleOnly if numbers and types never change and deleted fields are reserved
Renaming a field is a breaking change on the wireNot for binary; it is for JSON and generated code
HTTP 200 means the call succeededThe result is grpc-status in the trailers
gRPC has a default timeoutNo deadline by default: calls can wait forever
The server stops my handler when the deadline passesIt cancels the context; your code must check it
Kubernetes Services balance gRPCClusterIP balances connections; HTTP/2 pins calls to one pod
Retries are off unless configuredTransparent retries always happen; policies add more
Retrying on DEADLINE_EXCEEDED is safeThe operation may have completed; retry only idempotent calls
Browsers can call gRPC because they speak HTTP/2They cannot read trailers; use gRPC-Web, Connect or transcoding
JSON of a proto equals json.MarshalThe mapping quotes int64, uses enum names, lowerCamelCase, RFC 3339
Unknown fields are droppedProto3 keeps them in binary; JSON conversion drops them
optional is the default in proto3Scalars without optional have implicit presence: zero means "not set"
More keepalive pings are saferToo many pings get GOAWAY too_many_pings
Streaming is better than unaryStreams are hard to balance and retry; use them for real streams

Cheat sheet ​

TopicWhat to remember
Field numbersNever change or reuse; 1-15 for hot fields; reserved on delete
Wire types0 VARINT, 1 I64, 2 LEN, 5 I32; tag = (n << 3) | type
Negative numberssint32/sint64 (zigzag), not int64 (10 bytes)
Presenceoptional when zero is meaningful; oneof for exclusive choices
EvolutionAdd freely; never renumber; never move into a oneof; buf breaking in CI
JSONprotojson; int64 as string; enums as names; unknown fields lost
ChannelsOne per target, long-lived; never per call
DeadlinesAlways set; propagate ctx; check ctx.Done()
Status codesMost specific code + rich details; branch on codes, not text
RetriesOnly idempotent methods, UNAVAILABLE, max 3-4 attempts, throttling on
HedgingReads only, delay near p95, deadline covers all copies
Load balancingpick_first is default; use round_robin, a mesh or xDS; MaxConnectionAge
KeepaliveClient Time above server MinTime; below path idle timeouts
Message size4 MiB receive default; paginate or stream
BrowsersgRPC-Web (Envoy), Connect, or grpc-gateway / Envoy transcoding
ChoosingREST public edge, GraphQL front-end BFF, gRPC internal

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 colleague deletes string customer_email = 4; and, a month later, adds int64 loyalty_points = 4;. What happens to old stored messages, and what two things would have prevented it? Must-know ​

Answer

Answer: Old messages carry field 4 as LEN (wire type 2); the new reader expects VARINT for field 4, so parsing fails or, with a matching wire type, a wrong value is silently accepted. Adding reserved 4; reserved "customer_email"; in the deleting commit makes the compiler reject reuse, and buf breaking in CI flags both the removed field and later removal of the reservation.

2 — Why does -1 take 10 bytes as int64 but 1 byte as sint64? Good to know ​

Answer

Answer: int64 encodes negatives as two's complement, so the 64-bit value has its high bit set and the varint needs all 10 bytes. sint64 applies zigzag first (-1 becomes 1), and 1 is a one-byte varint.

3 — A client sends UpdateDiscount{percent: 0} with int32 percent = 2;. Why can the server not tell "set to zero" from "not sent", and what is the fix? Must-know ​

Answer

Answer: With implicit presence zero values are not serialized, so both cases produce the same bytes. Declare optional int32 percent = 2; (same number, wire compatible) and check HasPercent/pointer nil, or use a FieldMask.

4 — All your gRPC calls return HTTP 200 in the load balancer logs, yet users see errors. Where is the real status? Must-know ​

Answer

Answer: In the grpc-status trailer (with grpc-message and optionally grpc-status-details-bin). Monitor the gRPC code, for example OpenTelemetry rpc.grpc.status_code, not the HTTP status.

5 — After scaling a deployment from 3 to 10 pods behind a ClusterIP Service, the new pods get no gRPC traffic. Why, and name three fixes. Important ​

Answer

Answer: ClusterIP is L4 and balances connections; each client holds one long-lived HTTP/2 connection with all calls multiplexed on it. Fixes: headless Service with dns:/// and round_robin; a mesh (Linkerd, Istio) or L7 proxy; proxyless xDS; and server MaxConnectionAge to force periodic reconnects.

6 — Your retry policy lists DEADLINE_EXCEEDED for CreateOrder. What can go wrong and what should you do instead? Must-know ​

Answer

Answer: DEADLINE_EXCEEDED "may be returned even if the operation has completed successfully", so a retry can create a duplicate order. Remove the policy for the write (or limit it to UNAVAILABLE), and make the method idempotent with a client-supplied request id stored in an idempotency table.

7 — What is the difference between a retry policy and a hedging policy, and which methods may use either? Important ​

Answer

Answer: A retry policy sends the next attempt after a failure with a retryable code and backoff; hedging sends additional copies after hedgingDelay without waiting for failure and uses the first success, cancelling the rest. Both are only for idempotent methods; hedging is for tail latency on reads. maxAttempts above 5 is treated as 5, and the deadline covers all attempts.

8 — A client sets keepalive Time to 5 s against a grpc-go server with default settings. What happens? Important ​

Answer

Answer: grpc-go raises the client value to 10 s, but the server's default EnforcementPolicy.MinTime is 5 minutes, so it counts ping strikes and closes the connection with GOAWAY ENHANCE_YOUR_CALM and debug data too_many_pings. Set the client's Time above the server's MinTime (or lower MinTime on the server).

9 — A browser SPA must call OrderService including a live-tracking stream. Which options work and what are their limits? Important ​

Answer

Answer: gRPC-Web through Envoy supports unary and server streaming (not client or bidi streaming); Connect supports unary and server streaming over fetch without a proxy and allows GET for side-effect-free methods; grpc-gateway or Envoy transcoding gives REST/JSON with server streaming as newline-delimited JSON. Bidirectional tracking needs a WebSocket or two streams instead.

10 — Why does buf breaking with the WIRE category not report a field rename, while FILE does? Good to know ​

Answer

Answer: Names are not on the binary wire, so a rename is wire-safe; WIRE checks only binary compatibility. FILE (and PACKAGE) protect generated source code, where the accessor name changes, and WIRE_JSON protects the JSON mapping, where the key (json_name) changes.

11 — When would you choose GraphQL over gRPC for a new API, and when REST over both? Must-know ​

Answer

Answer: GraphQL when first-party front ends with many screens need different shapes of data from several services in one round trip (usually as a BFF). REST when the callers are public or partners, need any language and curl, and benefit from HTTP caching and CDNs. gRPC for internal service-to-service calls that need typed contracts, deadlines, streaming and per-call load balancing.

Glossary ​

TermMeaning
Protocol Buffers (Protobuf)Language-neutral schema language and binary encoding with numbered fields
proto3The Protobuf syntax revision declared with syntax = "proto3";
EditionsSuccessor to proto2/proto3 syntax with per-feature settings (edition = "2024")
Field numberThe integer that identifies a field on the wire; 1 to 536,870,911
Wire type3-bit code in the tag that says how the payload is encoded
TagVarint (field_number << 3) | wire_type that starts each record
VarintVariable-length base-128 integer, 7 bits per byte
ZigzagMapping of signed to unsigned integers used by sint32/sint64
Length-delimited (LEN)Wire type 2: varint length then bytes
Packed repeatedRepeated scalars stored in one LEN record (default in proto3)
Implicit presenceProto3 scalar without optional: zero value is not serialized
optionalExplicit presence for a proto3 scalar field
oneofGroup of fields of which at most one is set
mapKey/value field map<K, V>, encoded as repeated entries
repeatedList field
reservedDeclaration that forbids reuse of deleted field numbers or names
Unknown fieldsFields a reader does not know, preserved in binary round trips
Schema evolutionChanging a schema while old and new readers and writers coexist
Well-known typesStandard messages such as Timestamp, Duration, Any, Struct, FieldMask
TimestampPoint in time as seconds and nanos since the Unix epoch (UTC)
DurationSigned span of time; JSON form "1.5s"
AnyA packed message plus its type URL
StructSchemaless JSON object inside a typed message
JSON mappingOfficial Protobuf JSON form (lowerCamelCase, int64 as string, enum names)
protocThe reference Protobuf compiler
protoc-gen-goPlugin that generates Go message types
protoc-gen-go-grpcPlugin that generates Go gRPC client and server stubs
grpc_php_pluginPlugin that generates PHP gRPC client stubs
gRPCRPC framework and protocol over HTTP/2 using Protobuf by default
HTTP/2Binary, multiplexed HTTP version (RFC 9113) that gRPC runs on
ChannelClient-side virtual connection to a target, with resolver and LB policy
SubchannelOne connection to one backend address inside a channel
StubGenerated client object with one method per RPC
Unary RPCOne request, one response
Server streamingOne request, a stream of responses
Client streamingA stream of requests, one response
Bidirectional streamingBoth sides stream independently on one call
DeadlineAbsolute time after which the caller no longer wants the result
grpc-timeoutHeader that carries the remaining deadline as a relative timeout
CancellationSignal that the caller no longer wants the result (RST_STREAM)
MetadataKey/value headers and trailers on an RPC
TrailersHeaders sent after the last message; carry grpc-status
Status codeOne of 17 gRPC result codes (OK to UNAUTHENTICATED)
OK, CANCELLED, DEADLINE_EXCEEDED, UNAVAILABLESuccess; caller gave up; deadline passed; transient failure, retryable
NOT_FOUND, INVALID_ARGUMENT, RESOURCE_EXHAUSTEDEntity missing; bad request; quota, rate or size limit
Rich error detailsTyped messages in google.rpc.Status.details (BadRequest, ErrorInfo, RetryInfo)
grpc-status-details-binTrailer carrying the serialized google.rpc.Status
InterceptorMiddleware that wraps RPCs on client or server
Service configJSON document with LB policy, method timeouts, retry and hedging policies
Retry policyretryPolicy: automatic retries on listed codes with backoff
Transparent retryRetry gRPC does on its own when the server application never saw the call
HedgingSending extra copies of a request after a delay and using the first success
Retry throttlingToken bucket that pauses retries when failures dominate
Name resolverPlugin that turns a target URI into addresses and service config
pick_firstDefault LB policy: one connection to the first reachable address
round_robinLB policy that rotates calls across all addresses
xDSEnvoy's discovery APIs, used by proxyless gRPC to get endpoints and policy
KeepaliveHTTP/2 PINGs that detect dead connections
Max message sizePer-message limit, 4 MiB receive by default in Go
CompressionPer-message compression negotiated by grpc-encoding (gzip)
Health checkingStandard grpc.health.v1.Health service with Check and Watch
ReflectionStandard service that lists services and types for tools like grpcurl
gRPC-WebBrowser variant of gRPC with trailers in the body, via a proxy
grpc-gatewayprotoc plugin that generates a REST/JSON reverse proxy for gRPC
TranscodingTranslating REST/JSON requests to gRPC using google.api.http rules
ConnectBuf's RPC libraries and protocol that also speak gRPC and gRPC-Web
bufProtobuf toolchain: lint, breaking-change detection, generation, BSR
LintStyle and structure checks on .proto files (MINIMAL, BASIC, STANDARD)
Breaking changeA schema change that breaks old readers, writers or generated code
BSRBuf Schema Registry: versioned Protobuf modules and generated SDKs
REST vs gRPCResource-oriented HTTP + JSON versus typed RPC over HTTP/2 + Protobuf
GraphQL vs gRPCClient-shaped queries over one endpoint versus fixed RPC methods
grpcurlcurl-like CLI for gRPC that uses reflection or descriptor files
EnvoyL7 proxy with native gRPC, gRPC-Web and JSON transcoding filters

References ​

Built by Morteza Negahi