Real-time delivery: polling, SSE, WebSockets

In one sentence

Push server events over the simplest channel that fits (polling for rare updates, SSE for one-way streams, WebSockets for two-way); at scale, the hard part is the stateful gateway tier and fan-out.

Analogy: Polling is checking your mailbox every hour; long polling is waiting at the mailbox until the carrier comes; SSE is a radio broadcast; a WebSocket is a phone call.

Gateways only hold sockets. The chat service persists each message, then publishes it once; every gateway with a member of the room pushes it to its local clients.

How it works

  • Short polling is simplest but mostly empty; long polling holds each request until data arrives.
  • SSE: one long HTTP response, server to client, with built-in reconnect and Last-Event-ID resume.
  • WebSocket: full-duplex over one upgraded TCP connection; you own heartbeats, reconnects and auth.
  • At scale, stateful gateways hold sockets, and a pub/sub bus routes each message to the right gateways.
  • Persist first, push second: clients reconnect with jitter and fetch what they missed from the last event id.

Check yourself

Answer to mark it learned; your answers aren't scored.

You ship a live order-status feed over SSE, served on HTTP/1.1. It works with one or two tabs, but users with many tabs open say new tabs never receive updates. Most likely cause?

Go deeper

Full explanation

Four ways to get server events to a client:

  • Short polling: the client asks every N seconds. Simple, but latency is up to N and most responses are empty.
  • Long polling: the server holds each request open until there is data or a timeout, then the client asks again. Near real time over plain HTTP.
  • SSE (Server-Sent Events): one long HTTP response of text/event-stream, server to client only. The browser reconnects by itself and sends Last-Event-ID so you can resume. LLM APIs stream tokens this way (Streaming responses (SSE)).
  • WebSocket (RFC 6455): an HTTP upgrade to a full-duplex, message-framed TCP connection. For chat, games and collaboration; you own heartbeats, reconnects and auth.

At scale the problem is state. Each connection pins to one gateway server, and a message for user X must reach the gateway holding X. The usual design: services persist the message, then publish it on a pub/sub bus (Redis, Kafka, NATS); each gateway subscribes for the rooms or users it holds and pushes to its local sockets. Gateways hold sockets, not business logic. Deploys drop connections, so clients reconnect with jitter and resume from the last event id.

Code A WebSocket gateway fanning out from Redis pub/sub
pythonA WebSocket gateway fanning out from Redis pub/sub
import asyncio
import redis.asyncio as redis
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

app = FastAPI()
bus = redis.Redis(decode_responses=True)
rooms: dict[str, set[WebSocket]] = {}         # sockets held by THIS gateway only

@app.websocket("/ws/{room}")
async def connect(ws: WebSocket, room: str):
    await ws.accept()                             # authenticate before accepting in real life
    if room not in rooms:                         # first local member: subscribe once
        rooms[room] = set()
        asyncio.create_task(relay(room))
    rooms[room].add(ws)
    try:
        while True:
            await ws.receive_text()               # client heartbeats keep proxies from idling out
    except WebSocketDisconnect:
        rooms[room].discard(ws)

async def relay(room: str):
    pubsub = bus.pubsub()
    await pubsub.subscribe(f"room:{room}")        # one subscription per room per gateway
    async for msg in pubsub.listen():
        if msg["type"] != "message":
            continue
        for ws in list(rooms.get(room, ())):      # 1 bus message -> N local sockets
            try:
                await ws.send_text(msg["data"])   # toy: inline; prod uses per-socket queues
            except Exception:
                rooms[room].discard(ws)           # dead socket: the client will reconnect

# The chat service persists a message, then: await bus.publish(f"room:{room}", payload)
Real example

A team chat app: assume 10M concurrent clients and 100k WebSockets per gateway node, so ~100 gateways. A message to a 30,000-member channel is published once; each gateway delivers to its own members, so no single process sends 30k messages. Discord hit exactly this in 2017: publishing to its largest guilds took 900 ms–2.1 s until it batched sends per node (Manifold). On deploys, drain gateways gradually: 100k clients reconnecting at once is a thundering herd.

Trade-offs +3 · −3

+ You gain

  • Polling and SSE are plain HTTP: they pass proxies, CDNs and firewalls and are easy to debug.
  • SSE gets reconnect and resume for free in the browser.
  • WebSockets give low per-message overhead and true two-way messaging.

− You pay

  • Long-lived connections make servers stateful: deploys, autoscaling and load balancing get harder.
  • Over HTTP/1.1, browsers allow only 6 SSE connections per domain, across all tabs.
  • WebSockets sidestep HTTP tooling: caching, retries and auth need custom work.

Use it when

Polling: updates every minute or slower, or tiny scale. SSE: server-to-client feeds, notifications, LLM token streams. WebSocket: chat, multiplayer, collaborative editing, frequent client messages.

Avoid it when

Don't hold sockets open for data that changes hourly; polling or mobile push is cheaper. Don't pick WebSockets when SSE suffices: you inherit custom auth, proxies and protocol work for nothing.

Numbers to know 5
  • Browsers: 6 SSE connections per domain over HTTP/1.1, shared by all tabs; HTTP/2 negotiates streams (default 100) (MDN).
  • AWS ALB default idle timeout: 60 s. Send heartbeats more often or idle connections get cut.
  • Discord (2017): ~5M concurrent users; guilds up to 30k concurrent users; big-guild publishes took 900 ms–2.1 s before Manifold.
  • Slack (2023): tens of millions of connected clients; messages delivered worldwide in ~500 ms.
  • Gateway sizing (assumption): 10M connections ÷ 100k per node ≈ 100 nodes, plus headroom to lose a zone.
Common pitfalls 4
  • No heartbeats: proxies and load balancers drop idle connections, and neither side notices.
  • Synchronized reconnects after a deploy: every client hits the gateways at once. Add jitter and drain slowly.
  • Sending to each socket inline: one slow client stalls the whole room. Use per-connection buffers and drop slow consumers.
  • Treating the socket as the delivery guarantee: messages sent while a client was offline are lost unless it resumes from a stored cursor.
Interview questions 2

Answer out loud first, then reveal.

SSE or WebSockets for an LLM chat UI?Show answer

SSE. The heavy traffic is one-way: tokens streaming down. The user's prompt is a normal POST, so auth, retries and rate limiting stay in standard HTTP tooling. SSE passes proxies and CDNs, reconnects by itself and resumes with Last-Event-ID; that's why the major LLM APIs use it. I'd serve it over HTTP/2 to avoid the 6-connection limit, and pick WebSockets only for constant two-way traffic like collaborative editing.

How do you deliver a message to a user connected to one of 100 gateways?Show answer

Two options. Pub/sub: each gateway subscribes to the rooms or users it holds and the service publishes once; simple, but every gateway with a member receives that room's traffic. Or a connection registry: user to gateway in Redis, refreshed by heartbeats with a TTL, and the service sends directly. Either way I persist first, and clients fetch missed messages by cursor on reconnect: the socket is the fast path, not the source of truth.