Course contents

02. Networking and Internet Lesson 8 of 10

WebSockets

See the HTTP upgrade, two-way messages and fan-out through a pub/sub backplane, then size servers by open sockets and survive a reconnect wave after a crash.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A WebSocket starts as an HTTP request with Upgrade: websocket; after 101 Switching Protocols the connection carries messages both ways.
  • Each socket is pinned to one server, so cross-server delivery needs a pub/sub backplane.
  • Open sockets = connection rate × session length: plan memory and file descriptors for that number.
  • A server crash disconnects all its users at once; consistent hashing moves only those users.
  • Immediate reconnects create a thundering herd; backoff with jitter spreads them out.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

WebSocket (RFC 6455) is a protocol for a long-lived, full-duplex message channel between a client and a server over one TCP (and usually TLS) connection. It begins as an HTTP request and, once the server agrees, the connection stops carrying HTTP and carries WebSocket frames in both directions until either side closes it.

Why it exists

HTTP is request/response: the server can only answer. Before WebSockets, browsers faked server push with polling (frequent requests, mostly empty answers) or long polling (a held request per update). Both add latency, headers and connection churn. WebSockets give the server a way to send at any time, and the client a cheap way to send many small messages.

How it works

Upgrade. The client sends GET /chat with Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Version: 13 and a random Sec-WebSocket-Key. The server replies 101 Switching Protocols with Sec-WebSocket-Accept (a hash of the key) to prove it understood. Subprotocols (Sec-WebSocket-Protocol) and extensions such as per-message compression are negotiated here. Over HTTP/2 (RFC 8441) and HTTP/3 (RFC 9220) the same is done with an extended CONNECT on a single stream, so a WebSocket can share a multiplexed connection.

Frames. Messages are split into frames with a 2–14 byte header: text (UTF-8) or binary, plus control frames (ping, pong, close). Client-to-server frames are masked to defeat cache-poisoning attacks on old proxies. There is no request/response pairing: correlation, acknowledgements and resumption are the application’s job.

Server side. Each connection lives on one server process. Delivering a message to another user means finding the server that holds their socket: a pub/sub backplane (Redis pub/sub or Streams, NATS, Kafka, or a managed real-time service) carries messages between servers, each server subscribing to the channels (rooms, users) its connections care about.

Load balancing. The balancer picks a server when the connection opens and forwards it for its whole life (layer-4 or layer-7 with upgrade support). Long-lived connections make the open-time decision matter: least connections works better than round robin for balancing socket counts, and hashing a stable user id (consistent hashing) sends reconnects back to the same server when servers keep per-user state.

Liveness. Proxies and load balancers close idle connections (often after about 60 seconds). Ping/pong frames more frequent than the shortest idle timeout keep connections open and detect dead peers; TCP keepalive alone is usually too slow.

When to use it

  • Chat, collaborative editing, multiplayer games, trading screens: frequent messages in both directions with low latency.
  • Live dashboards and notifications where the client also sends commands on the same channel.
  • When you control both ends and can implement reconnect, resume and backpressure.

When not to

  • One-way server-to-client updates: Server-Sent Events are simpler and reconnect automatically.
  • Infrequent updates (minutes apart): polling or push notifications cost less than holding connections.
  • Request/response APIs: plain HTTP gets caching, retries, status codes and tooling for free.

Trade-offs

Choice You gain You pay
WebSockets instead of polling Low latency, tiny per-message overhead Stateful connections to size, balance, drain and reconnect
Pub/sub backplane Any server can reach any user Another system on the hot path; its failure stops cross-server delivery
Hash user → server Reconnects find their state Uneven load when a few users are very active; remapping on scale events
Keep state only in the backplane / a store Any server can take any user More reads on reconnect

Alternatives

  • Server-Sent Events for one-way streams over plain HTTP, with built-in reconnect and resume.
  • Long polling as a fallback where WebSockets are blocked.
  • WebTransport (HTTP/3) for multiple streams and unreliable datagrams, e.g. games and media.
  • Mobile push notifications for waking apps that are not running.
  • Managed real-time services that run the connection tier and backplane for you.

Failure modes

  • Server crash or deploy: every socket on the server closes at once; clients must reconnect and resynchronise.
  • Reconnect storm: synchronised reconnects (and the TLS handshakes and authentication behind them) overload the survivors and can cascade.
  • Silent half-open connections: a peer disappears without a close; without heartbeats the server keeps its resources.
  • Slow consumers: a client that cannot keep up makes the server buffer messages; without limits memory grows until the process dies.
  • Backplane outage: users on the same server can still talk, everyone else cannot.
  • Stale authentication: a socket outlives the token that opened it.

