WebSockets & Real-Time Delivery
Polling, long polling, SSE and WebSockets compared; how to scale millions of persistent connections and route a message to the right one.
#The problem
HTTP is request/response: the client asks, the server answers. But chat, notifications, live scores, collaborative editing, and presence all need the server to initiate. Four techniques exist, and picking the simplest one that works is the scored decision.
#The four options
#Short polling
Client asks "anything new?" every N seconds.
client ──GET /messages?since=t──► server → "nothing"
(wait 5s)
client ──GET /messages?since=t──► server → "nothing"
(wait 5s)
client ──GET /messages?since=t──► server → [msg]Trivial to build, works everywhere, stateless servers. Wildly wasteful: with 1M clients polling every 5 s you're serving 200K QPS of mostly empty responses, and worst-case latency is your poll interval.
Acceptable for low-frequency, latency-tolerant updates — and worth proposing when the requirement is "refresh within 30 seconds," because the operational simplicity is real.
#Long polling
Client requests; the server holds the connection open until data arrives or a timeout (~30 s) fires, then the client immediately reconnects.
Near-real-time latency without a new protocol, and it works through every proxy and firewall. Costs: a held connection per client (so servers must handle many idle connections), and a reconnect storm risk if everyone's timeout fires together — jitter the timeouts.
Still a legitimate fallback, and the right answer when infrastructure constraints rule out WebSockets.
#Server-Sent Events (SSE)
One long-lived HTTP connection over which the server streams events. Unidirectional (server → client only).
GET /stream Content-Type: text/event-stream
data: {"type":"like","post":42}\n\n
data: {"type":"comment","post":7}\n\n
...connection stays open...Underrated. It's plain HTTP (so it works with existing proxies, auth, and compression), has automatic reconnection with Last-Event-ID replay built into the browser — each event can carry an ID, and when the connection drops, the browser reconnects and tells the server the last ID it received, so the server can resend whatever was missed — and is far simpler than WebSockets. If the client only needs to receive — notifications, live feeds, progress updates, streaming LLM tokens — SSE is usually the right choice, and saying so instead of reflexively picking WebSockets is a good signal.
Limits: one direction only. And over HTTP/1.1, browsers allow only about six open connections per domain, so a few SSE tabs can use them all up; HTTP/2 largely resolves this by carrying many streams over one connection.
#WebSockets
The connection starts as an ordinary HTTP request and then asks to be upgraded: the same open socket stops speaking HTTP and starts carrying raw messages. From then on it's full-duplex — both sides can send whenever they like, without waiting to be asked, and each message carries only a few bytes of overhead.
GET /ws
Upgrade: websocket ← handshake over HTTP
───────────────────────────
◄──► binary/text frames, both directions, low overheadThe right choice when the client sends frequently too: chat, collaborative editing, multiplayer, live trading.
Costs, and these are the interview substance:
- Connections are stateful: user B's socket lives on one particular server, so your servers are no longer interchangeable. A message for B must reach that server.
- Load balancers must support the upgrade and keep connections open for hours.
- You must implement your own heartbeat, reconnection, and message-replay logic — none of it comes built in, unlike SSE.
- Scaling means managing millions of open sockets.
#Choosing
| Need | Use |
|---|---|
| Updates within ~30 s, simple infra | Short polling |
| Near-real-time, constrained infra | Long polling |
| Server → client only | SSE |
| Both directions, high frequency | WebSockets |
| Mobile app, background delivery | Push notifications (APNs/FCM) — the OS holds the connection, not you |
That last row matters: on mobile, the OS kills your socket in the background. Real-time delivery to a backgrounded app must go through platform push services.
#Scaling persistent connections
This is where the design gets interesting.
Connection capacity. A tuned server handles ~100K–1M concurrent WebSocket connections, but the binding constraint is usually memory, not CPU — each connection needs socket buffers and application state, typically 10–50 KB. At 30 KB, 1M connections ≈ 30 GB of RAM. You'll also raise operating-system limits. Each open connection uses a file descriptor (the OS's handle for an open file or socket), and the default cap is often just 1,024 per process. And each outgoing connection — such as from a proxy to your servers — needs a temporary local port, so you widen the ephemeral port range the OS picks those from.
The routing problem. This is the core difficulty: user B's message arrives at server 3, but user B's socket is on server 17.
1. REGISTRY: every connection records where it lives
Redis: conn:user_B → gateway-17 (TTL, heartbeat-refreshed)
2. Server 3 receives a message for user B
3. Look up registry → gateway-17
4. Forward via internal RPC or a pub/sub channel
5. Gateway-17 writes to B's socketTwo implementations:
- Registry + direct forward. Look up the owning node, send it an RPC. Efficient (one hop, no broadcast), needs a fast, highly-available registry. Best at large scale.
- Pub/sub broadcast. Publish to a channel per user/room; every gateway subscribes to the channels for its connected users. No registry needed, and it handles multi-device naturally (a user's phone and laptop on different gateways both subscribe to the same channel). But if subscriptions are coarse — say every gateway subscribes to one big shared channel — every message is sent to every gateway, and most of them throw it away. That waste grows with the number of gateways.
Most large systems use pub/sub for rooms and a registry for direct messages.
Sticky routing. While a WebSocket is open, every message on it naturally goes to the same server — it's one TCP connection, so the balancer has nothing to decide. The question is where a reconnect lands. Use L4 or an L7 balancer with upgrade support. If it routes by consistent hashing on user ID, a reconnecting user usually lands back on the same gateway, so the registry entry doesn't need updating.
#The operational details that matter
Heartbeats. TCP can hold a connection open long after the peer is gone ("half-open"). Send ping/pong every 30 s; close after two misses. Without this, your connection count drifts upward with ghosts and your registry lies about where users are.
Reconnection with backoff and jitter. When a gateway node restarts, all its connections reconnect simultaneously. Without jittered exponential backoff — each client waits a random time before reconnecting, and doubles its wait after each failed attempt — that's a self-inflicted DDoS on the remaining nodes — and it repeats, because the surge can knock over the next node. This is the thundering herd in its most dangerous form, and volunteering it is a strong signal.
Message delivery guarantees. A socket write is not a delivery guarantee — the client may disconnect mid-write. For anything that matters:
1. Persist the message durably FIRST
2. Attempt real-time delivery over the socket
3. Client ACKs with the message ID
4. On reconnect, client sends its last-seen ID;
server replays everything after itPersist-then-push, plus client-driven replay on reconnect, is the pattern. Treat the socket as a fast path — a quick way to deliver messages when everything is working — never as the system of record. The database is the record; if a socket write is lost, the replay on reconnect fills the gap.
Backpressure — what you do when you're producing faster than the other end can consume. A slow client can't keep up, so the server's queue of unsent messages grows and eats memory. Bound the per-connection queue and decide what happens on overflow — drop intermediate updates (fine for presence or a live counter, where only the latest matters) or disconnect the client and let it re-sync. An unbounded send buffer is a memory leak with a user attached.
Deploys. Restarting a gateway drops every connection on it. Drain gradually — stop accepting new connections, then close existing ones in batches with jitter, letting clients reconnect elsewhere. A naive rolling deploy of a connection tier is an outage.
#Presence
Presence is the "who's online" dot next to someone's name. It looks simple and is a classic scaling trap. The naive design: every client sends a heartbeat — a tiny "still here" message — every 5 seconds, and opening a friend list reads the state of every friend.
The cost is quadratic-ish — it grows with users times friends per user: 10M users heartbeating every 5 s is 2M writes/s, and each presence change must notify every friend. For a user with 5,000 friends, one status flip is 5,000 notifications.
Standard mitigations:
- Store presence in Redis with a TTL that the heartbeat refreshes. When heartbeats stop, the entry expires on its own, so no "went offline" write is needed.
- Only push changes, never steady state.
- Batch and debounce — wait a few seconds for a status to settle before announcing it. A user whose phone flips between Wi-Fi and mobile data doesn't need to trigger 6 notifications.
- For large friend lists, fetch presence on demand when the list is opened, rather than pushing every change. Many products deliberately reduce precision here — "active recently" instead of exact online status — because the exact version costs far more than it's worth.
#Check yourself
Short polling versus long polling: what does each cost?Show answer
When is Server-Sent Events the better choice than WebSockets?Show answer
What makes WebSockets harder to scale than plain HTTP?Show answer
A message for user B arrives at server 3, but B's socket is on server 17. How does it get there?Show answer
What is usually the binding resource for a WebSocket server, and how big is it?Show answer
Why do you need heartbeats on WebSockets?Show answer
How do you make WebSocket delivery reliable?Show answer
How do you deploy a connection tier without an outage?Show answer
#What to carry forward
- Pick the simplest technique that meets the latency need: polling, long polling, SSE, then WebSockets.
- SSE is the underrated choice for server-to-client streams; mobile background delivery needs platform push.
- Persistent connections make routing the core problem — a registry or pub/sub gets each message to the right gateway.
- Plan for memory per connection, heartbeats, jittered reconnects, bounded send queues and draining deploys.
- Persist first and replay on reconnect; keep presence cheap by pushing only changes, with TTLs.