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.