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 for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a binary schema and an RPC protocol at all | Why it exists |
| Proto1 to editions, Stubby to gRPC, gRPC-Web, Connect, buf | Where it comes from |
.proto files, protoc, protoc-gen-go, generated code | Contract and codegen |
| Field numbers, wire types, varint, zigzag, length-delimited | Wire format |
optional, oneof, map, repeated, presence | Field presence and shapes |
reserved, unknown fields, safe and unsafe changes | Schema evolution |
Timestamp, Duration, Any, Struct, JSON mapping | Well-known types and JSON |
HTTP/2 framing, grpc-timeout, trailers | gRPC on HTTP/2 |
| Unary and the three streaming shapes | RPC shapes |
| Deadlines, cancellation, propagation | Deadlines and cancellation |
Headers, trailers, -bin keys | Metadata |
OK to UNAUTHENTICATED, google.rpc.Status details | Status codes and rich errors |
| Middleware for RPCs | Interceptors |
retryPolicy, hedgingPolicy, retryThrottling | Retries, hedging, service config |
Resolvers, pick_first, round_robin, xDS, Kubernetes | Name resolution and load balancing |
| Keepalive, message size, compression, flow control | Connection knobs |
grpc.health.v1, server reflection, grpcurl | Health checking and reflection |
| Browsers: gRPC-Web, grpc-gateway, Envoy transcoding, Connect | Reaching browsers |
buf lint, buf breaking, BSR | buf |
| Size and speed against JSON, with numbers | Performance |
| Tables of codes, headers and knobs | Mechanics |
| Code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| REST vs GraphQL vs gRPC | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Protocol Buffers in one table.
| Concept | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Field number | The real name of a field on the wire | string id = 1; | Renumbering silently corrupts old data |
| Wire type | How many bytes follow a tag | 0 VARINT, 1 I64, 2 LEN, 5 I32 | A reader cannot skip a field it does not know |
| Varint | Small numbers take few bytes | 150 is 96 01 | Fixed 8-byte integers everywhere |
Zigzag (sint32/sint64) | Small negatives stay small | -500 is 2 bytes, not 10 | Refunds and deltas bloat messages |
| Length-delimited | Strings, bytes, sub-messages, packed lists | 0a 03 "EUR" | No nesting |
optional | Tells "not set" from "set to zero" | optional string note = 8; | 0 and "missing" look the same |
oneof | At most one of several fields | pickup_store_id or ship_to | Two contradictory fields set |
reserved | Tombstone for deleted numbers and names | reserved 4; reserved "customer_email"; | Someone reuses 4 for another type |
| Unknown fields | Fields from a newer writer survive in an older reader | Old binary forwards new field 12 | Data loss in proxies and middle tiers |
| Well-known types | Shared messages for time, durations, any | google.protobuf.Timestamp | Every team invents its own date format |
gRPC in one table.
| Concept | In plain words | Exact knob or wire name | Default |
|---|---|---|---|
| Channel | Long-lived virtual connection to a service name | grpc.NewClient("dns:///orders:443") | Reuse it; never one per call |
| Unary / streaming | One or many messages per side | rpc X(A) returns (stream B) | Unary |
| Deadline | Absolute "give up" time, sent as a timeout | grpc-timeout: 800m | None: waits forever |
| Metadata | Key/value headers and trailers | x-request-id, authorization, trace-bin | Empty |
| Status code | 17 codes, carried in trailers | grpc-status: 14 (UNAVAILABLE) | OK = 0 |
| Rich error details | Typed details inside google.rpc.Status | grpc-status-details-bin | None |
| Retry policy | Per-method automatic retry | retryPolicy.maxAttempts (capped at 5) | Only transparent retries |
| Hedging | Parallel copies to cut tail latency | hedgingPolicy.hedgingDelay | Off |
| Load balancing | Per-call choice of backend | pick_first, round_robin, xDS | pick_first |
| Max message size | Receive limit per message | MaxRecvMsgSize, grpc.max_receive_message_length | 4 MiB receive |
| Keepalive | HTTP/2 PING to detect dead links | keepalive.ClientParameters.Time | Client off; server ping policy 5 min |
| Health | Standard service grpc.health.v1.Health | Check, Watch | Not registered |
REST vs GraphQL vs gRPC in one table.
| Axis | REST (HTTP + JSON) | GraphQL | gRPC (HTTP/2 + Protobuf) |
|---|---|---|---|
| Best boundary | Public and partner APIs | Your own front ends, BFF | Your own services |
| Contract | Optional (OpenAPI) | Mandatory schema (SDL) | Mandatory .proto |
| Browser | Native | Native (POST or GET) | Needs gRPC-Web, Connect or transcoding |
| Streaming | SSE, WebSocket, chunked | Subscriptions (usually WebSocket) | Four native shapes |
| HTTP caching | Native: GET, ETag, CDN | Hard; persisted queries + GET | None (every call is POST) |
| Errors | HTTP status + Problem Details | errors array, HTTP 200 | 17 status codes + typed details |
| Payload size | Text, verbose | Text, only requested fields | Binary, field numbers |
| Tooling | curl, browsers, every language | GraphiQL, codegen | protoc/buf codegen, grpcurl, Postman |
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 message | Field numbers only; the schema is needed to read it |
| Contract optional; drift found in production | Contract mandatory; drift found at compile time and by buf breaking |
| Any client, any browser, curl | Generated stubs; browsers need a bridge |
| HTTP caching and CDNs work | No HTTP caching; every call is POST |
| Streaming bolted on (SSE, WebSocket) | Four streaming shapes built in |
| Timeouts per client library, not on the wire | Deadline on the wire (grpc-timeout), propagated |
| Errors: HTTP status + ad hoc bodies | 17 canonical codes + typed details |
| Connection-level load balancing works | HTTP/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
- "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.
- "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.
- "An HTTP 200 means the call succeeded." In gRPC almost every response is HTTP 200; the result is
grpc-statusin the trailers. A proxy, log line or dashboard that looks only at HTTP status will report a 100 % success rate while every call returnsNOT_FOUNDorINTERNAL.
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).
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/proto3Dates 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.
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 contractReal 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:
| Tool | Role | Notes |
|---|---|---|
protoc | Reference compiler | Plugins found on PATH as protoc-gen-NAME |
protoc-gen-go (google.golang.org/protobuf/cmd/protoc-gen-go) | Go message types | option go_package sets the import path |
protoc-gen-go-grpc (google.golang.org/grpc/cmd/protoc-gen-go-grpc) | Go client and server stubs | Embeds UnimplementedXServer for forward compatibility |
grpc_php_plugin + protobuf PHP | PHP classes and client stubs | PHP is client-only for gRPC |
buf generate | Runs plugins from buf.gen.yaml | Local 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.
// 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".
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 bytesReal 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 type | Wire type | Negative -1 costs | Use for |
|---|---|---|---|
int32 / int64 | VARINT | 10 bytes | Counters that are almost never negative |
sint32 / sint64 | VARINT (zigzag) | 1 byte | Values often negative: deltas, refunds, offsets |
uint32 / uint64 | VARINT | not allowed | Sizes, ids that are never negative |
fixed32 / fixed64 | I32 / I64 | n/a | Values usually large (hashes) |
sfixed32 / sfixed64 | I32 / I64 | 4 / 8 bytes | Large signed values |
double / float | I64 / I32 | 8 / 4 bytes | Measurements; never money |
string / bytes / message | LEN | n/a | Text 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).
// 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".
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 clearedReal 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:
| Language | optional scalar | oneof | map iteration |
|---|---|---|---|
Go (protoc-gen-go) | Pointer field *string, GetNote() returns "" when nil | Interface field with wrapper types (Order_PickupStoreId) | Go map, random order |
| PHP (protobuf) | hasNote(), clearNote() | getDelivery() returns the set field's name | MapField, undefined order |
| JSON mapping | Field omitted when unset | Only the set field appears | JSON 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.
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 CIReal 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:
| Change | Binary wire | JSON mapping | Generated code | buf breaking category that flags it |
|---|---|---|---|---|
| Add a field with a new number | Safe | Safe | Safe | none |
Delete a field and reserved its number + name | Safe | Safe if name reserved | Breaks users of the field | FILE, PACKAGE (deletion) |
Delete without reserved | Safe now, unsafe later | Unsafe later | Breaks users | WIRE too ("without reserving the number") |
| Rename a field | Safe | Breaks (json_name changes) | Breaks | FILE, PACKAGE, WIRE_JSON |
| Change a field number | Unsafe | Unsafe | Breaks | all four |
int32 to int64 | Compatible (truncation risk) | Safe | Breaks types | FILE, PACKAGE |
int64 to sint64 | Unsafe (encoding differs) | Safe | Breaks types | all |
Move a field into an existing oneof | Unsafe | Unsafe | Breaks | all |
| Add an enum value | Safe (unknown values preserved) | Old readers see the number | Exhaustive switches break | none |
Remove reserved entries | Unsafe | Unsafe | n/a | all 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.
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 inputReal 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:
| Type | Use | JSON form |
|---|---|---|
google.protobuf.Timestamp | A point in time (seconds + nanos since epoch, UTC) | RFC 3339 string |
google.protobuf.Duration | A span of time | "1.5s" |
google.protobuf.Any | Any message plus its type URL | Object with @type |
google.protobuf.Struct / Value / ListValue | Schemaless JSON | Plain JSON |
google.protobuf.FieldMask | Which fields a partial update touches | "note,labels" |
google.protobuf.Empty | No request or response data | {} |
Wrappers (StringValue, Int64Value, ...) | Presence before proto3 optional existed | The 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.
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".
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 finishReal 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:
| Product | gRPC support | Notes |
|---|---|---|
| Envoy (and Istio, which uses it) | Native HTTP/2, per-stream balancing, gRPC-Web filter, JSON transcoder | The reference gRPC proxy |
| NGINX | grpc_pass module | Needs HTTP/2 on the listener |
| HAProxy | HTTP/2 end-to-end mode | Configure proto h2 to the backend |
| AWS ALB | gRPC target groups | L7; NLB is L4 and balances connections only |
| Google Cloud Load Balancing | HTTP/2 backends | Traffic Director adds xDS |
| Linkerd | Transparent per-request gRPC balancing | Sidecar 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.
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 OKReal 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:
| Platform | Unary | Server streaming | Client streaming | Bidi |
|---|---|---|---|---|
| gRPC over HTTP/2 (Go, Java, C++, ...) | Yes | Yes | Yes | Yes |
| gRPC PHP extension (client only) | Yes | Yes | Yes | Yes |
| gRPC-Web in browsers | Yes | Yes (grpcwebtext mode) | No | No |
| Connect protocol | Yes (also GET) | Yes | Needs HTTP/2 | Needs HTTP/2 |
| grpc-gateway / Envoy JSON transcoding | Yes | Yes (newline-delimited JSON) | Limited | No |
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".
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 completionReal 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:
| Stack | Set a deadline | Propagation | What the handler must do |
|---|---|---|---|
Go (grpc-go) | context.WithTimeout(ctx, d) | Automatic when you pass the incoming ctx | select on ctx.Done(), pass ctx to SQL and HTTP |
| Java | stub.withDeadlineAfter(...) | Automatic via Context | Check Context.current().isCancelled() |
| C++ | ClientContext::set_deadline | Must be enabled explicitly | Check ServerContext::IsCancelled() |
| PHP extension | ['timeout' => microseconds] call option | Manual (PHP is client-only) | n/a |
| Service config | methodConfig.timeout | Default per method when the caller sets none | n/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."
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-totalReal 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:
| Stack | Send (client) | Read (server) | Send header / trailer (server) |
|---|---|---|---|
| Go | metadata.AppendToOutgoingContext(ctx, k, v) | metadata.FromIncomingContext(ctx) | grpc.SetHeader, grpc.SetTrailer / stream.SetTrailer |
| PHP | Second argument of the stub method: ['k' => ['v']] | n/a (client only) | Client reads $call->getMetadata(), trailers in $status->metadata |
| Envoy | request_headers_to_add | Header matching in routes | response_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".
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 -> OKReal 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 code | HTTP (grpc-gateway / Google APIs mapping) | Retry? |
|---|---|---|
OK | 200 | n/a |
INVALID_ARGUMENT, FAILED_PRECONDITION, OUT_OF_RANGE | 400 | No |
UNAUTHENTICATED | 401 | After refreshing credentials |
PERMISSION_DENIED | 403 | No |
NOT_FOUND | 404 | No |
ALREADY_EXISTS, ABORTED | 409 | ABORTED: retry the whole transaction |
RESOURCE_EXHAUSTED | 429 | With backoff, honour RetryInfo |
CANCELLED | 499 (non-standard "client closed") | No (the caller gave up) |
UNIMPLEMENTED | 501 | No |
UNAVAILABLE | 503 | Yes, with backoff (idempotent only) |
DEADLINE_EXCEEDED | 504 | Only if idempotent; outcome unknown |
INTERNAL, UNKNOWN, DATA_LOSS | 500 | No |
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.
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.3msReal 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:
| Stack | Mechanism | Ready-made examples |
|---|---|---|
| Go | Unary/stream, client/server interceptors | go-grpc-middleware (auth, logging, recovery, ratelimit), OpenTelemetry otelgrpc stats handler |
| Java | ClientInterceptor, ServerInterceptor | Built-in deadline and metadata utilities |
| PHP | Grpc\Interceptor + Interceptor::intercept($channel, ...) | Custom metadata and logging |
| Envoy / mesh | HTTP filters in the proxy | Retries, 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.
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 thisReal 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:
| Where | Configuration | Good for | Watch out |
|---|---|---|---|
| gRPC client service config | retryPolicy per method | Transient UNAVAILABLE on idempotent methods | Multiplies with retries in other layers |
| gRPC hedging | hedgingPolicy per method | Tail latency on reads | Extra load; only idempotent methods |
| Envoy / Istio route | retry_policy with retry_on: unavailable,resource-exhausted | Language-independent | Double retries with the client |
Application loop (PHP retry()) | Code | Languages without service-config retries | Must 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".
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 timeReal 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:
| Option | Where balancing happens | Pros | Cons |
|---|---|---|---|
| L4 balancer (ClusterIP, AWS NLB, HAProxy TCP mode) | Per connection | Simple, no client change | Pinning; new backends idle |
Client round_robin over DNS (headless Service) | Per call in the client | No extra hop | DNS 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 proxy | Any language, retries and mTLS centrally | Extra hop, proxy CPU |
| Proxyless xDS (istiod, Traffic Director) | Per call in the client, configured centrally | No sidecar hop, weights, locality | Client feature support varies by language |
Server MaxConnectionAge | Forces reconnect | Works with any client | Coarse; 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.
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:
| Knob | Go (grpc-go) | gRPC core (C++, PHP, Python, Ruby) channel arg | Default |
|---|---|---|---|
| Client ping interval | keepalive.ClientParameters.Time | grpc.keepalive_time_ms | Off |
| Ping ack timeout | ClientParameters.Timeout | grpc.keepalive_timeout_ms | 20 s |
| Ping with no calls | PermitWithoutStream | grpc.keepalive_permit_without_calls | false |
| Server minimum ping interval | EnforcementPolicy.MinTime | grpc.http2.min_ping_interval_without_data_ms | 5 min |
| Connection age | ServerParameters.MaxConnectionAge | grpc.max_connection_age_ms | Infinite |
| Receive limit | MaxRecvMsgSize, MaxCallRecvMsgSize | grpc.max_receive_message_length | 4 MiB |
| Send limit | MaxCallSendMsgSize | grpc.max_send_message_length | Unlimited in Go |
| Compression | grpc.UseCompressor(gzip.Name) | grpc.default_compression_algorithm | None |
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."
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.
| Product | Health integration |
|---|---|
| Kubernetes | Native grpc liveness/readiness probes |
| Envoy | grpc_health_check in cluster health checking |
| AWS ALB | gRPC health checks with expected gRPC codes |
grpc_health_probe | CLI 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.
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 -> 404Real 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.
| Approach | Browser streaming | Proxy needed | Human-readable | HTTP caching |
|---|---|---|---|---|
| gRPC-Web (grpc-web JS) | Server streaming only | Yes (Envoy, or in-process in some servers) | No (binary or base64) | No |
| Connect protocol | Unary + server streaming over fetch | No (server speaks it) | Yes with JSON | Yes for GET on side-effect-free methods |
| grpc-gateway | REST semantics | Yes (generated Go proxy) | Yes (JSON) | Yes for GET routes |
| Envoy gRPC-JSON transcoder | REST semantics | Yes (Envoy) | Yes | Yes for GET routes |
| Google Cloud Endpoints / API Gateway transcoding | REST semantics | Managed | Yes | Yes |
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.
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.
| Category | Protects | Typical use |
|---|---|---|
FILE | Generated source per file (C++, Python imports) | Default; public APIs |
PACKAGE | Generated source per package | Go, Java codebases |
WIRE_JSON | Binary and JSON encoding | Services exposed through transcoding |
WIRE | Binary encoding only | Pure 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.
version: v2
modules:
- path: proto
lint:
use:
- STANDARD
breaking:
use:
- FILEversion: v2
plugins:
- local: protoc-gen-go
out: gen
opt: paths=source_relative
- local: protoc-gen-go-grpc
out: gen
opt: paths=source_relativePerformance 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.
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 payloadsReal 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) | Protobuf | JSON | Ratio |
|---|---|---|---|
| Size of one Order | 113 B | 398 B (encoding/json) | 3.5x smaller |
| Marshal | ~520 ns/op, 5 allocs | ~840 ns/op, 5 allocs | 1.6x faster |
| Unmarshal | ~670 ns/op, 28 allocs | ~1,580 ns/op, 11 allocs | 2.4x faster |
protojson.Marshal (official JSON mapping) | ~2,500 ns/op | n/a | Slower 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.
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: ¬e,
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 id | Name | Used for | Payload |
|---|---|---|---|
| 0 | VARINT | int32, int64, uint32, uint64, sint32, sint64, bool, enum | Base-128 varint (zigzag for sint*) |
| 1 | I64 | fixed64, sfixed64, double | 8 bytes little-endian |
| 2 | LEN | string, bytes, messages, packed repeated | Varint length + bytes |
| 3 / 4 | SGROUP / EGROUP | proto2 groups | Deprecated |
| 5 | I32 | fixed32, sfixed32, float | 4 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
| Element | Wire form | Notes |
|---|---|---|
| Method | :method POST | Always POST in gRPC (Connect allows GET for side-effect-free methods) |
| Path | :path /orders.v1.OrderService/GetOrder | Package.Service/Method |
| Content type | content-type: application/grpc or application/grpc+proto | Other types get HTTP 415 |
| Proxy detection | te: trailers | Required; detects proxies that drop trailers |
| Deadline | grpc-timeout: 800m | At most 8 digits; units H, M, S, m, u, n |
| Compression | grpc-encoding, grpc-accept-encoding | Per message, flag byte = 1 |
| Message framing | 1 byte flag + 4 byte big-endian length + bytes | Length-Prefixed-Message |
| Status | grpc-status trailer | Decimal code 0-16 |
| Message | grpc-message trailer | Percent-encoded UTF-8 |
| Details | grpc-status-details-bin trailer | Base64 google.rpc.Status |
| Binary metadata | key ending in -bin | Base64 on the wire |
| Pushback | grpc-retry-pushback-ms trailer | Server tells client when (or not) to retry |
Status codes and what the caller does
| Code | Name | Generated by library? | Typical cause | Caller action |
|---|---|---|---|---|
| 0 | OK | Yes | Success | Use the response |
| 1 | CANCELLED | Yes | Caller cancelled, or server saw the deadline pass | Stop; nothing to retry |
| 2 | UNKNOWN | Yes | Unknown error space, handler panic converted | Alert; do not retry blindly |
| 3 | INVALID_ARGUMENT | No | Bad request regardless of state | Fix the request |
| 4 | DEADLINE_EXCEEDED | Yes | Deadline expired; operation may have completed | Retry only if idempotent |
| 5 | NOT_FOUND | No | Entity missing | Treat as absent |
| 6 | ALREADY_EXISTS | No | Create of an existing entity | Treat as success if idempotent create |
| 7 | PERMISSION_DENIED | No (except auth plugins) | Caller identified but not allowed | Do not retry |
| 8 | RESOURCE_EXHAUSTED | Yes (message too large, flow control) | Quota, rate limit, message size | Back off; honour RetryInfo |
| 9 | FAILED_PRECONDITION | No | State not suitable (non-empty dir) | Fix state first |
| 10 | ABORTED | No | Concurrency conflict | Retry the whole read-modify-write |
| 11 | OUT_OF_RANGE | No | Past the end (pagination, file offset) | Stop iterating |
| 12 | UNIMPLEMENTED | Yes | Method not registered, unsupported compression | Do not retry; check versions |
| 13 | INTERNAL | Yes | Invariant broken, protocol error | Alert |
| 14 | UNAVAILABLE | Yes | Connection failure, server shutting down | Retry with backoff (idempotent) |
| 15 | DATA_LOSS | No | Unrecoverable corruption | Page someone |
| 16 | UNAUTHENTICATED | Yes (credentials plugins) | Missing or invalid credentials | Refresh token, then retry once |
Service config fields
| Field | Meaning | Example |
|---|---|---|
loadBalancingConfig | Ordered list of LB policies; first supported wins | [{"round_robin": {}}] |
methodConfig[].name | Which service/method the entry applies to | {"service": "orders.v1.OrderService", "method": "GetOrder"} |
methodConfig[].timeout | Default deadline when the caller sets none | "2s" |
methodConfig[].waitForReady | Queue the call while the channel connects instead of failing fast with UNAVAILABLE | true |
methodConfig[].maxRequestMessageBytes / maxResponseMessageBytes | Per-method message limits | 1048576 |
retryPolicy | maxAttempts, initialBackoff, maxBackoff, backoffMultiplier, retryableStatusCodes | See Go |
hedgingPolicy | maxAttempts, hedgingDelay, nonFatalStatusCodes | "hedgingDelay": "0.05s" |
retryThrottling | maxTokens, tokenRatio | {"maxTokens": 10, "tokenRatio": 0.1} |
healthCheckConfig.serviceName | Client-side health checking per subchannel | "orders.v1.OrderService" |
Error messages you will actually see
| Message (verbatim or format) | Source | Meaning |
|---|---|---|
rpc error: code = DeadlineExceeded desc = context deadline exceeded | grpc-go status.Error string format rpc error: code = %s desc = %s | Client deadline passed |
rpc error: code = Unavailable desc = connection error: ... | grpc-go transport | No ready subchannel, dial failed |
grpc: received message larger than max (N vs. 4194304) | grpc-go rpc_util.go, code RESOURCE_EXHAUSTED | Receive limit (4 MiB default) |
GOAWAY ENHANCE_YOUR_CALM, debug data too_many_pings | grpc-go / core server keepalive enforcement | Client pings faster than server MinTime |
| HTTP 415 Unsupported Media Type | Server got a non-gRPC content type | A REST client or a misrouted request |
Previously present field "7" with name "created_at" on message "Order" was deleted. | buf breaking | A field number disappeared |
Previously present reserved range "[4]" on message "Order" is missing values: [4] were removed. | buf breaking | Someone un-reserved a number |
missing x-request-id metadata (INVALID_ARGUMENT) | This page's server interceptor | Required 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.
// 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.
// 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.
// 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.
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) replacesgrpc.Dial; it does no I/O, defaults to thednsresolver and connects on first use.WithBlockandWithTimeoutare ignored by it; use a per-call deadline orWaitForReadyinstead.- Deadlines are
context.Contextdeadlines. Pass the incomingctxto outgoing calls and propagation is automatic;status.FromContextError(ctx.Err())mapscontext.DeadlineExceededandcontext.Canceledto the right codes. google.golang.org/grpc/statusandcodesbuild errors;status.Convert(err).Details()returns typed details fromgoogle.golang.org/genproto/googleapis/rpc/errdetails.- Generated servers embed
UnimplementedOrderServiceServer, so adding an RPC to the.protodoes not break existing implementations (unimplemented methods returnUNIMPLEMENTED). - Generic stream types (
grpc.ServerStreamingServer[T],grpc.BidiStreamingServer[Req, Res]) are what currentprotoc-gen-go-grpcemits (this module was generated with v1.6.2). google.golang.org/grpc/test/bufconngives in-process tests with the real HTTP/2 transport;google.golang.org/grpc/healthandreflectionregister the standard services in one line each.protojsonis the only correct JSON encoder for Protobuf messages;encoding/jsonon generated structs ignores the mapping rules.- Connect for Go (
connectrpc.com/connect) serves gRPC, gRPC-Web and Connect from a plainnet/httphandler 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
// 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
// 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
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
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
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:
# 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: generatedThe Laravel angle
- Register the provider in
bootstrap/providers.php(Laravel 13 does this automatically forphp artisan make:provider). ImplementingDeferrableProviderwithprovides()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 usescoped()here: it would rebuild the channel every request under Octane.- The stub call returns a call object;
->wait()returns[$response, $status]where$status->codeis compared with\Grpc\STATUS_OK,\Grpc\STATUS_NOT_FOUND,\Grpc\STATUS_UNAVAILABLEand so on,$status->detailsis the message, and$status->metadataholds 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
retryPolicyfromgrpc.service_config(withgrpc.enable_retries); theretry(2, ..., 100, fn ($e) => ...)helper adds an application-level retry forUNAVAILABLEonly. 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
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
Client-side round_robin | Headless Service + dns:/// target + service config | Per-call spread, no proxy | Re-resolution lag; client config in every language |
| Service mesh | Linkerd or Istio sidecar | Per-request spread, mTLS, retries | Extra hop and proxy CPU |
| Proxyless xDS | xds:/// target + istiod or Traffic Director | Central policy, no sidecar | Language support varies |
Server MaxConnectionAge | keepalive.ServerParameters{MaxConnectionAge: 5 * time.Minute} | Works with any client, even pick_first | Coarse; minutes to rebalance |
| L7 load balancer | AWS ALB gRPC target group, Envoy edge | Per-request at the edge | Only for edge traffic |
Calls hang and goroutines pile up
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Deadline on every call | context.WithTimeout, PHP timeout option | Bounded wait | Must be derived from the budget |
Default per-method timeout | methodConfig.timeout in service config | Safety net for forgotten deadlines | Hidden from callers |
| Honour cancellation in handlers | ctx.Done(), pass ctx to SQL | Stops wasted work | Discipline in every handler |
| Keepalive | ClientParameters{Time, Timeout} | Detects dead connections | Must match server enforcement |
A deleted field number was reused
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
reserved numbers and names | reserved 4; reserved "customer_email"; | Compiler refuses reuse | Must be done in the deleting commit |
buf breaking in CI | buf breaking --against '.git#branch=main' | Catches removal of reserved, renumbering | Needs a baseline branch or BSR |
| New field for new meaning | int64 loyalty_points = 12; | Old data stays readable | Field numbers grow |
| New package for new semantics | orders.v2 | Clean break | Two versions to run |
Browsers and partners need the API
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| gRPC-Web + Envoy | envoy.filters.http.grpc_web | Typed browser client | No client or bidi streaming |
| Connect | Serve gRPC + gRPC-Web + Connect from one handler | No proxy, curl-friendly, GET caching | Server must use Connect libraries |
| grpc-gateway | google.api.http annotations + generated proxy | Real REST + OpenAPI | Extra process; mapping to maintain |
| Envoy JSON transcoder | Descriptor set in Envoy | No code | Proxy 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.
-- 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;| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Idempotency key in the request | string request_id = 1; + table above | Safe retries end to end | Storage and TTL |
| No retry policy on writes | Omit retryPolicy for the method | No duplicates from gRPC itself | Callers see transient errors |
ALREADY_EXISTS as success | Client treats it as done for creates with client-chosen ids | Natural idempotency | Needs client-generated ids |
The full design (TTL, fingerprint mismatch, concurrent duplicates) is in API Idempotency.
Large responses fail with RESOURCE_EXHAUSTED
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Pagination | page_size, page_token fields | Bounded messages | More round trips |
| Server streaming | returns (stream Order) | Constant memory | Harder to load-balance and retry |
| Raise the limit | MaxCallRecvMsgSize(16 << 20) | Quick | Memory spikes; hides design issues |
| Claim check | Store blob in object storage, send a URL | Tiny messages | Two systems |
Errors cannot be told apart
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Precise codes | NOT_FOUND vs FAILED_PRECONDITION vs ABORTED | Callers branch correctly | Needs a code review checklist |
| Rich details | BadRequest, ErrorInfo{reason}, RetryInfo | Machine-readable | Clients must decode details |
Dashboards on grpc-status | OpenTelemetry rpc.grpc.status_code | True error rate | HTTP-only dashboards must change |
Choosing
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.
| Axis | REST | GraphQL | gRPC |
|---|---|---|---|
| Audience | Public, partners, unknown clients | First-party UIs with many screens | First-party services |
| Browser support | Native | Native | gRPC-Web, Connect or transcoding |
| Contract and schema | OpenAPI, optional | SDL, mandatory, introspection | .proto, mandatory, reflection |
| Code generation | Optional (OpenAPI generators) | Common (typed queries) | Standard (protoc, buf) |
| Over/under-fetching | Fixed resource shapes | Client chooses fields | Fixed message shapes |
| Streaming | SSE, WebSocket, chunked | Subscriptions (WebSocket, SSE) | Server, client, bidi built in |
| HTTP caching / CDN | Excellent (GET, ETag, Cache-Control) | Poor without persisted queries | None (Connect GET is the exception) |
| Error model | HTTP status + RFC 9457 Problem Details | errors array, usually HTTP 200 | 17 codes + google.rpc.Status details |
| Deadlines on the wire | No standard | No standard | grpc-timeout, propagated |
| Load balancing | Any L4/L7 balancer | Any L7 balancer | Per-call LB needed (client, mesh, xDS) |
| Payload | JSON text | JSON text, only requested fields | Binary Protobuf |
| Versioning | URL or header versions | Additive schema, @deprecated | Additive fields, reserved, package v2 |
| Debugging | curl, browser devtools | GraphiQL, devtools | grpcurl, Postman, reflection |
| Gateway / edge products | Every API gateway | Apollo Router, GraphQL gateways | Envoy, Istio, Linkerd, NGINX grpc_pass, AWS ALB |
By workload
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Public API for third parties | REST + OpenAPI | Optionally generated from .proto via grpc-gateway | Everyone can call it; caching works |
| Mobile app talking to many backends | GraphQL BFF or REST BFF | gRPC from the BFF inward | One round trip, shape per screen |
| Internal service-to-service calls | gRPC | Deadlines, round_robin/mesh, buf breaking | Typed contracts, call semantics |
| High-fan-out low-latency reads | gRPC | Hedging near p95, small messages | Tail latency control |
| Real-time feed to browsers | SSE or WebSocket, or Connect server streaming | Reconnect with resume tokens | Browsers lack bidi gRPC |
| Bulk upload from devices or warehouses | gRPC client streaming | Batching, idempotent ids | One stream, one summary |
| Event streams between services | Kafka/RabbitMQ with Protobuf payloads | Schema registry | Async is a different decision (messaging) |
| Admin CRUD in Laravel | REST or Inertia/Livewire | gRPC client to internal services | Simplicity wins |
| Polyglot platform with many teams | gRPC + BSR | Generated SDKs per language | One contract, many languages |
Which gRPC feature to turn on
| Situation | Feature | Setting |
|---|---|---|
| Every call | Deadline | Derived from the user budget |
| Idempotent reads during deploys | retryPolicy | UNAVAILABLE, maxAttempts 3-4, throttling on |
| Tail latency on fan-out reads | hedgingPolicy | hedgingDelay near p95, maxAttempts 2-3 |
| Kubernetes without mesh | round_robin + headless Service | Plus server MaxConnectionAge |
| Idle connections through firewalls | Keepalive | Client Time above server MinTime |
| Large results | Streaming or pagination | Keep 4 MiB default |
| Cross-region bandwidth | gzip compression | Measure CPU cost |
| Graceful deploys | Health service | NOT_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:
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 mappingWhat 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
| Scale | What changes | gRPC / Protobuf decisions |
|---|---|---|
| 1x (a few services, one cluster) | Hand-run protoc or buf generate, client round_robin | Deadlines everywhere, health service, buf lint |
| 10x (dozens of services, several teams) | Schema repository or BSR, buf breaking in CI, a mesh or xDS | Retry policies per method, throttling, OpenTelemetry interceptors, MaxConnectionAge |
| 100x (hundreds of services, multi-region) | Proxyless xDS or mesh with locality, generated SDKs per language, schema governance | Hedging 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.
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/server2. Look at the bytes.
// 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: ¬e,
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)
}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.
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 bytes4. 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.
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).
// 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)
}
}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
| Belief | Reality |
|---|---|
| gRPC is always much faster than REST | Encoding is cheaper (we measured ~1.6x to 2.4x for one message), but I/O dominates most calls |
| Protobuf is automatically backward compatible | Only if numbers and types never change and deleted fields are reserved |
| Renaming a field is a breaking change on the wire | Not for binary; it is for JSON and generated code |
| HTTP 200 means the call succeeded | The result is grpc-status in the trailers |
| gRPC has a default timeout | No deadline by default: calls can wait forever |
| The server stops my handler when the deadline passes | It cancels the context; your code must check it |
| Kubernetes Services balance gRPC | ClusterIP balances connections; HTTP/2 pins calls to one pod |
| Retries are off unless configured | Transparent retries always happen; policies add more |
Retrying on DEADLINE_EXCEEDED is safe | The operation may have completed; retry only idempotent calls |
| Browsers can call gRPC because they speak HTTP/2 | They cannot read trailers; use gRPC-Web, Connect or transcoding |
JSON of a proto equals json.Marshal | The mapping quotes int64, uses enum names, lowerCamelCase, RFC 3339 |
| Unknown fields are dropped | Proto3 keeps them in binary; JSON conversion drops them |
optional is the default in proto3 | Scalars without optional have implicit presence: zero means "not set" |
| More keepalive pings are safer | Too many pings get GOAWAY too_many_pings |
| Streaming is better than unary | Streams are hard to balance and retry; use them for real streams |
Cheat sheet
| Topic | What to remember |
|---|---|
| Field numbers | Never change or reuse; 1-15 for hot fields; reserved on delete |
| Wire types | 0 VARINT, 1 I64, 2 LEN, 5 I32; tag = (n << 3) | type |
| Negative numbers | sint32/sint64 (zigzag), not int64 (10 bytes) |
| Presence | optional when zero is meaningful; oneof for exclusive choices |
| Evolution | Add freely; never renumber; never move into a oneof; buf breaking in CI |
| JSON | protojson; int64 as string; enums as names; unknown fields lost |
| Channels | One per target, long-lived; never per call |
| Deadlines | Always set; propagate ctx; check ctx.Done() |
| Status codes | Most specific code + rich details; branch on codes, not text |
| Retries | Only idempotent methods, UNAVAILABLE, max 3-4 attempts, throttling on |
| Hedging | Reads only, delay near p95, deadline covers all copies |
| Load balancing | pick_first is default; use round_robin, a mesh or xDS; MaxConnectionAge |
| Keepalive | Client Time above server MinTime; below path idle timeouts |
| Message size | 4 MiB receive default; paginate or stream |
| Browsers | gRPC-Web (Envoy), Connect, or grpc-gateway / Envoy transcoding |
| Choosing | REST public edge, GraphQL front-end BFF, gRPC internal |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Protocol Buffers (Protobuf) | Language-neutral schema language and binary encoding with numbered fields |
| proto3 | The Protobuf syntax revision declared with syntax = "proto3"; |
| Editions | Successor to proto2/proto3 syntax with per-feature settings (edition = "2024") |
| Field number | The integer that identifies a field on the wire; 1 to 536,870,911 |
| Wire type | 3-bit code in the tag that says how the payload is encoded |
| Tag | Varint (field_number << 3) | wire_type that starts each record |
| Varint | Variable-length base-128 integer, 7 bits per byte |
| Zigzag | Mapping of signed to unsigned integers used by sint32/sint64 |
| Length-delimited (LEN) | Wire type 2: varint length then bytes |
| Packed repeated | Repeated scalars stored in one LEN record (default in proto3) |
| Implicit presence | Proto3 scalar without optional: zero value is not serialized |
optional | Explicit presence for a proto3 scalar field |
oneof | Group of fields of which at most one is set |
map | Key/value field map<K, V>, encoded as repeated entries |
repeated | List field |
reserved | Declaration that forbids reuse of deleted field numbers or names |
| Unknown fields | Fields a reader does not know, preserved in binary round trips |
| Schema evolution | Changing a schema while old and new readers and writers coexist |
| Well-known types | Standard messages such as Timestamp, Duration, Any, Struct, FieldMask |
Timestamp | Point in time as seconds and nanos since the Unix epoch (UTC) |
Duration | Signed span of time; JSON form "1.5s" |
Any | A packed message plus its type URL |
Struct | Schemaless JSON object inside a typed message |
| JSON mapping | Official Protobuf JSON form (lowerCamelCase, int64 as string, enum names) |
protoc | The reference Protobuf compiler |
protoc-gen-go | Plugin that generates Go message types |
protoc-gen-go-grpc | Plugin that generates Go gRPC client and server stubs |
grpc_php_plugin | Plugin that generates PHP gRPC client stubs |
| gRPC | RPC framework and protocol over HTTP/2 using Protobuf by default |
| HTTP/2 | Binary, multiplexed HTTP version (RFC 9113) that gRPC runs on |
| Channel | Client-side virtual connection to a target, with resolver and LB policy |
| Subchannel | One connection to one backend address inside a channel |
| Stub | Generated client object with one method per RPC |
| Unary RPC | One request, one response |
| Server streaming | One request, a stream of responses |
| Client streaming | A stream of requests, one response |
| Bidirectional streaming | Both sides stream independently on one call |
| Deadline | Absolute time after which the caller no longer wants the result |
grpc-timeout | Header that carries the remaining deadline as a relative timeout |
| Cancellation | Signal that the caller no longer wants the result (RST_STREAM) |
| Metadata | Key/value headers and trailers on an RPC |
| Trailers | Headers sent after the last message; carry grpc-status |
| Status code | One of 17 gRPC result codes (OK to UNAUTHENTICATED) |
OK, CANCELLED, DEADLINE_EXCEEDED, UNAVAILABLE | Success; caller gave up; deadline passed; transient failure, retryable |
NOT_FOUND, INVALID_ARGUMENT, RESOURCE_EXHAUSTED | Entity missing; bad request; quota, rate or size limit |
| Rich error details | Typed messages in google.rpc.Status.details (BadRequest, ErrorInfo, RetryInfo) |
grpc-status-details-bin | Trailer carrying the serialized google.rpc.Status |
| Interceptor | Middleware that wraps RPCs on client or server |
| Service config | JSON document with LB policy, method timeouts, retry and hedging policies |
| Retry policy | retryPolicy: automatic retries on listed codes with backoff |
| Transparent retry | Retry gRPC does on its own when the server application never saw the call |
| Hedging | Sending extra copies of a request after a delay and using the first success |
| Retry throttling | Token bucket that pauses retries when failures dominate |
| Name resolver | Plugin that turns a target URI into addresses and service config |
pick_first | Default LB policy: one connection to the first reachable address |
round_robin | LB policy that rotates calls across all addresses |
| xDS | Envoy's discovery APIs, used by proxyless gRPC to get endpoints and policy |
| Keepalive | HTTP/2 PINGs that detect dead connections |
| Max message size | Per-message limit, 4 MiB receive by default in Go |
| Compression | Per-message compression negotiated by grpc-encoding (gzip) |
| Health checking | Standard grpc.health.v1.Health service with Check and Watch |
| Reflection | Standard service that lists services and types for tools like grpcurl |
| gRPC-Web | Browser variant of gRPC with trailers in the body, via a proxy |
| grpc-gateway | protoc plugin that generates a REST/JSON reverse proxy for gRPC |
| Transcoding | Translating REST/JSON requests to gRPC using google.api.http rules |
| Connect | Buf's RPC libraries and protocol that also speak gRPC and gRPC-Web |
| buf | Protobuf toolchain: lint, breaking-change detection, generation, BSR |
| Lint | Style and structure checks on .proto files (MINIMAL, BASIC, STANDARD) |
| Breaking change | A schema change that breaks old readers, writers or generated code |
| BSR | Buf Schema Registry: versioned Protobuf modules and generated SDKs |
| REST vs gRPC | Resource-oriented HTTP + JSON versus typed RPC over HTTP/2 + Protobuf |
| GraphQL vs gRPC | Client-shaped queries over one endpoint versus fixed RPC methods |
| grpcurl | curl-like CLI for gRPC that uses reflection or descriptor files |
| Envoy | L7 proxy with native gRPC, gRPC-Web and JSON transcoding filters |
References
- Protocol Buffers Language Guide (proto3): https://protobuf.dev/programming-guides/proto3/
- Protocol Buffers Encoding: https://protobuf.dev/programming-guides/encoding/
- Protocol Buffers ProtoJSON format: https://protobuf.dev/programming-guides/json/
- Field presence: https://protobuf.dev/programming-guides/field_presence/
- Proto best practices (dos and don'ts): https://protobuf.dev/programming-guides/dos-donts/
- Well-known types reference: https://protobuf.dev/reference/protobuf/google.protobuf/
- Protobuf overview and history: https://protobuf.dev/overview/ and https://protobuf.dev/history/
- Editions overview: https://protobuf.dev/editions/overview/
- PHP generated code: https://protobuf.dev/reference/php/php-generated/
- Go generated code: https://protobuf.dev/reference/go/go-generated/
- gRPC introduction and core concepts: https://grpc.io/docs/what-is-grpc/introduction/ and https://grpc.io/docs/what-is-grpc/core-concepts/
- gRPC principles (Stubby, 2015): https://grpc.io/blog/principles/
- gRPC guides: deadlines https://grpc.io/docs/guides/deadlines/, cancellation https://grpc.io/docs/guides/cancellation/, metadata https://grpc.io/docs/guides/metadata/, status codes https://grpc.io/docs/guides/status-codes/, error handling https://grpc.io/docs/guides/error/
- gRPC guides: retry https://grpc.io/docs/guides/retry/, hedging https://grpc.io/docs/guides/request-hedging/, service config https://grpc.io/docs/guides/service-config/
- gRPC guides: load balancing https://grpc.io/docs/guides/custom-load-balancing/, name resolution https://grpc.io/docs/guides/custom-name-resolution/, keepalive https://grpc.io/docs/guides/keepalive/, compression https://grpc.io/docs/guides/compression/, flow control https://grpc.io/docs/guides/flow-control/, wait-for-ready https://grpc.io/docs/guides/wait-for-ready/
- gRPC guides: health checking https://grpc.io/docs/guides/health-checking/, reflection https://grpc.io/docs/guides/reflection/, interceptors https://grpc.io/docs/guides/interceptors/, performance https://grpc.io/docs/guides/performance/, benchmarking https://grpc.io/docs/guides/benchmarking/, authentication https://grpc.io/docs/guides/auth/
- gRPC load balancing blog: https://grpc.io/blog/grpc-load-balancing/
- gRPC repository docs: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md, https://github.com/grpc/grpc/blob/master/doc/service_config.md, https://github.com/grpc/grpc/blob/master/doc/health-checking.md, https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md, https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md, https://github.com/grpc/grpc/blob/master/doc/load-balancing.md, https://github.com/grpc/grpc/blob/master/doc/naming.md, https://github.com/grpc/grpc/blob/master/doc/keepalive.md, https://github.com/grpc/grpc/blob/master/doc/grpc_xds_features.md
- gRFC A6 client retries: https://github.com/grpc/proposal/blob/master/A6-client-retries.md
- gRPC-Web: https://grpc.io/docs/platforms/web/basics/ and https://github.com/grpc/grpc-web
- gRPC PHP: https://grpc.io/docs/languages/php/basics/, https://grpc.io/docs/languages/php/quickstart/, https://github.com/grpc/grpc/tree/master/src/php
- gRPC core channel argument names: https://raw.githubusercontent.com/grpc/grpc/master/include/grpc/impl/channel_arg_names.h
- Go packages: https://pkg.go.dev/google.golang.org/grpc, https://pkg.go.dev/google.golang.org/grpc/status, https://pkg.go.dev/google.golang.org/grpc/metadata, https://pkg.go.dev/google.golang.org/grpc/keepalive, https://pkg.go.dev/google.golang.org/grpc/test/bufconn, https://pkg.go.dev/google.golang.org/grpc/health, https://pkg.go.dev/google.golang.org/grpc/reflection, https://pkg.go.dev/google.golang.org/protobuf, https://pkg.go.dev/google.golang.org/genproto/googleapis/rpc/errdetails
- buf: lint https://buf.build/docs/lint/, breaking https://buf.build/docs/breaking/, rules https://buf.build/docs/breaking/rules/, generate https://buf.build/docs/generate/, BSR https://buf.build/docs/bsr/, remote plugins https://buf.build/protocolbuffers/php and https://buf.build/grpc/php
- Connect: https://connectrpc.com/docs/introduction/, https://connectrpc.com/docs/protocol/, https://connectrpc.com/docs/multi-protocol/
- grpc-gateway: https://grpc-ecosystem.github.io/grpc-gateway/ and https://github.com/grpc-ecosystem/grpc-gateway (status mapping: https://raw.githubusercontent.com/grpc-ecosystem/grpc-gateway/main/runtime/errors.go)
- Envoy gRPC-JSON transcoder and gRPC-Web filter: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/grpc_json_transcoder_filter and https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/grpc_web_filter
- Google Cloud Endpoints transcoding: https://cloud.google.com/endpoints/docs/grpc/transcoding
- AIP-193 Errors: https://google.aip.dev/193
- Kubernetes: gRPC load balancing blog https://kubernetes.io/blog/2018/11/07/grpc-load-balancing-on-kubernetes-without-tears/ and gRPC probes https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
- GraphQL specification (October 2021): https://spec.graphql.org/October2021/
- RFC 9113 HTTP/2: https://www.rfc-editor.org/rfc/rfc9113.html
- grpcurl: https://github.com/fullstorydev/grpcurl
- Laravel 13: service providers https://laravel.com/docs/13.x/providers, service container https://laravel.com/docs/13.x/container, configuration https://laravel.com/docs/13.x/configuration, helpers (
retry) https://laravel.com/docs/13.x/helpers