System Design · 04. Communication · 10 min · Intermediate
Real-time Updates
How a server tells a browser the moment something changes.
In short
Polling asks 50,000 times a second and gets empty answers; long polling and SSE hold a request open; WebSockets give a two-way pipe. Push removes the wait: about 50 ms instead of up to 2 s.
Many connections need many gateways, pub/sub to reach the right one, heartbeats for presence, and clients that reconnect with backoff and catch up.
Key ideas
- Only listening: SSE. Talking both ways, fast: WebSockets. Rarely changing: plain polling is fine. (step 4)
- Reconnect is the normal case, not the rare one. Design for it: backoff, jitter and catch-up from the last id. (step 8)
Good to know
- It works everywhere, even through old proxies. The cost is a new request after every message. (step 2)
- SSE is the least work when the browser only listens. (step 3)
- Pub/sub lets you add gateways without changing the others. Gateways can come and go. (step 6)
- Scale by adding gateways, and by sharding pub/sub channels and the presence store by key. (step 9)
Watch out
- Polling is simple and fine for slow data (a build status every minute). For anything live, it is wasteful and late. (step 1)
- Connection servers hold state (who is connected). Keep them thin: they only move messages, while the logic lives elsewhere. (step 5)
- Do not tell all your friends every time you flicker offline. Add a short delay, or send presence only for the chat that is open. (step 7)
Key numbers
- Open connections
- 100,000
- New requests/s
- ~0
- Delay
- ~50 ms
Terms
- Polling
- The client asks for news on a timer, even when there is none.
- Long polling
- The server holds a request open until there is news, and the client asks again after each answer.
- Server-Sent Events (SSE)
- One long HTTP response that the server keeps writing to; one-way, with automatic reconnect.
- WebSocket
- A connection upgraded from HTTP that lets both sides send messages at any time.
- Gateway (connection server)
- A server that only holds open connections and moves messages to and from them.
- Pub/sub channel
- How a gateway reaches a user connected to a different gateway: publish to a channel the right gateway subscribes to.
- Presence
- Who is online, tracked with heartbeats and keys that expire.
- Heartbeat
- A small periodic message that tells the server the client is still there.
- Thundering herd
- Many clients reconnecting at the same moment and overloading the servers.
- Backoff with jitter
- Waiting a growing, random time before each retry so clients spread out.