Skip to main content

RPC & gRPC

Learning objectives
  • Explain what RPC abstracts away and which distributed-systems failures it cannot hide
  • Decode a Protobuf message by hand and apply the schema evolution rules that keep old and new services compatible
  • Describe how a gRPC call maps onto HTTP/2 streams, headers, length-prefixed messages and trailers
  • Use deadlines, cancellation, status codes, retries and interceptors correctly in Go
  • Load-balance gRPC across pods (L7 proxy vs client-side), expose it as REST with gRPC-gateway, and choose REST vs gRPC for a given interface

TL;DR​

  • RPC makes a remote call look like a local function. The network still fails: every call needs a deadline, a retry policy tied to idempotency, and a plan for "unknown outcome".
  • Protobuf encodes each field as a tag (field number + wire type) followed by the value; names are not on the wire. Compatibility rules: never change or reuse field numbers (use reserved), add fields freely, treat enums as open, and remember proto3 scalars have no presence unless marked optional.
  • gRPC = Protobuf (by default) over HTTP/2: each call is a stream, the method is the :path (/payments.v1.PaymentService/CreatePayment), messages are length-prefixed, and the result is in trailers (grpc-status). HTTP status is 200 even for errors.
  • Four call types: unary, server streaming, client streaming, bidirectional streaming.
  • Deadlines propagate (grpc-timeout header → server context). The default is no deadline — always set one.
  • Long-lived multiplexed connections break L4 load balancing. Use an L7 proxy (Envoy, mesh) or client-side balancing (round_robin over a headless Service), and cap connection age on servers.
  • Choose gRPC for internal, high-volume, strongly typed service-to-service calls and streaming; choose REST/JSON + OpenAPI for browsers, public and partner APIs. gRPC-gateway or Envoy transcoding gives you both from one schema.

Why it matters​

In a microservice platform, most traffic is east-west RPC: checkout calls pricing, inventory and payments; a transfer service calls limits, fraud and the ledger. The RPC layer decides:

  • Latency and cost: binary Protobuf over multiplexed HTTP/2 is cheaper to parse and smaller than JSON over HTTP/1.1, which matters at tens of thousands of calls per second.
  • Correctness: a payment RPC that times out may or may not have executed. Without idempotency keys and a status query, retries cause double debits — a classic finding in bank architecture reviews.
  • Evolvability: dozens of teams deploy independently. A careless Protobuf change (reusing a field number) silently corrupts data between versions — worse than a crash.
  • Operability: gRPC behind the wrong load balancer creates hot pods; missing deadlines create goroutine pile-ups and cascading failures.

Core concepts​

The RPC model and its traps​

An RPC framework generates a client stub that serializes arguments, sends them, waits, and deserializes the result, and a server skeleton that does the reverse and calls your implementation. It hides the network — which is exactly the danger. The "fallacies of distributed computing" (the network is reliable, latency is zero, bandwidth is infinite…) all apply:

Local callRemote call
Either returns or throwsCan succeed, fail, or time out with unknown outcome
NanosecondsMilliseconds, with long tails
Same process, same failure domainPartial failure: caller up, callee down, or the network in between
Pass pointersCopy data; size matters
Single version of the codeCaller and callee run different versions during deploys

Consequences for design: set deadlines everywhere, retry only idempotent operations (or attach idempotency keys), avoid chatty interfaces (one call returning a page beats 50 calls), and design schemas for mixed-version deployments. See Idempotency & Exactly-Once and Resilience Patterns.

Protobuf schema​

syntax = "proto3";

package payments.v1;

option go_package = "example.com/bank/gen/payments/v1;paymentsv1";

import "google/protobuf/timestamp.proto";

service PaymentService {
rpc CreatePayment(CreatePaymentRequest) returns (Payment);
rpc GetPayment(GetPaymentRequest) returns (Payment);
rpc WatchPayment(WatchPaymentRequest) returns (stream PaymentEvent);
}

message Money {
int64 amount_minor = 1; // minor units (cents); never float/double for money
string currency = 2; // ISO 4217 code, e.g. "USD"
}

message CreatePaymentRequest {
string idempotency_key = 1;
string debtor_account = 2;
string creditor_account = 3;
Money amount = 4;
reserved 5; // was: string channel (removed in v1.3)
reserved "channel";
string reference = 6;
}

