HTTP: semantics, 1.1 vs 2 vs 3, proxies and timeouts for LLM APIs

Reading: 45 min, plus 15 in closed details. Data as of October 2026; every exchange recorded against a local stand-in LLM API (nginx, hypercorn, h2, aioquic, the official Python SDKs) plus a few read-only public requests. Child of Topic: protocols.

The idea in one screen

HTTP is one fixed meaning (a method on a resource, header fields, a body, a status) carried by three wire formats, and re-sent by every proxy on the path: HTTP/1.1, 2 and 3 differ only in how they stop one slow or lost thing from holding up the rest, and whether a long LLM answer arrives is decided by the smallest timer on the path and by whether a failed request was provably never started.

Fig. 1 · One request, one meaning, re-sent and re-timed on every hop

  1. One meaning. Your code asks the SDK for a streamed answer, and it sends POST /v1/messages with a 117-byte JSON body. Every box on the path receives this same request: method, target, header fields, body (section 2).
  2. Re-sent on every hop. Each link is its own connection with its own wire format: HTTP/1.1 or 2 from the SDK to the CDN edge (chosen by ALPN; the SDKs default to 1.1, section 5), new connections behind the edge and the load balancer, HTTP/1.1 from nginx to the model server (its default). Every box re-parses, may rewrite, buffer, and answer with its own error (section 8).
  3. The answer streams back. The model server sends 200 text/event-stream at once, then one event per token; each hop passes the bytes on as they come, unless it buffers.
  4. 90 s of silence: the first timer to fire ends it. The model thinks 90 s before its first token, against each hop's documented default (section 9). The SDK's 600 s, the load balancer's 60 s and nginx's 60 s count silence; Cloudflare's 125 s only waits for the head, which came at once. At 60 s the load balancer's timer fires (nginx's at the same moment) and the stream is cut under a 200, whatever the SDK allows.
  5. A ping every 15 s keeps every idle timer down. An SSE comment is a byte, so each one empties the idle columns; the answer (61 tokens, 2 s apart) completes at 210 s.
  6. A total timer ignores pings. Swap the load balancer for Google Cloud's, whose 30 s backend timeout counts the whole response: the same pinged stream is cut at 30 s.

illustrative path; each timer is the hop's documented default, and the outcomes are computed by the timeout model of section 9, which reproduces eight measured runs.

You need TCP and QUIC as transports (Networking foundations) and, for https, the TLS handshake that picks the HTTP version (ALPN, TLS and certificates). The whole stack on one request is Topic: protocols; this page owns HTTP in depth. The running example: a chat app sends "What colour is the sky?" as one streaming POST /v1/messages with a 117-byte JSON body; five tokens come back, one every 50 ms after a 120 ms wait standing in for the model. The server is the root page's stand-in LLM API (its On the wire tab built it), with extra knobs: think time, keep-alive pings, injected errors. Labels: measured here, illustrative, derived (with its formula).

Message
start line (or pseudo-headers), header fields, empty line, optional body
Intermediary, hop
anything between client and origin that receives a message and sends a new one; each leg is a hop with its own connection
Safe, idempotent
asks for no change; same effect sent once or twice (GET, PUT, DELETE; never POST)
Stream, frame
one request and its response inside a shared HTTP/2 or 3 connection; the typed, length-prefixed pieces it travels in
Head-of-line blocking
one slow or lost item holding up everything queued behind it
Idle vs total timeout
a timer every byte resets, against one that counts the whole response
Idempotency key
a unique id on a POST so the server can recognise a retry and return the stored result
HTTP in one screen (six questions, short answers, where each is taught)
QuestionShort answerSection
What does a request mean?A method, a target, header fields, maybe a body. The method says whether a retry is safe: GET yes, POST (every LLM generation) no.2
Why three versions?HTTP/1.1 sends text, one response at a time per connection. HTTP/2 cuts requests into binary frames that share one connection and compresses headers. HTTP/3 does the same over QUIC, so one lost packet stalls only its own request.5 to 7
What does each cost in bytes?measured The running request's headers: 160 bytes of text every time on HTTP/1.1; 69 then 7 bytes on HTTP/2 (HPACK remembers them); 59 then 9 on HTTP/3 (QPACK, plus a one-off copy on a side stream).6, 7
Who is between me and the model?Usually several proxies (an SDK, a corporate proxy, a CDN, a load balancer, an ingress), each able to rewrite, buffer and cut the stream. All three public LLM APIs answered through a front proxy.8, 11
Why do long generations die?The smallest timeout on the path wins. Idle timeouts are reset by every streamed byte, so streaming plus pings keeps a slow answer alive; total timeouts (Google Cloud's 30 s backend timeout, API Gateway's 29 s) are not.9
When is a retry safe?When the server provably did not start (connection refused, REFUSED_STREAM, a stream above GOAWAY, 425 Too Early) or the method is idempotent. A read timeout on a POST is not safe, yet both official Python SDKs retry it: measured the server ran the request three times.10

Not here: SSE parsing, WebSockets and chunked streaming in depth (Streaming and real-time); REST and gRPC design, L4 and L7 load balancing (Service APIs); the credentials in the headers and OAuth (Auth); QUIC as a transport (Networking foundations); API design and server-side idempotency (Service APIs, sections 2 and 4); retry policy as a system (Reliability engineering).

Where and how this page measured (provenance)

Everything marked measured was run for this page on 5 October 2026 on an Apple M1 Pro laptop (macOS, Python 3.13, curl 8.7.1, nginx 1.31.6, hypercorn 0.18.0, h2 4.4.1, aioquic 1.3.0) against the local stand-in API on loopback, so every byte could be recorded (src/raw/, rerun with src/run_all.sh). No model runs and no real API is called, except one read-only, credential-free request to each of three public LLM hosts (5 October 2026, section 11) and three CORS preflights (24 October 2026, section 4). illustrative marks a picture of a shape, not data.

1. A message, piece by piece

Two programs that have never met must agree on what is asked, about which thing, under which conditions, and where the request ends. HTTP's answer is a message: a start line, header fields (name, colon, value), a blank line, an optional body. The client sends requests, the server answers, and the server that owns the resource (the model API) is the origin; anything in between that receives a message and sends it on is an intermediary, and each leg is a hop.

The URL, split. https://api.llm.test/v1/messages is a scheme (https: HTTP over TLS, port 443), an authority (host and optional port) and a path, optionally with a query (?limit=20). HTTP/1.1 puts the path in the start line and the authority in Host; HTTP/2 and 3 carry both as pseudo-headers (:method, :scheme, :authority, :path). One server hosts many names, so Host is mandatory: an HTTP/1.1 request without it gets 400 (RFC 9112 section 3.2; measured both nginx and hypercorn answered 400).

Where does the body end? A connection is a byte stream with no boundaries, so every version must say where a body stops. HTTP/1.1 has three ways: Content-Length (the request: 117), chunked transfer coding (the response: each piece prefixed by its size in hexadecimal, ended by a zero-size chunk), or closing the connection. HTTP/2 and 3 put the body in DATA frames and flag the last one end-of-stream. Getting this boundary wrong is the root of the worst HTTP bugs (request smuggling).

The running request as HTTP/1.1 sends it (277 bytes): tap any part

Tap a highlighted part.

measured Bytes from the root page's recording (src/wire/raw/h1_request.bin, h1_response.bin); ↵ marks the two invisible bytes CR LF that end every line in HTTP/1.1 (RFC 9112 section 2.1).

2. Meaning: methods, status codes, header fields

A client must be understood by a server it has never seen, through intermediaries that know nothing about the application. RFC 9110 (HTTP Semantics, June 2022) defines that shared meaning once, for every version; it is the one HTTP document worth reading end to end.

Methods, and the two promises that decide retries

A method names the operation. Two properties matter more than the names: a method is safe if it asks for no change on the server, and idempotent if sending it twice has the same intended effect as once: "PUT, DELETE, and safe request methods are idempotent" (RFC 9110 section 9.2.2). An idempotent request can be repeated after a network error without asking whether the first one ran; that is why the property exists.

MethodAsks forSafeIdempotentWhere you meet it in ML work
GETA representation of the resourceyesyesList models, download weights or a tokenizer, poll a batch job
HEADGET without the bodyyesyesCheck a file's size and ETag before downloading it
OPTIONSWhat the server allowsyesyesBrowser CORS preflight (section 4)
POSTProcess this bodynonoEvery generation (/v1/messages, /v1/chat/completions), tool calls, MCP and A2A requests
PUTReplace the resource with this bodynoyesUpload an object to a known key (S3 PUT, a model artefact)
PATCHApply these changesnono (in general)Update fields of a job or a config
DELETERemove the resourcenoyesCancel or delete a batch, a file, a fine-tune

RFC 9110 section 9 (PATCH is RFC 5789). Idempotency is a promise the server makes, not something the protocol enforces: a buggy PUT handler can still double-count. Generation is a POST, so if the connection breaks after the request left, the client cannot know whether the model is already generating (and billing); section 10 shows what the SDKs do about it.

Status codes: the first thing a client reads

A status code is three digits whose first digit is its class: 1xx more is coming, 2xx success, 3xx go elsewhere, 4xx the request is wrong, 5xx the server or something in front of it failed. Clients must treat an unknown code as the x00 of its class, which is why APIs can invent 529 and still be read as "server error" (RFC 9110 section 15). The words after the number (the reason phrase) are decoration: a FastAPI service under uvicorn answers 422 Unprocessable Entity, the older RFC 4918 name taken from Python's http.HTTPStatus, while RFC 9110 renamed it "Unprocessable Content"; HTTP/2 does not send a phrase at all, so clients read the number. The hero shows which hop usually writes which code.

CodeMeaningWho usually sends it, and what to do
200OKSent before the first token of a stream, so it cannot report a later failure; the Claude API can send an error event inside a stream that began with 200 (errors docs). Handle in-stream errors.
202Accepted, not yet doneLong jobs: submit, get an id, poll or get a webhook (batch APIs)
204, 304No content; not modified304 answers a conditional request: "your cached copy is still good" (section 3)
301, 302 / 307, 308Moved307 and 308 keep the method and body; 301 and 302 were historically turned into GET by clients, which silently drops a POST body (RFC 9110 section 15.4)
400, 422Malformed / well-formed but invalidYour bug; retrying will not help
401 vs 403Not authenticated / not allowed401: fix the key or token. 403: fix permissions or scopes (Auth)
408Request TimeoutThe server gave up waiting for your request bytes; safe to retry on a new connection
409ConflictState conflict, or an idempotency key reused with a different body
413Content Too LargeFor the Claude API the Messages limit is 32 MB, and "Cloudflare returns this error before the request reaches the API servers" (errors docs)
421Misdirected RequestA reused HTTP/2 or 3 connection reached a server that does not serve this host; retry on a new connection
425Too EarlyThe server will not act on a request sent as TLS early data (0-RTT) because it could be replayed; retry after the handshake (RFC 8470 section 5.2)
429Too Many RequestsRate limit (RFC 6585); wait as long as Retry-After says
500Internal errorRetry with backoff only if idempotent or carrying an idempotency key
502, 503, 504Bad gateway / unavailable / gateway timeoutUsually written by a proxy about the hop behind it: bad answer, nobody there, too slow; find which hop (section 8)
524, 529Not in any RFC524: Cloudflare's "origin did not answer in time" (125 s by default). 529: the Claude API's overloaded_error. Both read as 5xx.
Predict, then reveal

A streamed request returns HTTP/2 200, three tokens arrive, then the stream carries an overloaded_error event and ends. What status code did the request "have"?

Header fields: everything else

Fields fall into families. Representation: content-type (application/json, text/event-stream), content-length, content-encoding (gzip, br, zstd). Negotiation: accept, accept-encoding (what the client can take; the server picks and says so). Credentials: authorization or an API's own x-api-key. Caching and conditions: cache-control, etag, if-none-match (section 3). Browsers: origin, access-control-*, cookie, set-cookie (section 4). Limits: retry-after, rate-limit headers. Connection management: connection, keep-alive, transfer-encoding, upgrade, which apply to one hop only and which proxies must strip (section 8). Names are case-insensitive; HTTP/2 and 3 require lower case on the wire, which is why one hop shows Content-Type and the next content-type.

Content negotiation in LLM APIs. With "stream": true in the body, the Claude and OpenAI APIs answer text/event-stream; without it, one application/json body at the end. MCP's Streamable HTTP transport makes the same choice with the Accept header on one endpoint (MCP). Compression is negotiated the same way, with a streaming trap: a proxy that gzips an event stream may hold tokens until it has enough bytes to compress (the root's Failure lab: "A buffering proxy delays tokens"; it also reproduces 413, 429, 502 and 504 with real client error text). Resource design, error bodies (RFC 9457), pagination and versioning: Service APIs (section 2).

