WebSocket: upgrade, frames and backpressure
A WebSocket starts as HTTP and becomes a two-way message channel. Learn the handshake, the frame format and its masking, and the operational traps of stateful connections.
A WebSocket begins as an ordinary HTTP/1.1 GET with Upgrade: websocket and a random Sec-WebSocket-Key. The server proves it understood by hashing that key with a fixed GUID and returning the result in Sec-WebSocket-Accept, with status 101 Switching Protocols. From then on, the TCP connection carries WebSocket frames, not HTTP.
GET /realtime HTTP/1.1
Host: api.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=The frame
Anatomy of a WebSocket frame
| Bytes | Hex | Meaning |
|---|---|---|
| 0–1 | 81 82 | FIN + text opcode; mask bit + length 2 |
| 2–5 | 37 FA 21 3D | Masking key, random per frame |
| 6–7 | 7F 93 | “Hi” (48 69) XOR the key’s first two bytes |
Payloads of 126 bytes or more use a 2-byte or 8-byte extended length after the first two bytes. Server-to-client frames carry no mask.
| Opcode | Frame |
|---|---|
| 0x1 | Text (UTF-8) |
| 0x2 | Binary |
| 0x0 | Continuation of a fragmented message |
| 0x8 | Close |
| 0x9 / 0xA | Ping / Pong |
Unlike TCP, WebSocket preserves message boundaries: a message sent is a message received, though it may be split into several frames. Ping and pong frames give a built-in heartbeat for the idle-timeout problem from Module 4.
Go deeperWhy clients mask their frames
Every client-to-server frame is XORed with a random 4-byte key. It is not encryption: the key is in the frame. It defends intermediaries. Researchers showed that an attacker controlling the bytes a browser sends could craft data that a naive transparent proxy would interpret as a separate HTTP request, poisoning its cache.
Masking with a key the attacker's script cannot predict makes the bytes on the wire unpredictable, so they cannot be shaped into a valid HTTP request. Servers must reject unmasked client frames.
Operational traps
- Stateful load balancing. A WebSocket pins a client to one server for hours. Deploys must drain connections gracefully, and load spreads unevenly as old connections stay on old servers.
- No backpressure in the basic browser API.
socket.send()never blocks; data piles up inbufferedAmount. Check it and pause your producer, or use the newerWebSocketStreamwhere available. - Reconnection is yours. After a drop, the client must reconnect with backoff, re-authenticate and resynchronise state. Nothing is replayed automatically.
- Proxies and timeouts. Some corporate proxies break the upgrade; idle timeouts kill quiet sockets unless you ping.
const MAX_BUFFERED = 1 << 20; // 1 MiB
async function sendAll(socket: WebSocket, chunks: AsyncIterable<string>) {
for await (const chunk of chunks) {
while (socket.bufferedAmount > MAX_BUFFERED) {
await new Promise((resolve) => setTimeout(resolve, 20)); // let the network drain
}
socket.send(chunk);
}
}Polling bufferedAmount is crude but effective. On the server, Node's ws library exposes the socket's backpressure through its callback and stream APIs.
Where you will meet it
Voice agent APIs stream audio frames both ways over WebSocket, with ping frames keeping the connection alive through silences.
Editors send operations both ways and resynchronise from a version number after reconnecting.
Teams running WebSocket servers send a close frame with a “going away” code during deploys so clients reconnect to new instances.
Words to know
- Upgrade
- Switching an HTTP/1.1 connection to another protocol with 101 Switching Protocols.
- Opcode
- The frame type field: text, binary, close, ping, pong or continuation.
- Masking
- XORing client payloads with a random key to protect intermediaries.
- bufferedAmount
- Bytes queued by
send()but not yet transmitted.
Check yourself
Answer out loud before you open each one.
Why must clients mask frames?
To stop attacker-controlled bytes from being misread as HTTP requests by intermediary proxies.
Does WebSocket preserve message boundaries?
Yes. Messages may be fragmented into frames, but the receiver reassembles whole messages.
Why is load balancing WebSockets harder than HTTP?
Each connection is long-lived and stateful, so it pins a client to one server and load rebalances only as connections close.
Try it
In a browser console, open new WebSocket("wss://echo.websocket.org") (or any echo server), send 10 MB in a tight loop and watch bufferedAmount grow.