The protocol debate is usually conducted as a matter of taste — REST is "simple", GraphQL is "flexible", gRPC is "fast". None of those properties is what you are actually buying. You are buying a set of intermediaries that understand your traffic, a cost model for requests you did not anticipate, and a connection lifecycle that your load balancers, autoscalers and deploys must live with for years. This chapter picks protocols by the constraint that binds at each boundary, and walks through the production mechanics — cache-key cardinality, query cost, federated query plans, HTTP/2 connection skew, reconnect storms — that decide whether the choice holds up.
The useful framing is not "what does the payload look like" but "which parties between client and server can participate". REST puts meaning in the method, URL and status code, so every CDN, WAF, gateway and log pipeline can act on it. GraphQL moves the meaning into one opaque POST body; gRPC into HTTP/2 frames and binary protobuf. Each step trades ecosystem legibility for something else: client-shaped queries in one case, a strict schema and connection efficiency in the other.
The second axis is who controls both ends. When one team ships the client and the server in the same release train, the contract is cheap to change and almost any protocol works. When the client is a partner integration pinned to a version for three years, or an SDK installed on devices you will never update, the contract is effectively frozen, and you want the protocol with the most tolerant readers, the most debuggable wire format and the least cleverness. That is why nearly every serious public API — payments, communications, cloud control planes — is resource-oriented HTTP with JSON, even at companies that run gRPC for everything internal.
Constraint that is actually binding
REST / HTTP
GraphQL
gRPC
Clients you cannot redeploy (partners, SDKs in the wild)
Best: curl-able, tolerant readers
Risky: every query shape becomes a contract
Needs codegen on their side
Shared caching by intermediaries (CDN, browser)
Native: GET + Cache-Control + ETag
Only with persisted queries over GET
None — POST, binary, per-connection
Many screens, divergent data shapes, one backend
Endpoint sprawl or over-fetch
The reason it exists
Proto per screen = BFF by another name
East-west, polyglot, tight latency budgets
Fine; schema discipline is optional
Wrong tool: resolver overhead, no deadlines
Deadlines, codegen, multiplexing
Bidirectional or high-rate streaming
SSE one-way; WebSocket is off-protocol
Subscriptions: stateful, hard to scale
First-class, flow-controlled
Cost of an arbitrary request is bounded
Yes — you enumerated the endpoints
No — unless you analyse or allowlist
Yes — methods are enumerated
Commodity ops: WAF, per-route limits, access logs
Everything understands it
All traffic is POST /graphql 200
Needs gRPC-aware L7 (Envoy, mesh)
Read it row-first. Identify the one or two constraints that are genuinely binding for this boundary, and the choice usually falls out. Teams that read it column-first ("which protocol has the most green?") end up picking one protocol for every boundary in the company, which is the actual mistake.
The mistake to avoid is the company-wide mandate. "We are a GraphQL shop" or "everything is gRPC" optimises for the one boundary that was painful when the decision was made and quietly taxes the other three. A mature estate normally runs all three, plus asynchronous events, with an explicit rule for which boundary gets which — and one schema source so the translation between them is mechanical rather than hand-written. The rest of the chapter is the mechanics behind each row of that matrix.
Architect's note · the performance argument is usually a distraction
The underused part of REST is that HTTP defines a shared cache protocol that every layer between you and the user already implements. Cache-Control: s-maxage lets a CDN hold a response the browser must revalidate; stale-while-revalidate serves the cached copy instantly while one background request refreshes it; stale-if-error keeps serving the last good response when your origin returns 5xx. That last directive is an availability feature: for read-heavy, eventually-consistent resources — catalogue, pricing tiers, configuration, public profiles — it turns an origin outage into a staleness incident. No application-level retry logic buys you that as cheaply.
Two further mechanisms matter at scale. Request collapsing (most CDNs and Varnish-class caches coalesce concurrent misses on the same key into one origin fetch) is what protects the origin when a hot key expires; without it, a popular object's TTL expiry is a synchronized stampede. And conditional requests — ETag with If-None-Match — save bandwidth, but they only save origin compute if the ETag is cheap to derive. An ETag computed by hashing the rendered body means you did all the work to answer 304. Derive it from a row version or an aggregate's updated_at and the 304 path never touches the serializer. The same version is what makes If-Match optimistic concurrency work on writes.
Origin load is R × (1 − hit): 17 rps at 1k keys, 333 rps at 20k, 2,000 rps at 120k. Nothing about the code changed between those points — only the headers the response varies on. Hit ratio is a property of the contract's key space, which is why caching has to be designed into the resource model rather than bolted on at the CDN.
The failure mode is not a lack of caching but a key space that grew without anyone noticing. Every header in Vary multiplies the number of distinct cache entries. Add Accept-Language with twenty locales and a 99.8% hit ratio becomes 96.7%; that sounds small until you notice origin load went up about twenty-fold. Add a tenant-specific variant and you are at 80%. Add Vary: Authorization — or let a framework mark responses private because a session cookie was present — and the shared cache is gone entirely, usually discovered months later when the CDN bill drops and the database bill rises. The architectural fix is in the resource model: separate the public, highly shareable representation from the per-user overlay (entitlements, personalised prices) and fetch them as two resources, so the expensive one stays cacheable.
Pitfall · RPC over HTTP is not REST
POST /api/v1/getOrderSummary has HTTP's ergonomics and none of its semantics: no shared caching, no safe retries by intermediaries, no conditional requests. If the boundary is RPC-shaped, use an RPC protocol; if it is resource-shaped, model resources. The hybrid pays for both.GraphQL's promise is that clients ask for exactly the shape they need. The architectural consequence is that the server no longer enumerates the requests it will serve. A REST API has, say, 140 endpoints, each of which you can load-test, cache, rate-limit and capacity-plan. A GraphQL schema has a combinatorially large set of valid documents, and the most expensive one is usually a legal nested query nobody on your team ever wrote. The N+1 problem did not go away; it moved from the client's network waterfall into your resolvers, where it now executes inside your data centre at LAN speed — which makes it more efficient and far easier to abuse.
DataLoader-style batching is the standard mitigation: resolvers enqueue keys, and the loader dispatches one batched fetch per tick of the event loop, collapsing N+1 into roughly one query per level of the tree. Two properties are routinely misunderstood. The batching window is a scheduling artefact, so an await in the wrong place splits a batch and the N+1 comes back silently. And the loader's cache is per-request memoisation, not a cache — it does nothing for the next request, and making it cross-request introduces authorization leaks, because resolvers typically authorize by the viewer in context.
All three resolvers are "using DataLoader" and all three pass code review. Only A batches. The detection is cheap and should be a CI gate on every registered operation: record queries issued per loader per request and fail when it exceeds the depth of the document. Query count per operation is a better regression signal than latency, because B and C are fast on a laptop and slow at production cardinality.
query {
viewer {
repositories(first: 100) {
pullRequests(first: 50) {
reviews(first: 20) {
author { followers(first: 10) { login } }
bar length: log10(nodes)
Any depth limit loose enough for real screens allows this query. A cost model — multiply list-size arguments down each path and sum across siblings — totals it at ≈1.1M nodes (100 + 5k + 100k + 1M) and rejects it before a single resolver runs. The same arithmetic lets a public API meter by cost instead of by request count, which is the only rate limit that means anything when one request can be worth a million.
Depth limits are the usual first line of defence, and they are nearly useless: cost is multiplicative in list arguments, not additive in depth. A proper static cost analysis walks the document, multiplies the first/last bounds down each path, sums siblings, and rejects anything above a budget before execution. GitHub's public GraphQL API is the canonical example of doing this in public — it documents a node-count limit per query and a points-based hourly rate limit derived from the same calculation — and Shopify's Admin API similarly meters by calculated query cost. Two amplification vectors that cost analysis must also handle: aliases, which let one document invoke the same field hundreds of times (the known technique for batching credential-guessing through a login mutation past per-request rate limits), and fragments that fan out across interface implementations.
The deeper point is that for first-party clients the arbitrary-query problem is self-inflicted. Your web and mobile apps send a finite set of documents known at build time. Trusted documents (persisted queries registered in CI, referenced by hash, with the server rejecting anything unregistered) turn the unbounded query language back into an enumerable RPC surface: every operation can be cost-checked and load-tested before it ships, sent as a GET so HTTP caching works again, and named in metrics. At that point GraphQL for first-party clients is essentially a typed BFF generator with excellent tooling — which is a fine thing to be. Accepting arbitrary queries is a product decision that only makes sense for a genuinely public, developer-facing graph.
Two calibration details separate a cost model that works from one that gets switched off after the first false positive. The budget should be derived, not guessed: compute the static cost of every registered operation, set the enforcement ceiling at a multiple of the most expensive legitimate one, and alert (not block) on anything within that margin, so the budget moves with the product rather than with a Slack argument. And static cost is an upper bound — first: 100 on a connection that usually returns three items is scored at 100 — so for metering, charge the static estimate up front and reconcile against the actual node count after execution; otherwise honest clients are rate-limited for list bounds they never hit, and they respond by paginating in smaller pages, which multiplies request count and makes the problem worse.
The failure semantics deserve the same scrutiny, because they are part of the schema and nobody reviews them as such. When a non-null field fails to resolve, the null propagates to the nearest nullable ancestor. Mark Order.price: Money! as non-null because "an order always has a price", and the day the pricing subgraph times out, every Order in the list nulls — and if the list itself is [Order!]! under a non-null viewer, the entire response collapses to data: null. A single slow dependency has become a full-page outage, returned with HTTP 200. The design-review rule is that nullability is a blast-radius decision: fields backed by a different service, subgraph or datastore than their parent should be nullable so that partial failure stays partial, and non-null is reserved for fields that fail together with their parent anyway (the ID, fields in the same row).
Pitfall · every request is POST /graphql 200
errors array, and the endpoint is the same for the cheapest and the most expensive operation. Before launch, make the operation name mandatory, lift it into metrics and traces as the route, alert on error rates per operation, and rate-limit by computed cost. Teams that skip this discover the gap during their first GraphQL incident, when the dashboards say everything is fine.Federation (Apollo Federation being the dominant implementation) lets each domain team own a subgraph, and a router composes them into one schema. An entity like Product is defined by one subgraph and extended by others; the router resolves cross-subgraph references by calling each owning subgraph's _entities field with the keys it collected in the previous step. It solves the organisational problem of a monolithic GraphQL server every team has to edit, and it is also a query planner that generates distributed execution plans from a schema that looks flat to everyone who reads it.
The client sent one query to one endpoint. The router turned it into three dependent waves, because orders cannot be fetched until the viewer is known, and prices need SKUs from the orders. Nobody designed that waterfall; it emerged from where entity keys happen to live. Query plans are an artefact you must be able to inspect per operation.
The latency arithmetic is the part that surprises people. A wave of parallel calls completes when its slowest member does, so tail probabilities compound. If five subgraphs in a wave each meet a 50ms p99 independently, the chance that all five come in under 50ms is 0.995 ≈ 0.951 — roughly 5% of requests see at least one tail call. To hold the router's p99 at a given budget, each subgraph in a five-wide wave has to meet that budget at about its p99.8. Stack three dependent waves and you are summing those tails. Two schema details quietly add waves: a @requires field forces the router to fetch the required fields from their owner before it can call the requiring subgraph, and an entity whose @key is not available where the reference is made needs an extra hop to resolve the key. Neither is visible in the client's query. This is the same fan-out tail effect described in Google's "The Tail at Scale", now generated automatically by a planner rather than written deliberately by an engineer who could see it.
0.99⁵ ≈ 0.95
5-way wave, each at p99
p99.8
per-subgraph target for router p99
Σ waves
latency adds across dependencies
1 router
new tier-0 dependency
The operational and organisational consequences follow. The router is now a tier-0 service on every product request, and its query-plan cache, its memory under large responses and its behaviour when one subgraph is down (partial data with errors, or a failed request?) need an owner. Composition checks in CI become your schema governance: a subgraph change that breaks composition or changes a plan should fail the build of the team making it, not surface in the router at deploy time. And entity ownership becomes an org-design question — which team owns User, who is allowed to add fields to it, and what happens when two teams need contradictory semantics for the same field. There is also a batching trap one level down: the router sends a single _entities call carrying every representation it collected — 500 order IDs in one request — and a subgraph whose reference resolver fetches them one at a time has reintroduced N+1 inside itself, invisible to the router's trace except as one slow span. Federation does not remove the coordination cost of a monolithic schema; it relocates it into a planner and a review process.
Architect's note · when not to federate
HTTP/2 multiplexes many concurrent requests as streams over one TCP connection. gRPC exploits this aggressively: a channel typically holds one connection per backend and sends every RPC down it. That is efficient — no per-request handshake, header compression across calls — and it breaks every load balancer that makes its decision per connection. A Kubernetes ClusterIP service balances in kube-proxy at connection time; an L4 network load balancer does the same. Once a client has its connection, every RPC for the life of that connection goes to one pod.
Two failures follow. The first is static skew: with C clients each holding one connection to a random choice of S servers, the expected number of servers receiving no traffic at all is S(1 − 1/S)C. For ten clients and ten servers that is about 3.5 idle pods while the others run hot. The second is dynamic and worse: when the autoscaler adds pods, existing connections do not move, so the new capacity takes no load and the hot pods stay hot until something recycles connections. The gRPC client's default policy, pick_first, compounds this — even given multiple addresses from DNS, it connects to one and stays there.
The autoscaler did its job and the dashboard shows six healthy pods — while latency on the three original pods keeps climbing. Scaling out a gRPC service behind a connection balancer adds capacity nobody can reach until connections recycle. MaxConnectionAge bounds that window; request-level balancing removes it.
The fixes, in increasing order of capability. Server-side MaxConnectionAge (with a grace period) makes the server send GOAWAY periodically, forcing clients to reconnect and re-resolve; it is crude but bounds the imbalance window and is a one-line change. Client-side round_robin against a headless service gives request-level balancing with no proxy, but creates C × S connections — at 500 clients and 200 servers that is 100,000 connections, each with keepalive and TLS state — which is why large fleets use subsetting, where each client connects to a deterministic subset of backends (Google's SRE book describes deterministic subsetting in its datacentre load-balancing chapter). An L7 proxy or mesh (Envoy sidecar or proxyless xDS) balances per request, supports outlier ejection and least-request algorithms, and is where most organisations end up.
Strategy
Total connections
Fan-out
Balancing granularity
Extra hops
Use when
Connection balancer + MaxConnectionAge
C = 500
1 per client
bounded by age (minutes)
none
Small fleets, uniform RPC cost, scale events rare
Client round_robin, full mesh
C×S = 100,000
200 per client
per request
none
S under ~50 and C×S well below per-pod conn limits
Client round_robin + subsetting (k=20)
C×k = 10,000
20 per client · 50 per server
per request within subset
none
Large fleets without a mesh; needs deterministic subset assignment
L7 proxy / sidecar mesh
sidecar → upstream pools
1 local + proxy pools
per request, least-request, outlier ejection
1 extra hop each side
Heterogeneous RPC cost, polyglot clients, need for ejection
Proxyless xDS (gRPC client as data plane)
subset from control plane
per client policy
per request, weighted
none
Hot fan-out paths where sidecar CPU/latency is measurable
The subset size is the lever people forget to reason about. Each server receives about C × k ÷ S clients; with k = 20 that is 50, enough that random imbalance between clients averages out. Drop k to 3 and each server sees ~7-8 clients, and one hot client (a batch job, a retry storm) is now a large share of a single server's load. Random subsetting also leaves the per-server client count binomially spread (some servers get noticeably more clients than others); deterministic subsetting exists to make it exact. Thresholds in the right-hand column are rules of thumb, not limits.
The mesh is not free, and the case against it is quantitative rather than ideological. A sidecar adds two proxy traversals per call (client-side and server-side), each a user-space copy, TLS termination and filter chain. For a service whose calls take tens of milliseconds, that is noise. For an aggregator that fans out to 30 backends on the request path, the per-hop overhead is paid 60 times per user request, and the sidecar's CPU becomes a line item comparable to the application's own — measure both before deciding, on your payload sizes. This is the niche for proxyless gRPC: the client library takes endpoint and policy from the same xDS control plane, balances per request itself, and removes the hop, at the cost of tying balancing features to what each language's gRPC implementation supports. The practical rule: mesh by default, proxyless for the handful of fan-out-heavy paths where a profile shows the proxy, and never a third, hand-rolled scheme.
Two details decide whether the cheaper fixes actually work. First, in the major gRPC implementations the DNS resolver re-resolves when a connection closes or fails, not on a timer. A client doing round_robin against a headless service therefore does not discover new pods by itself either; it needs something to close a connection, which is why MaxConnectionAge is usually deployed alongside client-side balancing rather than instead of it. Second, MaxConnectionAge has a cost you can compute: a fleet holding N connections with age A reconnects at N/A per second in steady state. With 100,000 connections and a 5-minute age (illustrative) that is ~330 TLS handshakes a second, spread across the fleet, which is cheap; a 30-second age is ~3,300 a second, which is not. grpc-go adds ±10% jitter to the age so connections opened together do not all expire together; implementations or proxies that do not jitter will turn a deploy's simultaneous connection births into periodic synchronized reconnects.
The other HTTP/2 mechanics that bite in production: max concurrent streams per connection is a server setting, and a client that exceeds it queues RPCs locally, showing up as client-side latency with idle servers. Keepalive pings that are too aggressive get the connection closed by the server with GOAWAY ENHANCE_YOUR_CALM — a common cause of mysterious periodic failures after someone "tuned" keepalives. And because all streams share one TCP connection, a single lost packet stalls every in-flight RPC on it; inside a datacentre with low loss this is negligible, across lossy networks it is why HTTP/3 exists.
Architect's note · deadlines are the real feature
grpc-timeout), and the standard libraries propagate it through the context into downstream calls. That means a request abandoned at the edge after 800ms stops consuming capacity three hops down instead of completing work nobody will read — the difference between a latency spike and a retry-amplified overload. Make deadline propagation a platform default and treat a missing deadline as a bug. Retry policies, budgets and hedging are part of the reliability contract covered in Idempotency, Retries & Long-Running Operations.SSE (with Last-Event-ID resumption built in), WebSockets, GraphQL subscriptions and gRPC streams differ less than the thing they share: any long-lived stream turns a stateless tier into a stateful one: connections pin clients to instances, and your deploys, autoscaling and load balancing all now operate on connections rather than requests.
The consequences arrive in a predictable order. Deploys have to drain: a rolling restart of 20 pods holding 10,000 streams each either waits for streams to end naturally (possibly hours) or cuts them, and cutting them is a mass reconnection event. The less obvious effect is what a rolling restart does to the distribution. The 10,000 clients cut from pod 1 reconnect to the 19 pods still up; the restarted pod 1 comes back nearly empty and fills only from later cuts. By the end, the pods restarted first carry the accumulated displaced load and the last pod restarted carries almost none — a skew that persists until the next deploy, because long-lived streams never rebalance on their own. Least-connections balancing at the proxy, a per-pod stream cap that sheds with a jittered reconnect hint, or staggering cuts over a window longer than the rollout all counter it; doing nothing means your post-deploy capacity is set by your hottest pod. Idle timeouts on intermediaries — AWS ALB defaults to 60 seconds — silently kill quiet streams unless the protocol sends heartbeats more often than the shortest timeout on the path; some load balancers apply their request timeout to a WebSocket's total lifetime instead, which caps every stream regardless of heartbeats. And the load-skew problem from 2.5 applies with more force, because streams live longer than connections for unary RPC ever did.
Total load is unchanged; its distribution is not. The first pod restarted absorbs a share of every later cut and ends at ~1.7× its pre-deploy stream count, while the last one ends empty. If pods were sized with 50% headroom, the deploy itself has consumed it on pod 1 — and every subsequent deploy starts from this skew, not from even.
Same client count, same server capacity; the only difference is whether retry timing is randomised. Without jitter the herd stays synchronized, most of each wave fails, and the recovery takes minutes of saturated servers instead of 30 quiet seconds. All numbers illustrative.
The reconnect storm is the failure to design for. When a load balancer restarts, a region fails over, or a deploy cuts streams, every client reconnects at once, and reconnection is expensive: TLS handshake, token validation, rebuilding subscription state, replaying missed events. Clients using exponential backoff without jitter stay synchronized — each retry wave hits the servers together, most of it fails, and the storm lasts far longer than the outage that caused it. Full jitter spreads the herd across the backoff window; server-side admission control (reject early and cheaply with a retry-after hint) keeps the servers doing useful work while it drains. The sizing consequence is rarely stated: for a stateful edge, reconnect throughput, not steady-state throughput, sets the fleet size. Recovery time is roughly streams ÷ admission rate, and admission rate is bounded by handshake and resubscribe cost, not by message traffic. TLS session resumption, caching token validation and making resubscription cheap (a cursor, not a snapshot rebuild) raise that rate more than adding pods does. The storm is almost never load-tested; it should be a named test in the capacity plan.
Two contract-level decisions determine whether streaming is operable. First, resumption: every event on the stream should carry a cursor or sequence number, and reconnecting with the last seen value should resume from there, so a dropped stream is a gap you can close rather than data you lost. Second, backpressure: HTTP/2 flow control (the protocol's initial per-stream window is 65,535 bytes; gRPC implementations raise it via BDP estimation) will stop a slow consumer from reading, but the server then buffers everything it wants to send. Decide in the contract what happens to a consumer that cannot keep up — drop to snapshot-and-resume, coalesce updates, or disconnect — because the default is unbounded memory growth on the server. Browsers add one more constraint: they cannot speak native gRPC, so gRPC-Web or Connect sits in front, and they support client-to-server streaming poorly or not at all; for token streaming from LLM APIs, SSE has become the default for exactly these reasons (see LLM Ops).
Pitfall · streams as a message bus
Put together, the constraints produce a stable placement for most organisations. The first-party layer's design — GraphQL with trusted documents versus a BFF per client family — is covered in Gateways, Auth & the Edge.
Public & partner
REST/HTTP + OpenAPI · webhooks out
why · Clients you cannot redeploy; caching; curl; every WAF and gateway speaks it.
trap · Treating it as an RPC tunnel: POST /doThing kills caching and idempotency semantics.
First-party UI
GraphQL with trusted documents — or a REST BFF
why · Many screens, fast-moving UI, one team owning both sides of the contract.
trap · Letting the graph become the public API because it already exists.
East-west sync
gRPC + protobuf
why · Deadlines, codegen, streaming, multiplexing, strict schema in CI.
trap · Connection-level balancing; retries without budgets; no deadline propagation.
East-west async
Events on a log (see Data Engineering)
why · Temporal decoupling; many consumers; replay.
trap · Using gRPC streams as a poor man's message bus.
The trap in running several protocols is maintaining several hand-written contracts that drift. The better pattern is one schema, mechanically projected: define internal services in protobuf, annotate HTTP mappings (google.api.http), and let Envoy's gRPC-JSON transcoder or grpc-gateway serve a JSON/HTTP facade generated from the same source (Connect is the RPC-shaped alternative: the same handlers served as gRPC, gRPC-Web and plain POST-JSON). The public API then inherits the internal schema's compatibility checks — with one trap. Protobuf compatibility is defined on field numbers, JSON compatibility on field names. Renaming a field is wire-safe and breaks every JSON consumer; the proto3 JSON mapping also renders int64 as a string and enums as names, so renaming an enum value is a breaking change for JSON clients only. If a proto is transcoded, its breaking-change check has to run in JSON-aware mode (Buf's WIRE_JSON category), not wire-only. The caveat is that a generated facade exposes your internal decomposition to outsiders — resource boundaries that follow service boundaries rather than the customer's mental model. Transcoding works best when the public resource model is designed first and the internal services are shaped to it, or when a thin, deliberately designed edge layer sits in front; it works worst when an internal proto is published unchanged because it was convenient.
The final criterion is organisational. Each protocol implies a toolchain that someone has to own: a schema registry and breaking-change checks for protobuf, a composition pipeline and cost model for a graph, an OpenAPI linter and SDK generation for REST. A platform team can make two of these excellent; three is a stretch, and each additional protocol dilutes the investment in the others. Choose the smallest set that covers your binding constraints, make the boundary rule explicit in an architecture decision record, and make the paved road so good that nobody wants to leave it.
Questions to ask in the design review
Where next