Chapters

WebSockets

Kadé wants live order tracking: the shopper's app should show the rider moving on the map and the status changing the moment it happens. Plain HTTP cannot push anything to the app. This chapter covers the options, then WebSockets in depth: the handshake, the frames, and what it takes to run them in production.

Application protocols · chapter 26 of 34 · 8 min read

The problem: HTTP only answers

In classic HTTP the client must start everything (chapter 24). To get updates, apps resort to polling: asking "anything new?" over and over. It is wasteful and laggy. Most requests return nothing, and a real update waits until the next poll.

10,000 shoppers tracking orderspolling every 5 s = 2,000 requests per second to kade-api
Each request~700 bytes of headers (cookies, tokens) for a reply that is usually "no change"
A status changeseen 0-5 s late, 2.5 s on average

Four ways to get updates

#TechniqueHow it worksDirectionDelay
1Short pollingAsk every N secondsclient asksup to N seconds
2Long pollingAsk, and the server holds the request open until there is news (or a timeout), then the client asks again at onceclient asksabout half a round trip, plus a gap after each message
3Server-Sent Events (SSE)One HTTP response that never ends; the server writes events into it as they happenserver → client onlyabout half a round trip
4WebSocketOne long-lived connection where both sides send messages whenever they wantboth ways, at any timeabout half a round trip

Watch them side by side for one minute of order tracking. Stars are updates happening on kade-api; the bars show when each app learns about them:

Short polling (5 s)Long pollingServer-Sent EventsWebSocket↑ chat↑ chat0 s10 s20 s30 s40 s50 s60 s
  • diamond = update happens on kade-api
  • bar = how long the app waits to learn it
  • dot = delivered at once
  • grey tick = request that came back empty
  • ↑ = message from the app (WebSocket only)
TechniqueRequestsEmpty repliesAvg delayOverhead
Short polling (5 s)1383.0 s~700 B per request
Long polling6021 ms~700 B per request
Server-Sent Events1021 ms2-8 B per message
WebSocket1021 ms2-8 B per message

Per app, per minute, with a 41 ms round trip. Multiply the requests by 10,000 shoppers to see the load on kade-api.

What a WebSocket is

A WebSocket is a single, long-lived TCP connection that stays open and allows full-duplex communication: client and server can both send messages at any time, independently. No repeated requests, no waiting for a poll. Addresses use ws:// or, over TLS, wss:// (ports 80 and 443). Always use wss: it is encrypted, and it passes through proxies and firewalls much more reliably.

The handshake: an HTTP request that upgrades

A WebSocket begins life as a normal HTTP/1.1 request asking to upgrade. If the server agrees, it replies 101 Switching Protocols, and from that moment the same TCP connection speaks WebSocket instead of HTTP. Starting as HTTP means it works through existing web infrastructure: port 443, TLS, load balancers, cookies.

Request (from the app)

GET /track/1042 HTTP/1.1
Host: api.kade.lk
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://kade.lk
Cookie: sid=8f2a91c

Response (from kade-api)

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After the blank line, no more HTTP on this connection: only WebSocket frames.

Upgrade / Connection"Please switch this connection to the websocket protocol"
Sec-WebSocket-KeyA random 16-byte value (base64) from the client
Sec-WebSocket-Acceptbase64(SHA-1(key + a fixed GUID from the standard)). It proves the server really understands WebSockets, so a confused server or a caching proxy cannot accidentally "accept". It is not a security feature.
OriginWhich website opened it. The server must check it (section 10).
Sec-WebSocket-Protocol(optional) a sub-protocol both sides agree on, e.g. a message format version
Shopper appkade-apiTCP and TLS handshakes first (chapters 16 and 25)GET /track/1042 · Upgrade: websocket101 Switching Protocolsthe same TCP connection is now a WebSocketframe: {"track":1042}frame: {"status":"packing"}frame: {"rider":[6.912,79.861]}no request needed: the server just sends