In production

Size the connection tier by concurrent sockets and memory per socket. Use a pub/sub backplane and keep per-user state somewhere a reconnect can find it. Configure heartbeats below every idle timeout on the path. Clients reconnect with exponential backoff, full jitter and a cap, and resume from the last message they processed (sequence numbers). On deploys, drain servers gradually: stop accepting new connections, ask clients to reconnect in batches, then stop. Bound per-connection send buffers and drop or disconnect slow consumers. Re-authenticate periodically.

Common misconceptions

  • “WebSockets need sticky sessions.” An open connection is already pinned to its server. Affinity only matters for where reconnects land, and only if servers keep local state.
  • “WebSockets scale like HTTP.” The limiting resource is open connections and fan-out, not requests per second.
  • “A WebSocket delivers every message.” Messages in flight when a connection drops are lost unless the application acknowledges and replays them.
  • “WebSockets don’t work with HTTP/2.” They do, via extended CONNECT (RFC 8441), where servers and proxies support it.

Interview angle

For any real-time feature, say why WebSockets (two-way, frequent) rather than SSE or polling. Then cover the architecture: a connection tier behind a balancer, a pub/sub backplane for fan-out, where presence and session state live, and capacity in concurrent connections (do the Little’s law arithmetic). Interviewers often probe failure: what happens when a node with 50,000 connections dies (mass disconnect, jittered reconnect, resume from a sequence number) and how deploys avoid dropping everyone at once.

Model assumptions

Steps 1–3 are a scripted illustration: packets are placed by hand (10 ms between users and the load balancer, 2 ms inside the data centre). Steps 4–8 are simulated with one deliberate simplification: each simulated request is one WebSocket connection being opened (TLS, upgrade and authentication modelled as about 10 ms of server work); the open sockets themselves and the messages on them are not simulated, and the socket counts in the text come from Little’s law with an assumed 30-minute session. Each server has 2 workers (about 200 connection opens per second) and a backlog of 40. The balancer uses consistent hashing on a user id drawn uniformly from 500 users; health checks run every 250 ms with 2 failures to eject. Reconnect waves are modelled as extra connection attempts (about 1,500 within one second, or spread over six seconds), scaled down from the tens of thousands a real server would hold. Numbers are illustrative.

