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 orders | polling 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 change | seen 0-5 s late, 2.5 s on average |
Four ways to get updates
| # | Technique | How it works | Direction | Delay |
|---|---|---|---|---|
| 1 | Short polling | Ask every N seconds | client asks | up to N seconds |
| 2 | Long polling | Ask, and the server holds the request open until there is news (or a timeout), then the client asks again at once | client asks | about half a round trip, plus a gap after each message |
| 3 | Server-Sent Events (SSE) | One HTTP response that never ends; the server writes events into it as they happen | server → client only | about half a round trip |
| 4 | WebSocket | One long-lived connection where both sides send messages whenever they want | both ways, at any time | about 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:
- 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)
| Technique | Requests | Empty replies | Avg delay | Overhead |
|---|---|---|---|---|
| Short polling (5 s) | 13 | 8 | 3.0 s | ~700 B per request |
| Long polling | 6 | 0 | 21 ms | ~700 B per request |
| Server-Sent Events | 1 | 0 | 21 ms | 2-8 B per message |
| WebSocket | 1 | 0 | 21 ms | 2-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-Key | A random 16-byte value (base64) from the client |
| Sec-WebSocket-Accept | base64(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. |
| Origin | Which 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 |
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:
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.
| FIN | 1 = last frame of this message (big messages can be split into several frames) |
| Opcode | 1 text (UTF-8) · 2 binary · 0 continuation · 8 close · 9 ping · 10 pong |
| MASK + masking key | Every 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 length | 7 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:
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:
Where this fits, with Kadé examples:
| # | Use | Why a WebSocket | Kadé example |
|---|---|---|---|
| 1 | Chat | Messages flow both ways, instantly | Shopper ↔ support chat |
| 2 | Live dashboards and notifications | The server pushes the moment something changes | The warehouse packing screen showing new orders |
| 3 | Positions and presence | Frequent small updates, both directions | The rider's app sending GPS; the shopper's app receiving it |
| 4 | Collaborative editing, multiplayer games | Many 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:
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
| # | Risk | What to do |
|---|---|---|
| 1 | Anyone connecting | Authenticate 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. |
| 2 | Cross-site WebSocket hijacking | A 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. |
| 3 | Bad or huge messages | Validate every message; set a maximum message size; rate-limit per connection |
| 4 | Eavesdropping | wss only (TLS, chapter 25) |
| 5 | Long-lived sessions | A 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?
| # | Need | Good choice | Why |
|---|---|---|---|
| 1 | Server → client only (order status, notifications) | SSE | Plain HTTP, works over HTTP/2 and 3, automatic reconnect with last-event-ID built into the browser's EventSource, easy through proxies. Text only. |
| 2 | Both directions, often (chat, rider GPS in and out) | WebSocket | Full duplex, tiny frames, binary allowed |
| 3 | Rare updates, simple setup, or behind strict proxies | Polling (short or long) | Stateless, works everywhere, nothing to keep alive |
| 4 | Server → another server | Webhooks | PayGate calls a Kadé URL when a payment settles: an HTTP POST, not a held connection |
Summary
| # | Idea | In one line | New terms |
|---|---|---|---|
| 1-2 | The problem | HTTP cannot push; polling is wasteful and late | short polling, long polling, SSE |
| 3 | WebSocket | One long-lived, full-duplex connection; ws:// and wss:// | WebSocket, full duplex |
| 4 | Handshake | HTTP Upgrade → 101 Switching Protocols; Key/Accept | Upgrade, 101 |
| 5 | Frames | 2-14 byte header; opcodes; client frames masked | frame, opcode, masking |
| 7-8 | Operations | Ping/pong through idle timeouts; reconnect with backoff, jitter and catch-up | ping/pong, thundering herd |
| 9 | Scaling | Sockets are pinned; pub/sub between instances; plan by connections | pub/sub |
| 10 | Security | Auth at handshake (no custom headers in browsers); check Origin | cross-site WebSocket hijacking |
| 11 | Choosing | SSE for one-way, WebSocket for two-way, polling for rare, webhooks for servers | webhook |
Try it yourself
The handshake and every message
- Steps: Chrome DevTools → Network → filter WS, open any chat or live site
- What to look for: Status
101; the Messages tab lists frames sent (up) and received (down). - From section: 4. The handshake: an HTTP request that upgrades
An interactive WebSocket client
- What to look for: Type a line: it is sent as one text frame; replies print as they arrive.
- Runs on: or websocat
- From section: 4. The handshake: an HTTP request that upgrades
npx wscat -c wss://your-server/pathJust the handshake
- What to look for:
HTTP/1.1 101 Switching Protocolsand the matching Accept value. - From section: 4. The handshake: an HTTP request that upgrades
curl -i -N -H 'Connection: Upgrade' -H 'Upgrade: websocket' -H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' https://your-server/pathHow many sockets are open
- What to look for: Grows with connected apps, not with request rate.
- Runs on: Linux, on kade-api
- From section: 9. Scaling: connections are stateful
ss -tn state established '( sport = :443 )' | wc -lMax open files for the process
- What to look for: Often 1024 by default: too low for thousands of WebSockets.
- From section: 9. Scaling: connections are stateful
ulimit -n