After the upgrade: frames

Messages travel as frames with a tiny header of 2 to 14 bytes, compared with hundreds of bytes of headers on every HTTP request:

bit →08162431bytes 0-3FIN1RSV3Opcode4M1Payload len7Extended length (if 126 or 127)16 or 64 bitsnext 4Masking key (client → server frames only)32 bitsthenPayload: your messagetext or binary

A small server → client message needs only the first 2 bytes of header. A client message adds the 4-byte mask. Long messages add 2 or 8 bytes of length.

FIN1 = last frame of this message (big messages can be split into several frames)
Opcode1 text (UTF-8) · 2 binary · 0 continuation · 8 close · 9 ping · 10 pong
MASK + masking keyEvery client → server frame must be XOR-masked with a random 4-byte key. This stops a malicious page from making the browser send bytes that look like an HTTP request to a proxy in between (cache poisoning). Server → client frames are not masked.
Payload length7 bits (up to 125), or 126 + 2 more bytes, or 127 + 8 more bytes

A real frame: the shopper's app sends {"track":1042} (14 bytes) to subscribe to its order. 20 bytes on the wire in total:

000081FIN+text8eM+len 1437mask keyfa213d4c→ {d8→ "55→ t4f→ r56→ a99→ c4a→ k1f→ "0d→ :cb→ 1
001611→ 009→ 405→ 287→ }

Byte 0 = 81: FIN = 1 and opcode 1 (text). Byte 1 = 8e: MASK = 1 and length 14 (0x0e). Then the 4-byte masking key 37 fa 21 3d. Each payload byte is XORed with the key in turn; the small labels show the decoded characters: {"track":1042}. Only 6 bytes of overhead.

Full duplex in practice

Once open, either side sends whenever it wants. On one order-tracking connection:

Shopper appkade-api{"status":"out for delivery"}{"rider":[6.905,79.858]}{"chat":"please ring the bell"}the app sends whenever it wants, too{"rider":[6.908,79.860]}pingpongkeeps NAT and load balancers from forgetting the connection{"status":"delivered"}close (1000, normal)close (1000)then the TCP FIN exchange

Where this fits, with Kadé examples:

#UseWhy a WebSocketKadé example
1ChatMessages flow both ways, instantlyShopper ↔ support chat
2Live dashboards and notificationsThe server pushes the moment something changesThe warehouse packing screen showing new orders
3Positions and presenceFrequent small updates, both directionsThe rider's app sending GPS; the shopper's app receiving it
4Collaborative editing, multiplayer gamesMany small edits from many people, merged live-

Keeping connections alive

A WebSocket that sends nothing for a while meets every idle timeout from chapter 21: home and mobile NAT, firewalls, the load balancer. The protocol has ping and pong frames for this: one side pings, the other must pong. A ping every 20-30 seconds keeps middleboxes from forgetting the connection, and a missing pong tells the server the client is gone (a phone that lost signal never sends a close frame).

Reconnecting

WebSockets will drop: the rider's phone changes network, kade-api is redeployed, the load balancer cuts a long connection. The client must handle it:

  • Reconnect with backoff and jitter: wait 1 s, 2 s, 4 s … up to a limit, plus a random extra. Otherwise, when kade-api restarts, all 10,000 apps reconnect in the same second (a "thundering herd").
  • Catch up after reconnecting: messages sent while disconnected are simply lost. The app should re-fetch the current order state, or send the last event ID it saw so the server can replay what was missed.
  • Drain gracefully on deploy: tell clients to reconnect (close code 1001 "going away"), rather than killing them all at once.
function connect(attempt = 0) {
  const ws = new WebSocket('wss://api.kade.lk/track/1042');
  ws.onopen = () => { attempt = 0; refreshOrderState(); };    // catch up on what was missed
  ws.onmessage = (e) => render(JSON.parse(e.data));
  ws.onclose = () => {
    const wait = Math.min(30_000, 1000 * 2 ** attempt) + Math.random() * 1000;
    setTimeout(() => connect(attempt + 1), wait);             // backoff + jitter
  };
}