3. Caching and conditional requests

Fetching the same unchanged thing again (a model list, a 2 GB weights file, a tokenizer) wastes time. HTTP lets any client or intermediary keep a copy (a cache), and the response itself says how long the copy may be used and how to check it cheaply afterwards (RFC 9111, HTTP Caching). Two mechanisms work together: freshness (reuse without asking) and validation (ask "has it changed?" with a validator the server gave you).

max-age=60 allows reuse for 60 s; s-maxage applies to shared caches (CDNs) only; private forbids shared caches; no-store forbids keeping it at all; no-cache, despite its name, means "store it, but validate before every use". The validator is an ETag (an opaque version tag) sent back in If-None-Match, or a date in If-Modified-Since. Vary: Accept-Encoding tells caches to keep one copy per value of that request header. Two extensions matter in practice: stale-while-revalidate=30 lets a cache serve a stale copy for up to 30 more seconds while it refetches in the background (RFC 5861), and immutable says the body will not change, so a cache need not revalidate it even when the user reloads (RFC 8246); how apps and CDNs combine them (a file named by its content hash, cached for a year) is on Caching, section 9. On a 2 GB file the 304 is the difference between a round trip and a download, and weight-download tools rely on exactly this (they compare an ETag or a hash before fetching again).

The recorded exchange (curl -v; > sent, < received)

What it costs. A cache serves what was true when it was stored: a stale model list after a deployment, or worse, one user's response served to another if a private answer is cached by a shared proxy. CDNs are shared caches at the edge: cf-cache-status: DYNAMIC on all the LLM API responses in section 11 means "not cached". Generation responses are unique and sent with no-store or no-cache (the root's recording shows cache-control: no-cache on the stream). Provider prompt caching is a different mechanism entirely (the model server reuses computed state for a repeated prefix) and has nothing to do with these headers; every cache layer, CDN invalidation and the LLM caches are on Caching.

Fresh for 60 s without a request; after that one conditional request, and a 304 with no body

measured headers: the lab server's GET /v1/models answered etag: "models-v1" and cache-control: public, max-age=60; the same request with If-None-Match: "models-v1" got 304 and no body. illustrative timing: the two requests were sent a second apart; the time axis shows what the rule allows.

4. Browsers: CORS and cookies

Two header families exist for one client, the browser, which runs code from one site (an origin: scheme, host and port) while holding the user's cookies for others. They matter to you when a web page calls an LLM API or your own backend directly.

