WebSockets and server-sent events
HTTP lets the server answer, never speak first, yet chat messages and live comments appear the instant they are sent. Here is how: a connection kept open, either as a response that never ends or as a socket upgraded from HTTP, drawn message by message.
01 HTTP only ever answers
A chat or a live comment feed needs the server to say "something happened" the moment it happens. Plain HTTP cannot do that: the client sends a request, the server sends one response, and the exchange is over. The server has no way to start a conversation.
The first workaround is polling: ask again every few seconds.
- nothing new
- news, late
Two of three round trips carried nothing, and comment 42 waited up to one full interval before anyone asked for it.
Long polling improves on it: the server holds each request open until it has news (or a timeout passes), answers, and the client immediately asks again. Latency drops, but every message still costs a fresh request with full headers. The real fix is to keep one connection open and let the server write to it whenever it likes. There are two standard ways.
02 Server-sent events: a response that never ends
Server-sent events (SSE) is the smaller idea. The browser makes one normal GET, and the server sends headers and then keeps the response body open, writing a short text block each time there is news. The browser’s EventSource object reads those blocks and fires an event for each.
- just sent
- just changed
- lost
The page runs new EventSource('/events'). Nothing has been sent yet, and the object starts in state 0, CONNECTING.
On the wire an event is just lines of text, ended by a blank line. data: is the payload, id: is what the browser echoes back in Last-Event-ID, event: gives it a name, and retry: sets the reconnect delay in milliseconds. A line starting with : is a comment, which servers send as a heartbeat.
The browser only sends Last-Event-ID. Resuming is your job: the server has to keep recent events (in memory, Redis or the database) and replay everything after that id. If it ignores the header, every reconnect silently loses whatever was sent during the gap.
03 WebSocket: a request that becomes a socket
SSE only goes one way: the server talks, the client listens, and anything the client says still goes as a separate HTTP request. A WebSocket gives both sides a channel. It starts as an HTTP/1.1 request that asks to switch protocols; once the server agrees, the same TCP connection carries WebSocket frames in both directions until one side closes it.
- just sent
- just changed
The page runs new WebSocket('wss://chat.example.com/chat'). The TCP and TLS connection opens as for any HTTPS request; no HTTP has been sent yet.
The Sec-WebSocket-Accept value proves the server really speaks WebSocket and is not an HTTP server that happened to echo headers. It is the Base64 of the SHA-1 of the client’s key joined to a fixed string from the spec, RFC 6455:
This is a handshake check, not security. Authentication still comes from a cookie or a token sent with the upgrade request, and the browser adds an Origin header the server should check, because cross-site pages can open WebSockets too.
04 What a frame looks like
After the upgrade, every message travels as one or more frames. A frame header is at least 2 bytes, so a small message costs a few bytes of overhead instead of a full set of HTTP headers.
Byte 0: the top bit is FIN (this is the last piece of the message) and the low four bits are the opcode, 1 for text. Byte 1: the top bit is MASK (set on every client frame) and the low seven bits are the payload length, 2. Four bytes of masking key and the two masked bytes of hi follow.
| Opcode | Frame | Used for |
|---|---|---|
| 0x1 | text | A UTF-8 message, e.g. JSON |
| 0x2 | binary | Raw bytes, e.g. audio or a compact encoding |
| 0x0 | continuation | The next piece of a message split over several frames |
| 0x8 | close | Ending the connection, with a code such as 1000 |
| 0x9 / 0xA | ping / pong | Checking the connection is alive |
Lengths up to 125 fit in byte 1. A length of 126 there means the real length follows in the next 2 bytes, and 127 means the next 8. Client frames are masked: XORed with a random 4-byte key carried in the frame. That is not encryption (the key is right there); it stops a page from writing bytes that a confused proxy on the path might read as an HTTP request. Server frames are not masked.
05 Watch both from a terminal
This server uses only Node’s built-in modules. /events streams three SSE events a second apart and honours Last-Event-ID. An upgrade request gets the 101 handshake, one text frame (hi) and a close frame, written as raw bytes so you can see there is no magic.
Run node server.js, then in a second terminal stream the events. -N turns off curl’s buffering, so each event prints the moment it arrives:
Now send an upgrade request by hand, using the example key from the RFC. curl prints the 101 response; the frame bytes that follow show up as a couple of odd characters and hi.
Finally a real client. Node 22 and later ship the same WebSocket class as browsers:
These outputs are from real runs on Node 24 with curl 8.7. If you remove the close frame from the server, the client prints closed, code 1006: the connection ended without a close handshake, which is what you see when a network drops.
06 SSE or WebSocket?
| Question | Server-sent events | WebSocket |
|---|---|---|
| Direction | Server to client only | Both ways |
| Data | UTF-8 text | Text or binary |
| Protocol | Plain HTTP response | Its own framing after an HTTP upgrade |
| Reconnect | Built in, with Last-Event-ID | Write it yourself |
| Custom headers from the browser | No (cookies only) | No (cookies, or a token in the URL or first message) |
| Through proxies and HTTP/2 | Usually just works | Needs upgrade support on every proxy |
Pick SSE when the server mostly talks and the client mostly listens: live comments, notifications, progress bars, a stream of tokens from a language model. Pick a WebSocket when both sides send often and with low latency: chat with typing indicators, multiplayer games, collaborative editing.
07 When it bites
proxy_read_timeout 60sIdle connections get cutLoad balancers and proxies close connections that stay quiet; nginx’s default read timeout is 60 seconds. Send a heartbeat (an SSE comment or a WebSocket ping) more often than the shortest timeout on the path.X-Accel-Buffering: noA proxy buffers the streamA buffering proxy holds SSE events until it has a full buffer, so they arrive in bursts or not at all. Turn buffering off for the stream route, and avoid compressing it.6 per hostSSE over HTTP/1.1 runs out of connectionsBrowsers allow about 6 HTTP/1.1 connections per host, and each open EventSource keeps one. Several tabs can block the rest of the site. HTTP/2 carries all of them on one connection.user A on server 1, B on server 2Each connection lives on one serverA message posted on server 2 must reach the socket held by server 1. Add a pub/sub layer, such as Redis pub/sub, so every server hears every message.deploy → 50,000 reconnectsReconnect stormsWhen a server restarts, every client reconnects at once. Add random jitter to the reconnect delay (SSE’s retry: only sets a fixed value, so add jitter on the server side or in your own WebSocket client).A WebSocket has no built-in resume. If the connection drops, frames sent during the gap are simply gone. Give messages ids and let a reconnecting client ask for everything after the last id it saw, just as SSE does with Last-Event-ID.