Real-time means the server has news before the client knows to ask. Every way of delivering it is a choice of who opens the connection, which way bytes flow and how long it lives; and anything that lives long is cut by something on the path. So choose by direction (SSE when only the server talks, a WebSocket when both do, a webhook when the wait is hours), then design the heartbeat, the reconnect and the cancel.
Fig. 1 runs one real answer (below) through the four ways, then shows the fifth, which reverses the roles. measured Every request and event sits where the 100 ms round-trip run recorded it (section 1), slowed about seven times; orange travels from the client, blue from the server.
The running example. The parent topic's chat app asks "What colour is the sky?" with one 117-byte POST /v1/messages; the answer is five tokens (The, sky, is, blue, .) framed by message_start and message_stop: seven events in the shapes of Anthropic's Messages API. A stand-in model (no real model runs) waits 120 ms before the first token, standing in for prefill, then produces one every 50 ms. This page delivers that answer four ways, cuts it, resumes it, cancels it, and sends a webhook when a job ends. Everything marked measured was run on 5 October 2026 on an Apple M1 Pro (macOS, Python 3.13, aiohttp 3.14.3, websockets 17.2, nginx 1.31.6, Chrome 148, Node 22) against local servers, so every byte could be recorded.
You need HTTP requests, responses, headers, status codes and proxies (HTTP), and TCP connections (Networking foundations). This page owns the push layer on top of them.
text/event-stream HTTP response that stays open and carries text events.In HTTP the client always speaks first, and gets one response. Server push bends that in four ways: polling asks again on a timer; long polling asks and the server holds the request until it has news; SSE asks once and the response never quite ends; a WebSocket asks once to switch protocols and then either side sends at any time. (The fifth, a webhook, reverses the roles: section 9.) Predict before you press play: on a 50 ms round trip, how much later than SSE does polling every 100 ms deliver the last token?
What the run shows. On the 50 ms path the last token reached the client at 376 ms by SSE, 379 ms by WebSocket, 401 ms by long polling (6 requests for 7 events) and 528 ms by polling (4 requests). Once a stream is open, each token costs one one-way trip. Long polling needs the next request to be waiting at the server: at a 100 ms round trip, tokens 50 ms apart bunch two per response (4 requests for 7 events) and the last token lands at 446 ms against SSE's 428 ms. Polling's latency is set by its timer, not by the model.
measured Each row is one real run (the median of 7 by last arrival) through a relay that delays every byte by half the round trip each way (src/lab/relay.py; delay only, no loss or bandwidth limit). Bars are HTTP requests; dots are events reaching the client (blue: tokens). The top row is the earliest any push could deliver each event. Bytes count everything on the TCP connection, headers included; polling asks every 100 ms after each answer.
Polling is still often right: all of HTTP works unchanged (caching, retries, load balancers, auth, logs), and with an ETag most polls become an empty 304 Not Modified via If-None-Match (HTTP, section 3). A batch or fine-tuning API answers 202 Accepted with a job id and the client polls a status URL (or registers a webhook); A2A lets a client poll a task as well as stream it (Agent-to-agent).
Long polling, done safely. The client asks for everything after a cursor (GET /events?after=3), so events that happen while no request waits go to the next one, never lost. The server holds the request (cheap when asynchronous, fatal for thread-per-request) and answers with the events and the new cursor. Costs: one request per batch with full headers and a credential check; a connection held per waiting client (one of a browser's six per host on HTTP/1.1, section 3); a thundering herd when the server restarts and every held request retries at once (add jitter). Its problems are written down in RFC 6202 (Informational, April 2011, the "Comet" era), and it remains Socket.IO's fallback when a network blocks WebSockets.
Your long-polling endpoint holds requests for 90 s. Behind an nginx with default settings, what do clients see when nothing happens for two minutes?
proxy_read_timeout is 60 s (nginx docs): it waits that long for the upstream to send something, then answers 504 Gateway Timeout itself (the parent topic's Failure lab reproduces this as "Read timeout: connected, then nothing"; the HTTP page's section 9 has the other hops). Hold for less than the shortest timeout on the path (20 to 30 s is usual) and treat a 504 from a long-poll endpoint as "ask again".Bytes grow with idle time, not with the answer. Waiting one hour for a job, polling every second is 3,600 requests (3,600 s ÷ 1 s), long polling held 25 s per request is 144 (3,600 ÷ 25), and SSE is one request plus a comment line every 15 s (the HTML standard's keep-alive advice), 240 lines of 8 bytes (: ping plus two newlines). Derived, not measured.
measured For the seven events (539 bytes of JSON), on the 50 ms path:
| Mechanism | Requests | Bytes up | Bytes down | Where the extra bytes go |
|---|---|---|---|---|
| Polling (every 100 ms) | 4 | 668 | 1,738 | A request line and headers per poll, a response head per answer, empty answers when nothing is new |
| Long polling | 6 | 1,074 | 2,138 | The same per request, one request per event or batch |
| SSE | 1 | 325 | 1,019 | One request with its 117-byte body; one response head; event: and data: labels and HTTP/1.1 chunk sizes per event |
| WebSocket | 1 | 209 | 763 | The upgrade request and the 101 answer once; then 2 bytes of frame header per message |
Many small writes can bunch tokens for a different reason with the same symptom: Nagle's algorithm and delayed acknowledgements (Networking foundations, section 7). How the same request travels over HTTP/1.1, 2 and 3: the parent topic's On the wire tab.
SSE is an agreed text format for a response that does not end, defined in the HTML standard (WHATWG HTML, section 9.2, a living standard, last updated 5 October 2026), plus a small browser API, EventSource, that reads it. Fig. 2 is one token event of the running answer, exactly as sent.
The response head. Content-Type: text/event-stream is the only thing that makes it SSE (EventSource refuses any other type, and any status other than 200). Cache-Control: no-cache, because an event stream is not a document. X-Accel-Buffering: no is not in the standard; it tells nginx-style proxies not to buffer (the parent topic's Failure lab, "A buffering proxy delays tokens"); the standard way is now the Incremental header field (RFC 10036, August 2026). There is no Content-Length: on HTTP/1.1 the body travels in chunked encoding, on HTTP/2 and 3 in DATA frames, and the SSE parser sees neither, only text.
data: , 83 of JSON, 1 newline), 1 for the blank line. The token itself is 3 of them.| Line | What the parser does | Used for |
|---|---|---|
data: ... | Appends the value plus a newline; several data lines join with newlines, the final one removed on delivery. | The payload. LLM APIs put one JSON object here. |
event: name | Sets the type; without it the type is message. | Typed events. In a browser onmessage sees only untyped events; typed ones need addEventListener('name', ...), a classic "my handler never fires" bug. |
id: 42 | Sets the last event id, sent back as Last-Event-ID on reconnect. An id containing NUL is ignored. | Resuming after a cut (section 5). |
retry: 500 | Sets the reconnection delay in ms, if all digits. | Telling clients how fast to come back. |
: anything | A comment: ignored. | Keep-alives: the standard suggests one "every 15 seconds or so". |
| (blank line) | Dispatches the event if its data is not empty. | The end of every event. Forget it and nothing is delivered. |
The rules that bite. Lines end in LF, CR LF or a lone CR; exactly one space after the colon is removed (so data:{"text":"hi"} with no space delivers the whole JSON); a line with no colon is a field name with an empty value; a field name the parser does not know is ignored, including data with a space before the colon; an event the stream ends before its blank line is thrown away; one leading UTF-8 byte order mark is stripped; and a network read can end mid-line or mid-character, so a parser buffers bytes, never decodes each read alone. measured Of 8 real parsers fed 18 byte streams, each testing one rule, only Chrome's EventSource and Node's eventsource package followed the standard on all of them; the four Python parsers (inside the official OpenAI and Anthropic SDKs, httpx-sse, sseclient-py) each lost the first event after a byte order mark. Today's LLM APIs never send those shapes; it matters when you write the server or a proxy that re-frames events.
Each case is a tiny SSE stream testing one rule of the parsing algorithm (WHATWG HTML 9.2.6), sent as the dashed chunks shown (separate network writes, 30 ms apart). measured 5 October 2026; src/lab/parsers_py.py and parsers_node.mjs; raw results src/raw/parsers.jsonl. Besides the byte order mark, the OpenAI, Anthropic and httpx-sse parsers delivered an event that had no data line, which the standard says to skip; sseclient-py also delivered an event cut off by the end of the stream and kept an id containing NUL. All eight agree on the no-space case (nospace).
"ok" means the parser delivered exactly the events the standard requires (type, data and last event id). eventsource-parser reports each event's own id field rather than the last event id, by design, so its id differs in one case: a different contract, not a bug. Its second row decodes each network read separately, which is the caller's mistake, not the library's.
Parsers and versions: . Write a parser yourself and feed it reads that split events mid-line: JavaScript: the event loop, promises and streams, section 5. The full 1,062-byte HTTP/1.1 response with its chunk sizes: the parent topic's On the wire tab.
EventSource (new EventSource('/events')) opens, parses, delivers and reconnects on its own, and three limits decide when you can use it. GET only, no body: an LLM request carries the conversation as JSON, so it cannot be an EventSource request. No custom headers: no Authorization or x-api-key, only cookies (with withCredentials plus CORS for another origin), one more reason browser apps never hold an LLM key (Auth). Strict: a non-200 status or another content type "fails the connection" with no retry, while a network error or a stream that simply ends makes it reconnect. So LLM apps use fetch() with a POST, read response.body as a stream and run an SSE parser over the bytes (JavaScript: the event loop, promises and streams, section 5 builds it); in Python, httpx streaming plus httpx-sse, or the official SDKs with their own parser. Reconnection is then yours to write.
Every request to that host queues behind the streams. MDN notes the limit is per browser and host, across tabs, and that Chrome and Firefox marked the bug "Won't fix" (MDN: EventSource). The fix is HTTP/2 or HTTP/3, where each stream is one of many on a single connection; the server's SETTINGS_MAX_CONCURRENT_STREAMS sets how many, unlimited until it says otherwise, with a recommendation of at least 100 (RFC 9113 section 6.5.2).
MDN says the HTTP/2 limit "defaults to 100". The protocol has no default: until the server's SETTINGS arrive the number of streams is unlimited, and RFC 9113 only recommends that servers not set it below 100. Most servers announce 100 or more, so in practice the advice holds.
measured Chrome 148 against this page's HTTP/1.1 lab server: a page opened eight EventSource streams to one host; 6 opened within 10 ms and the other two never opened in the 3.5 s observed; a plain fetch() to the same host, started 0.3 s in, had not finished either. The HTTP/2 panel is illustrative (not run here: EventSource over h2 needs the browser to trust the lab's certificate).
measured Wikimedia publishes every edit to its wikis as an SSE stream. Four seconds of curl -N https://stream.wikimedia.org/v2/stream/recentchange on 5 October 2026: HTTP/2, content-type: text/event-stream; charset=utf-8, a first line :ok (a comment, sent at once so every proxy sees bytes), then 150 events and 228,771 bytes. Each event's id is a JSON array naming Kafka topics, partitions and timestamps or offsets: send it back as Last-Event-ID and the service resumes from that point in its log. Its documentation says the connection is cut after 15 minutes regardless, and that "a good SSE / EventSource client should be able to automatically reconnect and begin consuming at the right location" (EventStreams docs). Field values were not kept.
A streaming LLM call is an ordinary POST with "stream": true in the JSON body. The server answers 200 with text/event-stream at once, then writes one event per piece of the answer. Because the status line went out first, a later failure (the model overloaded halfway) cannot change it: it arrives as an event inside the stream. measured Fig. 4 is the running answer over SSE on the 50 ms path (median run of 7, section 1's relay); the ruler in front is drawn to scale.
message_start immediately; they reach the client at 57 ms, half a round trip after the request reached the server. The status is now fixed.message_stop arrive at 376 ms: one request, 325 bytes up and 1,019 bytes down for the whole answer.error event inside the stream and the stream ends; the 200 already sent stays the call's status.Anthropic's Messages API (streaming docs, read 5 October 2026) sends named events in a fixed order: message_start (a Message with empty content); per content block content_block_start, one or more content_block_delta, content_block_stop; one or more message_delta (stop reason, cumulative token usage); message_stop. Deltas are text_delta, input_json_delta for a tool call's arguments (partial JSON strings: accumulate and parse at content_block_stop), thinking_delta, and one signature_delta just before a thinking block closes. ping events and error (for example {"type": "error", "error": {"type": "overloaded_error", ...}}, which would have been an HTTP 529 had the response not started) can appear anywhere, and new event types may be added, so ignore types you do not know.
The OpenAI-compatible style sends unnamed events (data lines only) and ends with a sentinel whose data is [DONE]. To SSE that is ordinary data; the client must recognise it. The official Python SDK does, with if sse.data.startswith("[DONE]"): break (openai-python _streaming.py), and vLLM's OpenAI-compatible server ends streams with yield "data: [DONE]\n\n" (vLLM chat_completion/serving.py, read at commit b0eb87fe49, 4 October 2026). A client that forgets it tries to parse [DONE] as JSON and throws on the last event of every answer.
Your app streams from the Claude API. Halfway through, the stream delivers event: error with an overloaded_error, then ends. Your logs record each call's HTTP status. What do they record for this one?
message_stop, as their own metric, or your error rate reads zero during an overload.What the server must do so the stream really streams (you own this if you serve or proxy a model):
text/event-stream (gzip holds bytes until it has enough). Small writes can also be held by TCP itself (Nagle's algorithm, Networking foundations, section 7).X-Accel-Buffering: no for nginx, Incremental for intermediaries that support RFC 10036.: ping comment or a ping event) more often than the shortest idle timeout on the path. The HTTP page measured a 3 s think surviving a short idle timeout because of a comment every second, and owns the list of proxy timeouts, including total-duration ones that no heartbeat helps.The same format in agent protocols. MCP's Streamable HTTP answers each request with plain JSON, or with an SSE stream when it has progress to send first; since the 2026-07-28 revision those streams are no longer resumable (Last-Event-ID was removed) and servers should send X-Accel-Buffering: no (MCP measured both). A2A streams task updates over SSE and also offers polling and push notifications, which are webhooks (Agent-to-agent).
A stream ends early in three ways, each with its own answer: the network cuts it (a proxy timeout, a deploy draining a server, a phone moving from Wi-Fi to cellular), the user cuts it (Stop), or the server fails partway (the error event of section 4).
Predict: an EventSource stream without ids is cut after two tokens; what does a chat UI that appends every token show after the browser reconnects? Then switch the server setting.
measured Chrome 148's EventSource against src/lab/lab_server.py (/sse?drop_after=3: the server closes the TCP connection after three events per connection). Each glass slab is one connection; the row in front is what a chat UI renders by appending every token, red when repeated; the server log adds the Last-Event-ID each reconnect carried.
message_start, "The" and " sky" arrive between 0.008 and 0.177 s. No event carries an id: line.Last-Event-ID: there is nothing to send.open.message_start #0, "The" #1, " sky" #2, then the cut.Last-Event-ID: 2, the server resumed at event 3, and " is", " blue", "." (#3 to #5) arrived with no repeats. Then the next cut.Last-Event-ID: 5; the server sends message_stop #6 and the answer completed. The stream then ends normally.Last-Event-ID: 6; the server has nothing left to send.retry: 500. The stream also sets the reconnection delay to 500 ms; #0 to #2 arrive, then the cut.retry: 500 the reconnects came after 0.504 s; this one carries Last-Event-ID: 2 and #3 to #5 arrive.message_stop #6 completes the answer and the stream ends; EventSource reconnects once more, as before.204 No Content (not 200, so the connection "fails") stopped it: readyState CLOSED, no more reconnects.The standard leaves the default delay to the browser, "probably in the region of a few seconds"; 3 s is Chrome's.
Resuming is a server design, not a header. The server must answer "everything after event 2", so events must outlive the connection: generation runs as a job appending to the log, and the HTTP handler only tails it. A dropped connection then neither stops nor duplicates the work, and any server behind the load balancer can take the reconnect. Wikimedia's stream (section 3) is this shape over Kafka. The cost: storage, and a separate cancel path, since a disconnect no longer stops the job; Vercel's AI SDK states the rule: "In a resumable stream setup, client-side aborts are treated as disconnects. Closing a tab, refreshing the page, or calling stop() only closes the current HTTP connection and should not cancel the underlying generation" (AI SDK resumable streams). On the provider side, OpenAI's background mode is the one LLM API that resumes: create a response with background and stream both true, "keep track of a 'cursor' corresponding to the sequence_number you receive in each streaming event", then resume with starting_after; "Response data is temporarily stored to disk for roughly 10 minutes to enable asynchronous execution and polling" (OpenAI background mode). Elsewhere a cut stream is a failed request, retried from the start (with an idempotency key where supported, HTTP, section 10), and MCP removed SSE resumability in its 2026-07-28 revision.
design pattern The log can be a Redis stream, a Kafka topic or a table, keyed by response id with a retention window.
A stream that ends without its final event (message_stop, [DONE]) is a failure, even when no exception was raised: some proxies close a cut stream cleanly. Check for the terminator before you show or store the answer.
Stop closes the connection (on HTTP/2 it resets only that stream, RST_STREAM with error code CANCEL, RFC 9113 section 7). Whether the GPU stops is up to the server, which usually learns of a closed connection only when it next writes; during the think before the first token it writes nothing.
The naive handler burned 3.0 s of "GPU time" for a user gone at 0.5 s, against 0.51 s for the careful one; once tokens flow, both stop within one token, because the next write fails. Real servers do the careful version: vLLM wraps its OpenAI-compatible endpoints in a with_cancellation decorator that runs the handler beside a listener for the ASGI http.disconnect message and cancels the handler when it arrives (vllm/entrypoints/serve/utils/api_utils.py, read at commit 8c1557a79c). What that cannot see: a proxy that keeps its upstream connection open after the client left (some do, to reuse it) hides the disconnect entirely.
measured src/lab/cancel.py against lab_server.py (aiohttp 3.14.3): 200 tokens 20 ms apart; the client closes the connection 0.5 s after sending. "Careful" checks every 20 ms whether the connection is closing. "Think" stands for prefill or queueing: a stretch with nothing to write. While tokens flow, the naive handler wrote 22 events of which the client read 21.
SSE flows one way. A voice agent must hear the user while it speaks (barge-in), a shared document sends each keystroke while receiving everyone else's, a game sends moves while receiving the world. With HTTP that means a POST per client message beside a stream: two channels, two sets of ordering and failure, a request's headers on every keystroke. A WebSocket gives one connection on which either side sends a message at any moment, with 2 to 14 bytes of framing. It is RFC 6455 (December 2011, a Proposed Standard, updated by RFC 7936, 8307 and 8441), with the browser API in the WHATWG WebSockets standard.
The opening handshake is an ordinary HTTP/1.1 GET asking to switch protocols. measured The exact bytes this page's client sent to the lab's websockets 17.2 server, and its answer:
Upgrade: websocket and Connection: Upgrade ask for the switch. Both are hop-by-hop, so proxies drop them unless told to pass them (section 8).Sec-WebSocket-Key is 16 random bytes in base64, new per connection (this run used the sample key of RFC 6455 section 1.3). The server answers Sec-WebSocket-Accept = base64(SHA-1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")): measured s3pPLMBiTxaQ9kYGzzhZRbK+xOo=, exactly the RFC's value and this page's own computation. It is not security (anyone can compute it); it ensures a server or cache that does not speak WebSocket can never appear to accept.101 Switching Protocols ends HTTP on this connection; from the next byte both sides speak frames. Sec-WebSocket-Version: 13 is the only version; there is no WebSocket 2.Origin is sent by browsers and is the server's only defence against other sites opening sockets in the user's name (section 8).measured Fig. 6 replays the recorded session frame by frame, each envelope as long as its bytes on the wire (src/lab/ws_bytes.py, a client on a bare TCP socket).
Sec-WebSocket-Key.Sec-WebSocket-Accept; the client checks it against its own computation (it matches). From the next byte both sides speak frames.Two negotiations people confuse. Sec-WebSocket-Protocol names the application protocol inside (subprotocol; the client offers a list, the server picks one): graphql-transport-ws, MQTT, your own chat.v2; version your messages this way. Sec-WebSocket-Extensions changes the framing; in practice the one extension is permessage-deflate (section 7).
Authentication is awkward by design. The handshake is the only moment HTTP headers exist, and the browser's new WebSocket(url) cannot set any. The options: a cookie (then check Origin); a short-lived single-use ticket fetched over HTTPS and passed in the URL (keep URLs out of logs, expire in seconds); or an authentication message as the first frame. Realtime LLM APIs use tickets: OpenAI's browser clients get an ephemeral client secret from your server, which created it with POST /v1/realtime/client_secrets (OpenAI Realtime guide), and Google recommends ephemeral tokens for client-side Gemini Live connections (Gemini Live API). Server-side clients send the API key in the handshake header as usual (Auth covers token audience and lifetime).
measured The client's message "Stop" went out as 10 bytes: 81 84 (FIN, text; MASK = 1, length 4), four bytes of masking key, and four XORed bytes. Seven messages of the running answer: 539 bytes of JSON plus 14 bytes of headers (2 per message). Pick any frame of the recorded session below.
measured The bits are the server's token "The": 81 53 then 83 bytes of JSON. Opcodes: 0 continuation, 1 text (UTF-8), 2 binary, 8 close, 9 ping, 10 pong; the rest unassigned (IANA registry). Length 0 to 125 fits in the 7 bits; 126 means the next 2 bytes hold it, 127 the next 8. RSV1 is set by permessage-deflate on compressed messages. A message may be split into fragments: the first carries the type, the rest are continuations, and only the last has FIN = 1.
Unmasking, byte by byte. The server recovers each payload byte by XOR with the masking key, cycling through its four bytes.
measured A client written on a bare TCP socket against the websockets 17.2 server, 5 October 2026 (src/lab/ws_bytes.py, raw src/raw/ws_bytes.json). Orange: client to server; blue: server to client.
The slider moves through 0, 1, 3, 83, 125, 126, 1,000, 65,535, 65,536 and 1,048,576 bytes; lengths up to 125 fit in 7 bits, up to 65,535 take 2 more bytes, larger ones 8 more (RFC 6455 section 5.2).
Why clients mask. Not for secrecy: the key travels in clear beside the data. In 2011, researchers showed that some proxies, seeing an upgraded connection they did not understand, could be fed attacker-chosen bytes that looked like a second HTTP request and would cache the "response", poisoning the cache for everyone behind them. A fresh random key per frame means a script in a browser cannot choose the bytes on the wire (RFC 6455 section 10.3). It costs one XOR pass over every byte a client sends; servers never mask, every client frame must be masked, and a wrong MASK bit must fail the connection.
Control frames. Ping, pong and close carry at most 125 bytes and are never fragmented, so they slip between the fragments of a long message. A ping is answered by a pong with the same bytes, the built-in heartbeat (measured: the client's ping "hb" came back as 8a 02 68 62). Browsers answer pings automatically, but JavaScript can neither send nor see one, so browser apps send their own heartbeat messages.
Closing. Each side sends a close frame with an optional 2-byte code and reason, the other echoes it, then TCP closes (measured: 1000 "bye", echoed). The code to know is 1006 Abnormal Closure: never sent, only reported locally when the connection died without a close frame: idle timeouts, crashes, network loss and, in browsers, every failed handshake whatever the reason. 1000 is the intended end, 1001 Going Away a server shutting down or a page left, 1008 and 1011 "not allowed" and "we broke", and 4000 to 4999 are yours.
Compression (RFC 7692, December 2015) deflates each payload and sets RSV1. By default the compressor's state carries from message to message (context takeover), ideal for near-identical JSON (the figure: about eight times smaller). The price is memory per connection, 64 KiB to 316 KiB, so about 6 GiB against 30 GiB at 100,000 connections; and compressing a secret beside attacker-controlled text re-opens CRIME-style attacks, where the compressed size leaks the secret. Do not compress audio or images.
measured The websockets library's own encoder on a long answer: the 357 words of RFC 6455 section 1.1 sent one word per message in the running answer's JSON shape. Memory per connection is the library's documented measurement (websockets: compression).
Compression, the numbers. measured the short running answer took 553 bytes uncompressed and 198 compressed; the long one 31,759, 3,937 with zlib's defaults, 4,250 with the library's smaller defaults and 25,278 with no context takeover. The price is memory per connection: about 14 KiB without compression, 64 KiB with the library's defaults (window 212, memLevel 5), 316 KiB with zlib's (window 215, memLevel 8), from zlib's formula of 2windowBits+2 + 2memLevel+9 bytes to compress and 2windowBits to decompress. At 100,000 connections that is about 6 GiB against 30 GiB (derived: 100,000 × 64 KiB and × 316 KiB). Compressing a secret beside attacker-controlled text in one context re-opens CRIME-style attacks, where the compressed size leaks the secret; and compressing audio or images wastes CPU.
| Field | Size | Meaning |
|---|---|---|
| FIN | 1 bit | 1 on the last frame of a message. |
| RSV1 to RSV3 | 3 bits | 0 unless an extension says otherwise. |
| Opcode | 4 bits | The frame type (see the figure's note). |
| MASK | 1 bit | 1 on every client frame, 0 on every server frame. |
| Payload length | 7, 7+16 or 7+64 bits | 126 and 127 are markers for the extended lengths. |
| Masking key | 0 or 4 bytes | Present only when MASK = 1; the payload is XORed with it, repeating. |
| Code | Meaning (IANA name) | What it usually means in practice |
|---|---|---|
| 1000 | Normal Closure | The intended end. |
| 1001 | Going Away | A server shutting down, or a browser leaving the page. |
| 1002, 1003, 1007 | Protocol error, Unsupported Data, Invalid frame payload data | A framing bug, binary sent where only text is accepted, text that is not UTF-8. |
| 1005 | No Status Rcvd | Never sent: reported locally when a close frame had no code. |
| 1006 | Abnormal Closure | Never sent: the connection died without any close frame. |
| 1008, 1011 | Policy Violation, Internal Error | "Not allowed" and "we broke". |
| 1009 | Message Too Big | A message above the receiver's limit (1 MiB by default in the websockets library, 17.2). |
| 1012, 1013, 1014 | Service Restart, Try Again Later, a bad gateway | Registered later with IANA; useful for draining a server during a deploy and for shedding load. |
| 4000 to 4999 | Reserved for Private Use | Your application's own codes. |
WebSockets over HTTP/2 and HTTP/3. The upgrade above exists only in HTTP/1.1. RFC 8441 (September 2018) carries a WebSocket as one stream of an HTTP/2 connection through an "extended CONNECT" request with :protocol: websocket, and RFC 9220 (June 2022) does the same for HTTP/3. Both are Proposed Standards; which browsers, proxies and servers implement them was not checked for this page, so the HTTP/1.1 upgrade remains the safe assumption, and a load balancer may speak HTTP/2 to the client and HTTP/1.1 upgrade to your server.
A WebSocket is a long-lived, stateful connection running through infrastructure built for short requests. Three things were broken on purpose here, through nginx 1.31.6 in front of the lab's websockets server, each seen by three clients.
proxy_http_version 1.1 (the default since nginx 1.29.7), nginx does not pass the hop-by-hop Upgrade and Connection unless told; the server sees a plain GET and answers 426 Upgrade Required. Fix: proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; (nginx: WebSocket proxying). JavaScript never sees the 426, only close code 1006: debug with the network panel or curl.proxy_read_timeout (60 s by default; 2 s here) and nginx closes both sides with no close frame: every client reports 1006, and nginx logs it only at info level, which the default error level hides. With the client pinging every second (the pong comes back from the server, so the proxy sees upstream bytes) the same quiet 6 s survived and all seven messages arrived.Origin: https://evil.example and sent all seven messages; with origins=["https://chat.example"] it answered 403.Numbers match the list on the left. measured through nginx 1.31.6.
| Failure | Python websockets 17.2 | Node ws | Chrome 148 |
|---|
measured src/lab/ws_proxy.py and ws_proxy_node.mjs; nginx_ws.conf.in has both proxy configurations. "Origin check" is the server refusing a page from another origin.
The fixes generalise. A heartbeat more frequent than the shortest idle timeout on the path: the websockets library pings every 20 s by default, and cloud load balancers and NAT gateways have their own limits (AWS's NAT gateway drops a connection idle for 350 s, Networking foundations, section 9); raise the proxy timeout for WebSocket routes too, but never rely on that alone. Check Origin against a list in the handshake (it protects browser users; other clients can send any Origin), prefer tickets to cookies, and re-check authorisation periodically, closing with 1008 when it lapses: the handshake authenticates once, and a socket can outlive a logout.
A notebook's kernel keeps "disconnecting" every 60 s when idle, but only through the company proxy. The browser console shows close code 1006. What is the most likely cause?
WebSocket.send() never blocks: it queues, and bufferedAmount says how much waits. A producer that ignores it fills memory on a slow network. WebSocketStream gives streams with automatic backpressure, but it is non-standard and, per MDN's compatibility data, shipped only in Chrome (since 124), not Firefox or Safari (MDN: WebSocketStream). Server libraries have their own limits (the websockets library queues at most 16 incoming messages by default, then stops reading, so TCP's flow control pushes back on the sender).ulimit -n; cap message size, message rate and connections per IP: the protocol itself has no limits, so an unlimited reader is a denial of service.A fine-tuning job runs for four hours: a stream held that long is fragile (Wikimedia cuts its streams at 15 minutes) and polling is wasteful. With a webhook you register a URL, and when something happens the provider POSTs a JSON description of the event to it. It is a convention on HTTP, not a protocol, and correctness lives in three rules both sides must follow; a community specification, Standard Webhooks, writes them down (spec, v1.0.0 December 2025; the parent topic's Protocol atlas checked its versions).
Rule 1: verify the signature, over the raw bytes. Your endpoint is public; anyone can POST to it. The provider signs each delivery with an HMAC-SHA256 under a secret it shared with you. Standard Webhooks signs id.timestamp.body and sends webhook-signature: v1,<base64>; Stripe signs timestamp.body; GitHub signs the body only, so it has no built-in replay protection (formats below). measured The same JSON re-serialised by json.loads and json.dumps failed verification, and a correctly signed message 10 minutes old was rejected (evidence below). So read the raw body before any framework parses it, compare with a constant-time function (hmac.compare_digest), and reject stale timestamps so a captured request cannot be replayed.
Rules 2 and 3: duplicates and disorder are normal. A provider retries any delivery that did not get a 2xx in time, with backoff over hours or days: Standard Webhooks' example schedule is immediately, then 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 20 h, 24 h (about 75 hours in all), and Stripe retries "for up to three days" in live mode. Delivery is therefore at least once (duplicates allowed, loss not): the same event arrives several times (a slow handler that finished after the sender gave up), and in any order (a retried early event lands after a later one). Stripe says both plainly: no order guarantee, and endpoints "might occasionally receive the same event more than once". Predict: two events, a receiver that does 1.5 s of work before answering a sender with a 1 s timeout; how many times does the work run?
measured src/lab/webhooks.py: a sender following Standard Webhooks' rules (its first four delays, scaled down 60 times, and a 1 s timeout) delivers job.running and, 20 ms later, job.succeeded for one fine-tuning job. The receiver answers the first attempt of job.running with 503 (a deploy in progress). The work takes 1.5 s. Fig. 9 runs the two receivers side by side, the provider between them: each arrow is one of the sender's attempts with the answer it got, and the notes count the finished work and the statuses it stored.
json.loads and json.dumps it failed ("No matching signature found"); a correctly signed message 10 minutes old failed too ("Message timestamp too old").job.running with 503. The careful receiver answered 200 within milliseconds to job.succeeded, and then to the retried job.running, queueing both; the naive receiver did the work before answering, so the sender, with its 1 s timeout, saw a failure.job.running finished. The careful worker finishes both events and writes the status as re-read from the source of truth: "succeeded", although job.running finished last.webhook-id and kept the right final status.measured src/lab/webhooks.py, raw src/raw/webhooks.json. Blue lines are the sender's attempts with the result it got; green lines are work done, orange are refusals.
The sender's side. Sending webhooks (an agent platform notifying customers, A2A push notifications) means making HTTP requests to URLs your users chose, from inside your network. Standard Webhooks tells senders to route them through a proxy that refuses internal addresses, or an attacker registers http://169.254.169.254/ and reads your cloud metadata (server-side request forgery, SSRF; the DNS page covers the rebinding variant). Sign every delivery, keep payloads small (the spec suggests under 20 KB), retry with jitter, and disable endpoints that fail for days, telling their owner another way. The outbox pattern that makes "update the database and send the webhook" reliable is on Queues, streams and async work; webhook API design on Service APIs (section 6).
Designing webhooks as part of your own API (signing, the retry schedule, event shapes, thin against snapshot events) is on Service APIs, section 6; this section is the receiver's and the sender's wire-level discipline. Inside your own infrastructure the same need is met by a queue or event bus (SNS, EventBridge, Pub/Sub, Kafka) with the same at-least-once discipline: a function triggered by a queue also sees duplicates. An ML engineer meets webhooks at the end of long jobs: fine-tuning, batch inference, evaluations, training runs on a managed platform.
measured GitHub's published test vector (secret "It's a Secret to Everybody", payload "Hello, World!") reproduced exactly with a three-line HMAC. With the standardwebhooks Python library and a made-up secret, the raw body verified; the same JSON after json.loads and json.dumps (which adds spaces after colons and commas) failed with "No matching signature found"; a correctly signed message 10 minutes old failed with "Message timestamp too old" (the library's tolerance is 5 minutes).
| Who | Header | What is signed |
|---|---|---|
| Standard Webhooks | webhook-id, webhook-timestamp, webhook-signature: v1,<base64> (several, space separated, during secret rotation) | id.timestamp.body; secret written whsec_<base64>, 24 to 64 random bytes |
| Stripe | Stripe-Signature: t=<unix time>,v1=<hex> | timestamp.body (Stripe webhooks); its libraries reject timestamps more than 5 minutes off |
| GitHub | X-Hub-Signature-256: sha256=<hex> | the body only (GitHub: validating deliveries) |
A voice agent streams audio both ways at once and must stop when the user speaks over it (barge-in), which rules out SSE and makes loss matter far more than for text. The realtime LLM APIs use a WebSocket from servers and WebRTC from browsers and phones: OpenAI's Realtime API connects over WebRTC "in the browser or WebSocket on the server" (Realtime guide, read 5 October 2026), and Google's Gemini Live API is a "stateful WebSocket connection (WSS)" with WebRTC through partners (Gemini Live API). Over a WebSocket the audio is raw PCM, base64 inside JSON events, and that sets the bit rate:
What WebRTC is for. A WebSocket rides on TCP, which delivers bytes in order: one lost packet on a phone's radio holds back every later byte until it is resent (head-of-line blocking, measured on HTTP/1.1, 2 and 3 in the parent topic's On the wire tab), so speech stalls, then bursts. WebRTC is the browser's real-time media stack: media over UDP with jitter buffers that skip a lost packet instead of waiting, a compressed codec instead of raw PCM, and the browser's echo cancellation. Hence the pattern OpenAI's docs recommend: WebRTC from the user's device, WebSocket between your server and the provider, where the network is clean and you already have raw audio.
OpenAI's Realtime API also documents telephony (SIP) integrations (WebSocket guide, read 5 October 2026). Over WebSocket, audio goes up inside JSON events (input_audio_buffer.append) as base64 of raw PCM: 16-bit mono at 24 kHz (default) or 16 kHz, or G.711 at 8 kHz; the same guide points to a separate full-duplex model, gpt-live-1, with its own WebSocket endpoint (wss://api.openai.com/v1/live/sessions). Gemini Live: input 16-bit PCM at 16 kHz, output 16-bit PCM at 24 kHz.
gRPC's four call types (unary, server streaming, client streaming, bidirectional) are one shape on the wire: a single HTTP/2 stream on which either side writes length-prefixed messages in DATA frames, so a streaming call costs no new connection and HTTP/2 flow control gives each stream its backpressure. Like SSE, the response starts with :status 200; the outcome travels last, in trailers ("Status must be sent in Trailers even if the status code is OK"), so a stream that fails halfway still had HTTP 200, and your metrics must read grpc-status. A client cancels with RST_STREAM CANCEL, mapped to call cancellation; a deadline travels as the grpc-timeout header ("If Timeout is omitted a server should assume an infinite timeout"). Browsers cannot read HTTP/2 trailers, so they speak gRPC-Web, which carries the status as the last message of the body ("Due to browser limitation, the Web client library implements a different protocol", PROTOCOL-WEB.md), normally through a translating proxy. gRPC as an API style (protobuf contracts, when to choose it over REST, load balancing long-lived HTTP/2 connections) is Service APIs's.
From gRPC's PROTOCOL-HTTP2.md (read 24 October 2026). Each message is a 1-byte compressed flag, a 4-byte big-endian length, then the bytes (usually protobuf).
WebTransport gives a web page what WebSockets cannot: several independent streams on one connection (a loss on one does not stall the others), unreliable datagrams for data useless if late (game state, live media), and QUIC's faster setup. It runs over HTTP/3 (draft-ietf-webtrans-http3, revision 16 of 6 July 2026, still a draft), using HTTP datagrams (RFC 9297) and QUIC datagrams (RFC 9221). MDN marks the browser API "Baseline 2026, newly available" since March 2026: Chrome 97, Firefox 114, Safari 26.4 (MDN: WebTransport API, compatibility data checked 5 October 2026). Networks that block UDP need a WebSocket fallback, server and proxy support is thinner than for HTTP/1.1 and 2, and for an LLM text stream it adds nothing over SSE.
A different use of a WebSocket: the client subscribes to a query and the server keeps a local copy of the results up to date. Meteor's Distributed Data Protocol (DDP, about 2012) is the early, documented example (DDP specification): over WebSockets or SockJS, the client sends sub, and the server sends added, changed and removed messages for documents, then ready; the same connection carries method calls with their result and updated messages. Two ideas outlived it: the server tracks what each client has and sends differences, not snapshots; and the client applies a method's effect immediately and reconciles when the answer arrives (latency compensation). Live-query features in Firebase, Supabase Realtime and Phoenix LiveView are the same shape. (In ML, "DDP" means PyTorch's DistributedDataParallel, unrelated: Distributed training.)
| You need | Use | Why not the others |
|---|---|---|
| LLM tokens to a browser or another service | SSE on a POST response (fetch plus a parser) | One direction is enough, and it keeps HTTP: headers and a JSON body, status codes, retries, proxies, HTTP/2 multiplexing. A WebSocket adds a stateful connection to balance and keep alive and loses all of that; polling adds latency |
| Progress of a short job, then its result (seconds to minutes) | SSE | Webhooks need a public endpoint; polling is fine if latency does not matter |
| "Tell me when it finishes" (minutes to days) | Webhook, or polling a status URL | A connection held for hours will be cut |
| A live feed many clients watch, resumable | SSE with ids over a durable log | WebSockets have no resume built in |
| The user interrupts while the agent speaks; collaborative editing; games | WebSocket (WebTransport where you control both ends) | SSE plus a side POST works but splits ordering across two channels |
| Voice from a phone or browser | WebRTC to the device, WebSocket server to provider | TCP stalls audio on loss |
| A hostile network where nothing long-lived survives | Long polling | It is the only one that looks like ordinary requests |
| Streams between your own services | gRPC server, client or bidirectional streaming | Typed messages, per-stream flow control and cancellation on one HTTP/2 connection (section 10; the API style is Service APIs's) |
Most stream bugs are one of a dozen symptoms, each taught in a section above; the table maps symptom to first check. The first move is always the same: curl -N against each hop in turn, timing each event, and for a WebSocket a curl or websocat handshake through the proxy.
| Symptom | First check | Usual cause and fix |
|---|---|---|
| Tokens arrive all at once at the end | curl -N straight at the model server, then through each hop, timing each event | A hop buffers or compresses: proxy_buffering off or X-Accel-Buffering: no, no gzip on event streams (Failure lab: "A buffering proxy delays tokens") |
| Tokens arrive in small clumps, one clump per round trip | TCP_NODELAY on the server socket; is it long polling? | Nagle's algorithm (Networking foundations section 7), or long polling's extra round trip (section 1) |
| Long answers die at a round number of seconds | Which hop has that timeout; does the failure need silence (think time) or only length? | Idle timeout: heartbeat comments and a longer timeout. Total timeout: raise it or go asynchronous (HTTP sections 8 and 10; Failure lab: "Idle timeout cuts an SSE stream mid-answer") |
| Answer shown twice after a network blip | Does the stream carry id:? What Last-Event-ID did the reconnect send? | EventSource replayed from the start: number events and resume, or clear the partial answer on reconnect (section 5) |
| The browser keeps reconnecting after a finished answer | Network panel: repeated requests every few seconds | EventSource treats an ended stream as dropped: close it on the final event, or answer the reconnect with 204 |
| A browser handler never fires, but curl shows events | Does the stream use event: names? | onmessage only sees untyped events: addEventListener('name', ...) |
| The page hangs while streams are open | Protocol column in the network panel: http/1.1? | Six connections per host (section 3): serve over HTTP/2, or share one stream per tab |
| GPU busy after users press Stop | Server log: work time after client disconnect | Watch for disconnect during prefill and queueing, not only on write (section 5) |
| WebSocket closes with 1006 | Is the interval a round number? Does the server log a close? | Idle timeout or a crash: heartbeat below the shortest idle timeout; nginx logs the timeout only at info (section 8) |
| Handshake fails behind a proxy; the browser only says 1006 | curl -si -H "Upgrade: websocket" -H "Connection: Upgrade" ... through the proxy, or websocat | Upgrade headers not passed (426 or 400), or the Origin check refused it (403) |
| Webhook signature fails although the secret is right | Compute the HMAC over the bytes exactly as received | The framework parsed and re-serialised the body; use the raw body (section 9) |
| A webhook's work runs twice; status goes backwards | Deliveries per webhook-id; handler duration against the sender's timeout | Dedupe on id, answer first and work from a queue, re-read the state instead of trusting order |
data (append plus newline), event (set type), id (set last id unless it contains NUL), retry (set delay if all digits); ignore other fields. At end of stream, discard an undispatched event.Last-Event-ID (or a query parameter for fetch clients) and sends events with id: lines. Then any server instance can serve a reconnect, the work is neither repeated nor lost, and a final event plus a 204 on later reconnects ends it cleanly. Cost: storage, and a cancellation path, since a disconnect no longer stops the job by itself.with_cancellation does with ASGI http.disconnect, and make sure proxies propagate the close.proxy_read_timeout defaults to 60 s, many load balancers default to similar values. Confirm by sending traffic (pings) and seeing whether the drops stop, and by checking the proxy's log at info level. Fix with application or protocol pings well under the shortest idle timeout, raise the timeout for the WebSocket route, and make clients reconnect with backoff and jitter.Origin header against an allow-list in the handshake, preferring short-lived tickets over cookies, setting SameSite on cookies, and re-authorising long-lived sockets.This page replaces two old written pages, "Real-time and event delivery: WebSockets, SSE, webhooks, long polling" and "WebSocket protocol (RFC 6455) in depth" (both last edited 2026-09-22, kept verbatim in the parent topic's src/read/old/). Every fact was checked; src/coverage.json lists where each one lives now. Corrections and changes:
gpt-live-1, with its own WebSocket endpoint. The date, the price and the transports other than WebSocket were not confirmed and are not stated.websockets library's own measurements, which also show its default settings use 64 KiB.data: [DONE] sentinel (unconfirmed on the parent topic): confirmed in the OpenAI Python SDK and in vLLM's OpenAI-compatible server source.sub, added, changed, removed, ready, method, result, updated); "minimongo" and the list of modern sync engines are kept only as names.The whole stack on one request. Tabs: On the wire, Failure lab (including "A buffering proxy delays tokens" and "Idle timeout cuts an SSE stream mid-answer"), Protocol atlas (SSE, WebSockets, webhooks checked against their specs). 33 min plus tabs
What SSE rides on: semantics, chunked encoding and DATA frames, proxies, the timeout chain, retries. 45 min
Nagle and token clumping (section 7), idle connections and NAT (section 9), QUIC. 49 min
Why wss:// and https:// streams pass through middleboxes intact. 45 min
DNS rebinding and SSRF, which webhook senders must defend against. 45 min
API keys, tokens, audiences: what the WebSocket ticket and webhook secret patterns build on. 42 min
Streamable HTTP: JSON or an SSE stream per request, resumability removed in 2026-07-28. 37 min
A2A task updates by SSE streaming, polling or push notifications. 39 min
gRPC's streaming modes between services. 52 min
Sibling reading times are each page's Reading tab, without its labs.
What the think before the first token is made of: queueing, prefill, decode; server-side TTFT. see its header
Builds an SSE client on fetch and feeds it reads that split events mid-line. 14 min
At-least-once delivery, the outbox pattern, Kafka: the machinery behind reliable webhooks and resumable streams. 40 min
Designing webhook payloads, long-running operations and status endpoints. 32 min
The format, the parser algorithm, EventSource. Short and readable. 25 min
Read sections 1.3 (handshake), 5 (framing), 7 (closing) and 10 (security). 1 h 45 min
permessage-deflate and its window and context parameters. 40 min
The known issues of the pre-WebSocket techniques. 35 min
Headers, signatures, retries, status handling, SSRF advice for senders. 25 min
Length-prefixed messages, trailers, status codes, timeouts and RST_STREAM mapping; PROTOCOL-WEB.md beside it for gRPC-Web. 20 min
The protocol under the WebTransport browser API. 1 h
The browser side, with examples. 20 min
The browser API and its limits. 30 min
Ilya Grigorik's chapter on framing, deployment and performance; the SSE chapter is next to it. 45 min
Every event type, with tool use and thinking. 20 min
Audio over WebSocket events, formats, when to use WebRTC instead. 25 min
A stateful WebSocket voice API, ephemeral tokens. 20 min
Measured memory and compression per setting. The library's deployment and keepalive topics are worth the same time. 15 min
The upgrade headers and the read timeout. 5 min
A mature provider's rules on signatures, retries, order and duplicates. 30 min
The attack, with a lab. 20 min
A public, resumable SSE service over Kafka; try it with curl. 15 min
The early sync-engine protocol over WebSockets. 20 min
Python: websockets (asyncio; used here), httpx with httpx-sse, aiohttp. Node: ws, eventsource-parser, eventsource; Socket.IO is its own protocol on top, with fallbacks. Go: coder/websocket, gorilla/websocket. Rust: tokio-tungstenite. Command line: curl -N for SSE, websocat for WebSockets. Conformance: the Autobahn TestSuite (20 min for its README and reports).