enum PaymentStatus {
PAYMENT_STATUS_UNSPECIFIED = 0;
PAYMENT_STATUS_PENDING = 1;
PAYMENT_STATUS_COMPLETED = 2;
PAYMENT_STATUS_FAILED = 3;
}

message Payment {
string payment_id = 1;
PaymentStatus status = 2;
Money amount = 3;
google.protobuf.Timestamp created_at = 4;
}

message GetPaymentRequest { string payment_id = 1; }
message WatchPaymentRequest { string payment_id = 1; }

message PaymentEvent {
string payment_id = 1;
PaymentStatus status = 2;
google.protobuf.Timestamp at = 3;
}

Protobuf wire encoding​

Each field is encoded as a key followed by a value. The key is a varint: (field_number << 3) | wire_type.

Wire typeIDUsed for
VARINT0int32, int64, uint32, uint64, sint32, sint64, bool, enum
I641fixed64, sfixed64, double
LEN2string, bytes, embedded messages, packed repeated fields
SGROUP / EGROUP3 / 4Deprecated groups
I325fixed32, sfixed32, float

Varints use 7 bits per byte, with the high bit meaning "more bytes follow", least-significant group first.

Worked example — amount_minor = 150 in field 1:

BytesMeaning
08Key: field 1, wire type 0 → (1 << 3) | 0 = 8
96 01Varint 150: 0x96 = 1 (continue) + 0010110 (22); 0x01 = 1 → 22 + 1 × 128 = 150

And currency = "USD" in field 2: 12 03 55 53 44 — key (2 << 3) | 2 = 0x12, length 3, then the UTF-8 bytes.

Consequences worth knowing:

  • Field names are not on the wire — only numbers. Renaming is wire-safe; renumbering is not.
  • Fields 1–15 take a one-byte key; use them for frequent fields. 16–2047 take two bytes.
  • Negative int32/int64 values always take 10 bytes (sign extension). Use sint32/sint64 (ZigZag encoding) for fields that are often negative.
  • In proto3, scalar fields at their default value (0, "", false) are not encoded, so the receiver cannot tell "zero" from "not set". For money, an amount of 0 vs missing can matter: use optional, a wrapper message (like Money above, which has presence), or explicit validation.
  • Unknown fields are preserved when a message is parsed and re-serialized (proto3 since 3.5), so an intermediate service on an old schema does not drop new fields it passes through.
  • Protobuf is not self-describing: you need the schema to decode meaningfully. Keep schemas in a registry or shared repo.

Schema evolution rules​

ChangeSafe?Notes
Add a new field with a new numberYesOld readers ignore it; old writers omit it (receiver sees default)
Remove a fieldYes, if you reserved the number and nameOtherwise someone reuses the number later and old data is misread
Reuse a field number for a different meaningNeverSilent data corruption between versions
Rename a fieldWire-safeBreaks JSON mapping (protojson uses names), generated code and grpc-gateway URLs
Change int32 ↔ int64 ↔ uint32 ↔ uint64 ↔ boolWire-compatibleValues may be truncated or reinterpreted; avoid unless you control all data
Change string ↔ bytesCompatible if bytes are valid UTF-8
Change sint32 ↔ int32NoDifferent encodings (ZigZag)
Change singular ↔ repeatedRiskyBehaviour differs by type and language
Move a field into or out of a oneofRiskyCan lose data when multiple members were set
Add an enum valueYes, with careOld code receives an unknown numeric value; always handle a default case. First value must be *_UNSPECIFIED = 0
Change a message's package or service nameNo for gRPCThe :path changes; old clients get UNIMPLEMENTED

Enforce the rules in CI with a breaking-change detector (e.g. buf breaking --against the main branch). Version packages (payments.v1, payments.v2) for genuinely incompatible changes and run both during migration. Newer Protobuf releases introduce Editions as the successor to the proto2/proto3 syntax flag; the evolution rules above still apply.