CORS: the server must opt in to cross-origin calls

A page on https://example.com may send a request to api.anthropic.com, but the browser only lets the page read the answer if the response says Access-Control-Allow-Origin for that origin. Anything beyond a "simple" request (methods GET, HEAD or POST, and a Content-Type of only application/x-www-form-urlencoded, multipart/form-data or text/plain) is first checked with a preflight: an OPTIONS request listing the method and headers to come (Fetch Standard, CORS protocol). A JSON body or an x-api-key header always triggers one.

The Anthropic SDK's dangerouslyAllowBrowser option is what adds that header: the API serves browsers only when the developer accepts that the key is visible to anyone who opens the page. Three rules explain most CORS errors. CORS protects the user's browser, not the server: curl, Python and servers ignore it entirely. The preflight answer is cached for access-control-max-age seconds. And Access-Control-Allow-Origin: * does not work for requests with credentials, which the Fetch Standard defines as "HTTP cookies, TLS client certificates, and authentication entries" (Fetch, CORS protocol and credentials): an API key in a custom header is not one of them, so * is enough here.

Cookies: state on a stateless protocol

HTTP keeps no memory between requests. A cookie adds it: the server sends Set-Cookie: name=value; attributes, and the browser returns Cookie: name=value on later requests that match (RFC 6265). A session is a cookie whose value is an id the server looks up. The attributes decide where it goes:

measured One of the two cookies Cloudflare set on the preflight to api.openai.com (value redacted). __cf_bm is Cloudflare's bot-management cookie, which "expires after 30 minutes of continuous inactivity" (Cloudflare cookies); the other, _cfuvid, lets a rate-limiting rule tell apart users who share an IP address.

HttpOnly
page scripts cannot read it, so an injected script cannot steal the session
Secure
sent over HTTPS only
SameSite
Strict or Lax keep it off requests started by other sites (the defence against cross-site request forgery); None sends it everywhere and requires Secure (RFC 6265bis draft)
Domain, Path
which hosts and paths receive it; without Domain, only the exact host that set it
Expires, Max-Age
without either, it lives until the browser closes (a session cookie)
__Host- prefix
a name starting __Host- makes the browser refuse the cookie unless it is Secure, has Path=/ and no Domain, so a sibling subdomain cannot plant or overwrite it (rfc6265bis, revision 22, August 2026, not yet an RFC)

For APIs called by programs, cookies are noise: SDKs authenticate with a header on every request; their httpx client does store cookies a CDN sets, like these, and sends them back, which is harmless. Browser sign-in, sessions and tokens are on Auth.

Same browser, same POST: the preflight fails until the page sends the opt-in header

measured 24 October 2026: credential-free OPTIONS https://api.anthropic.com/v1/messages with Origin: https://example.com and Access-Control-Request-Method: POST (src/lab/cors_cookies.sh, src/inputs/cors_cookies.txt). Without the opt-in header listed: 400 and no access-control-allow-origin, so a browser blocks the POST. With it: 200, access-control-allow-origin: *, access-control-max-age: 600. The same preflight to api.openai.com/v1/chat/completions got 200 with the page's own origin echoed and max-age 86400.

5. HTTP/1.1: text on a connection, one response at a time

HTTP/1.0 (1996) opened a new TCP connection per request, paying a handshake each time. HTTP/1.1 (1997; today RFC 9112) made connections persistent by default (keep-alive): after one response ends, the next request can use the same connection, which is why the body boundary of section 1 matters so much. Messages are lines of text ending in CR LF; a body whose length is unknown when the headers go out (a stream of tokens) uses chunked coding, and chunks can be followed by trailer fields, headers sent after the body (gRPC relies on the HTTP/2 equivalent for its status). Expect: 100-continue asks "will you take this big body?" before sending it; Upgrade switches the connection to another protocol, which is how a WebSocket starts (Streaming and real-time).

The cost: head-of-line blocking at the HTTP layer. On one connection, responses come back in request order. A client may send the next request before the previous answer arrives (pipelining), but a slow first answer then holds up every answer behind it. Browsers never enabled pipelining by default and opened about six connections per host instead; HTTP libraries keep a connection pool for the same reason. Predict how long B, a 1 ms health check sent 10 ms after a generation A that thinks for 1 s, waits in each case before the figure gets there.

Fig. 2 · A slow, B quick: one connection or two, HTTP/1.1 or 2

  1. HTTP/1.1, one connection: B queues behind A. A, a generation that thinks for 1 s, goes first; B, a health check, follows 10 ms later on the same connection (pipelined). The server has B's answer at once, but HTTP/1.1 must return responses in request order.
  2. B waits for all of A. A's tokens stream back and A completes at 1,206.3 ms; only then can B's answer leave, arriving at 1,207.1 ms: a 1,197.1 ms wait for a 1 ms job. That is head-of-line blocking.
  3. Two connections: B never meets A. On a connection of its own B is answered at 13.5 ms while A still thinks; the price is a second TCP and TLS handshake and twice the server state.
  4. HTTP/2: two streams, one connection. A is stream 1 and B stream 3; B's frames pass while A thinks, and B is answered at 14.4 ms on the single connection.

measured Medians of three runs each against the lab server on loopback (src/lab/hol_app.py, raw/hol_app.json); times from sending A. Both servers answered a pipelined pair correctly, so the queue is the protocol, not a bug.

HTTP/1.1 is still often right: a few long calls per connection (most LLM generations) lose nothing, every tool understands it, and you can read it with nc. Python's requests speaks only HTTP/1.1, and httpx needs http2=True (and the h2 package). measured The official Anthropic (1.11.0) and OpenAI (3.24.0) Python SDKs, built on an httpx fork, spoke HTTP/1.1 to the lab server over TLS even though it offered HTTP/2, and HTTP/2 only when given a client with http2=True (raw/sdk_version.json). For an agent firing dozens of parallel calls that means dozens of connections.

How it fails: the keep-alive race
A pooled connection is closed by the server at the moment the client reuses it, and the request fails with "connection reset" or "server disconnected", only after idle periods. Cause: the server's keep-alive idle timeout is shorter than the client pool's. Fix: client keep-alive shorter than the server's, and retry idempotent requests on a fresh connection. The root's Failure lab reproduces it ("Reused keep-alive connection closed by the server"); AWS documents the same race producing 502s behind its load balancer (section 9).

6. HTTP/2: binary frames, many streams, compressed headers

