Service APIs: REST, gRPC, GraphQL and load balancing

Reading: 52 min, plus 16 in closed details. Data as of October 2026; every gRPC exchange, failure and balancer run recorded locally on 5 October 2026. Child of Topic: protocols.

The idea in one screen

A service API is a contract for a call that can fail halfway. REST, gRPC and GraphQL write that contract down and put it on the wire differently, but every good API answers the same questions: what may be sent, how long the caller waits, what each failure means, whether a retry is safe, and which copy of the service answers.

Fig. 1 · One LLM request crosses three API styles before a token comes back

  1. Four parties, one request. Your app (curl, an SDK, a browser), the API front door (auth, rate limits, idempotency, translation), a router that picks a replica for each call, and three copies of the inference server. The running example is the root page's request, POST /v1/messages with "What colour is the sky?".
  2. Outside the front door: REST with SSE (sections 2 to 7), because anyone with curl must be able to call it. The body is 117 bytes of JSON; the root's HTTP/1.1 recording sent a 277-byte request and got 771 bytes of SSE payload for five tokens. Versions, errors, pagination, the OpenAPI contract, the Idempotency-Key, 429 and rate-limit headers and the provider's format all live on this hop.
  3. Inside: gRPC (sections 8 to 12), because both ends are yours and the calls are many, typed and streaming. The same request is 49 bytes of protobuf behind a 5-byte prefix on one HTTP/2 stream; a deadline that shrinks each hop rides in grpc-timeout, and the status comes last, in the trailers.
  4. Who answers (sections 12 and 13). The router reads each call and picks a replica: measured, 30 calls through an L7 balancer landed 10 / 10 / 10. An L4 balancer chooses once per connection and pinned all 30 to one replica.
  5. Later, the front door calls you (section 6). When a batch ends, it POSTs a signed event to a URL your app registered: a webhook, the same API problems with the roles swapped.
  6. Other faces of the same services (sections 14 to 16): gRPC-Web and Connect for browsers, GraphQL for many front ends that each name the fields they want, JSON-RPC for MCP and A2A, where a model or an agent is the caller.

You need: HTTP methods, status codes and HTTP/2 streams (HTTP, sections 2 and 6), and what an SSE stream is (Streaming and real-time). Credentials on these calls are Auth's; MCP's own use of JSON-RPC is MCP's.

New terms

Idempotent: doing it twice has the same effect as once.
Idempotency key: a client-chosen id that makes one POST safe to retry.
Cursor: an opaque token meaning "the rows after the last one you saw".
Schema or IDL: a machine-readable description of messages and operations (OpenAPI, .proto, GraphQL SDL).
Webhook: your server POSTs to a URL the client registered when an event happens.
Field number: the integer that names a protobuf field on the wire; names never travel.
Deadline: the moment after which the caller no longer wants the answer; gRPC passes what is left to each hop.
Trailers: header fields sent after the body; gRPC puts its result there.
Channel: a gRPC client's long-lived handle on a target: names, connections, calls.
L4 / L7 balancer: chooses a replica once per TCP connection / once per call.
Resolver: the GraphQL function that produces one field's value.
Replica: one running copy of a service.

1. What an API style decides

Two programs written by different teams must agree on what a request contains, how it becomes bytes, how the bytes travel, what shape a call has, and how it fails. An API style is a bundle of answers. Put the four styles you will meet side by side on those questions:

REST (JSON over HTTP)gRPCGraphQLJSON-RPC 2.0
ContractOptional: OpenAPI if you write oneA .proto file, required; code generatedA typed schema, requiredNone of its own
EncodingJSON textProtobuf binaryJSON (a query names the fields)JSON
TransportHTTP/1.1, 2 or 3HTTP/2 onlyUsually one HTTP POST endpointAny channel: stdio, WebSocket, HTTP
Call shapeRequest and response; SSE for a stream of eventsUnary and three streaming shapes, nativeQuery, mutation, subscriptionRequest, response, notification
FailureHTTP status plus a JSON error body; no deadline17 status codes in a trailer; deadlines built inUsually 200 with an errors arrayAn error object with a numeric code
Best atPublic APIs any client can call; caches and proxies understand itInternal calls you own at both ends; streamingMany front ends reading overlapping dataA tiny call format for MCP, A2A and editors
CostsBulky text; contract drift if there is no specBrowsers cannot call it directly; L4 balancers pin itN+1 backend calls, query cost limits, HTTP caching mostly lostSchema, streaming and transport left to whoever adopts it

RPC (remote procedure call) makes a call on another machine look like a local one, stub.Generate(request): a generated stub turns it into bytes, a server-side servicer you fill in answers it. Its old trap is that a network call can be slow, half-done or lost in ways a local call never is, which is why sections 4, 10 and 11 exist. REST takes the other road: named things (resources) and a fixed set of verbs whose meaning (safe, idempotent, cacheable) every proxy already knows.

2. REST done properly: resources, errors, pages, versions