gRPC over HTTP/2​

  • Every message is framed as 1 byte compressed-flag + 4 bytes big-endian length + payload, so messages can be split across DATA frames.
  • Metadata = HTTP/2 headers (lower-case keys; binary values use a -bin suffix and base64).
  • Status lives in trailers: grpc-status and grpc-message. Proxies that do not support HTTP/2 trailers (and browsers' fetch) break plain gRPC — hence gRPC-Web.
  • Many RPCs share one connection as separate streams; flow control and MAX_CONCURRENT_STREAMS apply. See HTTP/1.1, HTTP/2, HTTP/3.

Four call types​

TypeShapeExample
UnaryOne request → one responseCreatePayment, GetBalance
Server streamingOne request → stream of responsesWatchPayment status updates, streaming a large statement, price feed for a symbol list
Client streamingStream of requests → one responseBulk upload of settlement records, telemetry batches
Bidirectional streamingBoth sides stream independentlyInteractive fraud scoring session, chat relay between internal services

Streams are long-lived: they pin to one backend for their lifetime, survive only as long as the connection, and need application-level resume logic (sequence numbers) after a disconnect.

Status codes​

CodeMeaningRetry?
OK (0)Success—
CANCELLED (1)Caller cancelledNo
INVALID_ARGUMENT (3)Bad input regardless of stateNo
DEADLINE_EXCEEDED (4)Deadline passed — outcome unknown for mutationsOnly if idempotent / keyed
NOT_FOUND (5), ALREADY_EXISTS (6)Resource stateNo
PERMISSION_DENIED (7), UNAUTHENTICATED (16)AuthZ / AuthN failureNo (refresh credentials first for 16)
RESOURCE_EXHAUSTED (8)Quota or rate limitWith backoff
FAILED_PRECONDITION (9)System not in required state (insufficient funds, account frozen)No
ABORTED (10)Concurrency conflict (optimistic lock)Yes, at a higher level (re-read, retry)
UNIMPLEMENTED (12)Method not supported (often a version mismatch)No
INTERNAL (13), UNKNOWN (2), DATA_LOSS (15)Server bugs / corruptionUsually no
UNAVAILABLE (14)Transient: server down, connection refused, drainingYes, with backoff

For richer errors (field violations, retry hints), attach google.rpc.Status details such as BadRequest, ErrorInfo and RetryInfo.

Deadlines and cancellation​

  • The client sets a deadline (absolute time); gRPC sends the remaining time as grpc-timeout (e.g. 800m = 800 ms). The server's handler context carries that deadline; when it passes, or the client cancels, ctx.Done() fires.
  • Propagate the context to every downstream call and database query. If checkout gives payments 800 ms, and payments calls fraud, fraud automatically gets what is left — no work continues after the user has given up.
  • Budget, do not just pass through: reserve time for your own work and fallbacks (e.g. call fraud with min(remaining − 100 ms, 300 ms)).
  • No deadline = infinite. A slow dependency then holds goroutines, connections and memory until something else breaks.
  • A DEADLINE_EXCEEDED on a mutation means unknown outcome: the server may have committed. Resolve by retrying with the same idempotency key or querying status (GetPayment), never by blindly creating a new payment.

Interceptors​

Interceptors are gRPC middleware, on the client and server, for unary and streaming calls. Chain them with grpc.ChainUnaryInterceptor / grpc.ChainStreamInterceptor. Typical server chain, outermost first: recovery (panic → INTERNAL) → tracing/metrics → logging → authentication → authorization → rate limiting → validation → handler. OpenTelemetry instrumentation for gRPC is provided as a stats handler in current Go releases. Keep interceptors generic; domain rules belong in handlers.

Load balancing gRPC​

An HTTP/2 connection is long-lived and carries many RPCs. An L4 load balancer (or a Kubernetes ClusterIP Service, which balances per connection) picks a backend once per connection, so a client with one connection sends all its RPCs to one pod. New pods added during a scale-out get no traffic from existing clients.

ApproachHowStrengthsWeaknesses
L7 proxy (Envoy, Linkerd, Istio, NGINX grpc_pass, cloud L7 LBs with gRPC support)Proxy terminates HTTP/2 and balances each streamLanguage-agnostic, retries/outlier detection in the proxy, no client changesExtra hop; proxy must be scaled and configured
Client-side (round_robin or least_request-style policies)Client resolves all backend addresses (headless Service, xDS) and spreads RPCs over subchannelsNo extra hop, lowest latencyEvery client language must support it; discovery freshness matters
Proxyless xDSgRPC library receives endpoints and policy from a control planeMesh features without sidecarsControl-plane dependency; feature support varies by language
L4 + max connection ageServer sets MaxConnectionAge; clients reconnect periodically and land on other podsSimple mitigationStill coarse; reconnect cost

With client-side balancing via DNS, the gRPC DNS resolver does not poll continuously; it re-resolves mainly when connections fail or close. Setting MaxConnectionAge on the server (e.g. a few minutes, with a grace period) makes clients reconnect and pick up new pods.

Keepalive pitfall: if a client sends HTTP/2 pings more often than the server's enforcement policy allows, the server closes the connection with GOAWAY (too_many_pings). Align client keepalive Time with the server's EnforcementPolicy.MinTime.

gRPC-gateway, transcoding and gRPC-Web​

Browsers and many partners need REST/JSON. Options that keep one Protobuf contract:

  • gRPC-gateway: a protoc plugin that generates a Go reverse proxy translating REST/JSON to gRPC, driven by google.api.http annotations. It can also generate OpenAPI specs.
  • Envoy gRPC-JSON transcoder: the same translation in the proxy layer, no extra Go service.
  • gRPC-Web: a browser-compatible variant (no reliance on HTTP/2 trailers) that needs a proxy (Envoy) or a server that speaks it.
  • Connect (connectrpc): a protocol and libraries that serve gRPC, gRPC-Web and a simple HTTP/JSON-friendly protocol from the same handlers.
import "google/api/annotations.proto";

service PaymentService {
rpc GetPayment(GetPaymentRequest) returns (Payment) {
option (google.api.http) = {get: "/v1/payments/{payment_id}"};
}
rpc CreatePayment(CreatePaymentRequest) returns (Payment) {
option (google.api.http) = {post: "/v1/payments" body: "*"};
}
}

REST vs gRPC​

CriterionREST / JSON (+ OpenAPI)gRPC (Protobuf)
ClientsBrowsers, mobile, partners, any language with an HTTP clientServices with generated stubs; browsers need gRPC-Web
ContractOpenAPI (often written after the fact).proto is the contract; code generated from it
PayloadText, human-readable, largerBinary, compact, faster to parse
StreamingSSE / WebSocket alongsideNative, four call types
CachingHTTP caching, CDNsNot cacheable by HTTP intermediaries
Tooling & debuggingcurl, browser, every API gatewaygrpcurl, reflection; fewer generic tools
Error modelHTTP status codes + problem JSON17 status codes + rich details
EvolutionAdditive JSON fields; versioned URLsField-number rules; versioned packages
Typical usePublic, partner and open-banking APIs, BFF for webInternal service-to-service, high-RPS paths, streaming, polyglot microservices

A common bank/e-commerce pattern: REST at the edge (mobile, web, partners via the API gateway) and gRPC inside (checkout → pricing/inventory/payments, transfer → limits/fraud/ledger), with transcoding where both are needed. Broader comparison including GraphQL: API Design.

Trade-offs​

OptionStrengthsWeaknessesChoose when
gRPC unaryTyped, fast, deadlines and status built inNeeds HTTP/2-aware infra, binary debuggingInternal request/response calls
gRPC streamingPush and flow control without extra protocolsPins to one backend; resume logic needed; harder LBStatus feeds, bulk transfer, interactive sessions
REST/JSONUniversal, cacheable, easy to debugLarger payloads, looser contractsPublic/partner APIs, browsers
Async messaging instead of RPCDecoupling, buffering, no temporal couplingEventual consistency, harder request/responseWorkflows that need not complete in-line (notifications, settlement) — see Message Queues
L7 proxy balancingUniform, language-agnosticExtra hop and componentPolyglot services, service mesh already present
Client-side balancingNo extra hopPer-language support, discovery freshnessGo/Java-only fleets, latency-critical paths
gRPC-gateway / transcodingOne schema for REST and gRPCMapping quirks, another layerYou need both internal gRPC and external REST

In practice​

The Go examples below use code generated by protoc-gen-go and protoc-gen-go-grpc from the schema above into the package paymentsv1.

Server with interceptors, idempotency, deadline awareness, streaming and connection-age limits:

package main

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

"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"

paymentsv1 "example.com/bank/gen/payments/v1"
)