HTTP/1.1 needs one connection per request in flight and repeats hundreds of bytes of identical headers on every request. HTTP/2 (2015, from Google's SPDY; today RFC 9113, June 2022) keeps the meaning and changes only the wire: one connection carries many requests at once, and headers are compressed against what both sides already sent.

Frames on streams

Everything is a frame: a 9-byte header (length 24 bits, type 8, flags 8, one reserved bit, a 31-bit stream id) and up to 16,384 bytes of payload unless the peer allows more. A stream is one request and its response; the client numbers its streams 1, 3, 5, so frames of different streams interleave and the receiver sorts them by number; stream 0 is the connection itself. Over TLS the version is chosen by ALPN (the client offers h2; TLS and certificates); the client then sends a fixed 24-byte connection preface and both sides send SETTINGS. Step through the recorded connection: the request once, again on the same connection, then twice at once.

Every frame of the running request, decoded: watch the header blocks shrink and streams 5 and 7 interleave

How the frames were recorded, the frame types, and the SETTINGS each side sent

▶ client to server, ◀ server to client; times in ms from the first byte sent. HTTP/2 frames were parsed from the bytes the h2 library wrote to and read from the TLS socket (RFC 9113 section 4.1 frame layout); header blocks were decoded by src/lab/hpack_parse.py, which reports each field's representation and checks its result against the hpack library. HTTP/3 frames were split from the bytes on each QUIC stream as aioquic sent and received them (RFC 9114 section 7.1); QPACK field lines are classified by RFC 9204 section 4.5. HTTP/1.1 is the root page's plain-text recording, cut where each recv() returned. Not shown: TCP segments, TLS records and QUIC packets below the frames (packet capture needs root here); the root's On the wire tab sizes those.

Frame typeCarriesSeen in the running request
HEADERS (0x1) and CONTINUATION (0x9)A compressed header block; CONTINUATION extends one that did not fitRequest and response heads
DATA (0x0)Body bytes; the END_STREAM flag marks the lastThe JSON body; one per SSE event
SETTINGS (0x4)Each side's limits: table size, window, frame size, concurrent streamsBoth sides, first thing; then empty ACKs
WINDOW_UPDATE (0x8)Flow-control credit for a stream or the connectionThe 200 KB download below
RST_STREAM (0x3)Cancel one stream, with an error codeNot here
GOAWAY (0x7)"No new streams; I processed up to stream N"The client's clean close
PING (0x6)Liveness check and round-trip measurementNot here
PRIORITY (0x2), PUSH_PROMISE (0x5)Old priority tree; server pushBoth effectively retired

Both advertise a 65,535-byte initial window, 16,384-byte frames and a 4,096-byte header table, the protocol's initial values (RFC 9113 section 6.5.2), and 100 concurrent streams. The server turns server push off (ENABLE_PUSH 0) and offers extended CONNECT (for WebSockets over HTTP/2, RFC 8441).

The same headers sent twice: text every time on HTTP/1.1, one-byte indexes the second time on HTTP/2

measured The running request's HPACK bytes are the HEADERS frames of a real HTTP/2 connection (raw/h2_frames.json); the other two header sets were encoded by the same h2 library on a fresh connection and parsed field by field (src/lab/hpack_sizes.py, hpack_parse.py). QPACK sizes are pylsqpack's (aioquic's encoder). Bars to scale within each set. "HTTP/1.1 text" is the same fields as HTTP/1.1 lines (141 bytes; the root's recording is 160 because it also sends connection: close).

HPACK: why the second request's headers cost 7 bytes

Requests to one API repeat the same fields: host, path, content type, key, user agent. HPACK (RFC 7541, May 2015) compresses them with three tools: a static table of 61 common fields (index 2 is :method: GET, 3 is :method: POST), a dynamic table (4,096 bytes by default) to which each side adds fields as it sends them, so a repeat becomes a one-byte index, and a fixed Huffman code for literal text (26% smaller on the SDK header values below: 164 bytes of values became 121). Predict the second request's size before the figure gets there.

Fig. 3 · The same headers sent twice

  1. Request 1: the table starts empty. HPACK finds :method: POST and a few more fields in the static table (one byte each) and spells out the rest, adding each to the dynamic table as it goes; a credential marked never-indexed is spelled out and kept out of every table. On HTTP/1.1 every field is plain text.
  2. Request 2: the same fields again. On the same connection, every field now in the dynamic table is a one-byte index: the running request's header block falls from 69 to 7 bytes. HTTP/1.1 keeps no memory between requests and sends every byte again.

Secrets in a compression table. Compression leaks when an attacker can mix guesses with a secret and watch the size (the CRIME and BREACH attacks). HPACK lets a literal be marked never indexed, sent in full every time and never added to any table (RFC 7541 section 7.1.3). measured The h2 library marks authorization never-indexed automatically (the "Bearer" set costs 32 bytes on every request instead of 7), but not x-api-key, which it added to the dynamic table. HPACK's per-connection table and fixed Huffman code make the attack far harder than with gzip, so this is defence in depth, not an open hole; but know your library's list of sensitive headers when the key travels in a custom one.

Flow control: a window, and credit returned by WINDOW_UPDATE

Many streams share one connection, so a receiver needs to say "slow down on this one" without stopping the others (TCP can only throttle the whole connection). Each stream, and the connection, has a window: the DATA bytes the sender may send before it must wait. The receiver returns credit with WINDOW_UPDATE frames as it consumes data. So a stream moves at most one window per round trip: throughput ≤ window / RTT, whatever the link. Predict the stalls for a 200,000-byte body with a 64 KB window, then pick the three windows in turn: the figure opens on the whole recorded download, and the scrubber walks it frame by frame.

The default 65,535-byte window caps one stream at about 0.65 MB/s at 100 ms round trip (65,535 / 0.1 s). Servers that move large bodies raise it (SETTINGS_INITIAL_WINDOW_SIZE for streams, a WINDOW_UPDATE on stream 0 for the connection, which always starts at 65,535); the root's Failure lab measures the cap on a real path ("One stream's throughput is capped at window / round trip"). Token streams of a few KB never notice.

A small window makes the server stop and wait for credit, once per round trip

measured A 200,000-byte GET /big over HTTP/2 (src/lab/flow_h2.py, raw/flow_h2.json): every DATA frame and WINDOW_UPDATE with its time. simulated Loopback has almost no round trip, so the client holds each WINDOW_UPDATE for 50 ms, standing in for one; the server's behaviour is real. derived Expected time is about ceil(200,000 / window) × 50 ms when the window is the limit.

Ending streams safely, and how HTTP/2 still fails

RST_STREAM cancels one stream (a user pressed stop). GOAWAY starts a graceful shutdown and carries the highest stream id the server may have processed: requests on higher-numbered streams "are therefore guaranteed to be safe to retry", and so is any request reset with REFUSED_STREAM, "even those with non-idempotent methods" (RFC 9113 section 8.7). A server being deployed should send GOAWAY and let in-flight streams finish; the client retries what was never started (section 10).

  • One lost TCP packet stalls every stream: all streams share one ordered byte stream, so one loss delayed all three concurrent streams by 43 to 68 ms in the root's recording (Fig. 4). HTTP/3 fixes this.
  • Streams queue beyond SETTINGS_MAX_CONCURRENT_STREAMS (100 here); the root's Failure lab shows it ("Max concurrent streams").
  • One connection, one backend: a long-lived HTTP/2 connection through a connection-level (L4) load balancer pins every request to one backend (Service APIs; Failure lab "gRPC behind an L4 load balancer").
What was retired (priorities, server push, h2c upgrade) and two attacks (Rapid Reset, CONTINUATION flood)
  • Priorities. RFC 7540 let clients build a dependency tree of streams with weights. Few servers implemented it well, and RFC 9113 "deprecates the priority signaling defined in RFC 7540" (section 5.3.2). Its replacement is a simple Priority header (urgency 0 to 7, incremental or not) shared with HTTP/3 (RFC 9218, June 2022).
  • Server push. The server could send responses the client had not asked for. Chrome turned it off by default in Chrome 106, after measuring that only 1.25%, later 0.7%, of HTTP/2 sites used it; 103 Early Hints (a hint, not the bytes) replaced it (Chrome, 18 Aug 2022). The server recorded here sends ENABLE_PUSH 0.
  • Upgrading a cleartext connection to h2c. The Upgrade: h2c dance is deprecated in RFC 9113 (section 3.1). Cleartext HTTP/2 itself is alive inside clusters, started with "prior knowledge" (the client just sends the preface): that is how much gRPC traffic runs.
  • Rapid Reset (CVE-2023-44487). An attacker opens a stream and immediately cancels it with RST_STREAM, again and again: cancelled streams do not count against the concurrency limit, but the server has already started work on each. Cloudflare saw a peak just above 201 million requests per second from about 20,000 machines; Google saw 398 million (Cloudflare, 10 Oct 2023; Google Cloud). Fix: servers now count resets and close abusive connections.
  • CONTINUATION flood (April 2024). HEADERS followed by endless CONTINUATION frames without END_HEADERS makes a server buffer headers forever; one connection could crash many implementations, and because no request ever completes, nothing appears in access logs (Nowotarski, 3 Apr 2024).

7. HTTP/3: the same streams on QUIC

HTTP/2 removed the queue between requests but kept one underneath: TCP delivers one ordered byte stream, so a single lost packet holds every stream until it is resent. HTTP/3 (RFC 9114, June 2022) moves HTTP/2's idea onto QUIC, a transport over UDP with TLS 1.3 built in and many independently ordered streams (RFC 9000; the transport is on Networking foundations). A lost packet stalls only its own stream, and setup takes one round trip instead of two.

Fig. 4 · One lost packet: HTTP/2 against HTTP/3

  1. HTTP/2: three streams, one ordered byte stream. Three copies of the running request go 10 ms apart on one TCP connection (25 ms each way). Their tokens come back interleaved in one file, and each lands in its stream's row when it arrives.
  2. One packet lost: every stream waits. The packet carrying stream 1's second token is lost. TCP hands nothing after a gap to the application, so the tokens of streams 3 and 5 that arrived behind it wait too: the second tokens land 68, 56 and 43 ms late, all at once.
  3. HTTP/3: each stream ordered on its own. The same three requests on one QUIC connection over UDP. QUIC numbers the bytes of each stream separately, so each row only waits for its own bytes.
  4. One packet lost: only its stream waits. One QUIC packet is really dropped and resent. Stream 0's second token lands 66 ms late; streams 4 and 8 carry on as if nothing had happened.
  5. The cost per token. Every token's extra delay in the loss run against the run without loss, as bars: on HTTP/2 the stall spreads across all three streams; on HTTP/3 it stays in one row. Both runs finish at about the same time: a loss costs a stall mid-answer, not a slower total.

measured by the root page: three requests 10 ms apart through its network emulator, 25 ms each way (topic_protocols/src/wire/hol.sh, raw/hol/). For QUIC one packet was really dropped; for TCP, whose kernels would resend a dropped segment invisibly, one server-to-client chunk was held 67 ms, the QUIC stall measured first, standing in for detection and retransmission. Times are when each token reached the application.

What it costs. QUIC runs in user space and encrypts nearly every header, so it costs more CPU per byte than kernel TCP and packet tools see little. UDP 443 is blocked or throttled on some corporate networks, forcing a fallback to TCP after a delay. Inside a data centre, where loss is rare, HTTP/2 over TCP is simpler and as fast; HTTP/3 pays on lossy, mobile and long-distance client links. The loss runs in Fig. 4 are the root's, from its On the wire tab, which also times HTTP/1.1 and the handshakes.

How it works. Each request is one client-opened bidirectional stream (ids 0, 4, 8, ...), carrying HTTP/3 HEADERS and DATA frames whose type and length are QUIC variable-length integers rather than HTTP/2's fixed 9-byte header; the stream id lives in QUIC, not in the frame. Connection business moves to unidirectional streams each side opens once: measured the client opened its control stream (id 2, carrying SETTINGS), a QPACK encoder stream (6) and a QPACK decoder stream (10); the server opened the same three as 3, 7 and 11.

QPACK, and why HPACK could not be reused. HPACK assumes both sides see header blocks in the order they were sent; QUIC streams arrive in any order, so a block could refer to a table entry the decoder has not received yet. QPACK (RFC 9204) puts table insertions on the encoder stream and lets the encoder choose, per request, between entries the decoder has acknowledged (never blocks) and newer ones (smaller, but the request waits if the insertion has not arrived: a blocked stream, capped by QPACK_BLOCKED_STREAMS). measured aioquic's encoder sent request 1 with the static table only (59 bytes, plus 3 bytes on the encoder stream to set the table size), then inserted the fields on the encoder stream (53 bytes) and sent request 2's headers in 9 bytes that referred to those not-yet-acknowledged entries. Toggle QPACK in the header animation to compare.

How a client finds HTTP/3. It cannot know a server speaks QUIC before trying, so servers advertise it: Alt-Svc: h3=":443"; ma=86400 ("HTTP/3 on UDP 443; remember for a day", RFC 7838) or an HTTPS record in DNS (RFC 9460; DNS). Browsers then race QUIC against TCP and keep the winner. measured 5 October 2026: api.openai.com and generativelanguage.googleapis.com advertised h3; api.anthropic.com did not; curl negotiated HTTP/2 with all three (section 11).

0-RTT and 425. A client that has talked to a server before can send its first request inside the first packet (TLS early data). An attacker who copies that packet can replay it, so the request must be safe to repeat; a server that will not take the risk answers 425 Too Early and the client resends after the handshake (RFC 8470). Never let a POST that starts a generation be accepted as early data.

Each request on its own QUIC stream; settings and the QPACK tables on six one-way streams

measured Every HTTP/3 frame and QPACK instruction of the recorded connection, by QUIC stream and time (raw/h3_frames.json, aioquic 1.3.0): the request alone, again on the same connection, then two at once. A loss on stream 0 would delay only stream 0's row.

8. Proxies: everything between you and the model

Real requests rarely go straight to the origin: something adds TLS, balances load, caches, enforces limits, logs, or controls what leaves a company network. An intermediary receives a full HTTP message, may change it, and sends a new message on the next hop.

KindWho runs it, for whomOn an LLM request's path
Forward proxyThe client's side; every outgoing request goes through itA corporate egress proxy, set with HTTPS_PROXY, which httpx, requests and the SDKs read from the environment by default (httpx trust_env=True)
Tunnel (CONNECT)A forward proxy asked to open a raw TCP tunnelFor https:// the client sends CONNECT api.anthropic.com:443 and speaks TLS through it, so the proxy sees only the host name, unless it intercepts TLS with its own CA (TLS and certificates)
Reverse proxy / gatewayThe server's side; clients think it is the originnginx, Envoy, an API gateway, a Kubernetes ingress in front of vLLM or your app
CDN edgeA reverse proxy run by a CDN close to usersAll three public LLM APIs answered through one (section 11)
Load balancerL7 parses HTTP and routes each request; L4 forwards TCP connections unreadAWS ALB (L7) vs NLB (L4); depth on Service APIs

What a proxy changes in your request

A proxy does not pass bytes through: it parses the message and writes a new one. Predict what the backend receives when curl sends the running request over HTTP/2 to nginx with nothing but proxy_pass configured.

The version changed (HTTP/2 in, HTTP/1.1 out), because the proxy terminates one connection and opens another. Host was rewritten to the upstream's address unless configured (proxy_set_header Host $host; $host drops the port). The client's address is gone unless the proxy adds X-Forwarded-For (or the standard Forwarded, RFC 7239); any client can send those, so take the address appended by your own outermost proxy and trust the header only from proxies you run. Header order and case changed, harmless except to anything that signs raw header bytes.

Hop-by-hop headers. Connection and every field it names, Keep-Alive, Transfer-Encoding, TE, Upgrade and Proxy-Authorization describe one connection; a proxy must not forward them (RFC 9110 section 7.6.1), and HTTP/2 and 3 forbid them outright: measured nginx 1.31.6 answered 400 to an HTTP/2 request carrying transfer-encoding, a rule added in nginx 1.31.0 (13 May 2026).

Docs disagree with the software: nginx's upstream defaults changed in 2026
nginx's proxy module page still lists proxy_set_header Connection close as a default, and older guides say nginx talks HTTP/1.0 to the backend. Since nginx 1.29.7 (24 March 2026) "the default value for proxy_http_version is 1.1; the Connection proxy header is not sent by default anymore", and upstream keep-alive is on by default (nginx CHANGES, kept in src/inputs/nginx_changes_excerpt.txt). measured The capture above shows HTTP/1.1 and no Connection header; configurations that add proxy_set_header Connection "" are now harmless but redundant.

Buffering. By default nginx reads the upstream's response into buffers before sending it on (proxy_buffering on): for a token stream the user sees nothing, then everything. Turn it off for streaming locations, or let the app send X-Accel-Buffering: no (nginx proxy module); ingress-nginx defaults to proxy-buffering: off (ConfigMap docs). The root's Failure lab measures the delay ("A buffering proxy delays tokens") and reproduces 502 and 504 with real error text.

The backend gets a different message: new version, rewritten Host, the client's address gone

Client sent
Backend received

Request smuggling: two parsers, two answers

A front proxy and a backend share one keep-alive connection for many users' requests. If they disagree about where a request ends, an attacker can send bytes the proxy sees as one message and the backend as two; the hidden second request is glued to the front of the next user's request on that connection, bypassing the proxy's checks and possibly capturing that user's request. The classic disagreement is a message with both Content-Length and Transfer-Encoding: chunked.

The rule: a server receiving both "MAY reject" the request or use Transfer-Encoding alone, and "Regardless, the server MUST close the connection after responding" (RFC 9112 section 6.3). measured Eight ambiguous HTTP/1.1 messages and three HTTP/2 ones, sent raw to nginx 1.31.6 and to hypercorn 0.18.0 (parser h11 0.16.0): nginx refused every one with 400 or 501 and forwarded nothing. hypercorn followed Transfer-Encoding, answered 400 to the empty POST, and then answered the hidden GET /smuggled as a second request on the same connection, where RFC 9112 section 6.3 says it MUST close it.

A finding, not a vulnerability report
Behind nginx this cannot be exploited, because nginx rejects such messages first; behind a front proxy that trusted Content-Length it would be the textbook desync. Run a strict proxy in front, keep the same parser behaviour on every hop, and prefer HTTP/2 end to end where you can. AWS's ALB ships a "desync mitigation mode" for exactly this, defensive by default (ALB attributes).

HTTP/2 at the front does not remove the problem when the back hop is HTTP/1.1: a header value containing CR LF, or a content-length that disagrees with the DATA frames, can become two requests after the downgrade (James Kettle, "HTTP/2: The Sequel is Always Worse", PortSwigger, 5 Aug 2021). measured nginx rejected all three HTTP/2 probes with 400 and passed nothing on.

Every probe and each server's answer

The same bytes are one request to a Content-Length parser and two to a chunked parser

illustrative drawing of the first probe below: a parser that trusts Content-Length (4) reads 4 bytes of body and leaves the rest on the connection; one that follows chunked coding reads the empty chunk 0 and sees a second request, GET /smuggled.

9. Timeouts: the smallest one on the path wins

A program waiting on the network must eventually give up, or one dead server ties up threads, connections and memory forever, so every client, proxy and server has timeouts. An LLM generation is unusual traffic: it can think for a minute before the first token and stream for ten more, which is what most timeouts were tuned to kill.

KindClock startsReset byTypical names
ConnectOpening the TCP (or QUIC) connectionnothinghttpx connect, nginx proxy_connect_timeout
TLS handshakeAfter connectnothingoften folded into connect
First byte (headers)Request sentthe response head arrivingundici headersTimeout; Cloudflare's 524
Idle (read)Each byte receivedevery byte, including a keep-alive commenthttpx read, nginx proxy_read_timeout, ALB idle timeout, undici bodyTimeout
Total (deadline)Request sentnothing: the whole response must finishcurl --max-time, Envoy route timeout, Google Cloud backend service timeout, API Gateway integration timeout
Keep-alive idleA connection goes unusedthe next requestnginx keepalive_timeout, pool idle timeouts

The distinction that matters most is idle against total: streaming defeats idle timeouts, because every token resets them, and does nothing against a total timeout. measured The running request through nginx 1.31.6 with proxy_read_timeout 2s (idle), and with client-side limits (src/lab/proxy_runs.py, raw/timeouts.json); each step replays one run over its measured time:

Fig. 6 · Six measured runs through nginx's 2 s idle timeout

  1. Bytes keep the idle timer down. A 1 s think, then five tokens: nginx's timer climbs halfway during the think, then every byte empties it. Complete in 1.22 s.
  2. 3 s of silence: cut at 2 s, under a 200. nginx gives up at 2.01 s. It had already passed on the 200 head, so curl sees a broken body: exit 18, "transfer closed with outstanding read data remaining", 0 tokens. httpx with a 2 s read timeout, straight to the server, raises ReadTimeout at 2.02 s.
  3. A ping every second keeps it open. The same 3 s think with an SSE comment (: ping) each second: the comment is a byte, SSE clients ignore it, and the two pings reset the timer. Complete in 3.22 s.
  4. Idle timers do not count length. Eight tokens 1.5 s apart, 11.5 s in all, pass the 2 s idle timeout untouched: complete in 11.52 s (httpx with a 2 s read timeout: 11.6 s).
  5. A total limit counts everything. The same stream with curl --max-time 5: cut at 5.02 s after three tokens, exit 28. Streaming does nothing against a total timeout.
  6. Not streamed: a clean 504. An answer sent only at the end, after 3 s: no head had passed, so nginx answers 504 Gateway Time-out at 2.01 s.
The eight runs as a table (curl through nginx, and httpx direct)

Build your own path. The lab beside this text replays one generation, byte by byte, against every timer on a path you choose, each at the hop's documented default (the closed table below lists them with sources). The first timer to reach its limit ends the request. Predict first: a 90 s think behind nginx's defaults. Then add pings; switch the load balancer to Google Cloud's and watch pings stop helping; pick httpx's 5 s default.

Does the model match reality? (8 measured runs, and its assumptions)

Assumptions: the server sends the response head the moment it accepts a streamed request (the lab server does; most streaming APIs do) and nothing else until the first token, unless pings are on; an idle timer starts when the request is sent and restarts on every byte; a first-byte timer stops when the head arrives; a total timer never restarts. Real hops add what this leaves out: connect and TLS timeouts, keep-alive races, proxies that buffer and so delay bytes to the next hop, and retries by intermediaries. Python check: src/recompute.py runs the same model on the same cases.

The trap: two hops count total time
Google Cloud's 30 s backend service timeout and API Gateway's 29 s count the whole response. Behind either, a generation longer than 30 s fails even when it streams perfectly, and no amount of pings helps: raise the limit, or switch to the async shape (submit, get a job id, poll or receive a webhook). Envoy's 15 s route timeout is total too, and is usually the first thing to bite a streaming service behind Istio.

Build a path and replay one generation against every hop's timer: the first to fire ends it

Before / after:

model Each default is the documented one (table below). Run on the eight measured cases above, the model reproduces all eight independently: the measurement is not an input (closed block below).

Defaults you will meet, with sources (checked 5 October 2026)
HopSettingDefaultKind
Anthropic and OpenAI Python SDKstimeout600 s, connect 5 s (both); Anthropic's SDKs also refuse a non-streaming request expected to exceed 10 minutes (errors docs)idle per read (httpx)
httpx (plain)Timeout5 s of inactivity (docs)connect, read, write, pool; no total
Node fetch (undici)headersTimeout, bodyTimeout300 s each; connect 10 s (docs)first byte; idle
Python requeststimeout=none: "requests do not time out unless a timeout value is set explicitly" (docs)connect, read (idle)
Cloudflare (proxied site)Proxy Read Timeout125 s, then error 524; Enterprise up to 6,000 s (docs)waiting on the origin
AWS Application Load Balanceridle timeout60 s (1 to 4,000); HTTP/2 PING frames do not reset it (docs)idle
AWS API Gateway (REST)integration timeout50 ms to 29 s; Regional and private APIs can raise it, possibly at the cost of throttle quota (quotas)total
Google Cloud external Application LBbackend service timeout30 s; "the load balancer expects the backend to deliver the entire" response within it (docs)total
Envoyroute timeout; stream idle15 s ("typically a problem for streaming responses"); 5 min (FAQ)total; idle
nginxproxy_read_timeout60 s, "only between two successive read operations" (docs)idle
ingress-nginx (Kubernetes)proxy-read-timeout60 s; connect 5 s (ConfigMap)idle

Keep-alive timeouts in the wrong order. If the application closes idle connections sooner than the load balancer does, the balancer "might send a request to the application before it receives the packet indicating that the connection is closed", and the client gets a 502; keep the application's idle timeout larger than the balancer's (ALB docs). In general each hop's keep-alive idle timeout should be longer than that of the hop in front of it. Choosing values and propagating deadlines through a system: Reliability engineering.

Predict, then reveal

A model thinks for 45 s before its first token, then streams for 3 minutes. Path: Anthropic SDK, AWS ALB, nginx, model server, all at defaults; the server sends the 200 head at once and nothing else until the first token. What happens?

10. Retries and idempotency, at the protocol level

A request failed. If the server never started, send it again; if it finished but the answer was lost, a retry does the work twice: two generations billed, two tool calls executed. The protocol question is always: can the client prove the server did not start?

Where the failure happened decides whether a POST may be retried

Static diagram of one POST's life. Safe: the request never reached HTTP, or the server guarantees it did not act (RFC 9113 section 8.7 for REFUSED_STREAM and GOAWAY; RFC 8470 for 425; 429 and 503 with Retry-After refuse before the work by contract). Unknown: anything after the request bytes left, unless it carries an idempotency key the server honours. 500 and 529 probably failed, not guaranteed; the Claude docs say to retry 500 with backoff. An error event mid-stream: the partial output is not resumable, start a new request.

What the official SDKs actually do (measured)

The Anthropic (1.11.0) and OpenAI (3.24.0) Python SDKs share one generated base client. Its source retries on connection errors, timeouts, 408, 409, 429 and every 5xx, twice by default; waits 0.5 s, then 1 s, up to 8 s, each multiplied by a random factor between 0.75 and 1 ("jitter"); and obeys retry-after-ms, Retry-After and a non-standard x-should-retry: true|false header from the server. Predict how many POSTs the server sees after a read timeout; then look at the read-timeout row.

What this means
On a read timeout (1 s client timeout, a server that takes 2.5 s) and on a connection dropped after the request was sent, both SDKs sent the same POST three times, and no attempt carried an idempotency key: the base client has an idempotency header slot, but neither SDK sets it. Against a real API each attempt may run a full generation, so a client timeout shorter than the model's real latency multiplies load and cost by up to three: fail fast on connect, not on read; set the read timeout above the longest generation, or stream. The server has a say too: api.anthropic.com answered our credential-free request with x-should-retry: false on its 401 (section 11).

Making a POST safe to retry. The client sends a unique idempotency key header; the server stores the key with the result and, on a retry with the same key, returns the stored result instead of working again (Stripe's design). The IETF draft that would standardise an Idempotency-Key header reached revision 07 and expired without becoming an RFC (Datatracker), so each API defines its own. The server side, including work outside your database, is on Service APIs (section 4); retry budgets, backoff and the retry storms they prevent are on Reliability engineering.

A read timeout or a dropped connection: the same POST arrives three times, with no idempotency key

measured src/lab/sdk_retries.py, raw/sdk_retries.json, errors injected by the lab server. Each dot is one request the server received, at its time after the first; gaps include the random jitter, so they vary run to run. No real API was called.

Predict, then reveal

A deployment sends GOAWAY with last stream id 41 on an HTTP/2 connection where your client had streams 39, 41 and 43 in flight, all POSTs. Which may it retry automatically?

11. What this means for LLM APIs

measured One credential-free GET /v1/models to each of three public LLM hosts on 5 October 2026, with curl 8.7.1 (request ids and cookies removed; src/lab/public.sh, raw/public_headers.txt):

All three negotiated HTTP/2 through ALPN. Two answered through Cloudflare (server: cloudflare, cf-cache-status: DYNAMIC): your request ends at a CDN edge, which makes its own request to the provider, so CDN limits (the 125 s read timeout, the 413 for oversized bodies) apply before the API sees anything. OpenAI and Google advertise HTTP/3 with alt-svc; Anthropic does not, so browsers stay on HTTP/2 there. Anthropic's 401 carries x-should-retry: false, which its SDK obeys. Each refusal used the status code that fits (401 no credentials, 403 for Google's API key requirement).

A checklist for calling a model over HTTP

  • Stream long generations: it keeps idle timeouts happy, gives a first token early, and is what the Claude docs recommend for requests that could exceed 10 minutes; for anything that can wait, use the batch API (the 202-and-poll shape).
  • Handle errors in the stream, not only the status code (section 2), and treat a stream that ends without its final event as a failure even when no exception was raised. SSE parsing rules byte by byte (eight real parsers) and resuming with Last-Event-ID: Streaming and real-time.
  • Set your client timeout above the slowest real generation, knowing the SDK will retry a timeout twice (section 10).
  • Read the rate-limit headers. On a 429, wait retry-after seconds; the Claude API also sends anthropic-ratelimit-requests-remaining, -tokens-remaining and their reset times on every response (rate limits), so a client can slow down before it is refused. A 429 from a spend cap carries no retry-after and will not clear by retrying.
  • Log the request id (request-id on the Claude API) with every failure; support will ask for it.
  • Reuse connections: one client object per process, not per call. A new connection pays the TCP and TLS round trips again (the root measured 108 ms against 54 ms to the first byte on a 50 ms path) and leaves sockets in TIME_WAIT; in serverless functions, create the client outside the handler.
  • Behind your own proxy: buffering off for streams, idle timeouts above the longest think, keep-alive timeouts ordered, no total timeout shorter than the longest generation.
  • Serving a model yourself (vLLM and Ollama expose OpenAI-style HTTP APIs): send the response head and periodic SSE comments early, so every proxy in front sees bytes; return 429 or 503 with Retry-After when the queue is full instead of letting requests time out.

12. Debugging HTTP: tools and symptoms

ToolWhat it shows
curl -v URLConnection, TLS and ALPN choice, every request and response header (> sent, < received). --http1.1, --http2 or --http3 (if built in) force a version, -N shows a stream as it arrives, --resolve host:443:IP aims at one server, --trace-ascii - prints every byte
curl -w '%{time_connect} %{time_appconnect} %{time_starttransfer} %{time_total}\n'Where the time went: TCP done, TLS done, first byte, all done
curl -sI URL | grep -i alt-svcWhether the server offers HTTP/3
curl -v -X OPTIONS URL -H 'Origin: https://example.com' -H 'Access-Control-Request-Method: POST'What a browser's preflight will get (section 4)
Python: logging.getLogger("httpx").setLevel("DEBUG"); SDKs: ANTHROPIC_LOG=debug or OPENAI_LOG=debugEach request, response status, and retries with their delays
nghttp -nv URL (nghttp2)Every HTTP/2 frame, like the frame viewer in section 6
Browser DevTools, Network panel (Protocol column)Which version each request used, timing per phase, CORS failures
A proxy's own logsnginx's $upstream_response_time and $request_time separate "the backend was slow" from "the client was slow"
SymptomMost likely causeFirst check
Tokens arrive all at once at the endA buffering proxy, or compression on the streamcurl -N against each hop in turn; proxy_buffering, gzip settings
Long answers fail at a round number of seconds (30, 60, 100, 125)A proxy timeout: idle if pauses matter, total if length mattersTime the failure; match it to the defaults (section 9)
Stream cut mid-answer, status was 200Idle timeout on a hop that had already sent the headcurl exit 18; the proxy's error log
502 after idle periods onlyKeep-alive timeouts in the wrong orderCompare the app's and the balancer's keep-alive idle
504 from the proxyBackend slower than the proxy's timeout before any headerProxy's upstream timing in its logs
Duplicate side effects after network errorsRetries of a non-idempotent POSTSDK debug logs: retry count; server logs: same body twice
Works with curl, fails in the browserCORS: preflight refused or no Access-Control-Allow-OriginThe preflight with curl (above); DevTools console
Works with curl, fails in the appDifferent proxy environment variables, HTTP version or timeout defaultsPrint the client's effective config; env | grep -i proxy
Parallel calls barely faster than sequentialA small connection pool, or HTTP/1.1 where HTTP/2 was expectedPool limits; the negotiated version in debug logs

39 failures reproduced with the exact error text of curl, requests, httpx and Node, in a drill mode: the root's Failure lab.

Reference

Interview rehearsal (eight questions, with model answers)

What happens, at the HTTP level, when I call an LLM API with stream=true? The SDK opens (or reuses) a TLS connection, ALPN picks HTTP/1.1 or HTTP/2, and it sends POST /v1/messages with a JSON body and credentials in a header. The server answers 200 with content-type: text/event-stream right away, then writes SSE events as tokens are produced: as chunked coding on HTTP/1.1, as DATA frames on HTTP/2. The status is fixed before the first token, so later failures arrive as error events. Every proxy on the path must forward bytes as they come (no buffering) and must not hit its idle timeout between events.

HTTP/1.1 vs HTTP/2 vs HTTP/3: what does each fix, and what does each still cost? Same semantics (RFC 9110), different framing. HTTP/1.1: text, one outstanding response per connection, so clients open several connections; headers repeated in full. HTTP/2: binary frames, many streams on one TCP connection, HPACK header compression, per-stream flow control; still stalls every stream on one lost TCP packet, and one long connection can pin a backend behind an L4 balancer. HTTP/3: the same over QUIC, so a loss stalls only its own stream and setup is one round trip; costs more CPU, UDP may be blocked, fewer tools. Inside a data centre HTTP/2 is the usual answer; HTTP/3 pays on lossy client links.

Our streaming endpoint works locally but users see the whole answer at once in production. Why? Something on the path buffers the response: nginx's default proxy_buffering on, a compression filter that waits for enough bytes, a serverless platform that does not stream, or a CDN rule. Check hop by hop with curl -N and timestamps; fix with proxy_buffering off or X-Accel-Buffering: no on that location, no gzip on text/event-stream, and send an early byte.

Long generations fail after exactly 60 seconds. Walk me through it. A round number means a configured timeout. 60 s is nginx's proxy_read_timeout, ingress-nginx's default and the AWS ALB idle timeout. If the failure depends on silence (a long think before the first token) it is an idle timeout: send SSE keep-alive comments and raise it. If it depends on total length even while tokens flow, it is a total timeout (Envoy route 15 s, Google Cloud backend 30 s, API Gateway 29 s): raise it or go asynchronous. A cut stream under a 200 means the head had passed; a 504 means it had not.

When is it safe to retry a failed POST? When the server provably did not process it: connection refused, TLS failure, REFUSED_STREAM, a stream above GOAWAY's last stream id, 425 Too Early, 429 or 503 with Retry-After. A reset or timeout after the request was sent is ambiguous, so retry only with an idempotency key the server honours. Use capped exponential backoff with jitter and honour Retry-After; budget retries so layers do not multiply them.

What is HTTP request smuggling and how do you prevent it? A front proxy and a backend that disagree about where a request ends (Content-Length against Transfer-Encoding, duplicate lengths, malformed chunking, CR LF injected through an HTTP/2 to HTTP/1.1 downgrade) let an attacker hide a second request that is then prefixed to another user's. Prevent it by rejecting ambiguous messages at the edge (nginx does, measured here), closing connections after any ambiguity as RFC 9112 requires, using the same strict parser on every hop, and HTTP/2 end to end where possible.

Why does HTTP/3 need QPACK instead of HPACK? HPACK assumes header blocks are decoded in the order they were sent, which TCP guarantees. QUIC streams arrive independently, so a block could reference a dynamic table entry the decoder has not seen. QPACK sends table insertions on a separate encoder stream and lets the encoder choose between references the decoder has acknowledged (never blocks) and newer ones (smaller, may block, capped by QPACK_BLOCKED_STREAMS).

What is the difference between 502, 503 and 504? All three are usually written by a proxy about the hop behind it. 502 Bad Gateway: the upstream answered with something invalid or closed the connection (often a keep-alive race or a crashed backend). 503 Service Unavailable: no healthy upstream, or the server is shedding load, ideally with Retry-After. 504 Gateway Timeout: the upstream did not answer within the proxy's timeout. Each points at a different fix, so find which hop wrote it.

Corrections to the old page ("HTTP: 1.1, 2, 3, and what matters for LLM services")

The old written page ("HTTP: 1.1, 2, 3, and what matters for LLM services", last edited 2026-09-22) is kept verbatim in the root's src/read/old/. Each of its facts was checked; src/coverage.json lists where each one lives now. Corrections:

  • "HTTP/3: no head-of-line blocking". No blocking between streams on packet loss, yes; but QPACK can block a stream that refers to a table entry not yet received (section 7), and data within one stream is still delivered in order.
  • "HPACK makes repeated headers like authorization cost a few bytes". measured The h2 library sends authorization as a never-indexed literal: 32 bytes on every request, by design. A custom x-api-key was indexed (7 bytes for the whole repeat block).
  • "Retry only on connection errors, 408, 429, 5xx". A connection error after the request was sent is ambiguous for a POST; and the official Python SDKs do retry those, three attempts in all, without an idempotency key (measured, section 10).
  • "Streaming resets idle timers". True for idle timeouts only; total timeouts (Google Cloud 30 s, API Gateway 29 s, Envoy route 15 s) are not affected.
  • "An IETF draft exists" for Idempotency-Key. It expired at revision 07 without becoming an RFC.
  • "Stream prioritization" as an HTTP/2 feature: deprecated by RFC 9113 (2022); RFC 9218's Priority header replaces it.
  • "Handshake TCP + TLS (2-3 RTT)". Two round trips with TLS 1.3, three only with TLS 1.2 (the root's On the wire tab measures both).
  • The "web.dev: HTTP/3 and QUIC" resource linked to an article about content delivery networks; replaced in Further reading.
  • "LLM APIs switch JSON vs SSE with Accept: text/event-stream". The Claude and OpenAI APIs switch on "stream": true in the body; it is MCP's Streamable HTTP that negotiates with Accept.
  • "Client SDKs implement token-bucket-aware backoff". The measured Python SDKs use exponential backoff with jitter and obey Retry-After; there is no token bucket in their code.
  • nginx no longer talks HTTP/1.0 to backends by default (since 1.29.7; section 8).
  • Not confirmed, dropped: the old page's remark on Lambda response streaming payload and duration caps (not checked against AWS documentation today).
Glossary (every term defined on this page, linked to where it is defined)