Real-time push: WebSockets, SSE and long polling
Get events to browsers and phones in under a second, and survive the reconnects.
15 min readThe options
There are four ways to get server events to a client, from simplest to most capable.
- Short polling: ask every few seconds. Simple, but 1 million clients polling every 5 seconds is 200 000 requests per second, mostly returning nothing
- Long polling: the server holds the request open until there is data or a timeout, then the client asks again
- Server-Sent Events (SSE): one long HTTP response streaming events from server to client, with automatic reconnect and resume via Last-Event-ID
- WebSockets: a full-duplex connection for both directions, needed for chat, games and collaborative editing
Connection servers are stateful
A persistent connection lives on one specific server. A tuned gateway can hold on the order of 100 000 or more idle connections, each costing tens of kilobytes of memory, so 10 million concurrent users needs around 100 gateway servers plus headroom. The load balancer must support long-lived connections, and you can no longer send a message to a user by calling any server: you need to know which server holds their socket.
Routing a message to the right socket
Two designs dominate. In the first, a presence registry (often Redis) maps each user to their gateway server, and the sender's service forwards the message there. In the second, each gateway subscribes to pub/sub channels for the rooms or users it currently serves, and the sender publishes once to the channel. Either way, write the message to durable storage first; the push is a fast notification, and the database remains the source of truth.
Reconnects and missed messages
Connections drop constantly: phones switch networks, gateways are deployed, servers crash. When a gateway with 100 000 connections dies, all of them reconnect at once, so clients must reconnect with backoff and jitter. On reconnect the client sends the last sequence number it saw, and the server replays anything newer from storage. Heartbeats every 20 to 30 seconds detect dead connections and stop proxies from closing idle ones.
Key takeaways
- Use SSE for one-way server push and WebSockets when the client also sends in real time
- Gateways are stateful: track which server holds each connection or route through pub/sub
- Persist first, then push; the push is a notification, storage is the truth
- Design for reconnect storms with jittered backoff and resume from the last sequence number
Sign in to track lessons and earn badges.