type paymentServer struct {
paymentsv1.UnimplementedPaymentServiceServer

mu sync.Mutex
byKey map[string]*paymentsv1.Payment // idempotency key -> stored result
}

func (s *paymentServer) CreatePayment(ctx context.Context, req *paymentsv1.CreatePaymentRequest) (*paymentsv1.Payment, error) {
if req.GetIdempotencyKey() == "" {
return nil, status.Error(codes.InvalidArgument, "idempotency_key is required")
}
if req.GetAmount().GetAmountMinor() <= 0 {
return nil, status.Error(codes.InvalidArgument, "amount must be positive")
}
if err := ctx.Err(); err != nil { // the caller already gave up
return nil, status.FromContextError(err).Err()
}

s.mu.Lock()
defer s.mu.Unlock()
if p, ok := s.byKey[req.GetIdempotencyKey()]; ok {
return p, nil // a retry: return the original result (real code also compares the payload)
}
p := &paymentsv1.Payment{
PaymentId: "pay_" + req.GetIdempotencyKey(),
Status: paymentsv1.PaymentStatus_PAYMENT_STATUS_PENDING,
Amount: req.GetAmount(),
CreatedAt: timestamppb.Now(),
}
s.byKey[req.GetIdempotencyKey()] = p
return p, nil
}

