Plain HTTP is request/response: the server can only speak when spoken to. Chat, live scores, collaborative editors, dashboards and notifications need the opposite: the server must push data the moment it exists. This lesson compares the four main techniques (short polling, long polling, Server-Sent Events and WebSockets), touches on WebRTC, and shows how to scale stateful WebSocket servers to millions of connections.
Think of it like
Waiting for a package
Short polling is walking to the mailbox every five minutes. Long polling is calling the post office and staying on hold until your package arrives, then calling again. SSE is a radio station that announces deliveries as they happen: you just listen. WebSockets are an open phone line where both sides can talk at any time. WebRTC is the courier handing the package to you directly, skipping the depot.
The problem: the client always asks first
HTTP was designed for documents: the client requests, the server responds, done. To show new data in real time, the client has to either ask repeatedly or keep a long-lived connection open so the server can push. Every technique below is one of those two ideas. Watch them side by side in the simulation above: same events, very different traffic.
Short polling
The client sends a normal request every few seconds: "anything new?" It is trivial to build, works everywhere and is stateless on the server. But most responses are empty, and a new event waits on average half the polling interval before anyone sees it.
Long polling
The client sends a request and the server holds it open until there is data (or a timeout, typically 20 to 30 s, elapses). The server responds, and the client immediately sends the next request. Latency drops to roughly one network trip after an event, with far fewer empty responses.
- Every message still pays for a full HTTP request with headers.
- Events that occur between one response and the next request must be buffered server-side, or they are lost. Clients should send the last ID they saw.
- Each waiting client ties up a connection (cheap with async servers, expensive with thread-per-request ones).
- Proxies and load balancers may cut idle requests, so timeouts must be tuned below theirs.
Server-Sent Events (SSE)
SSE is a standard for one-way, server-to-client streaming over plain HTTP. The client opens a request with the browser's EventSource API; the server responds with Content-Type: text/event-stream and never finishes the response, writing events as they happen.
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
retry: 3000
id: 41
event: score
data: {"home": 2, "away": 1}
: keep-alive comment, ignored by the client
id: 42
event: score
data: {"home": 3, "away": 1}- Automatic reconnection is built in (
retry:sets the delay in milliseconds): the browser reconnects and sendsLast-Event-ID: 42so the server can replay what was missed. - It is just HTTP, so it passes through proxies, load balancers and auth middleware unchanged (disable response buffering in proxies like nginx).
- Text only (UTF-8); binary must be base64-encoded.
- Over HTTP/1.1, browsers allow only about 6 connections per origin, so many tabs can exhaust them. HTTP/2 multiplexes SSE streams and removes the problem.
- Client-to-server messages go through ordinary
POSTrequests.
WebSockets
A WebSocket is a persistent, full-duplex channel over a single TCP connection. It starts life as an HTTP request that asks to upgrade; after the server agrees, both sides exchange lightweight frames in either direction at any time, with no headers per message.
The upgrade handshake
GET /chat HTTP/1.1
Host: chat.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://app.example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=The server proves it understood the WebSocket protocol by appending a fixed GUID (258EAFA5-E914-47DA-95CA-C5AB0DC85B11) to the client's key, hashing with SHA-1 and returning the base64 result. This is not security; it stops caches and confused servers from accidentally accepting the upgrade. Use wss:// (WebSocket over TLS) in production, and check the Origin header to prevent cross-site WebSocket hijacking.
Framing
| Field | Size | Purpose |
|---|---|---|
| FIN | 1 bit | Last fragment of a message (large messages can be split into frames) |
| Opcode | 4 bits | 0x1 text, 0x2 binary, 0x0 continuation, 0x8 close, 0x9 ping, 0xA pong |
| MASK | 1 bit | Client-to-server frames must be masked (protects naive proxies from cache poisoning) |
| Payload length | 7 bits, or 7 + 16, or 7 + 64 | Up to 125 inline; 126 and 127 signal 16-bit and 64-bit extended lengths |
| Masking key | 0 or 4 bytes | XOR key for the payload (client frames only) |
Heartbeats and reconnection
A TCP connection can die silently: a phone loses signal, a NAT entry expires, a load balancer drops an idle connection (60 seconds is a common default). Neither side notices until it tries to send. Heartbeats solve this: the server sends periodic ping frames and closes connections that miss a pong. Browsers cannot send protocol-level pings from JavaScript, so clients usually add an application-level ping message too.
export class ReconnectingSocket {
private ws?: WebSocket;
private attempt = 0;
private heartbeat?: ReturnType<typeof setInterval>;
private lastPong = 0;
constructor(
private readonly url: string,
private readonly onMessage: (msg: { type: string; [key: string]: unknown }) => void,
) {
this.connect();
}
private connect(): void {
const ws = new WebSocket(this.url);
this.ws = ws;
ws.onopen = () => {
this.attempt = 0; // healthy again: reset the backoff
this.lastPong = Date.now();
this.heartbeat = setInterval(() => {
if (Date.now() - this.lastPong > 45_000) {
ws.close(); // no pong for 45 s: treat the connection as dead
return;
}
ws.send(JSON.stringify({ type: "ping" }));
}, 15_000);
};
ws.onmessage = (event) => {
const msg = JSON.parse(event.data as string);
if (msg.type === "pong") {
this.lastPong = Date.now();
return;
}
this.onMessage(msg);
};
ws.onclose = () => {
clearInterval(this.heartbeat);
// Full jitter: random delay in [0, cap) so a crashed server's clients
// don't all reconnect in the same instant (thundering herd)
const cap = Math.min(30_000, 500 * 2 ** this.attempt);
this.attempt += 1;
setTimeout(() => this.connect(), Math.random() * cap);
};
}
send(data: unknown): void {
if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(data));
}
}WebRTC
WebRTC connects browsers peer to peer for audio, video and arbitrary data, mostly over UDP (SRTP for media, SCTP data channels), with mandatory encryption. Servers are still needed for signaling (exchanging connection offers, often over a WebSocket) and for NAT traversal: STUN servers tell a peer its public address, and TURN servers relay traffic when a direct path is impossible (see NAT in Networking Essentials). Use it for video calls, screen sharing and low-latency peer data, not for server push.
Side-by-side comparison
| Short polling | Long polling | SSE | WebSocket | |
|---|---|---|---|---|
| Direction | Client pulls | Server push (emulated) | Server → client | Full duplex |
| Transport | Repeated HTTP requests | Held HTTP requests | One long HTTP response | Upgraded TCP connection |
| Delay for new data | Up to one interval | About one trip, plus re-request gaps | Immediate | Immediate |
| Overhead per message | Full request, even when empty | Full request per batch | A few bytes | 2 to 14 bytes |
| Server state | None | One parked request per client | One open stream per client | One stateful connection per client |
| Binary data | Yes | Yes | No (text only) | Yes |
| Reconnect and resume | Not needed | Manual | Built in (Last-Event-ID) | Manual |
| Infrastructure friendliness | Excellent | Good (watch timeouts) | Good (disable buffering) | Needs Upgrade support and long idle timeouts |
| Typical use | Rarely changing data, simple jobs | Legacy fallback | Notifications, feeds, dashboards, LLM streaming | Chat, games, collaborative editing, trading |
Choose SSE when
- Data flows mostly server → client
- You want plain HTTP: auth, proxies, CDNs, HTTP/2
- Built-in reconnect and resume matter
- Messages are text or JSON
Choose WebSockets when
- Both sides send frequently (chat, games, cursors)
- Per-message overhead and latency must be minimal
- You need binary frames
- You can invest in stateful connection infrastructure
Choose polling when
- Updates are rare or a few seconds of delay is fine
- Client count is small
- Infrastructure cannot hold long connections
- Simplicity beats efficiency
Scaling WebSocket servers
Stateless HTTP servers are easy to scale: any server can handle any request. WebSocket servers are stateful: each one holds a set of live connections, and a message for Alice must reach the specific server that holds Alice's socket. Scaling them means solving routing, fan-out and failure.
- Connection state
- Each gateway keeps sockets, subscriptions and buffers in memory. Budget memory per connection (often tens of KB), file descriptors and kernel buffers; a tuned server holds on the order of 100k or more mostly idle connections.
- Sticky routing
- A WebSocket is one long-lived TCP connection, so it naturally stays on the gateway it first reached. Stickiness matters for fallbacks like long polling, which span many requests. The load balancer must allow long idle timeouts.
- Session registry
- A fast store (often Redis) mapping
user → gateway, written on connect and refreshed by heartbeats. Doubles as presence (online/offline). - Pub/sub backplane
- Gateways subscribe to channels for the users they hold. Any service publishes to
user:alice, and only the gateway holding Alice receives it. Redis Pub/Sub, NATS or Kafka are common choices. See Message Queues & Pub/Sub. - Separation of concerns
- Gateways only manage connections; business logic (persisting messages, permissions) lives in stateless services behind them, so gateways stay simple and can be deployed independently.
Concurrent users
10M
Peak connected clients
Per gateway
~100k
Conservative planning figure
Gateways
~100
Plus headroom for failures and deploys
Heartbeats
~670k/s
10M ÷ 15 s interval
- Deploys: restarting a gateway disconnects all its clients. Drain gradually (stop accepting new connections, ask clients to reconnect elsewhere over a few minutes) to avoid reconnect storms.
- Load balancer limits: each LB-to-gateway IP pair has about 64k source ports; spread across multiple gateway IPs or ports at very high connection counts.
- Backpressure: a slow client's send buffer grows without bound. Cap it and drop or disconnect slow consumers.
- Autoscaling: scale on connection count and memory, not CPU or request rate. New gateways only receive new connections, so rebalancing is gradual.
Implementation
A single-process relay: each connection registers under its user ID, and messages are forwarded to the target's socket. Across many servers, the lookup becomes a publish to the backplane.
# pip install "websockets>=13"
import asyncio
import json
from websockets.asyncio.server import ServerConnection, serve
connections: dict[str, ServerConnection] = {}
async def handler(ws: ServerConnection) -> None:
user_id = ws.request.path.rstrip("/").rsplit("/", 1)[-1] # ws://host/ws/alice
connections[user_id] = ws
try:
async for raw in ws:
msg = json.loads(raw)
if msg.get("type") == "ping": # application-level heartbeat from browsers
await ws.send(json.dumps({"type": "pong"}))
continue
target = connections.get(msg["to"])
if target is not None:
# Single process only: across servers you would PUBLISH to a backplane
await target.send(json.dumps({"type": "message", "from": user_id, "text": msg["text"]}))
finally:
if connections.get(user_id) is ws:
del connections[user_id]
async def main() -> None:
# The library sends protocol pings every 20 s and closes peers that miss the pong
async with serve(handler, "0.0.0.0", 8765, ping_interval=20, ping_timeout=20) as server:
await server.serve_forever()
asyncio.run(main())Key takeaways
- Short polling is simple but wasteful and slow; long polling cuts latency but still pays a full request per message.
- SSE streams server-to-client events over plain HTTP with built-in reconnect and
Last-Event-IDresume: ideal for one-way push. - WebSockets upgrade an HTTP request into a full-duplex, low-overhead channel: ideal for chat, games and collaboration.
- Long-lived connections die silently, so use heartbeats, and reconnect with exponential backoff plus jitter.
- WebSocket servers are stateful: scale them with a session registry, a pub/sub backplane, and persistence with sequence numbers for resume.
Common pitfalls
- Reaching for WebSockets when data only flows server-to-client, where SSE is simpler and works with standard HTTP tooling.
- Reconnecting without jitter, so a gateway crash triggers a synchronized reconnect storm.
- Treating reconnection as recovery: without persisted, sequenced messages, anything sent during the gap is lost.
- Load balancer or proxy idle timeouts shorter than the heartbeat interval, silently killing connections.
- Autoscaling WebSocket gateways on CPU instead of connection count and memory.
Interview tips
- Justify the choice by direction and frequency: one-way push suggests SSE; frequent two-way traffic suggests WebSockets.
- Always address the multi-server problem: how does a message reach a user connected to a different gateway?
- Mention presence, heartbeats, ordering via sequence numbers and resume-after-reconnect; they are the follow-up questions.
Real-world applications
- Chat and messaging (Slack, WhatsApp Web, Discord).
- Live dashboards, sports scores and stock tickers.
- Collaborative editors with live cursors (Google Docs, Figma).
- Streaming LLM responses token by token over SSE.
- Video calls and screen sharing over WebRTC.
Test yourself
1 million clients short-poll every 10 seconds. Roughly how many requests per second hit the servers?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.