codequest / system design
Core concept 14 of 21

Real-time: polling, SSE & WebSockets

How servers push updates to clients, from simple polling to persistent WebSocket connections, and what each costs.

The problem

HTTP is request-response: the client asks, the server answers. Chat, live scores, notifications and collaborative editing need the opposite: the server must tell the client something the moment it happens. There are four common ways to get there.

TechniqueHow it worksLatencyCostGood for
Short pollingClient asks "anything new?" every few secondsUp to the poll intervalMany empty requestsDashboards that refresh every 30 s
Long pollingServer holds the request open until there's news (or a timeout), then the client asks againNear real-timeOne open request per client; reconnect after each messageSimple notifications, older environments
Server-Sent Events (SSE)One long-lived HTTP response streaming events from server to clientReal-timeOne open connection; server-to-client onlyLive feeds, notifications, AI token streaming
WebSocketsUpgrades the connection to a persistent two-way channelReal-time, both directionsOne stateful connection per clientChat, multiplayer, collaborative editing

Scaling WebSockets

A WebSocket server holds a connection per online user, often hundreds of thousands per machine. That makes these servers stateful: to deliver a message to Priya, you must reach the server holding Priya's connection.

  • Keep a connection registry (user → server) in a fast store like Redis, or
  • Use pub/sub: each server subscribes to channels for its connected users, and senders publish to the channel.
  • Plan for reconnects: phones drop connections constantly. Clients reconnect with backoff and fetch what they missed since their last message ID.
  • Use a separate pool of connection servers, so a deploy of the main API doesn't drop every live connection.

In the interview

  • Chat or collaboration: WebSockets. One-way live updates: SSE. Rare updates: polling is fine and simpler.
  • Explain how a message finds the right connection server (registry or pub/sub).
  • Messages are stored first, then pushed, so an offline user gets them when they reconnect.