func (s *paymentServer) WatchPayment(req *paymentsv1.WatchPaymentRequest, stream paymentsv1.PaymentService_WatchPaymentServer) error {
steps := []paymentsv1.PaymentStatus{
paymentsv1.PaymentStatus_PAYMENT_STATUS_PENDING,
paymentsv1.PaymentStatus_PAYMENT_STATUS_COMPLETED,
}
for _, st := range steps {
select {
case <-stream.Context().Done(): // client cancelled or deadline passed
return status.FromContextError(stream.Context().Err()).Err()
case <-time.After(500 * time.Millisecond):
}
ev := &paymentsv1.PaymentEvent{PaymentId: req.GetPaymentId(), Status: st, At: timestamppb.Now()}
if err := stream.Send(ev); err != nil {
return err
}
}
return nil
}

func logging(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
start := time.Now()
budget := time.Duration(0)
if dl, ok := ctx.Deadline(); ok {
budget = time.Until(dl)
}
resp, err := handler(ctx, req)
log.Printf("method=%s code=%s took=%s budget=%s", info.FullMethod, status.Code(err), time.Since(start), budget)
return resp, err
}

func auth(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
md, _ := metadata.FromIncomingContext(ctx)
if len(md.Get("authorization")) == 0 {
return nil, status.Error(codes.Unauthenticated, "missing credentials")
}
// Validate the token and/or the mTLS peer identity here.
return handler(ctx, req)
}

func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatal(err)
}
srv := grpc.NewServer(
grpc.ChainUnaryInterceptor(logging, auth),
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionAge: 5 * time.Minute, // clients reconnect and re-resolve
MaxConnectionAgeGrace: 30 * time.Second,
}),
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
MinTime: 20 * time.Second, // reject clients pinging more often
PermitWithoutStream: true,
}),
// In production: grpc.Creds(credentials.NewTLS(mtlsConfig)).
)
paymentsv1.RegisterPaymentServiceServer(srv, &paymentServer{byKey: make(map[string]*paymentsv1.Payment)})
log.Printf("listening on %s", lis.Addr())
log.Fatal(srv.Serve(lis))
}

Client with client-side round-robin, a per-method timeout and retry policy, metadata, and error handling by status code:

package main

import (
"context"
"log"
"time"

"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"

paymentsv1 "example.com/bank/gen/payments/v1"
)

// Retrying CreatePayment is safe only because every request carries an idempotency key.
const serviceConfig = `{
"loadBalancingConfig": [{"round_robin": {}}],
"methodConfig": [{
"name": [{"service": "payments.v1.PaymentService"}],
"timeout": "1s",
"retryPolicy": {
"maxAttempts": 3,
"initialBackoff": "0.1s",
"maxBackoff": "1s",
"backoffMultiplier": 2,
"retryableStatusCodes": ["UNAVAILABLE"]
}
}]
}`

func main() {
conn, err := grpc.NewClient(
"dns:///payments.payments.svc.cluster.local:50051", // headless Service: one address per pod
grpc.WithTransportCredentials(insecure.NewCredentials()), // mTLS in production
grpc.WithDefaultServiceConfig(serviceConfig),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 30 * time.Second, // >= server EnforcementPolicy.MinTime
Timeout: 10 * time.Second,
}),
)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
client := paymentsv1.NewPaymentServiceClient(conn)

ctx, cancel := context.WithTimeout(context.Background(), 800*time.Millisecond)
defer cancel()
ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer demo-token")

