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
POST /v1/messages with "What colour is the sky?".grpc-timeout, and the status comes last, in the trailers.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
.proto, GraphQL SDL).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) | gRPC | GraphQL | JSON-RPC 2.0 | |
|---|---|---|---|---|
| Contract | Optional: OpenAPI if you write one | A .proto file, required; code generated | A typed schema, required | None of its own |
| Encoding | JSON text | Protobuf binary | JSON (a query names the fields) | JSON |
| Transport | HTTP/1.1, 2 or 3 | HTTP/2 only | Usually one HTTP POST endpoint | Any channel: stdio, WebSocket, HTTP |
| Call shape | Request and response; SSE for a stream of events | Unary and three streaming shapes, native | Query, mutation, subscription | Request, response, notification |
| Failure | HTTP status plus a JSON error body; no deadline | 17 status codes in a trailer; deadlines built in | Usually 200 with an errors array | An error object with a numeric code |
| Best at | Public APIs any client can call; caches and proxies understand it | Internal calls you own at both ends; streaming | Many front ends reading overlapping data | A tiny call format for MCP, A2A and editors |
| Costs | Bulky text; contract drift if there is no spec | Browsers cannot call it directly; L4 balancers pin it | N+1 backend calls, query cost limits, HTTP caching mostly lost | Schema, 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.
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.
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:
: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.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.
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.
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.
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.
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).
| Strategy | Looks like | Who | Cost |
|---|---|---|---|
| Major version in the path | /v1/messages, later /v2/ | OpenAI, Anthropic, most public APIs | A v2 is a second API to run; everything between majors must be additive |
| Dated version in a header | anthropic-version: 2023-06-01, then 2026-10-21 | Anthropic (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 transforms | Stripe-Version: 2017-05-24 | Stripe | Core 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.
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.
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).
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).
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
Idempotency-Key: 7f3c9a0e-...; at 0.000 s the server inserts the key with the request's fingerprint and status started, under a unique constraint, so of two simultaneous attempts exactly one wins.done.done, so no work runs: the stored 201 for msg_1 comes back marked Idempotent-Replayed: true, in under a millisecond.started, the same request comes again: 409, retry later. Running it would charge twice; waiting is the only safe answer.done: the stored 201 for msg_1 comes back, Idempotent-Replayed: true. One message, 10 credits.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).
| Question | IETF 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 request | 422 | An error |
| Retry while the first runs | 409 | 409 |
| What is stored | The resource's choice; fingerprint the request | Status 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.
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:
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.
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.
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).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).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.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=0HTTP/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.
Header names and the signed string follow the Standard Webhooks spec; retry timings follow its suggested schedule; ids and times illustrative.
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:
webhook-id, webhook-timestamp, webhook-signature: v1,...) travel with the body.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".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.
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".
POST /v1/chat/completions
{"model": "...", "messages": [{"role": "user", "content": "Weather in Paris?"}],
"tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {...}}}]}
"choices": [{"message": {"role": "assistant",
"tool_calls": [{"id": "call_1", "type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\":\"Paris\"}"}}]},
"finish_reason": "tool_calls"}]
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".
POST /v1/responses
{"model": "...", "input": "Weather in Paris?",
"tools": [{"type": "function", "name": "get_weather", "parameters": {...}}]}
{"id": "resp_1", "output": [
{"type": "function_call", "call_id": "call_1", "name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"}]}
POST /v1/responses
{"previous_response_id": "resp_1",
"input": [{"type": "function_call_output", "call_id": "call_1", "output": "18 C, clear"}]}
Everything is a typed item ("Items are distinct from one another and better represent the basic unit of model context"): messages, function calls, their outputs and reasoning are siblings in one list. The server can hold the conversation: "Responses are stored by default", and previous_response_id lets OpenAI "manage prior response context", so step 3 sends only the new item. Definitions are internally tagged, and "omitting strict attempts strict mode". Arguments are still a JSON string.
POST /v1/messages anthropic-version: 2023-06-01
{"model": "...", "max_tokens": 1024, "messages": [{"role": "user", "content": "Weather in Paris?"}],
"tools": [{"name": "get_weather", "input_schema": {...}}]}
{"content": [
{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "Paris"}}],
"stop_reason": "tool_use"}
POST /v1/messages
{"messages": [ ...the whole history again...,
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "18 C, clear"}]}],
"tools": [...]}
A turn's content is a list of typed blocks (text, tool_use, thinking), so text and calls interleave in one message. input is a parsed JSON object; the result goes back as a tool_result block in the next user message. Stateless: the client resends the history (prompt caching makes the repeated prefix cheap). The version is a date header, and max_tokens is required.
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 choice | Chat Completions | Responses | Messages | What it costs or buys |
|---|---|---|---|---|
| Where the conversation lives | Client resends it | Server can hold it (store, previous_response_id) | Client resends it | Stateless: 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 output | One message with optional tool_calls | A list of typed items | A list of typed content blocks | Typed parts let text, calls and reasoning interleave and let streams name what is arriving |
| Tool arguments | JSON string | JSON string | JSON object | A string preserves exactly what the model wrote; an object means the server parsed it for you |
| Pairing call and result | tool_call_id | call_id | tool_use_id | Ids let several calls run in parallel and return in any order |
| Versioning | Path /v1 | Path /v1 | Path plus anthropic-version date | Section 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.
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:
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):
| Change | What the old reader saw | Verdict |
|---|
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).
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.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 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:
| Format | Bytes | Encode ms | Decode ms |
|---|
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:
:path /llm.v1.Inference/Generate is /package.Service/Method, always a POST, so proxies can route on it like any URL.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.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.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.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:
| Part | REST + 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.
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.
"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
grpc-timeout: 595m on the second hop, so the inference service starts with 0.594 s.grpc-timeout on the second hop.grpc-status 0.grpc-timeout reached the inference service, yet the downstream call was cancelled at 607.8 ms and it stopped after 10 tokens (details below). Run D shows the accident not happening.ctx.add_callback(call.cancel).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.
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).
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.
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 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".
| Code | Meaning | Library may generate it? | HTTP at a gateway |
|---|---|---|---|
| 0 OK | Success | 200 | |
| 1 CANCELLED | The caller cancelled | yes | 499 |
| 2 UNKNOWN | The handler threw, or an error from an unknown space | yes | 500 |
| 3 INVALID_ARGUMENT | Bad input, whatever the system state | never | 400 |
| 4 DEADLINE_EXCEEDED | Out of time; the work may still have happened | yes | 504 |
| 5 NOT_FOUND | No such entity | never | 404 |
| 6 ALREADY_EXISTS | Create of something that exists | never | 409 |
| 7 PERMISSION_DENIED | Known caller, not allowed | rarely (HTTP/2 INADEQUATE_SECURITY maps to it) | 403 |
| 8 RESOURCE_EXHAUSTED | Quota, rate limit, message too large, out of memory | yes | 429 |
| 9 FAILED_PRECONDITION | Wrong system state; do not retry until fixed | never | 400 |
| 10 ABORTED | Concurrency conflict; retry the whole read-modify-write | never | 409 |
| 11 OUT_OF_RANGE | Past the end (useful to stop iterating) | never | 400 |
| 12 UNIMPLEMENTED | No such method, or unsupported compression | yes | 501 |
| 13 INTERNAL | An invariant broke (bad framing, parse failure) | yes | 500 |
| 14 UNAVAILABLE | Transient: cannot connect, shutting down, connection lost | yes | 503 |
| 15 DATA_LOSS | Unrecoverable corruption | never | 500 |
| 16 UNAUTHENTICATED | No valid credentials | yes | 401 |
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, 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).
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).
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.
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.
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.
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
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.grpc_pass), which reads each call's HEADERS and keeps its own connection to every replica: 10 / 10 / 10.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.{"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.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.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.
| Setup | backend-1 | backend-2 | backend-3 | Why |
|---|
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".
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.
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.
| Setup | Calls after backend-3 joined | backend-3's share |
|---|
grpc_pass, Istio or Linkerd, a cloud L7 balancer). Cost: one more hop to run and scale.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.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.
ExternalProcessor.Process, a bidirectional gRPC stream (rpc Process(stream ProcessingRequest) returns (stream ProcessingResponse) in Envoy's ext_proc API).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).
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:
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).
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.
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.
| tRPC | gRPC | |
|---|---|---|
| Contract | TypeScript types, compile time only | .proto schema, enforced on the wire |
| Code generation | None | Required, one generator per supported language |
| Who can call it | Your own TypeScript front end in the same codebase | Any service in any supported language |
| Wire | JSON over HTTP/1.1 or later | Protobuf over HTTP/2 |
| Streaming | Subscriptions (SSE or WebSockets) | Four native shapes |
| Evolving it | Refactor the monorepo; client and server deploy together | Field-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.
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).
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).
| Nesting depth | Estimated fields | Resolver 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.
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):
{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "get_weather", "arguments": {"city": "Paris"}}}{"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).
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.
| Situation | Choose | Because |
|---|---|---|
| Public API, unknown clients, LLM tokens to stream | REST (level 2) + SSE | Every client and proxy speaks it; SSE streams one way |
| Internal calls, both ends yours, many languages or high call rates | gRPC | Generated clients, compact messages, deadlines, four call shapes |
| Internal, but browsers or curl must also call it | gRPC with Connect, gRPC-Web or transcoding | One .proto, several wire faces |
| Many UI clients reading overlapping data from many backends | GraphQL, with batching and cost limits from day one | Each client asks for its shape; pay in resolver load and caching |
| A model or agent is the caller; stdio or a single endpoint | JSON-RPC via MCP or A2A | The ecosystem already speaks it (section 16 and the MCP page) |
| A TypeScript app whose only client is its own front end | tRPC | Types end to end, nothing to generate |
| System | REST / HTTP | gRPC | Notes |
|---|---|---|---|
| Public LLM APIs (Anthropic, OpenAI) | Yes: JSON over HTTPS, SSE for streams | No | Date-style version header (anthropic-version), idempotency and rate-limit headers; the root page's running request |
| vLLM v0.31.0 | OpenAI-compatible server | vllm serve <model> --grpc | The 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.21 | OpenAI-compatible server | A gRPC server entry point | python/sglang/srt/entrypoints/grpc_server.py in the release tree |
| NVIDIA Triton v2.73.0 | Port 8000 (KServe v2 protocol) | Port 8001 | Metrics on 8002; unary inference recommended, bidirectional stream for sequences; a binary tensor extension puts raw little-endian tensors in HTTP bodies (quickstart, protocols) |
| TensorFlow Serving | Port 8501 | Port 8500 | TF Serving with Docker |
| Ray Serve (Ray 2.59.0) | HTTP proxy | gRPC proxy, port 9000 by default | Off unless grpc_servicer_functions is set (Ray Serve gRPC guide) |
| OpenTelemetry (OTLP) | Port 4318 | Port 4317 | Traces, metrics and logs from your services to a collector (OTLP spec) |
| Inference gateways (Gateway API Inference Extension, llm-d) | Client traffic through Envoy | Envoy to Endpoint Picker over ext_proc | Per-request routing on KV cache and load (section 13) |
| Vector databases (Qdrant) | REST | "For faster, production-tier searches" | Qdrant README |
| Agent protocols | MCP over Streamable HTTP; A2A HTTP+JSON binding | A2A gRPC binding | Both 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.
| Symptom | First check | Likely cause and fix |
|---|---|---|
| One replica at 100%, the others idle; adding replicas does nothing | Per-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 stalls | Is 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 left | Server logs: do cancelled requests stop? Count tokens generated after cancel | Cancellation not propagated; hook the incoming call's cancel to the outgoing one |
UNAVAILABLE: Too many pings, GOAWAY ENHANCE_YOUR_CALM | Client keepalive_time_ms against server min_recv_ping_interval_without_data_ms | Slow the client's pings or let the server accept them (section 12) |
RESOURCE_EXHAUSTED: ... larger than max (N vs. 4194304) | Message size | Raise max_receive_message_length on the receiver, or stream in chunks |
UNAVAILABLE: Received http2 header with status: 502 | A proxy between you and the server; its logs | The 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_EXCEEDED | Server's max concurrent streams; calls per channel | Calls queue on one connection: more connections or replicas (root Failure lab) |
| A field "became" a different value after a deploy | git 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 request | N+1: DataLoader batching; cost limits (section 15) |
| Dashboards green while users see errors (GraphQL) | The errors array in 200 responses | Alert 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.
Each answer was checked against this page's recordings or the cited spec.
The running request with max_tokens = 300 instead of 16. How many bytes is the protobuf message now (it was 49)?
10); 300 needs 9 bits, so two varint bytes, ac 02 (the varint box in section 8 shows exactly these bytes). The tag 18 (field 3, wire type 0) does not change. Try it in the varint box in section 8.Team A deletes uint32 max_tokens = 3 and later adds uint32 priority = 3. An old inference server receives priority = 9. What does it do?
max_tokens, so that is what it reads (measured in section 8). Answer b is what happens when the reused number has a different wire type. Prevention: reserved 3; when deleting.A gRPC call to a server that is down returns in 1 ms. What code, and what would make it wait instead?
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?
grpc-timeout: on the second hop in run A. The header carries a relative timeout recomputed at each hop, so elapsed time is subtracted and no clocks need to agree.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?
round_robin over a headless Service.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?
pick_first; measured: three addresses, 30/0/0. Set round_robin in the service config ({"loadBalancingConfig": [{"round_robin": {}}]}) or with the channel option, as the lab did (10/10/10).A GraphQL query lists 50 models and, for each, its provider. Without batching, how many database calls?
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.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.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.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).errors array, and per-field authorisation.The whole stack on one request. Its Failure lab reproduces "gRPC behind an L4 load balancer" and "Max concurrent streams"; its Protocol atlas has checked entries for REST, gRPC, GraphQL and JSON-RPC. 33 min plus tabs
HTTP/2 frames, HPACK and flow control under gRPC; method semantics, proxies, timeouts, and what the SDKs retry. 45 min
TCP underneath every connection on this page; why gRPC and Go set TCP_NODELAY. 49 min
Service discovery by name, headless Services, why DNS round robin balances badly. 45 min
ALPN h2, which gRPC over TLS needs; mTLS between services. 45 min
SSE, the REST side's answer to server streaming; WebSockets; webhooks compared with the other ways to push. 38 min
Credentials on these calls: API keys, OAuth 2.1, JWTs, mTLS, workload identity. 42 min
JSON-RPC 2.0 as MCP uses it, over stdio and Streamable HTTP. 37 min
A2A and its three bindings (JSON-RPC, gRPC, HTTP+JSON), with one job recorded end to end. 39 min
Sibling reading times are each page's Reading tab, without its labs.
A first service built in FastAPI, every exchange captured: validation, the data layer and its pools, workers, background work and graceful shutdown; its script recorded the Postgres pagination measurement quoted in section 2. 27 min
LLM gateways: translating between provider formats, fallbacks, budgets and rate limits across providers. 37 min
The tool-call formats of section 7 down to tokens, streaming arguments, parallel calls. 41 min
Routing across serving replicas, autoscaling, cold starts: what section 13's LLM balancing leads to. 34 min
The outbox pattern and delivery semantics behind idempotent side effects and webhook receivers. 40 min
Balancing algorithms with measured runs, queueing, health checks, draining, real balancer configs. 39 min
Timeouts, deadlines, retries with budgets, circuit breakers as a system. 40 min
The serving systems behind the gRPC hop: batching, KV cache, routing. 34 min
An SSE parser on fetch, fed reads that split events mid-line. 14 min
An MCP server and client in TypeScript, every message recorded. 23 min
The wire spec: headers, length-prefixed messages, trailers, error mapping. 20 min
Tags, varints, wire types, packed fields, last-one-wins. 25 min
Field numbers, reserved, evolution rules. 50 min
Services, the four call shapes, deadlines, cancellation, metadata, channels. 30 min
The four guides that cover what bites in production. 45 min
Retry and hedging policies, throttling, pushback, transparent retries. 40 min
Proxy against client-side balancing, still the clearest explanation. 15 min
What REST is, and how RESTful an API is. 60 min
Resource-oriented design, custom methods (AIP-136), long-running operations (AIP-151), transcoding (AIP-127), errors (AIP-193). 2 h for the core AIPs
Working knowledge, then the HTTP rules (status codes, GET for queries). 1 h 45 min
The reference design of section 4. 30 min
Signing, headers and retry schedule for webhooks. 20 min
The two provider designs of section 7, from the source. 30 min
The whole specification. 15 min
gRPC semantics that curl and browsers can call. 20 min
Per-request, KV-cache-aware routing for LLM serving on Kubernetes. 30 min