Scaling: connections are stateful

An HTTP request can go to any kade-api instance. A WebSocket is pinned to the instance that accepted it, for as long as it lives. When Kadé runs two instances, the rider's location may arrive at instance A while the shopper watching that order is connected to instance B:

Rider's appsends GPSShopper's appwatching order 1042kade-api · Aholds the rider's socketkade-api · Bholds the shopper's socketPub/sub channel "order:1042"Redis, or GCP Pub/Subpublishdeliverpush

Wide by design - scroll it sideways.

  • A shared message channel (pub/sub) lets any instance publish, and every instance holding interested sockets deliver.
  • Memory per connection: each open socket costs buffers and app state, often tens of KB. 10,000 idle trackers is fine for one Node instance; plan capacity by open connections, not requests per second.
  • File descriptor limits: every socket is an open file; raise the OS limit (ulimit -n) on busy servers.

Security

#RiskWhat to do
1Anyone connectingAuthenticate during the handshake. Gotcha: the browser's WebSocket API cannot set custom headers, so no Authorization: Bearer. Use the session cookie, or a short-lived ticket in the URL or in the first message.
2Cross-site WebSocket hijackingA malicious site can open a WebSocket to api.kade.lk and the browser attaches Kadé's cookie. CORS does not protect WebSockets. The server must check the Origin header against its own sites.
3Bad or huge messagesValidate every message; set a maximum message size; rate-limit per connection
4Eavesdroppingwss only (TLS, chapter 25)
5Long-lived sessionsA token checked once at connect may expire while the socket stays open. Re-check periodically, or close sockets when the session ends.

WebSocket, SSE or polling?

#NeedGood choiceWhy
1Server → client only (order status, notifications)SSEPlain HTTP, works over HTTP/2 and 3, automatic reconnect with last-event-ID built into the browser's EventSource, easy through proxies. Text only.
2Both directions, often (chat, rider GPS in and out)WebSocketFull duplex, tiny frames, binary allowed
3Rare updates, simple setup, or behind strict proxiesPolling (short or long)Stateless, works everywhere, nothing to keep alive
4Server → another serverWebhooksPayGate calls a Kadé URL when a payment settles: an HTTP POST, not a held connection
The classic WebSocket runs on its own HTTP/1.1 connection. Newer standards can carry WebSockets inside HTTP/2 and HTTP/3 streams, and WebTransport (on QUIC) is emerging for low-latency apps.

Summary

#IdeaIn one lineNew terms
1-2The problemHTTP cannot push; polling is wasteful and lateshort polling, long polling, SSE
3WebSocketOne long-lived, full-duplex connection; ws:// and wss://WebSocket, full duplex
4HandshakeHTTP Upgrade → 101 Switching Protocols; Key/AcceptUpgrade, 101
5Frames2-14 byte header; opcodes; client frames maskedframe, opcode, masking
7-8OperationsPing/pong through idle timeouts; reconnect with backoff, jitter and catch-upping/pong, thundering herd
9ScalingSockets are pinned; pub/sub between instances; plan by connectionspub/sub
10SecurityAuth at handshake (no custom headers in browsers); check Origincross-site WebSocket hijacking
11ChoosingSSE for one-way, WebSocket for two-way, polling for rare, webhooks for serverswebhook

Try it yourself

The handshake and every message

An interactive WebSocket client

npx wscat -c wss://your-server/path

Just the handshake

curl -i -N -H 'Connection: Upgrade' -H 'Upgrade: websocket' -H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' https://your-server/path

How many sockets are open

ss -tn state established '( sport = :443 )' | wc -l

Max open files for the process

ulimit -n

Spotted a mistake, or something unclear? Suggest an edit on GitHub