p, err := client.CreatePayment(ctx, &paymentsv1.CreatePaymentRequest{
IdempotencyKey: "7c1f8a2e-4b9d-4f61-9a55-2f0c3e1d9b77",
DebtorAccount: "ACC-001",
CreditorAccount: "ACC-002",
Amount: &paymentsv1.Money{AmountMinor: 12_500, Currency: "USD"},
})
switch status.Code(err) {
case codes.OK:
log.Printf("payment %s is %s", p.GetPaymentId(), p.GetStatus())
case codes.DeadlineExceeded:
// Unknown outcome: query GetPayment or retry with the SAME idempotency key.
log.Printf("timed out, outcome unknown: %v", err)
case codes.InvalidArgument, codes.FailedPrecondition:
log.Printf("rejected, do not retry: %v", err)
default:
log.Printf("create payment failed: %v", err)
}
}

Tools: enable server reflection in non-production environments and use grpcurl:

grpcurl -plaintext localhost:50051 list
grpcurl -plaintext -H 'authorization: Bearer demo-token' \
-d '{"idempotency_key":"k1","debtor_account":"A","creditor_account":"B","amount":{"amount_minor":100,"currency":"USD"}}' \
localhost:50051 payments.v1.PaymentService/CreatePayment
buf breaking --against '.git#branch=main' # fail CI on incompatible schema changes

Numbers (rough, workload-dependent): Protobuf payloads are commonly several times smaller than equivalent JSON and cheaper to encode/decode; the saving matters most for high-RPS internal calls with many small messages. Measure with your own payloads before using it as a justification.

Common pitfalls​

  • No deadline. Symptom: during a dependency slowdown, goroutines and connections grow without bound; the caller fails long after the user gave up.
  • Retrying non-idempotent RPCs. Symptom: duplicate payments or orders after a network blip. Use idempotency keys and only retry UNAVAILABLE automatically.
  • Reusing a deleted field number. Symptom: old clients interpret the new field as the old one — wrong amounts, wrong statuses, no errors.
  • Treating proto3 zero as "not set". Symptom: a partial update sets an amount to 0 or a flag to false unintentionally. Use optional, wrappers or field masks.
  • Unhandled new enum values. Symptom: an old service crashes or misroutes when it sees PAYMENT_STATUS_REVERSED. Always have a default branch.
  • gRPC behind an L4 load balancer. Symptom: one pod at high CPU, new pods idle after scale-out.
  • Keepalive too aggressive. Symptom: connections closed with GOAWAY too_many_pings; intermittent UNAVAILABLE.
  • Huge messages. Symptom: RESOURCE_EXHAUSTED: received message larger than max (default receive limit is 4 MB in grpc-go). Page results or stream instead of raising limits blindly.
  • Leaking server streams. Symptom: goroutines per stream never exit because the handler ignores stream.Context().Done().
  • Returning UNKNOWN/INTERNAL for business errors. Symptom: callers cannot distinguish "insufficient funds" from a bug; alerts fire on normal declines. Map domain errors to precise codes.

Interview angle​

  • "REST or gRPC for this system?" Decide per interface: edge/partner → REST with OpenAPI; internal hot paths and streaming → gRPC. Mention browser support, caching, tooling, and contract evolution.
  • "How does gRPC work under the hood?" HTTP/2 stream per call, :path with service/method, length-prefixed Protobuf messages, status in trailers, deadlines via grpc-timeout.
  • "How do you evolve the API without breaking clients?" Field-number rules, reserved, additive changes, open enums, CI breaking-change checks, versioned packages for hard breaks.
  • "Why is one pod hot?" Connection-level balancing of multiplexed HTTP/2; fix with L7 proxy or client-side balancing and max connection age.
  • Follow-ups: what happens on DEADLINE_EXCEEDED for a payment, interceptor ordering, gRPC-Web for browsers, streaming backpressure, how to test compatibility.
  • Red flags: using double for money in a schema, "we retry everything three times", no deadlines, renumbering fields, believing gRPC makes calls reliable.

Self-check​

1. Decode the Protobuf bytes 08 96 01 and explain each byte.

08 is the key: field number 1, wire type 0 (varint), because (1 << 3) | 0 = 8. 96 01 is a varint: 0x96 has the continuation bit set and contributes 0x16 = 22; 0x01 contributes 1 × 128. Total 150. So field 1 = 150.

2. A team deletes field 5 channel and later adds string merchant_id = 5. What breaks?

