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
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).200 text/event-stream at once, then one event per token; each hop passes the bytes on as they come, unless it buffers.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).
| Question | Short answer | Section |
|---|---|---|
| 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).
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.
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).
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).
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.
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.
| Method | Asks for | Safe | Idempotent | Where you meet it in ML work |
|---|---|---|---|---|
GET | A representation of the resource | yes | yes | List models, download weights or a tokenizer, poll a batch job |
HEAD | GET without the body | yes | yes | Check a file's size and ETag before downloading it |
OPTIONS | What the server allows | yes | yes | Browser CORS preflight (section 4) |
POST | Process this body | no | no | Every generation (/v1/messages, /v1/chat/completions), tool calls, MCP and A2A requests |
PUT | Replace the resource with this body | no | yes | Upload an object to a known key (S3 PUT, a model artefact) |
PATCH | Apply these changes | no | no (in general) | Update fields of a job or a config |
DELETE | Remove the resource | no | yes | Cancel 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.
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.
| Code | Meaning | Who usually sends it, and what to do |
|---|---|---|
| 200 | OK | Sent 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. |
| 202 | Accepted, not yet done | Long jobs: submit, get an id, poll or get a webhook (batch APIs) |
| 204, 304 | No content; not modified | 304 answers a conditional request: "your cached copy is still good" (section 3) |
| 301, 302 / 307, 308 | Moved | 307 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, 422 | Malformed / well-formed but invalid | Your bug; retrying will not help |
| 401 vs 403 | Not authenticated / not allowed | 401: fix the key or token. 403: fix permissions or scopes (Auth) |
| 408 | Request Timeout | The server gave up waiting for your request bytes; safe to retry on a new connection |
| 409 | Conflict | State conflict, or an idempotency key reused with a different body |
| 413 | Content Too Large | For the Claude API the Messages limit is 32 MB, and "Cloudflare returns this error before the request reaches the API servers" (errors docs) |
| 421 | Misdirected Request | A reused HTTP/2 or 3 connection reached a server that does not serve this host; retry on a new connection |
| 425 | Too Early | The 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) |
| 429 | Too Many Requests | Rate limit (RFC 6585); wait as long as Retry-After says |
| 500 | Internal error | Retry with backoff only if idempotent or carrying an idempotency key |
| 502, 503, 504 | Bad gateway / unavailable / gateway timeout | Usually written by a proxy about the hop behind it: bad answer, nobody there, too slow; find which hop (section 8) |
| 524, 529 | Not in any RFC | 524: Cloudflare's "origin did not answer in time" (125 s by default). 529: the Claude API's overloaded_error. Both read as 5xx. |
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"?
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).
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).
> 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.
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.
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.
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.
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.
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, only the exact host that set it__Host- prefix__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.
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.
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
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.
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.
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.
▶ 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 type | Carries | Seen in the running request |
|---|---|---|
| HEADERS (0x1) and CONTINUATION (0x9) | A compressed header block; CONTINUATION extends one that did not fit | Request and response heads |
| DATA (0x0) | Body bytes; the END_STREAM flag marks the last | The JSON body; one per SSE event |
| SETTINGS (0x4) | Each side's limits: table size, window, frame size, concurrent streams | Both sides, first thing; then empty ACKs |
| WINDOW_UPDATE (0x8) | Flow-control credit for a stream or the connection | The 200 KB download below |
| RST_STREAM (0x3) | Cancel one stream, with an error code | Not here |
| GOAWAY (0x7) | "No new streams; I processed up to stream N" | The client's clean close |
| PING (0x6) | Liveness check and round-trip measurement | Not here |
| PRIORITY (0x2), PUSH_PROMISE (0x5) | Old priority tree; server push | Both 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).
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).
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
: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.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.
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.
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.
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).
Priority header (urgency 0 to 7, incremental or not) shared with HTTP/3 (RFC 9218, June 2022).103 Early Hints (a hint, not the bytes) replaced it (Chrome, 18 Aug 2022). The server recorded here sends ENABLE_PUSH 0.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.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
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.
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.
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.
| Kind | Who runs it, for whom | On an LLM request's path |
|---|---|---|
| Forward proxy | The client's side; every outgoing request goes through it | A 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 tunnel | For 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 / gateway | The server's side; clients think it is the origin | nginx, Envoy, an API gateway, a Kubernetes ingress in front of vLLM or your app |
| CDN edge | A reverse proxy run by a CDN close to users | All three public LLM APIs answered through one (section 11) |
| Load balancer | L7 parses HTTP and routes each request; L4 forwards TCP connections unread | AWS ALB (L7) vs NLB (L4); depth on Service APIs |
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).
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.
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.
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.
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.
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.
| Kind | Clock starts | Reset by | Typical names |
|---|---|---|---|
| Connect | Opening the TCP (or QUIC) connection | nothing | httpx connect, nginx proxy_connect_timeout |
| TLS handshake | After connect | nothing | often folded into connect |
| First byte (headers) | Request sent | the response head arriving | undici headersTimeout; Cloudflare's 524 |
| Idle (read) | Each byte received | every byte, including a keep-alive comment | httpx read, nginx proxy_read_timeout, ALB idle timeout, undici bodyTimeout |
| Total (deadline) | Request sent | nothing: the whole response must finish | curl --max-time, Envoy route timeout, Google Cloud backend service timeout, API Gateway integration timeout |
| Keep-alive idle | A connection goes unused | the next request | nginx 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
: ping) each second: the comment is a byte, SSE clients ignore it, and the two pings reset the timer. Complete in 3.22 s.curl --max-time 5: cut at 5.02 s after three tokens, exit 28. Streaming does nothing against a total timeout.504 Gateway Time-out at 2.01 s.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.
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.
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).
| Hop | Setting | Default | Kind |
|---|---|---|---|
| Anthropic and OpenAI Python SDKs | timeout | 600 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) | Timeout | 5 s of inactivity (docs) | connect, read, write, pool; no total |
| Node fetch (undici) | headersTimeout, bodyTimeout | 300 s each; connect 10 s (docs) | first byte; idle |
Python requests | timeout= | none: "requests do not time out unless a timeout value is set explicitly" (docs) | connect, read (idle) |
| Cloudflare (proxied site) | Proxy Read Timeout | 125 s, then error 524; Enterprise up to 6,000 s (docs) | waiting on the origin |
| AWS Application Load Balancer | idle timeout | 60 s (1 to 4,000); HTTP/2 PING frames do not reset it (docs) | idle |
| AWS API Gateway (REST) | integration timeout | 50 ms to 29 s; Regional and private APIs can raise it, possibly at the cost of throttle quota (quotas) | total |
| Google Cloud external Application LB | backend service timeout | 30 s; "the load balancer expects the backend to deliver the entire" response within it (docs) | total |
| Envoy | route timeout; stream idle | 15 s ("typically a problem for streaming responses"); 5 min (FAQ) | total; idle |
| nginx | proxy_read_timeout | 60 s, "only between two successive read operations" (docs) | idle |
| ingress-nginx (Kubernetes) | proxy-read-timeout | 60 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.
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?
ping events do), or every idle timeout on the path above the longest expected silence. Try it in the chain above.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?
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.
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.
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.
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.
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?
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).
Last-Event-ID: Streaming and real-time.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.request-id on the Claude API) with every failure; support will ask for it.Retry-After when the queue is full instead of letting requests time out.| Tool | What it shows |
|---|---|
curl -v URL | Connection, 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-svc | Whether 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=debug | Each 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 logs | nginx's $upstream_response_time and $request_time separate "the backend was slow" from "the client was slow" |
| Symptom | Most likely cause | First check |
|---|---|---|
| Tokens arrive all at once at the end | A buffering proxy, or compression on the stream | curl -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 matters | Time the failure; match it to the defaults (section 9) |
| Stream cut mid-answer, status was 200 | Idle timeout on a hop that had already sent the head | curl exit 18; the proxy's error log |
| 502 after idle periods only | Keep-alive timeouts in the wrong order | Compare the app's and the balancer's keep-alive idle |
| 504 from the proxy | Backend slower than the proxy's timeout before any header | Proxy's upstream timing in its logs |
| Duplicate side effects after network errors | Retries of a non-idempotent POST | SDK debug logs: retry count; server logs: same body twice |
| Works with curl, fails in the browser | CORS: preflight refused or no Access-Control-Allow-Origin | The preflight with curl (above); DevTools console |
| Works with curl, fails in the app | Different proxy environment variables, HTTP version or timeout defaults | Print the client's effective config; env | grep -i proxy |
| Parallel calls barely faster than sequential | A small connection pool, or HTTP/1.1 where HTTP/2 was expected | Pool 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.
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.
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:
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)."stream": true in the body; it is MCP's Streamable HTTP that negotiates with Accept.The whole stack on one request. Its tabs: On the wire (waterfalls, one lost packet on HTTP/1.1, 2 and 3), Failure lab (39 failures reproduced), Protocol atlas. 33 min plus tabs
What HTTP runs on: TCP's windows and loss recovery, QUIC as a transport. 49 min
The handshake that carries ALPN, 0-RTT, certificates, mTLS. 45 min
Finding the server, and HTTPS records that advertise HTTP/3. 45 min
SSE in depth, WebSockets at the wire level, webhooks, long polling. 38 min
REST, gRPC on HTTP/2, GraphQL, L4 and L7 load balancing. 52 min
The credentials that ride in HTTP headers: API keys, OAuth 2.1, JWTs, mTLS. 42 min
Streamable HTTP as an agent transport. 37 min
Sibling reading times are each page's Reading core, without closed details or labs; pages rebuilt in October 2026 state theirs in their header.
API design over HTTP: resources, errors, pagination, idempotency keys (server side), versioning. 32 min
Timeouts, deadlines, retries with backoff and budgets, circuit breakers, as a system. 40 min
Every cache layer including HTTP and CDN caching, and the LLM caches. 43 min
Parses an SSE stream chunk by chunk with fetch. 14 min
The one to read: methods, status codes, fields, intermediaries. Sections 6 to 9 and 15 first. 4 h (2 h for the core)
Freshness, validation, Cache-Control. 1 h 30 min
Message syntax, body length rules (section 6), security considerations on smuggling (section 11). 1 h
Frames, streams, flow control, request reliability (8.7); header compression and its security (section 7). 2 h 30 min
HTTP over QUIC streams; compression that tolerates reordering. 2 h 30 min
0-RTT replay and 425 Too Early. 20 min
The canonical reference for headers, status codes, caching and negotiation. 1 h for the core pages
Free book; TCP, TLS, HTTP/1.1 and HTTP/2 performance explained from the ground up (written before HTTP/3). 9 h; HTTP chapters 2 h
Short free book by curl's author on QUIC and HTTP/3. 1 h
Deployment view of HTTP/3 and QUIC (2019). 20 min
The attack class explained with labs, plus the HTTP/2 downgrade research. 1 h
Preflights, credentials and the response headers, with the browser errors each causes. 25 min
The classic treatment of retries with idempotency keys. 15 min
How a protocol feature became a record DDoS. 15 min
Status codes, long requests, rate-limit headers for one real LLM API. 20 min
Recorded 5 October 2026 (CORS preflights 24 October 2026); rebuilt to the teaching contract on 24 October 2026. Built from src/ (see src/README.md): every recording in src/raw/ can be rerun with src/run_all.sh. Old page "HTTP: 1.1, 2, 3, and what matters for LLM services" saved verbatim in the root's src/read/old/; its web.dev link (which pointed at an article on CDNs) is replaced by Stenberg's book.