WebSockets & Real-time

Chat, live scores, cursors: polling vs SSE vs WebSocket, and how millions of connections are handled.

Intermediate7 min read
Language
Theme
PollingClientServernew?no / yesask every N sec (mostly empty)SSEClientServerevents streamone-way stream: server to clientWebSocketClientServertwo-way, full duplexScale WS with: many WS servers + Redis pub-sub between them + connection state in Redis
Key idea at a glance

HTTP cannot push. That is the whole problem.

HTTP is request-response: the client asks, the server answers, connection closes. A chat message arrives, a wicket falls, a stock ticks: the server knows, the client does not, until it asks. Every real-time technology is a workaround for this one fact.

The four options, oldest to newest

  • Short polling: client asks every N seconds "anything new?" Simple, works everywhere, but ~99% of responses are empty and latency is up to N seconds. At 1M clients polling every 5s, that is 200k RPS of mostly "no".
  • Long polling: client asks; the server holds the request open until there is data or a timeout (~30s), then the client immediately re-asks. Near-real-time with plain HTTP; but each message still costs connection churn, and proxies/firewalls sometimes kill long-held connections.
  • Server-Sent Events (SSE): one persistent HTTP connection over which the server streams events as text. One-way only (server to client), auto-reconnect built into the browser. Perfect for scores, notifications, price tickers, live blogs.
  • WebSocket: starts as HTTP, then "upgrades" the same connection to a persistent, full-duplex channel: both sides send frames anytime, with tiny per-message overhead (no headers per message). The standard for chat, multiplayer games, collaborative editing, live cursors.

Why WebSockets are hard to scale

HTTP servers are stateless: any server can take any request. WebSocket servers are stateful: the connection lives on one specific server, which must remember it. At 1M concurrent connections:

  • Spread connections across many WS servers (one tuned box holds tens of thousands of connections; the limits are memory and file descriptors, not CPU).
  • Cross-server delivery: user A (server 1) messages user B (server 2). Server 1 publishes to a shared bus (Redis pub-sub / Kafka); every WS server subscribes and delivers to its own local connections. This is the piece interviewers probe.
  • Presence/connection state: which user is connected where: Redis with heartbeat TTLs.
  • Dead connections: clients vanish silently (phone in a tunnel). Heartbeat/ping-pong frames every ~30s detect and reap them.
  • Reconnection + missed messages: on reconnect, the client sends "last message I have is ID 4,521" and the server backfills. Without this, tunnels eat messages.

Choosing (the honest guide)

  • Server-to-client updates, want simple and firewall-friendly: SSE.
  • Two-way, high-frequency (chat, games, collab): WebSocket.
  • Updates every few minutes, small scale: short polling is legitimate engineering; do not gold-plate.
  • Mobile push when the app is closed: none of these; that is FCM/APNs (see the notifications lesson).

Worked example: live cricket score for 2M fans

One-way updates only: SSE from edge servers. Score updates published to Redis pub-sub; 200 edge-connected SSE servers subscribe and fan out to their local clients. 2M connections / 200 servers = 10k connections each: comfortable. Total origin traffic: one event, not 2M requests.

Common interview traps

  • WebSocket with no cross-server delivery plan.
  • Connection state kept only in server memory.
  • No heartbeat/reconnect/backfill story.
  • Using WebSocket where SSE or polling would do.

Interview Q&A

Q: A user's chat works on WiFi but loses messages on mobile data. Why?
A: Mobile networks silently drop idle TCP connections. Missing heartbeats mean the client does not notice the dead socket, and there is no backfill on reconnect. Fix: ping/pong every ~30s and a last-seen-message-ID handshake on reconnect.

Q: Why not just use Kafka between clients and servers?
A: Kafka is a server-side log, not a client protocol: browsers cannot speak it, and per-client offsets for millions of users is the wrong tool. Pattern: WebSocket/SSE at the edge, Kafka as the internal backbone between services.

Key takeaways

Interview pointer

In a chat design, saying WebSocket triggers the follow-up: 'how does a message reach a user connected to another server?' Answer: WebSocket servers coordinate through Redis pub-sub or Kafka, and the user-to-server mapping lives in Redis.