Old binaries still write channel as field 5 and new binaries read it as merchant_id (and vice versa), so values silently land in the wrong field — no parse error. Stored data and messages in queues are also misread. The fix is to declare reserved 5; reserved "channel"; when deleting and to use a new number for merchant_id, enforced by a breaking-change check in CI.

3. How does a gRPC deadline set in checkout reach a database query in the fraud service two hops away?

Checkout creates a context with a deadline; the gRPC client sends the remaining time as the grpc-timeout header. The payments server's handler context carries that deadline; when payments calls fraud with the same (or a derived, shorter) context, the remaining time is sent again. Fraud passes its context into the database driver, which cancels the query when the deadline passes. Each hop sees only the time that is actually left.

4. CreatePayment returns DEADLINE_EXCEEDED. What should the caller do?

Treat the outcome as unknown — the server may have committed the payment after the client stopped waiting. Either query the payment status (GetPayment by idempotency key or reference) or retry with the same idempotency key so the server returns the original result instead of creating a second payment. Never retry with a new key, and surface "processing" to the user rather than "failed".

5. After scaling the inventory service from 3 to 10 pods, the new pods receive almost no traffic. Why, and what are two fixes?

Callers hold long-lived HTTP/2 connections to the original pods, and connection-level (L4 / ClusterIP) balancing never moves existing RPCs. Fixes: put an L7 proxy or service mesh in the path so each RPC is balanced individually, or use client-side round-robin over a headless Service; in both cases set MaxConnectionAge on servers so clients periodically reconnect and discover new pods.

6. Why can't a browser call a gRPC service directly, and what are the options?

Browser APIs do not expose HTTP/2 framing and trailers in the way gRPC needs (status is in trailers). Options: gRPC-Web through Envoy or a gRPC-Web-capable server, the Connect protocol, or REST/JSON via gRPC-gateway or Envoy's JSON transcoder generated from the same Protobuf contract.

7. Which gRPC status code would you return for “insufficient funds”, “account not found”, “optimistic lock conflict” and “ledger database down”?

Insufficient funds: FAILED_PRECONDITION (the request is valid, the system state does not allow it). Account not found: NOT_FOUND. Optimistic lock conflict: ABORTED (the client can re-read and retry at a higher level). Ledger database down: UNAVAILABLE (transient; retryable with backoff for idempotent calls).

🧠 Flashcards0/10 learned · 0 retries

Exercise​

  1. Generate and run. Put the schema in proto/payments/v1/payments.proto, generate Go code with buf generate (or protoc --go_out=. --go-grpc_out=.), and run the server and a client pointed at dns:///localhost:50051. Call it with grpcurl (enable reflection.Register(srv) for this).
  2. Deadlines. Add a 2-second time.Sleep (respecting ctx) in CreatePayment; call with a 800 ms deadline and confirm the client gets DEADLINE_EXCEEDED and the server handler sees ctx.Done(). Then retry with the same idempotency key and confirm a single payment exists.
  3. Evolution. Run buf breaking --against '.git#branch=main' after: (a) adding a field — passes; (b) changing amount_minor from 1 to 7 — fails; (c) deleting reference without reserved — observe what buf reports.
  4. Encoding. Marshal a Money{amount_minor: 150, currency: "USD"} with proto.Marshal and print the bytes in hex; match them against the table on this page.
  5. Load balancing (optional, needs a cluster). Deploy 3 server replicas behind a ClusterIP Service and a headless Service. Send 1,000 RPCs from one client through each and count requests per pod (from the logging interceptor).

Done when: you can show the deadline and idempotent-retry behaviour, the hex dump matches your hand decoding, buf flags the breaking changes, and (optionally) you have per-pod request counts demonstrating the L4 vs client-side difference.

Further reading​

  • Designing Data-Intensive Applications — Martin Kleppmann, chapter 4 "Encoding and Evolution".
  • Protocol Buffers — Encoding and the proto3 language guide on protobuf.dev.
  • gRPC documentation — core concepts, deadlines, status codes, load balancing, keepalive.
  • gRPC: Up and Running — Kasun Indrasiri & Danesh Kuruppu (O'Reilly).
  • "A Note on Distributed Computing" — Waldo, Wyant, Wollrath & Kendall (Sun Microsystems, 1994).
  • Buf documentation — breaking change detection and linting.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).