The lesson as textEvery step of the simulation, written out.
  1. 1. Start as HTTP, switch protocols

    *Scripted illustration.* A WebSocket starts life as an ordinary HTTP/1.1 request: GET /chat with Upgrade: websocket, Connection: Upgrade and a random Sec-WebSocket-Key. The server agrees with 101 Switching Protocols and a Sec-WebSocket-Accept derived from the key.

    From that moment the TCP (and TLS) connection no longer carries HTTP. It is a long-lived, full-duplex channel owned by one server, WS 1 here, for as long as Alice stays connected. (Over HTTP/2 and HTTP/3 the same upgrade is done with an extended CONNECT request on one stream.)

    Scene: Alice sends an HTTP upgrade request through the load balancer to WS 1, which answers 101 Switching Protocols. The connection stays open as a WebSocket.

    Key idea: One HTTP round trip turns a connection into a persistent two-way channel pinned to one server.

  2. 2. Messages in both directions, any time

    *Scripted.* Now either side can send a message whenever it wants, framed with only 2–14 bytes of header (client-to-server frames are also masked). Alice sends “typing…”, the server answers, and then the server pushes two messages Alice never asked for: Bob came online, a new chat message arrived.

    No polling, no new requests, no repeated headers or cookies: just small frames on an open connection, with latency close to one network trip. Ping and pong control frames keep the connection alive through proxies.

    Scene: Messages flow between Alice and WS 1 in both directions over the open connection, including two messages the server pushes without Alice asking.

    Key idea: After the upgrade there are no requests and responses, only messages, sent by either side at any time.

  3. 3. Bob is connected to another server

    *Scripted.* Alice writes in the room “general”. Bob is in the same room, but his socket lives on WS 3. WS 1 cannot write to a connection it does not hold.

    So servers share a pub/sub backplane (Redis pub/sub, NATS, Kafka or a managed service): WS 1 publishes the message to the room’s channel, every server with members in that room receives it, and WS 3 pushes it down Bob’s socket. Alice gets an acknowledgement. Without a backplane, users on different servers cannot talk to each other.

    Scene: Alice’s message reaches WS 1, which publishes it to the pub/sub backplane. The backplane delivers it to WS 3, which pushes it to Bob. WS 1 acknowledges to Alice.

    Key idea: Connections are spread over servers, so messages between users must cross a shared pub/sub layer.

  4. 4. Thousands of sockets, few handshakes

    *Simulated from here.* Each packet you now see is one connection being opened: TLS, the upgrade and authentication, about 10 ms of server work. Users open 60 connections per second.

    Sessions last about 30 minutes, so by Little’s law there are 60 × 1,800 ≈ 108,000 open sockets, about 36,000 per server. Opening them keeps each server only about 10% busy. What limits a WebSocket server is the open connections: memory per socket, file descriptors, heartbeats, and what happens when all of them have to move at once.

    Scene: Users open 60 WebSocket connections per second, spread over three servers. Each server is only lightly busy with handshakes but holds about 36,000 open sockets.

    Key idea: Open connections = connection rate × session length. Plan WebSocket servers by concurrent sockets, not by requests per second.

  5. 5. Send each user back to the same server

    An open WebSocket is pinned to its server anyway: the balancer forwards the upgraded connection for its whole life. The question is where a user lands when they reconnect (network change, laptop wakes up). If servers keep per-user state in memory — presence, a replay buffer, cached permissions — landing on the same server is cheaper.

    Switch the balancer to consistent hashing on the user id. Every connection a user opens now goes to the same server; across users the load stays roughly even.

    Scene: The load balancer hashes the user id: each user’s connections always go to the same server, and the three servers receive similar numbers of connections.

    Key idea: Hash on a stable user id so reconnects return to the same server, without sticky cookies.

  6. 6. A server dies with 36,000 sockets

    One second in, WS 3 crashes. All of its connections break at the same instant: about 36,000 clients see their socket close. In the model, the handshakes WS 3 was working on fail, and new connections hashed to it are refused until two failed health checks take it out of rotation.

    After that, the hash ring sends WS 3’s users to the next server on the ring. Users of WS 1 and WS 2 are not moved: consistent hashing only reassigns the keys of the server that left.

    Scene: WS 3 crashes. Connection attempts sent to it fail until the load balancer ejects it; then WS 3’s users are hashed to WS 1 and WS 2, while everyone else keeps their server.

    Key idea: A WebSocket server failure disconnects all of its users at once; consistent hashing moves only those users.

  7. 7. Everyone reconnects at once

    Naive clients reconnect immediately after a close. Here a scaled-down wave of about 1,500 reconnects hits within one second, half a second in. The two survivors can open about 400 connections per second together.

    Their backlogs fill, handshakes queue for hundreds of milliseconds, and many connection attempts are rejected. Rejected clients would retry at once too, making the next wave as big. This is a thundering herd, and it can take down the survivors and turn one failure into an outage.

    Scene: About 1,500 reconnects arrive within one second. WS 1 and WS 2 saturate, their backlogs fill and many connection attempts are rejected.

    Key idea: Synchronised reconnects concentrate a whole server’s worth of handshakes into a moment.

  8. 8. Back off with jitter

    Clients now wait a random delay before reconnecting (exponential backoff with full jitter, plus a cap). The same 1,500 reconnects are spread over about six seconds: roughly 250 per second on top of the normal 60.

    The survivors stay below their 400 per second. Handshakes barely queue and almost nothing is rejected; the last users are back after a few seconds instead of fighting for minutes. Servers can help by sending a close code with a retry hint, and by draining connections gradually during deploys instead of dropping them all at once.

    Scene: The same number of reconnects is spread over about six seconds. WS 1 and WS 2 stay below capacity and almost no connection attempts fail.

    Key idea: Randomised backoff turns a reconnect spike into a manageable ramp.

  9. 9. Running WebSockets at scale

    WebSockets give low-latency, two-way messaging over one upgraded connection. The cost moves from requests to connections: size servers by open sockets, connect servers through a pub/sub backplane, hash users to servers if they keep state, and make reconnects safe: backoff with jitter, resumable state, gradual draining on deploys.

    Also set heartbeats shorter than every idle timeout on the path (load balancers often close idle connections after about 60 seconds), and authenticate on connect and periodically, since a socket can outlive the token that opened it.

    Scene: Users open 60 connections per second through a consistent-hashing load balancer to WS 1 and WS 2; WS 3 is still offline.

    Key idea: Persistent connections trade request overhead for connection management: plan for count, fan-out and mass reconnects.