A public LLM API is called by curl, SDKs, browsers and proxies you have never seen; the one thing they share is HTTP. "REST" in practice means resource-shaped HTTP with JSON (Fielding's full style, below, is rarely followed), and what separates a good one is a handful of decisions client code depends on.

Resources and methods

Model the API as nouns with URLs (/v1/chats/{id}/messages), plural collections, one level of nesting for real ownership, and opaque prefixed string ids (chat_ae8136d1b896 rather than 17, which leaks volume and invites guessing). Let the method be the verb: GET is safe, PUT and DELETE are idempotent, POST is neither (HTTP section 2 owns those semantics). Return the created object with 201 and Location. For edits, PUT replaces the whole resource, so sending it twice is harmless; PATCH sends only what changes, and with a JSON merge patch (RFC 7396) {"title": "Trips 2027"} changes the title and leaves the rest. Most JSON APIs use PATCH for edits and POST for creation, and do not offer PUT. Two shapes cover what CRUD does not:

  • Custom methods. An action that is not create, read, update or delete gets a :verb suffix on the resource, POST /v1/{name=publishers/*/books/*}:archive in Google's rules (AIP-136). Never a GET with side effects: crawlers, link previews and caches send GETs freely.
  • Long-running work. When a call takes minutes, answer at once with a handle to poll: Google returns an Operation resource (AIP-151); plain HTTP says 202 Accepted. Anthropic's Message Batches API is this pattern: a batch starts in_progress, you poll until ended, results stay for 29 days (Claude docs, batch processing); a webhook (section 6) is the push alternative to polling.

The running request is a function call wearing a resource's URL (POST /v1/messages creates nothing you GET later), which is fine: the expensive call hangs off an ordinary resource that can be stored, billed, listed and made idempotent. For searches with large bodies, RFC 10008 (June 2026) adds QUERY: a safe, idempotent request that carries a body, so a search or GraphQL query no longer has to choose between a huge URL and an uncacheable POST.

Errors: three layers

Client code must decide, for every failure, whether to show a message, retry, give up or re-authenticate. It can only do that if errors have three layers: the status code (whose fault, retry or not), a stable error type that code switches on and that is append-only (never renamed or reused), and human text that no code parses. Add a request id in a header and in the body (Anthropic: request-id; OpenAI: x-request-id). The standard shape is RFC 9457 problem details, application/problem+json with type, status, title, detail, instance (RFC 9457, July 2023, obsoletes RFC 7807); its default type is about:blank, meaning "no additional semantics beyond that of the HTTP status code". Where the status alone cannot settle whether to retry, say so explicitly: Stripe sends a Stripe-Should-Retry header (Stripe, advanced error handling). LLM providers predate it and keep their own envelopes with the same layers (Anthropic's types run from invalid_request_error, 400, to overloaded_error, a non-standard 529, and "the type values will grow over time"). Two rules people break: one shape for every error, including a proxy's HTML 502 page; and once a stream has started the status is already 200, so later errors arrive as an event inside the stream.

A well-designed call carries its contract in the URL, the headers and the error body
POST /v1/messages HTTP/1.1 anthropic-version: 2023-06-01 Idempotency-Key: 7f3c9a0e-2b41-4c55-9d1e-6a8f0b2c4d71 content-type: application/json {"model": "...", "max_tokens": 16, "stream": true, "messages": [...]} HTTP/1.1 429 Too Many Requests retry-after: 2 request-id: req_011CSHoEeqs5C35K2UUqR7Fy content-type: application/json {"type": "error", "error": {"type": "rate_limit_error", "message": "..."}}
Click a highlighted part.

Request and response shapes follow the Claude API's documented headers and error body (Claude API errors, versioning); the idempotency header is shown for the pattern of section 4, not as a claim that this API accepts it. Illustrative values.

The seven parts: 1. a plural noun with a major version in the path; 2. a dated version in a header, pinned per request; 3. a client-chosen key that makes this POST safe to retry (section 4); 4. the status says whose fault and whether to retry; 5. how long to wait (section 5); 6. a request id to quote to support and to search your logs for; 7. a stable, documented error type that code can switch on.

Pagination: offset shifts under writes, a cursor does not

A list endpoint returns a page and a way to ask for the next. Offset (?limit=20&offset=40) is easy and lets a UI jump to page 7, but the database still reads every skipped row, and rows added while the user pages shift everything. A cursor encodes the sort key of the last row seen, WHERE (created_at, id) > (:t, :id), so an index seeks straight to it.

What the user sees when rows change between requests (illustrative: eight chats c1 to c8, newest first, pages of three): page 1 is c8, c7, c6. If c9 is created before page 2, offset skips 3 rows of the new list (c9, c8, c7) and the user gets c6 again, then c5 and c4; if c5 is then deleted, page 3 skips 6 rows of the shorter list, starts at c2, and c3 is never shown. One chat shown twice and another never, without any error, from two ordinary writes. A cursor asks for the rows after the last one seen: after c6 it gets c5, c4, c3 (the new c9 does not disturb it), after c3 it gets c2, c1 (the deleted c5 simply is not there), so every chat that existed is shown exactly once. The cost differs as much: one 20-row page at depth 500,000 in a million-row Postgres 16.2 table took 98.1 ms with offset and 0.032 ms with a cursor (median of 7 runs, 4 October 2026, on an Apple M1 Pro; recorded by the Building a backend API page's script, copied here as src/inputs/pagination_pg.json). Why, with the plans behind the two numbers and the cost at every depth, is Query planning and performance's, section 8.

The rules from the big style guides: cursors are opaque ("must be opaque (but URL-safe) strings, and must not be user-parseable", AIP-158), because anything clients can decode they will depend on; an empty next token is the only end signal (AIP-158: "If the end of the collection has been reached, the next_page_token field must be empty"), so clients never guess from a short page; cap limit; sort by a unique key (add the id as a tie-breaker, or equal timestamps skip or repeat across a page boundary); skip total_count unless needed, since counting a filtered set is itself a scan. Offset keeps a place in small admin tables.

Filters and sorts meet the cursor in two more rules. Allow-list filter fields and sort keys to those you have indexes for: a generic "filter on any column" becomes a full table scan the first time someone filters on an unindexed one, and a way to probe fields you never meant to expose. Bind the filters into the cursor: a cursor made under model=large means nothing under model=small, so store a hash of the filters inside it and reject a mismatch. Sorting descending needs the keyset comparison reversed (< instead of >) and an index in that order, or one Postgres can scan backwards; Markus Winand's "We need tool support for keyset pagination" makes the case for keysets with Postgres and MySQL plans.

Versioning: never break a client you cannot see

A breaking change is any change after which a correct existing client stops working or starts doing something different: removing or renaming a field, changing its type, making an optional field required, changing a default ("Changing the default value is considered breaking", AIP-180), or changing behaviour under the same shape. In practice the contract is wider than the documentation: Hyrum's law, "With a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody" (Hyrum Wright, hyrumslaw.com); a phone app version can stay installed for years, so everything observable is contract. Adding endpoints, optional fields, response fields and enum values is safe only if clients are tolerant readers that ignore what they do not know; Anthropic's contract reserves the right, within a version, to "add new variants to enum-like output values (for example, streaming event types)" (Claude API versioning).

StrategyLooks likeWhoCost
Major version in the path/v1/messages, later /v2/OpenAI, Anthropic, most public APIsA v2 is a second API to run; everything between majors must be additive
Dated version in a headeranthropic-version: 2023-06-01, then 2026-10-21Anthropic (required on every request)URLs stay stable; old dates keep working, breaking changes ship as a new date; SDKs set it, hand-written clients forget it
Dated versions pinned per account, with transformsStripe-Version: 2017-05-24StripeCore code emits only the newest shape; one small module per breaking change walks a response back to the caller's date, forever (Stripe, API versioning, 2017)

What a dated header buys shows in Anthropic's second date. 2023-06-01 served every client for over three years while the API grew additively; the breaking changes then shipped together as anthropic-version: 2026-10-21 (21 October 2026): temperature, top_p and top_k return 400 "even at the parameter's default value", a document block directly in an assistant message returns 400, and so does a non-empty citations array on a text block in a user message (migration guide). Nothing forces the move: the guide gives no sunset for 2023-06-01 and tells a request that relies on non-default sampling to stay on it. The new SDK major versions send the new date by default, so the upgrade happens when a team bumps a major dependency, the moment it expects to read a changelog.

For an LLM API the model is part of the contract: the same request to a new model gives different answers, lengths and costs, so production code pins dated snapshot names rather than moving aliases.

Depth: what Fielding's REST actually is, the Richardson levels, retiring endpoints

REST is an architectural style Roy Fielding described in chapter 5 of his 2000 dissertation to explain why the web scaled (Fielding, chapter 5). Its constraints, each with what it buys: resources, not functions (you transfer representations of a named thing); a uniform interface (a small fixed set of verbs with universal meaning: this, not JSON, is the deepest difference from RPC, since every intermediary knows what a GET may do); statelessness (each request carries everything needed, the API key and the full conversation, which is what lets any replica answer any request); cacheable and layered (proxies and caches can sit in between without understanding your app); and hypermedia (HATEOAS: responses carry links to the next actions; the least followed constraint, whose one mass deployment is the human web of HTML links and forms).

Martin Fowler's write-up of Leonard Richardson's maturity levels is the usual yardstick (Fowler, 2010): level 0 is one endpoint taking POSTs (RPC in JSON), level 1 adds resources with their own URLs, level 2 uses the HTTP verbs and status codes properly, level 3 adds hypermedia links. Level 2 is where almost every good API stops, and the running request is level 2; "HTTP API" is the honest name.

Retire anything with a date, a warning while it still works (the Deprecation header, RFC 9745, and Sunset, RFC 8594), and logs that show nobody still calls it. A fourth versioning school uses no URL versions at all and evolves compatibly, new media types if forced (Zalando's guidelines: "MUST not use URL versioning"). Stripe's post reports close to 100 backwards-incompatible upgrades over six years handled by its transform modules without breaking integrations; most teams should start with /v1/ plus strictly additive changes and add a version header when the first unavoidable break arrives.

3. OpenAPI and schema-first design: the contract as data

Without a written contract, clients and servers drift apart silently: a renamed field is found by a customer, not a compiler. A schema turns the contract into data that tools check. For REST that is an OpenAPI document (paths, methods, parameters, request and response schemas, auth schemes); for gRPC it is the .proto file (section 8); for GraphQL its SDL. Everything else is generated from it:

Code-first writes the server and exports the spec (FastAPI serves one at /openapi.json); schema-first writes the spec, reviews it like code, and generates server stubs and clients from it. Larger organisations with many teams tend to the second, because the review happens before anyone depends on the shape, and a CI job that diffs the new spec against the published one fails the build when a field disappears. Several API companies, LLM providers among them, generate their official SDKs from an OpenAPI spec with commercial generators. OpenAPI 3.1 aligned its schemas with JSON Schema; 3.2.0 (19 September 2025) added sequential and streaming media types such as text/event-stream, so SSE endpoints can finally be described; the current release is 3.2.1 (10 September 2026, the root's Protocol atlas entry).

One schema, five things that can no longer drift from it

The fan-out is the same for an OpenAPI document and a .proto file; only the tools differ (OpenAPI Generator and commercial generators, oasdiff; protoc, buf breaking).

4. Idempotency keys and retries across services

The user presses Send; after 30 seconds nothing has come back. Either the request never arrived, or it arrived, the model answered, the credits were charged and the reply was lost. The client sees the same timeout in both cases: retrying risks paying twice, not retrying risks losing the message. GET, PUT and DELETE may be retried because they are idempotent; generation is a POST. An idempotency key makes one POST idempotent: the client generates a unique value per logical action, sends it on every retry of that action, and the server answers repeats from what it stored the first time. The page's toy front door ran the same lost reply four ways; pick one:

Fig. 2 · The retry is harmless only when the server remembers the key

  1. The request leaves without a key. The toy client sends the message at 0.000 s with a 0.2 s read timeout; the toy server's "model" takes 0.3 s.
  2. The work commits. At 0.301 s the server saves msg_1 and charges 10 credits in one transaction.
  3. The reply is lost. The client gave up at 0.201 s, so the 201 written at 0.301 s reaches nobody. A tunnel, a proxy reset, a phone that slept: the client cannot tell this from a request that never arrived.
  4. The client retries. It must, or the message is lost. At 0.601 s the same body arrives with nothing to recognise it by, so the model runs again: msg_2 and 10 more credits, answered at 0.902 s.
  5. What the user ends up with. Two messages and 20 credits for one press of Send, and a duplicate in the chat.

measured 7 November 2026 by src/lab/idem_run.py: a standard-library HTTP server with SQLite (Python , SQLite ) standing in for the front door. The work time (0.3 s), the client's timeout (0.2 s) and the price (10 credits) are the toy's settings, illustrative; statuses, headers, counts and times are measured. The mechanism follows Stripe's design (Stripe, idempotent requests; Brandur Leach, 2017).

The server side, in three steps. (1) Claim the key atomically: insert (user, key, request fingerprint, status started) under a unique constraint, so exactly one of two simultaneous attempts wins; never "select, and if absent insert", which races. (2) If it exists, compare and replay: a different fingerprint means the client reused a key for a different action (422); started means the first attempt is still running (409, retry later); done means return the stored status and body (Stripe marks it Idempotent-Replayed: true). (3) Do the work and store the result in one transaction, so the message, the charge and the stored response commit together. Then release the claim on every exit that did not store a response, and give claims an expiry, or a crash between steps 1 and 3 leaves the key stuck at started and every retry gets 409 forever (Code design found and measured exactly that bug in the Building a backend API demo).

Depth: what the IETF draft and Stripe each specify
QuestionIETF draft (draft-07, 2025-10-15)Stripe (docs, read 2026-10-04)
Key format"It is RECOMMENDED that a UUID or a similar random identifier be used"V4 UUIDs suggested; up to 255 characters; never personal data
Same key, different request422An error
Retry while the first runs409409
What is storedThe resource's choice; fingerprint the requestStatus code and body of the first request, "regardless of whether it succeeds or fails", 500s included
Expiry"SHOULD define such expiration policy and publish it"Keys pruned after at least 24 hours

The Idempotency-Key header is not an RFC: the IETF draft reached revision 07 and is listed as expired (datatracker, checked 2026-10-04), though its implementation list names Stripe, Adyen, PayPal, Square, Twilio and others. Use the header name; do not cite it as a standard.

Across services: one retry layer, one deadline, one key

Behind the front door the same request crosses a router and an inference service, and each hop has a client that could retry. Three rules keep that safe:

  • Retry at one layer. If three layers each make 3 attempts, one failing call becomes 3 × 3 × 3 = 27 attempts at the bottom, arriving exactly when the bottom is already failing (attempts multiply: aL for a attempts at each of L layers). Retry at the edge, or in the client closest to the failure, and let the others fail fast. Retry budgets and circuit breakers that cap this system-wide are Reliability engineering's.
  • Every attempt shares the original deadline. gRPC's deadline "applies across all attempts" (section 11); a retry that resets the clock outlives the user who asked.
  • Pass the key down. A retried front-door request must not become a second charge two hops down, so the service that owns the side effect (the billing call, the outbox row) receives a key derived from the caller's, and dedupes on it. When the side effect leaves your database (a payment provider, a message queue), store the intent and the key first and send later: the outbox pattern on Queues, streams and async work. Brandur Leach's design generalises this: split the request into atomic phases ("a set of local state mutations that occur in transactions between foreign state mutations") with a recovery point after each, because "once we make our first foreign state mutation, we're committed one way or another" (brandur.org); a retry resumes from the last recovery point. For an LLM call: record that the model was called and store its output before charging and answering, and pass your own idempotency key to any provider that accepts one.

The official Anthropic and OpenAI Python SDKs retry connection errors, 408, 409, 429 and 5xx themselves, with no idempotency key; HTTP section 10 measures their attempts, and is the owner of retry safety at the protocol level.

5. Rate limits and quotas at the API

A rate limit caps what one caller may use per unit of time, so one runaway script cannot take capacity from everyone; for LLM APIs it is counted in tokens as well as requests, because a 100,000-token prompt and a 50-token one are not the same load. How the server counts (token bucket, sliding window) is Reliability engineering's; budgets across many providers at a gateway are Gateways and routing's. What this page owns is the contract with the client: what the API says before, at and after the limit.

  • At the wall: 429 Too Many Requests (RFC 6585) with Retry-After in seconds or as an HTTP date (RFC 9110). A well-behaved client waits that long; the official SDKs honour it automatically. In gRPC the same signal is RESOURCE_EXHAUSTED, with the wait in a RetryInfo detail or the grpc-retry-pushback-ms trailer (section 11).
  • Before the wall: remaining-budget headers on every response let a client slow down before it is refused, which is cheaper for both sides than a 429 and a retry.
  • A quota is not a rate limit. "1,000 messages a month" or a spend cap will not clear by waiting a second, so say so in the error type and omit retry-after: Anthropic's spend-cap 429 has the same error type as a rate limit but no retry-after, and tells itself apart with error.details.error_code enforced_spend_limit_reached; "Retrying, including the SDK's automatic retries, fails until access resumes" (rate-limits page, read 2026-10-24).
  • Limit before expensive work, and before the idempotency layer. Stripe notes that "rate limiters run before the API's idempotency layer" (Stripe, advanced error handling), so a 429 is not stored against the key and the retry gets a fresh chance.
  • Limit per key, per model, per dimension. Anthropic publishes separate limits for requests, input tokens and output tokens per minute, per model (same rate-limits page); a client that only counts requests will be surprised by the token limit. What counts is a design decision with consequences: on most Claude models only uncached input tokens count toward input tokens per minute, and max_tokens "does not factor into OTPM rate limit calculations", so prompt caching raises effective throughput and a large max_tokens costs nothing against the limit. The server counts with a token bucket, so capacity refills continuously rather than at fixed intervals.
Tell the client where it stands on every response, and exactly how long to wait at the wall
Before the wall: every response
HTTP/1.1 200 OK
anthropic-ratelimit-requests-remaining: 41
anthropic-ratelimit-tokens-remaining: 18000
(and their reset times)
RateLimit-Policy: "burst";q=5;w=5
RateLimit: "burst";r=4;t=0
At the wall
HTTP/1.1 429 Too Many Requests
retry-after: 2
content-type: application/json

{"type": "error", "error":
 {"type": "rate_limit_error", ...}}

Header names from the Claude API rate limits page and the IETF RateLimit header fields draft (draft-11, 2026-05-23, an active draft, not an RFC: quota 5 per 5-second window, 4 remaining, resets in 0 s); values illustrative. OpenAI sends the same information as x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens and their reset times.

At-least-once delivery: sign, retry with backoff, and let the receiver dedupe on the event id

Header names and the signed string follow the Standard Webhooks spec; retry timings follow its suggested schedule; ids and times illustrative.

6. Webhooks: your API, called in reverse

Some events happen later: a batch finishes, a payment clears, a moderation review completes. Clients could poll; a webhook turns it around: the client registers a URL and your server POSTs to it when the event happens. Now you are the client, calling code you do not control, over a network that fails, so everything from sections 2 to 5 applies with the roles swapped. Step through one delivery that goes wrong in the usual way:

  1. The event. Batch msgbatch_1 ended. The provider builds the payload and signs the id, the timestamp and the exact bytes of the body: HMAC-SHA256(secret, "msg_2Kx.1729760000.<raw body>").
  2. Attempt 1. The signature headers (webhook-id, webhook-timestamp, webhook-signature: v1,...) travel with the body.
  3. The receiver is slow. It verifies on the raw bytes and checks the timestamp is within 5 minutes, which is right; then it does the work before answering, which is the mistake.
  4. Timeout. No 2xx arrives before the provider's timeout, so attempt 1 failed. The provider cannot know the work happened, so it must try again.
  5. Attempt 2. After 5 s, the same webhook-id with a new signature. The schedule backs off: immediately, 5 s, 5 min, 30 min, on up to 24 hours.
  6. Dedupe. The receiver has already processed msg_2Kx, so it answers 204 with no second side effect. At-least-once delivery means the receiver, not the provider, guarantees "once".
  7. The fix. The better receiver verifies, records the id, puts the event on a queue and answers 204 within milliseconds; a worker does the work from the queue, and the provider never times out.
  • Sign every delivery with an HMAC-SHA256 over the id, a timestamp and the exact body, using a secret shared with that receiver: Standard Webhooks signs msg_id.timestamp.payload and sends webhook-id, webhook-timestamp and webhook-signature: v1,<base64>; Stripe signs timestamp.payload into Stripe-Signature: t=...,v1=... (Stripe webhooks). Receivers verify against the raw bytes before parsing (re-serialised JSON changes spacing and key order), compare in constant time, and reject old timestamps to stop replays: Stripe's libraries default to "a default tolerance of 5 minutes".
  • Retry with backoff, for days. Stripe retries "for up to three days with an exponential back off in live mode"; Standard Webhooks suggests immediately, 5 seconds, 5 minutes, 30 minutes, and on up to 24 hours. Then mark the endpoint failing and let the user redeliver. Not every provider retries: GitHub "does not automatically redeliver failed deliveries" (GitHub, failed deliveries), so a receiver that is down simply misses them unless it asks for redelivery.
  • Expect duplicates and disorder. Delivery is at-least-once, so "Use the webhook-id header as an idempotency key"; Stripe "doesn't guarantee the delivery of events in the order that they're generated", so receivers fetch current state rather than trust event order.
  • Receivers answer 2xx fast and work later: put the event on a queue (Queues, streams and async work). Thin events carry only the type and ids, and the receiver fetches the object, so it always gets current data and no personal data travels in the webhook; Stripe now offers both "thin" and "snapshot" events.

How webhooks compare with SSE, WebSockets and polling as ways to push news to a client is Streaming and real-time's; this section owns the API design of one.

7. LLM provider APIs: one design problem, three answers

Every LLM provider faces the same design problem: a conversation that grows each turn, model output that is sometimes text and sometimes a request to run a tool, and a result that has to come back paired with the call that asked for it. OpenAI's Chat Completions, OpenAI's Responses API, which replaced it as the recommended API ("While Chat Completions remains supported, Responses is recommended for all new projects"), and Anthropic's Messages API answer it differently. Same input in all three, one tool-call round trip: the user asks for the weather in Paris, the model calls get_weather, your code sends back "18 C, clear".

Where the conversation lives, and what a tool call is, differ more than the field names
1. Request
POST /v1/chat/completions
{"model": "...", "messages": [{"role": "user", "content": "Weather in Paris?"}],
 "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {...}}}]}
2. The model asks for a tool
"choices": [{"message": {"role": "assistant",
   "tool_calls": [{"id": "call_1", "type": "function",
     "function": {"name": "get_weather", "arguments": "{\"city\":\"Paris\"}"}}]},
  "finish_reason": "tool_calls"}]
3. Your code sends the result
POST /v1/chat/completions
{"messages": [ ...the whole history again...,
  {"role": "tool", "tool_call_id": "call_1", "content": "18 C, clear"}], "tools": [...]}

The call is a field on an assistant message; arguments is a JSON string the model wrote, so your code parses it and must handle invalid JSON. The client resends the whole conversation every turn; tool definitions are externally tagged ({"type":"function","function":{...}}) and "non-strict by default".

Shapes from OpenAI's migration guide (quotes read 2026-10-24) and function-calling guide, and Anthropic's handle tool calls page; model names omitted, ids and values illustrative. Highlighted: what differs.

Design choiceChat CompletionsResponsesMessagesWhat it costs or buys
Where the conversation livesClient resends itServer can hold it (store, previous_response_id)Client resends itStateless: any replica can answer, nothing to delete, but the payload grows every turn. Stateful: small requests and hidden reasoning can carry over, but data retention, region and a provider-held state you cannot replay elsewhere
Unit of outputOne message with optional tool_callsA list of typed itemsA list of typed content blocksTyped parts let text, calls and reasoning interleave and let streams name what is arriving
Tool argumentsJSON stringJSON stringJSON objectA string preserves exactly what the model wrote; an object means the server parsed it for you
Pairing call and resulttool_call_idcall_idtool_use_idIds let several calls run in parallel and return in any order
VersioningPath /v1Path /v1Path plus anthropic-version dateSection 2

The pattern to take away is the stateless-against-stateful choice (section 2's REST constraint, bought or given up), and typed parts over bare strings. Translation between formats loses whatever one has and the other lacks (cache breakpoints, thinking blocks and their signatures, reasoning items): Gateways and routing records a gateway sending the same request as Responses or Chat Completions depending on a prefix. How these formats become tokens inside the model, and the open-model template that has no ids at all, is Building a harness's; their streaming events are Streaming and real-time's.

8. Protobuf: the bytes inside every gRPC call

JSON spells out every field name in every message ("max_tokens":16 is 15 bytes to say "16"), stores numbers as text, and has no schema, so a typo in a field name is silently ignored. Between your own services, millions of times a second, that costs CPU and bandwidth and hides bugs. Protocol Buffers fix all three: a schema both sides compile, and a binary encoding that sends field numbers and compact values. The running request as the lab's llm.proto (in src/lab/):

message GenerateRequest {
  string model = 1;
  repeated Message messages = 2;
  uint32 max_tokens = 3;
  bool stream = 4;
}
service Inference {
  rpc Generate(GenerateRequest) returns (stream Token);  // server streaming
}

The numbers after = are the contract; protoc turns the file into classes and stubs for each language. On the wire every field is a tag, (field_number << 3) | wire_type, then a value; the wire type says how to find the value's end: 0 VARINT (integers, booleans, enums), 2 LEN (a length, then bytes: strings, nested messages, packed lists), 1 and 5 for fixed 8- and 4-byte values (encoding guide). A varint is 7 bits per byte, low group first, the top bit set on every byte but the last: 150 is 1 0010110 in binary, so 0x96 (low 7 bits plus "more") then 0x01, written 96 01. Type a number in the box beside this text.

bytes of protobuf against of JSON, 49 bytes against 117, so JSON is 2.4 times protobuf here (measured). The saving is names ("max_tokens": becomes the one tag byte 18), quotes and braces; strings cost the same in both ("What colour is the sky?" is 23 bytes either way), which is why protobuf's win on chat text is modest and its win on numbers (token ids, logits, embeddings) large. Each streamed token is a 5-to-9-byte message (" sky" at index 1 is 0a 04 20 73 6b 79 10 01).

The page's 15-line encoder is checked against the protobuf library's own bytes for 1, 127, 128, 150, 300, 16384 and 2,147,483,647 when the page loads (measured, protobuf ):

The whole running request, serialised by the library; click any byte:

Each coloured group is one field; bold bytes are tags.

Schema evolution: why the numbers are sacred

Services deploy one at a time, so for a while a new writer talks to an old reader. A reader keeps fields it does not know as unknown fields and carries on. The lab tried three changes against the old reader (measured):

ChangeWhat the old reader sawVerdict
The failure is silent

Reusing a number raises no error. With the same wire type the old reader reads your new priority = 9 as max_tokens = 9 and generates nine tokens; with a different wire type it drops the field and max_tokens falls back to its default, 0. The fix is a habit: when you delete a field, write reserved 3; reserved "max_tokens"; so the compiler refuses to reuse it (protobuf best practices: "Never re-use a tag number"), and run a breaking-change check such as buf breaking in CI (section 3).

Depth: zigzag, packed lists, field-number ranges, ProtoJSON, and tensors in four formats
  • Negative numbers. An int32 of -1 is sign-extended to 64 bits and costs 10 bytes; sint32 uses zigzag (-1 becomes 1, 1 becomes 2) and costs 1. Measured: against . Use sint32/sint64 for fields that are often negative.
  • Packed lists. In proto3, repeated numbers are packed by default: one tag and a length for the whole list. Five token ids took bytes packed against with one tag per element.
  • Field numbers 1 to 15 cost one tag byte, 16 to 2047 two; give them to the fields you send most. Valid numbers run from 1 to 536,870,911, with 19,000 to 19,999 reserved (proto3 guide).
  • ProtoJSON, the canonical JSON form gateways and logs use, turns the running request into : field names become lowerCamelCase (maxTokens; ProtoJSON format), a frequent surprise when a REST gateway fronts a gRPC service.

The old page said tensors in protobuf "beat base64-in-JSON by a wide margin". The lab measured one million float32 values (4,000,000 raw bytes) four ways:

FormatBytesEncode msDecode ms

Correction to the old page
Against a JSON list of numbers, protobuf wins by about five times in size and far more in time. Against base64 inside JSON the size gap is only 4/3 (base64's fixed overhead: against bytes); the bigger win is skipping the text decode. Triton accepts raw binary tensors over plain HTTP for the same reason (its binary tensor data extension, section 17). Protobuf decode times are parse-only; turning values into Python objects costs extra in every format.

9. gRPC on the wire

Protobuf gives bytes; a call also needs a method name, a deadline, credentials, streams both ways and an outcome, over connections that stay open for hours. gRPC (open-sourced by Google in 2015 from its internal Stubby) maps every call onto one HTTP/2 stream (gRPC over HTTP/2 spec); HTTP/2 frames and HPACK themselves are HTTP's. The lab ran the running request through a logging proxy that decodes every HTTP/2 frame (no packet capture: the proxy sits on the socket between grpcio client and server), asking for 5 tokens with a 2-second deadline. Click any frame in the viewer, or step through it with the arrows:

Four things in that stream are gRPC's own:

  1. The method is the path: :path /llm.v1.Inference/Generate is /package.Service/Method, always a POST, so proxies can route on it like any URL.
  2. te: trailers and content-type: application/grpc: the first tells proxies the client understands trailers; the spec uses it "to detect incompatible proxies". A server sent a non-gRPC content type should answer 415.
  3. A 5-byte prefix on every message: the request DATA frame is 00 00 00 00 31 then the 49 bytes of section 8 (one byte "compressed?", four bytes of length, 0x31 = 49). Each token arrives the same way, 10 to 14 bytes in all. Frame boundaries need not match message boundaries, so readers parse by prefixes, never by frames.
  4. The outcome comes last: HTTP status is 200 even for failures; the real result is the trailer grpc-status (0 = OK) with grpc-message. A call that fails before any message gets one trailers-only HEADERS frame: the call to a missing method came back as :status 200, grpc-status 12, grpc-message Method not found! in a single frame.
A gRPC call is a POST whose real result arrives last, in trailers

measured 5 October 2026 by src/lab/frame_proxy.py: times are milliseconds since the TCP connection opened, as the proxy saw them (the two directions are read by two threads, so frames crossing within a fraction of a millisecond may print slightly out of order); bytes are exact; protobuf inside DATA frames is decoded with llm.proto.

The rest is HTTP/2 housekeeping: SETTINGS (both sides advertised 4 MB windows and frame size), WINDOW_UPDATE, and PINGs that gRPC sends to estimate the bandwidth-delay product and grow its windows (BDP probing). Against the root page's REST and SSE recording of the same request:

PartREST + SSE (root page)gRPC (this lab)Why

REST figures are the root's HTTP/1.1 recording (277-byte request, 771 bytes of SSE payload for the same five tokens); gRPC figures count HTTP/2 frame payloads. The first HEADERS on a fresh connection is large because HPACK's table starts empty; later calls on the connection shrink it.

Four call shapes, one stream each: unary (most calls), server streaming (the token stream above), client streaming (audio chunks in, one transcript out) and bidirectional (realtime voice, Triton's sequence models, Envoy talking to an external processor). The shape only changes how many prefixed messages each side sends before closing its half; HTTP/1.1 cannot carry both bodies at once or trailers every client honours, hence HTTP/2.

Channels. Client code makes a channel to a target and a stub on it; the channel resolves the name, opens one connection per backend address (a subchannel), keeps them alive, reconnects with backoff, and multiplexes every call as a new stream. A channel is expensive (TCP, maybe TLS, SETTINGS) and a call cheap: one channel per target, shared, never one per call (performance guide); its hours-long connection is what confuses load balancers (section 13). Credentials, logging and tracing go in interceptors, gRPC's middleware.

10. Deadlines and cancellation: giving up together

The user closes the tab after the ninth token. The front door notices; behind it, the router and the inference server do not, and the GPU keeps decoding an answer nobody will read, while abandoned work queues ahead of live work. Every hop needs two facts: how long the caller will wait, and whether it is still there. In gRPC the caller sets a deadline; it travels as a relative timeout in grpc-timeout (at most 8 digits plus a unit, H M S m u n), and each hop subtracts the time already spent before passing it on, so no clocks need to agree (deadlines guide). When it passes, both ends end the call with DEADLINE_EXCEEDED and the client sends RST_STREAM with code CANCEL (8); cancellation for any other reason uses the same frame.

The default is "wait forever"

"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." Propagation "is supported by some gRPC implementations": on by default in Java and Go when you pass the incoming context on, opt-in in C++, and in Python you do it yourself (timeout=ctx.time_remaining()). Stopping the work is the server's job: "The server application is responsible for stopping any activity it has spawned to service the RPC."

The lab chained client, gateway and inference service (three processes, real gRPC, a frame log on the second hop). The inference service emits up to 40 tokens, the first after 0.12 s then one every 0.05 s, so a full answer takes about 2.1 s; in every run the client stops after 0.6 s. Predict which runs keep the GPU busy, then pick a run:

Fig. 3 · One abandoned request, four endings

  1. The call and its deadline. The client sets a 0.6 s deadline. The gateway sees 0.598 s left and passes on what remains: grpc-timeout: 595m on the second hop, so the inference service starts with 0.594 s.
  2. Tokens stream back. After 0.12 s of prefill the first token, then one every 0.05 s, each going inference to gateway to client as one length-prefixed message.
  3. The deadline expires. At 0.607 s, after 8 tokens, the client ends the call with DEADLINE_EXCEEDED and resets its stream (RST_STREAM, CANCEL).
  4. Downstream stops too. The inference service had its own deadline, and the gateway also cancelled it (RST_STREAM CANCEL on the second hop at 601.6 ms): it stopped after 8 tokens, in 0.601 s.
  5. The bill. 8 tokens generated, 8 delivered: nothing generated for nobody.

Counts, end times, headers and RST_STREAM frames are measured (grpcio , 5 October 2026); the tokens' positions on the time axis follow the configured schedule, not individual timings.

Depth: why run B was rescued by accident

No grpc-timeout reached the inference service in run B, yet it stopped early: when the client left, gRPC Python closed the gateway's generator, CPython freed the abandoned downstream call object at once, and freeing it cancelled the stream (the frame log shows the gateway's RST_STREAM CANCEL). Change the code shape, as run D does with a worker thread, and the rescue disappears.

Choosing the number. Start from what the caller will tolerate (a chat UI with a 60-second spinner sets about 60 s at the front door) and let each hop inherit what is left; gRPC suggests an educated guess "validated by some load testing". A deadline covers queueing as well as work (the root's Failure lab case "Max concurrent streams: calls queue on the connection" shows calls failing at 2.5 s that the server never saw fail); retries share it (section 11); and a streamed generation needs a deadline sized for the whole stream, or an idle timer instead (HTTP's section 9 plays that out for HTTP hops). With HTTP there is no deadline header: each hop sets its own timeout, cancellation is the connection closing, and the server must notice (details below).

Depth: noticing a disconnected HTTP client in Python

vLLM's OpenAI-compatible server races the handler against the ASGI http.disconnect message in its with_cancellation decorator, noting that the simpler request.is_disconnected "does not work with middleware" (vLLM v0.31.0, api_utils.py). The equivalent discipline to gRPC deadlines: a timeout on every outgoing call and a server that stops work when its incoming request is gone. Timeouts per hop for HTTP (connect, read, idle, total) are HTTP's.

11. Status codes, errors and retries

When a call fails the caller must decide in microseconds: give up, retry here, retry elsewhere, or tell the user something specific. HTTP's codes were designed for documents; gRPC's 17 codes, carried in the grpc-status trailer under an HTTP 200, were designed for that decision (gRPC status codes). The decision is drawn beside this text: six groups of codes, each with what the caller should do.

The code says whether a retry is safe, and at what scope

The rule for three easily confused codes, paraphrased from gRPC's statuscodes.md and google/rpc/code.proto: UNAVAILABLE if the client can retry just this call, ABORTED if it should retry a larger transaction (a read-modify-write), FAILED_PRECONDITION if it should not retry until someone fixes the state. DEADLINE_EXCEEDED "may be returned even if the operation has completed successfully".

Reference: all 17 codes, which ones the library itself may produce, and their HTTP equivalents
CodeMeaningLibrary may generate it?HTTP at a gateway
0 OKSuccess200
1 CANCELLEDThe caller cancelledyes499
2 UNKNOWNThe handler threw, or an error from an unknown spaceyes500
3 INVALID_ARGUMENTBad input, whatever the system statenever400
4 DEADLINE_EXCEEDEDOut of time; the work may still have happenedyes504
5 NOT_FOUNDNo such entitynever404
6 ALREADY_EXISTSCreate of something that existsnever409
7 PERMISSION_DENIEDKnown caller, not allowedrarely (HTTP/2 INADEQUATE_SECURITY maps to it)403
8 RESOURCE_EXHAUSTEDQuota, rate limit, message too large, out of memoryyes429
9 FAILED_PRECONDITIONWrong system state; do not retry until fixednever400
10 ABORTEDConcurrency conflict; retry the whole read-modify-writenever409
11 OUT_OF_RANGEPast the end (useful to stop iterating)never400
12 UNIMPLEMENTEDNo such method, or unsupported compressionyes501
13 INTERNALAn invariant broke (bad framing, parse failure)yes500
14 UNAVAILABLETransient: cannot connect, shutting down, connection lostyes503
15 DATA_LOSSUnrecoverable corruptionnever500
16 UNAUTHENTICATEDNo valid credentialsyes401

statuscodes.md lists the codes the libraries never produce, so seeing one means an application chose it; the HTTP column is from the comments in google/rpc/code.proto.

Measured: each failure as a Python client sees it (11 cases), including the 4 MiB limit, a proxy's 502 and fail-fast connects

measured, grpcio , each failure caused on purpose against the same inference service.

Three of those recordings teach something the table does not. The 5 MB prompt failed with RESOURCE_EXHAUSTED because the default receive limit is 4 MiB (the details give both numbers, 4194304): long contexts and embedding batches hit it, and the fix is grpc.max_receive_message_length on the receiver (vLLM's gRPC server sets it to unlimited). A dead backend behind the L7 balancer reached the client as UNAVAILABLE with "Received http2 header with status: 502": clients synthesise a gRPC status when a proxy answers in plain HTTP. And UNAVAILABLE to a closed port came back in about 1 ms, because a call fails fast when the channel cannot connect unless you ask for wait_for_ready=True (wait-for-ready guide).

Retries: off by default, on by configuration

gRPC retries two ways (retry design A6). Transparent retries are always on: when the call never left the client, or reached the server but not your handler, the library retries, because nothing can have happened twice. A retry policy exists only if the service config (JSON given to the channel, or published by the name resolver) has one: which codes, up to how many attempts (values above 5 are treated as 5), exponential backoff with plus or minus 20% jitter, and the deadline "applies across all attempts". Each retry carries grpc-previous-rpc-attempts.

{"methodConfig": [{"name": [{"service": "llm.v1.Inference", "method": "Who"}],
  "retryPolicy": {"maxAttempts": 4, "initialBackoff": "0.1s", "maxBackoff": "1s",
                  "backoffMultiplier": 2, "retryableStatusCodes": ["UNAVAILABLE"]}}]}

Against a replica that answers UNAVAILABLE twice while "warming up", the call without the policy failed at once; with it, the server log shows three attempts , and the caller saw only success (measured). Two valves stop retries becoming a storm: retry throttling (a per-server token bucket: with "maxTokens": 10, "tokenRatio": 0.1 each failure costs a token, each success returns 0.1, and retries stop while the count is at or below half) and server pushback (grpc-retry-pushback-ms says when, a negative value says never). Hedging sends a second copy after a delay without waiting for the first to fail, for idempotent calls with long tails; Go and C-core had not implemented it when the design was last updated (2024-08-23).

Correction to the old page
The old page said "only UNAVAILABLE-class errors are safely retryable by default". By default no application-level retry happens at all, only the transparent ones. Which codes are safe depends on whether the method is idempotent (or carries an idempotency key, section 4); gRPC's docs say there is "no fixed list of status codes on which it is appropriate to retry in all applications". UNAVAILABLE is the usual choice because it normally means the request was not processed; DEADLINE_EXCEEDED is the dangerous one.

Richer errors. A code and a string are often not enough ("which field?", "retry after how long?"). The trailer grpc-status-details-bin carries a serialised google.rpc.Status with typed details such as BadRequest or RetryInfo (AIP-193): the gRPC twin of section 2's three error layers.

12. Connections: keepalive, limits, health and reflection

A channel keeps its connections for hours. Meanwhile a NAT box may silently drop an idle connection, a server may drain for a deploy, and a big message may exceed a limit. A keepalive is an HTTP/2 PING on a quiet connection; no ACK within 20 s (the default timeout) and the connection is declared dead, so calls fail with UNAVAILABLE instead of hanging. Client keepalive is off by default in gRPC core, and servers defend themselves against ping floods: by default they expect at least 5 minutes between pings on a connection carrying no data, and after 2 "strikes" they send GOAWAY with ENHANCE_YOUR_CALM (keepalive guide). The lab reproduced it: a client with grpc.keepalive_time_ms=1000 made a call whose first token takes 8 s. At first nothing happened (the client's own brake, max_pings_without_data, default 2, stopped it after two pings); with that brake removed the server cut the connection mid-call (the recorded frames, beside this text).

The client saw UNAVAILABLE: Too many pings and lost the in-flight call. vLLM's gRPC server (v0.31.0) carries exactly this fix, noting that keepalive and BDP-probe pings during a non-streaming Generate "are strikes and eventually earn a GOAWAY(ENHANCE_YOUR_CALM, "too_many_pings") that fails every in-flight RPC", so it sets grpc.http2.max_ping_strikes to 0 (grpc_server.py). Rule: client keepalive slower than the server's minimum interval, or tell the server to accept faster pings. The same file records a second trap: a misspelt option "and gRPC Core silently ignores unknown keys, so the misspelt form left the 300s default in force"; check channel arguments against the core list and test that behaviour changed.

GOAWAY and connection age. GOAWAY is "no new streams on this connection": it names the last stream accepted, so the client knows which calls to resend elsewhere. Servers send it when shutting down, and on a timer if configured: MAX_CONNECTION_IDLE, MAX_CONNECTION_AGE (plus or minus 10% jitter so clients do not reconnect together) and MAX_CONNECTION_AGE_GRACE, all infinite by default (proposal A9), whose stated purpose includes L4 balancers: "This option can force the client to periodically reconnect to a L4 LB which allows spreading load more quickly." Section 13 measures it.

Depth: message and stream limits, flow-control windows, health checking and reflection
  • Message size: 4 MiB received by default (measured in section 11); sending is unlimited by default in gRPC core.
  • Concurrent streams: a server can cap streams per connection with SETTINGS_MAX_CONCURRENT_STREAMS; calls beyond it queue on the client. The root's Failure lab reproduced it ("Max concurrent streams: calls queue on the connection": six 1-second calls finishing at 1, 2 and 3 s in pairs with a limit of 2). Fix with more connections (a channel pool) or more replicas.
  • Flow-control windows: the recorded SETTINGS show 4 MB windows, grown further by BDP probing; on long links one stream's throughput is window divided by round-trip time (Networking foundations). gRPC sets TCP_NODELAY on its sockets, so small messages are not held back by Nagle's algorithm.

Health (grpc.health.v1.Health/Check, answering SERVING or NOT_SERVING, optionally per service) is what balancers and Kubernetes probe; Kubernetes has had native gRPC liveness probes since v1.27, stable (Kubernetes probes). The recorded check answered the two bytes 08 01: field 1 = 1, SERVING. Reflection lets a tool ask the server for its schema, which is what makes grpcurl list work without the .proto; the lab's server listed . Turn reflection off on anything internet-facing: it hands an attacker your whole API surface.

13. Load balancing gRPC: L4, L7 and the client

Three replicas should take a third of the calls each. Where and how often a replica is chosen decides whether they do, or one is hot and two idle; with gRPC's long-lived multiplexed connections this is the number-one production surprise. Predict where backend-3's calls come from in each setup before steps 5 to 8.

L4 (AWS NLB, Linux IPVS, kube-proxy, nginx stream) sees TCP and copies bytes without reading them. L7 (Envoy, nginx grpc_pass, a mesh sidecar, AWS ALB, which has supported gRPC since 29 October 2020, AWS) terminates HTTP/2, reads each call's HEADERS and can route on :path, retry and count calls in flight. Client-side: the channel learns every address (DNS or a control plane) and picks per call with a policy: pick_first (the default), round_robin, or xDS policies (gRPC load balancing).

Fig. 4 · An L4 balancer chooses once per connection; an L7 balancer or the client chooses once per call

  1. Behind an L4 balancer, one choice. One client channel opens one TCP connection; the L4 balancer (nginx stream) picks a replica once, for that connection. It balanced connections, and there was one, so all 30 calls went to backend-1: 30 / 0 / 0.
  2. Behind an L7 balancer, a choice per call. The client still opens one connection, to the proxy (nginx grpc_pass), which reads each call's HEADERS and keeps its own connection to every replica: 10 / 10 / 10.
  3. The client chooses, with the default policy. A client given all three addresses still sent everything to backend-1, because pick_first "attempts to connect to those addresses one at a time, in order, until it finds one that is reachable" and then sends every call there: 30 / 0 / 0.
  4. The client chooses, round_robin. Asked for explicitly ({"loadBalancingConfig": [{"round_robin": {}}]} in the service config, or the channel option), the channel keeps one connection per replica and rotates the calls: 11 / 9 / 10.
  5. A replica joins, behind plain L4. Autoscaling makes it worse. Each run started with backend-1 and backend-2, sent one call every 50 ms for 7 s, and backend-3 joined at 1.5 s (nginx reloaded with the longer list). The existing connection stays where it is until something closes it: of the 96 calls after the join, backend-3 got none.
  6. L4 with MAX_CONNECTION_AGE. With an age of 1 s on the servers, each connection was closed gracefully with GOAWAY about every second and the client reconnected through the balancer, a new choice each time: backend-3 took its first call at 4.28 s and 17 of the 97 calls after the join, with no failed calls.
  7. L7. The proxy sent backend-3 a call 0.22 s after the reload, and 32 of the 100 calls after the join.
  8. A fixed client list. round_robin over the two addresses it was given was perfectly even over what it knew (48 / 47 after the join) and blind to what it did not: backend-3 got nothing.

Call counts per replica are measured (5 October 2026, nginx 1.31.6, grpcio ; tables below); each stack is one setup's calls, drawn to scale within each half of the figure.

Measured: 30 calls on one channel, three replicas

Setupbackend-1backend-2backend-3Why

measured with nginx 1.31.6 (stream module for L4, grpc_pass for L7, both round robin) and grpcio ; one channel making 30 sequential unary calls per row, except the three-channel row. The root's Failure lab has the L4 case as "gRPC behind an L4 load balancer: one backend takes everything".

Measured: a replica joins at 1.5 s

Every call of the four runs, as recorded: each tick is one call, placed when it was sent, on the replica that answered. The viewer opens on the end of the runs; scrub back to watch backend-3 join.

Behind L4 a new replica waits for a reconnect; behind L7 it takes calls at once

measured 5 October 2026: three Python gRPC servers (grpcio ), one client channel per run; the client round_robin run was given backend-1 and backend-2 only. The hatched part of backend-3's track is before it existed. Script: src/lab/lb_run.py.

SetupCalls after backend-3 joinedbackend-3's share

What to do, in order of preference

  1. An L7 proxy that speaks HTTP/2 (Envoy, nginx grpc_pass, Istio or Linkerd, a cloud L7 balancer). Cost: one more hop to run and scale.
  2. Client-side round_robin over every replica: in Kubernetes a headless Service (clusterIP: None) makes DNS return one record per Pod instead of a virtual IP (Kubernetes Services), and the target dns:///name resolves them all. Cost: a connection from every client to every replica; new Pods seen only on re-resolution.
  3. Proxyless xDS: endpoints and policies from a control plane, no proxy in the path; most moving parts.
  4. L4 plus MAX_CONNECTION_AGE when nothing else is possible: it bounds imbalance at the price of reconnects (TCP and maybe TLS each), so minutes, not seconds.

Kubernetes' default ClusterIP Service is L4: in iptables mode kube-proxy picks a backend Pod "at random" for each new connection (Kubernetes virtual IPs), so a gRPC client of a plain Service behaves like the L4 rows.

LLM calls are not equal. A 50-token turn and a 100,000-token document differ in cost by orders of magnitude, and a replica that already holds a conversation's prefix in its KV cache skips most of the prefill, so an LLM router reads the request and each replica's state (queue depth, cache contents, loaded adapters): L7 by definition. Routing across serving replicas, and its visual, are LLM serving in production's; balancing algorithms (least outstanding requests, power of two choices, consistent hashing) are Capacity planning and performance's.

Depth: the inference gateway's gRPC side channel (Gateway API Inference Extension, llm-d), and when pinning is wanted
  • Gateway API Inference Extension (an official Kubernetes project, v1.6.2 on 17 September 2026) turns any gateway that supports Envoy's external processing into an "inference gateway": an Endpoint Picker chooses the replica per request from model-server metrics such as prefix-cache status and LoRA adapter availability (project README). The picker's main implementation has moved to the llm-d project's router.
  • The side channel is gRPC. Envoy asks the picker over ExternalProcessor.Process, a bidirectional gRPC stream (rpc Process(stream ProcessingRequest) returns (stream ProcessingResponse) in Envoy's ext_proc API).
  • llm-d (v0.10.0, 29 September 2026) packages prefix-cache-aware and load-aware routing with vLLM and reports "3x higher output throughput and 2x faster TTFT" against round robin on Llama 3.1 70B with 4 AMD MI300X (llm-d README; project-reported, not reproduced here).

Sometimes you want the pinning: Triton recommends unary inference calls, but notes that a bidirectional stream "will hold a single connection throughout the lifetime and hence ensure the requests are delivered to the same Triton instance", which sequence models need (Triton inference protocols).

DNS round robin and why it balances badly: DNS. The original explanation of proxy against client-side balancing: gRPC blog, Load Balancing in gRPC (2017).

14. Browsers, gateways and the gRPC family

A browser's fetch cannot read HTTP trailers or control HTTP/2 framing, so it cannot speak gRPC as section 9 recorded it; nor can many HTTP/1.1-only proxies, serverless platforms or a developer with only curl. Three answers keep one .proto and change the wire face:

gRPC-Web

The same messages with the trailers moved into the body: a final length-prefixed frame whose flag byte has its top bit set (0x80) carries grpc-status as text. HTTP/1.1 works; unary and server streaming only; a proxy (Envoy's grpc_web filter) translates (PROTOCOL-WEB.md).

Connect

A protocol and libraries (a CNCF sandbox project, per connectrpc.com): a unary call is a plain POST /package.Service/Method with application/json or application/proto, Connect-Protocol-Version: 1 and Connect-Timeout-Ms for the deadline; errors use ordinary HTTP status codes with a JSON body. Unary and server streaming over HTTP/1.1; bidirectional needs HTTP/2 (Connect protocol). curl-able, which is the point.

HTTP/JSON transcoding

Annotate each RPC with its REST shape and a gateway (Envoy's JSON transcoder, grpc-gateway) serves both: option (google.api.http) = { post: "/v1/{parent=publishers/*}/books" body: "book" }. Google's rule is that APIs "must" provide this for every RPC except bidirectional streaming (AIP-127).

tRPC is not related: no protobuf, no HTTP/2 requirement, no code generation. It is a TypeScript library where the client imports the server router's type, giving "fully typesafe APIs without schemas or code generation"; on the wire it is ordinary JSON over HTTP, with batching and subscriptions (tRPC README, v11.19.0 on 16 September 2026). Use it for a TypeScript product whose only client is its own front end; put REST or gRPC at any boundary another team or language must cross. ML serving never uses it.

Depth: tRPC against gRPC, row by row
tRPCgRPC
ContractTypeScript types, compile time only.proto schema, enforced on the wire
Code generationNoneRequired, one generator per supported language
Who can call itYour own TypeScript front end in the same codebaseAny service in any supported language
WireJSON over HTTP/1.1 or laterProtobuf over HTTP/2
StreamingSubscriptions (SSE or WebSockets)Four native shapes
Evolving itRefactor the monorepo; client and server deploy togetherField-number rules, reserved

The JavaScript and TypeScript pages build an SSE client and an MCP server: JavaScript: the event loop, promises and streams, section 5 and TypeScript: LLM apps and agents, section 8.

15. GraphQL: when the client should choose the shape

A catalogue page wants each model's name and provider, the mobile app adds eval scores, an internal tool wants licences: REST gives one call per object or an endpoint per screen. GraphQL (created at Facebook, now a Linux Foundation specification; current edition September 2025, per the root's atlas) gives one endpoint and a typed schema, and each client names exactly the fields it wants, { models(first: 20) { name provider { name } } }. The server runs a resolver per field and returns JSON of that shape: on the lab's toy catalogue (20 made-up models, 12 fields each) a REST list of every field is bytes, the GraphQL names-only query . The price comes in three parts.

One query, many backend calls. Resolvers run per object, so 20 models whose provider resolver queries the database make 1 + 20 queries: the N+1 problem. A DataLoader fixes it: resolvers ask a loader for a key, it waits one tick of the event loop, then fetches every requested key in one batched call. Measured with graphql-core against a counting fake database (beside this text).

Batching turns 141 database calls for one page view into 4

Database calls are measured; the fake database sleeps 2 ms per call. Wall times were close because the resolvers run concurrently on one event loop: the price of N+1 here is load on the database, which is what falls over in production.

One query can ask for the world. Nesting multiplies: with first: 20 then first: 10 five levels deep, the lab's static estimate (multiply each list's first down the tree, before running anything) came to fields. Public GraphQL APIs price queries before running them: GitHub caps a call at 500,000 nodes, requires first or last between 1 and 100 on every connection, charges computed points against 5,000 per hour per user, allows no more than 2,000 points per minute, and stops any request after 10 seconds (GitHub GraphQL limits). Other defences: depth limits and persisted queries (only queries registered in advance, sent by hash).

Measured: fan-out by nesting depth
Nesting depthEstimated fieldsResolver and database calls (measured)

HTTP stops helping. Queries usually travel as POST, which caches ignore (the GraphQL-over-HTTP draft allows GET for queries, never mutations, "MUST respond with an appropriate 4xx", 405 recommended; RFC 10008's QUERY now offers a cacheable request with a body). And a field can fail while the rest succeeds: in the lab one resolver failed and the result carried data with null there plus an errors array naming its path:


Classic servers answer 200 with that body, so monitoring that counts 5xx sees nothing; the GraphQL-over-HTTP working draft fixes this for clients sending Accept: application/graphql-response+json (400 for a document that does not parse, 422 for one that fails validation; draft, read 5 October 2026). Alert on the errors array, not only on status codes. When it fits: many clients needing different shapes of one graph of data, where round trips are expensive (mobile, aggregating many backends). In ML work you will mostly consume it (GitHub's API from tooling and agents); it is rarely right for model serving, where the request shape is fixed and the cost is in the GPU, not in fetching fields.

16. JSON-RPC 2.0: the smallest call format

Sometimes you need named method calls over a channel that is not HTTP at all: a pipe to a child process (an MCP server on stdio, a language server), a WebSocket, a single endpoint. JSON-RPC 2.0 is "a stateless, light-weight remote procedure call (RPC) protocol", "transport agnostic" (specification, 2010, updated 2013):

Request
{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
 "params": {"name": "get_weather", "arguments": {"city": "Paris"}}}
Response (same id)
{"jsonrpc": "2.0", "id": 1, "result": {...}}
{"jsonrpc": "2.0", "id": 1,
 "error": {"code": -32601, "message": "Method not found"}}

The id pairs answers with requests, so many calls can be in flight and answers may return in any order; a notification has no id and must not be answered (progress events); a batch is an array answered by an array. Reserved errors: -32700 parse error, -32600 invalid request, -32601 method not found, -32602 invalid params, -32603 internal error, -32000 to -32099 for the server implementation. What it leaves out (schema, streaming, deadlines, transport, auth) is the point: a protocol that adopts it must add those, which is most of what the MCP and A2A specifications are. MCP allowed JSON-RPC batches in its 2025-03-26 revision and removed them in 2025-06-18 (MCP).

Correction carried from the root
The old page said agent protocols "chose JSON-RPC over HTTP (+SSE) rather than gRPC". True of MCP. A2A v1.0 separates the protocol from three bindings: JSON-RPC 2.0, gRPC and HTTP+JSON/REST (root Protocol atlas, corrections list, item 3; A2A v1.0.1 specification; Agent-to-agent and beyond).

For a new internal protocol: JSON-RPC when the other end is a model or an editor plugin, messages are few, humans read the logs and the channel may be stdio; gRPC when calls are many, typed and streaming and cross-language teams need generated clients.

17. Choosing, and where each style lives

SituationChooseBecause
Public API, unknown clients, LLM tokens to streamREST (level 2) + SSEEvery client and proxy speaks it; SSE streams one way
Internal calls, both ends yours, many languages or high call ratesgRPCGenerated clients, compact messages, deadlines, four call shapes
Internal, but browsers or curl must also call itgRPC with Connect, gRPC-Web or transcodingOne .proto, several wire faces
Many UI clients reading overlapping data from many backendsGraphQL, with batching and cost limits from day oneEach client asks for its shape; pay in resolver load and caching
A model or agent is the caller; stdio or a single endpointJSON-RPC via MCP or A2AThe ecosystem already speaks it (section 16 and the MCP page)
A TypeScript app whose only client is its own front endtRPCTypes end to end, nothing to generate
Reference: where each style lives in ML serving (versions and ports checked 5 October 2026)
SystemREST / HTTPgRPCNotes
Public LLM APIs (Anthropic, OpenAI)Yes: JSON over HTTPS, SSE for streamsNoDate-style version header (anthropic-version), idempotency and rate-limit headers; the root page's running request
vLLM v0.31.0OpenAI-compatible servervllm serve <model> --grpcThe gRPC mode uses the smg-grpc-servicer package (a model-gateway project), registers the standard health service and reflection, sets unlimited message sizes and tolerates frequent pings (grpc_server.py)
SGLang v0.5.21OpenAI-compatible serverA gRPC server entry pointpython/sglang/srt/entrypoints/grpc_server.py in the release tree
NVIDIA Triton v2.73.0Port 8000 (KServe v2 protocol)Port 8001Metrics on 8002; unary inference recommended, bidirectional stream for sequences; a binary tensor extension puts raw little-endian tensors in HTTP bodies (quickstart, protocols)
TensorFlow ServingPort 8501Port 8500TF Serving with Docker
Ray Serve (Ray 2.59.0)HTTP proxygRPC proxy, port 9000 by defaultOff unless grpc_servicer_functions is set (Ray Serve gRPC guide)
OpenTelemetry (OTLP)Port 4318Port 4317Traces, metrics and logs from your services to a collector (OTLP spec)
Inference gateways (Gateway API Inference Extension, llm-d)Client traffic through EnvoyEnvoy to Endpoint Picker over ext_procPer-request routing on KV cache and load (section 13)
Vector databases (Qdrant)REST"For faster, production-tier searches"Qdrant README
Agent protocolsMCP over Streamable HTTP; A2A HTTP+JSON bindingA2A gRPC bindingBoth carry JSON-RPC 2.0 (section 16)

The common shape, the running example's: REST and SSE at the public edge because every client can speak it, gRPC behind the gateway because both ends are yours and the calls are many, a translating hop in between (your API server, Envoy transcoding, or a model gateway). vLLM and SGLang serve OpenAI-compatible REST first because ecosystem compatibility beats wire efficiency at the edge; their gRPC modes exist for the gateway-to-engine hop, where a router sends many requests and needs health, cancellation and streaming without JSON parsing. Not carried from the old page because they could not be confirmed from a primary source: that Ray's internals and the Milvus database use gRPC (only the Ray Serve proxy above is confirmed), and the statements about AWS API Gateway and Lambda not supporting gRPC.

Debugging: symptom, first check, fix
SymptomFirst checkLikely cause and fix
One replica at 100%, the others idle; adding replicas does nothingPer-replica call counts; is the balancer L4? what is the client's LB policy?Connection pinning (section 13): L7 proxy, round_robin with a headless Service, or MAX_CONNECTION_AGE
Calls hang forever when a dependency stallsIs a deadline set? (grpc-timeout in the request headers, or timeout= in code)No deadline by default: set one per call and propagate it (section 10)
GPU busy with requests whose users leftServer logs: do cancelled requests stop? Count tokens generated after cancelCancellation not propagated; hook the incoming call's cancel to the outgoing one
UNAVAILABLE: Too many pings, GOAWAY ENHANCE_YOUR_CALMClient keepalive_time_ms against server min_recv_ping_interval_without_data_msSlow the client's pings or let the server accept them (section 12)
RESOURCE_EXHAUSTED: ... larger than max (N vs. 4194304)Message sizeRaise max_receive_message_length on the receiver, or stream in chunks
UNAVAILABLE: Received http2 header with status: 502A proxy between you and the server; its logsThe proxy could not reach a backend, or speaks HTTP/1.1 upstream (gRPC needs HTTP/2 end to end)
Latency grows in steps under concurrency, some DEADLINE_EXCEEDEDServer's max concurrent streams; calls per channelCalls queue on one connection: more connections or replicas (root Failure lab)
A field "became" a different value after a deploygit log on the .proto: was a field number reused?Never reuse numbers; reserved them (section 8)
GraphQL page slow, database at 100%Resolver tracing: queries per requestN+1: DataLoader batching; cost limits (section 15)
Dashboards green while users see errors (GraphQL)The errors array in 200 responsesAlert on GraphQL errors, or use application/graphql-response+json

Tools. grpcurl -plaintext host:port list and grpcurl -d '{...}' host:port pkg.Service/Method (needs reflection or the .proto); curl --http2-prior-knowledge -H 'content-type: application/grpc' -H 'te: trailers' --data-binary @msg.bin for raw calls (the root's atlas does a health check this way); GRPC_TRACE=http for the C-core libraries' HTTP/2 debug logs (its companion GRPC_VERBOSITY is now deprecated and changes logging for the whole process, per gRPC's environment variables doc); and a logging proxy like this page's frame_proxy.py (100 lines of Python) when you need every frame without packet capture.

Optional rehearsal: seven predict-then-reveal checks and six interview questions

Each answer was checked against this page's recordings or the cited spec.

Predict, then reveal (protobuf)

The running request with max_tokens = 300 instead of 16. How many bytes is the protobuf message now (it was 49)?

Predict, then reveal (schema evolution)

Team A deletes uint32 max_tokens = 3 and later adds uint32 priority = 3. An old inference server receives priority = 9. What does it do?

Predict, then reveal (status)

A gRPC call to a server that is down returns in 1 ms. What code, and what would make it wait instead?

Predict, then reveal (deadlines)

Client deadline 600 ms. The gateway spends a few milliseconds and calls the inference service, propagating the deadline. What grpc-timeout does the inference service receive?

Predict, then reveal (load balancing)

A Kubernetes Deployment of 3 gRPC Pods sits behind a normal ClusterIP Service. One client process sends 3,000 calls per second on one channel. How are the calls spread?

Predict, then reveal (client policy)

You switch to a headless Service; DNS now returns all three Pod addresses. You change nothing else in the client. How are the calls spread?

Predict, then reveal (GraphQL)

A GraphQL query lists 50 models and, for each, its provider. Without batching, how many database calls?

Why does gRPC need HTTP/2, and what breaks if a proxy in the path speaks HTTP/1.1 upstream?
gRPC maps each call to one HTTP/2 stream, sends request and response bodies concurrently for streaming calls, and puts the outcome in trailers after the body. HTTP/1.1 has no multiplexing and no trailers that clients reliably honour, so a proxy that downgrades upstream either fails or loses the status. The te: trailers header exists to detect such proxies; the client then synthesises a status from the HTTP response, which is how the lab saw "Received http2 header with status: 502". gRPC-Web and Connect exist for paths that cannot be HTTP/2 end to end.
Explain deadline propagation and what happens without it in an LLM serving stack.
The caller sets a deadline; each hop passes on the remaining time in grpc-timeout and cancels downstream calls when its caller cancels. Without it, a user who leaves does not stop the generation: in the lab's run D the inference service produced tokens over s for a client that had stopped after . On GPUs that is wasted capacity and longer queues for live users. Also: gRPC sets no deadline by default, retries share the original deadline, and stopping work is the server's job.
Your gRPC service is behind an AWS NLB and one instance is hot. Explain and fix.
An NLB is L4: it balances connections, and gRPC clients hold few long-lived connections, so load follows connections, not calls. Options: an ALB (gRPC since 2020) or Envoy for per-call L7 balancing; client-side round_robin with service discovery; or server MAX_CONNECTION_AGE (minutes) so clients reconnect and spread over time. The lab measured 30/0/0 through L4, 10/10/10 through L7, and a new replica reached only after reconnects.
How do you evolve a protobuf schema safely?
Add fields with new numbers (old readers keep them as unknown fields and re-serialise them unchanged, measured); never change a field's number or type; when deleting, reserved both the number and the name; prefer optional or wrapper semantics when "unset" must differ from zero; remember ProtoJSON renames fields to lowerCamelCase, so JSON clients see a second contract. Run a breaking-change checker in CI (buf breaking is one).
When would you choose GraphQL over REST, and what would you put in place on day one?
When many clients need different shapes of the same graph of data and round trips are expensive (mobile, aggregating many backends). Day one: DataLoader batching on every resolver that fetches, a cost or depth limit evaluated before execution, pagination arguments with a maximum (GitHub's 1 to 100), persisted queries for first-party clients, monitoring on the errors array, and per-field authorisation.
Which gRPC status codes would you retry, and how do you stop retries from making an outage worse?
UNAVAILABLE for any method (normally means not processed); others only for idempotent methods. Never blindly retry DEADLINE_EXCEEDED on non-idempotent calls, since the work may have happened. Bound it: maxAttempts (capped at 5), exponential backoff with jitter, retry throttling (token bucket per server), server pushback, the overall deadline, and a retry budget across the system.