Workspace

WebSocket: upgrade, frames and backpressure

3 day streakD

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.

DepthLesson 3 of 618 min

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.

upgrade.txtText
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

Figure 3.1

Anatomy of a WebSocket frame

Client sends the text message “Hi”
1FINlast fragment
000RSV1–3extensions
0001opcodetext
1MASKclient frame
0000010length2 bytes
BytesHexMeaning
0–181 82FIN + text opcode; mask bit + length 2
2–537 FA 21 3DMasking key, random per frame
6–77F 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.

Two bytes of header carry the final-fragment flag, the opcode, the mask bit and a 7-bit length. Longer payloads add 2 or 8 bytes of extended length. Client frames add a 4-byte masking key, and the payload is XORed with it.
OpcodeFrame
0x1Text (UTF-8)
0x2Binary
0x0Continuation of a fragmented message
0x8Close
0x9 / 0xAPing / 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 in bufferedAmount. Check it and pause your producer, or use the newer WebSocketStream where 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.
ws-backpressure.tsTypeScript
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

Realtime voice

Voice agent APIs stream audio frames both ways over WebSocket, with ping frames keeping the connection alive through silences.

Collaborative editors

Editors send operations both ways and resynchronise from a version number after reconnecting.

Deploys

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.

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap