Summary#
HTTP is request/response, so the server cannot speak first. To deliver updates, clients can poll (ask every few seconds), long poll (ask, and the server holds the request until there is news), or keep a stream open: server-sent events (SSE) for one-way server-to-client updates, WebSockets for full two-way messaging. Webhooks push events server-to-server by calling a URL you provide. WebRTC carries audio, video and data directly between browsers. Pick the simplest one that meets the latency and direction you need, and plan for the cost of many open connections.
Why It Exists#
Chat messages, live scores, notifications, stock tickers, collaborative cursors and payment confirmations all need the server to tell the client "something happened" quickly. Plain HTTP only answers when asked. Each technique on this page is a different answer to that problem, trading latency, simplicity and infrastructure cost.
How It Works#
The two hops of every real-time feature#
Every real-time update makes two trips, and it helps to design them separately:
- Hop one, server to client: how does a server that has news get it onto the user's screen? This is the choice between polling, long polling, SSE, WebSockets and WebRTC, and it decides what kind of connection the client holds.
- Hop two, source to server: the event is born somewhere else, such as another user's message, a price change in a database, or a driver's location update. How does it reach the particular server that holds the right user's connection? This is the choice between polling a database, routing with consistent hashing, or pub/sub.
Candidates often solve hop one ("we use WebSockets") and forget hop two, which is where most of the difficulty of scaling real-time systems lives. With one server, hop two is a function call. With 500 servers, the server where the event happens is almost never the one holding the receiver's connection. Both hops are covered below.
Why plain HTTP cannot push#
HTTP is a request/response protocol. The client opens a TCP connection, sends a request, and the server sends exactly one response. The server has no way to start a conversation: it does not know the client's address in a usable way, and most clients sit behind NAT devices and firewalls that block unsolicited inbound connections anyway. So every technique on this page is a way to keep a door open from the client side. Polling opens a new door each time. Long polling holds a door open until there is something to say. SSE turns one response into an endless stream. WebSockets turn the connection into a two-way pipe. WebRTC punches a path through NAT so two clients can talk directly.
Under each technique sits TCP (or UDP for WebRTC media). Keeping a TCP connection open costs the server memory for buffers and a file descriptor, and costs every middlebox on the path (load balancers, proxies, NAT gateways) a table entry. That cost per open connection is the main reason real-time systems are designed differently from ordinary request/response APIs.
Short polling#
The client sends a request on a timer (say every 5 seconds); the server answers immediately, usually with "nothing new". Simple and works through any proxy or cache. But latency is up to the interval, and most requests are wasted: 1 million clients polling every 5 seconds is 200,000 requests per second, mostly empty.
Short polling in depth#
Short polling is the baseline, and it is better than its reputation. Its strengths are that every request is an ordinary stateless HTTP request: any server can answer it, load balancers and caches treat it normally, it survives deploys without special handling, and it works through every proxy and firewall.
The cost, worked out. Polling load equals clients divided by interval. 1 million active clients polling every 5 seconds is 200,000 requests per second. If a typical client gets news once a minute, 11 of every 12 requests return nothing. The average delay before seeing an update is half the interval (2.5 s here), and the worst case is the full interval. Halving the delay doubles the load, which is why short polling stops scaling when latency targets are below a few seconds.
Making polling cheap:
- Conditional requests. Send
If-None-Matchwith the ETag of the last response; the server answers304 Not Modifiedwith no body. Cheaper, but still one request. - Cursors. Send "give me events after ID 1042" so the server returns only new items and nothing is missed between polls.
- Cache the poll target. If many clients poll the same resource (a match score), a CDN or cache with a 1-second TTL answers almost all of them. Millions of clients can poll a cached score cheaply.
- Adaptive intervals. Poll fast while the user is active or a job is running, slowly when idle or in a background tab, and stop when the page is hidden.
- Server hints. The response can say when to poll next (
Retry-Afteror a field in the body), letting the server slow clients during overload.
When it is the right answer. A job status page ("your export is processing") polled every 5-10 seconds, an admin dashboard with a few hundred users, or an update that happens a few times per hour. In an interview, starting with polling and explaining when you would move off it shows good judgement; reaching straight for WebSockets for a once-a-minute update does not.
Long polling#
The client sends a request; the server holds it open until there is new data or a timeout (often 20-60 seconds), then responds. The client immediately sends the next request. Updates arrive almost instantly, with plain HTTP. Downsides: one held request per client, reconnect overhead after every message, and ordering and missed-message handling when updates come while the client is reconnecting (send the last seen ID with each poll).
Long polling in depth#
Long polling makes polling event-driven. The client asks; if the server has nothing new, it parks the request instead of answering, and answers the moment an event arrives or a timeout passes. The client then immediately asks again.
Details that matter in practice:
- The cursor is essential. Between one response and the next request, new events may arrive. Because the next request says "after 1043", the server returns them at once instead of losing them. Events must therefore be stored, at least for a short window, not just passed through.
- Timeouts must line up. The server's hold time must be shorter than every idle timeout on the path: load balancers (AWS ALB defaults to 60 s), proxies, and the client's own HTTP timeout. A 25-30 second hold is a common safe choice.
- Servers must be asynchronous. A thread-per-request server (one thread blocked per parked request) runs out of threads with a few thousand waiting clients. Event-driven servers (Node.js, Netty, Go, async Python) hold tens of thousands of parked requests cheaply, because a waiting request is just a small object.
- Bursts are inefficient. If 10 events arrive in one second, a naive server answers after the first, and the client needs a full round trip before it can receive the second. Servers usually wait a few milliseconds to batch events into one response.
- It is HTTP. Long polling works through proxies and firewalls that break streaming, which is why libraries such as Socket.IO historically began with long polling and upgraded to WebSockets when possible.
Long polling, often grouped with related tricks under the name "Comet", powered early web chat: Facebook described its original 2008 web chat as using long polling against Erlang servers. Today it is mostly a fallback, but a perfectly good choice when updates are infrequent and you want plain HTTP.
Server-sent events (SSE)#
The client opens one HTTP request with Accept: text/event-stream; the server keeps the response open and writes events as lines of text. Browsers provide the EventSource API, which reconnects automatically and sends a Last-Event-ID header so the server can resume. SSE is one-way (server to client); the client sends anything else with normal HTTP requests. It works well over HTTP/2, where many streams share one connection.
HTTP/1.1 200 OK
Content-Type: text/event-stream
id: 1042
event: score
data: {"match": 77, "home": 2, "away": 1}
id: 1043
event: score
data: {"match": 77, "home": 3, "away": 1}SSE in depth#
The idea. A normal JSON API sends one complete document and the client parses it once it has fully arrived, which is useless for live updates. SSE keeps the same HTTP request and response but never finishes the response. The server writes one small event at a time, and the client handles each event as soon as its lines arrive. It is one long HTTP response, carried over one TCP connection, delivered in many small pieces.
The wire format is plain UTF-8 text. Each event is a group of field: value lines ending with a blank line:
| Field | Purpose |
|---|---|
data: | The payload; several data: lines are joined with newlines |
id: | Event ID; the browser remembers the last one |
event: | Event type, so the client can listen for score separately from chat |
retry: | How many milliseconds the browser should wait before reconnecting |
A line starting with : | A comment, often sent every 15-30 s as a heartbeat to keep proxies from closing an idle connection |
Reconnection and resume. Connections do not live forever: servers restart, load balancers and proxies close idle or long-lived connections, and mobile networks change. The browser's EventSource object reconnects automatically and sends the last ID it saw in a Last-Event-ID header. That only helps if the server can answer "what happened after 1043?", so the server (or a shared store such as Redis Streams or Kafka) must keep recent events for long enough to cover typical disconnections. Forgetting this is the most common SSE bug: reconnection works, and messages silently disappear.
Real-world sharp edges. Anyone who has run SSE in production has met these:
- Buffering middleboxes. Some proxies, corporate gateways and antivirus software collect the whole response before passing it on, turning a stream into one late lump. Reverse proxies need buffering disabled for streams (for example
proxy_buffering offin Nginx, or theX-Accel-Buffering: noresponse header). Compression can buffer too, unless the server flushes after each event. - Connection limits on HTTP/1.1. Browsers allow about 6 connections per host on HTTP/1.1, and each SSE stream holds one, so several open tabs can starve the page's other requests. HTTP/2 multiplexes many streams on one connection and removes the problem.
- Text only and one-way. Binary data must be encoded (for example base64), and anything the client wants to say goes through normal HTTP requests.
- Native
EventSourcecannot set custom headers, so authentication usually relies on cookies; many apps use a small fetch-based client instead to send anAuthorizationheader.
Where it shines. Live auction prices (every bidder sees the current price the moment it changes), sports scores, dashboards, notification feeds, deployment logs, and streaming responses from AI chat assistants, where tokens are pushed to the browser as they are generated. In all of these the server talks and the client mostly listens.
// Server side (Node.js, framework-free sketch)
function stream(req, res) {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
});
const after = Number(req.headers["last-event-id"] ?? 0);
for (const e of store.eventsAfter(after)) send(res, e); // replay missed events
const unsubscribe = bus.subscribe((e) => send(res, e));
const beat = setInterval(() => res.write(": ping\n\n"), 20000);
req.on("close", () => { unsubscribe(); clearInterval(beat); });
}
function send(res, e) {
res.write(`id: ${e.id}\nevent: ${e.type}\ndata: ${JSON.stringify(e.data)}\n\n`);
}WebSockets#
A WebSocket starts as an HTTP request that asks to upgrade the connection. After a 101 Switching Protocols reply, the same TCP connection carries full-duplex framed messages in both directions, with very little overhead per message.
WebSockets suit high-frequency, two-way traffic. The costs: connections are stateful (a server must know which users are connected to it), you must handle reconnects and missed messages yourself, and some corporate proxies interfere with them.
WebSockets in depth#
WebSockets were standardised as RFC 6455 in 2011. They give the browser what it never had: a persistent, two-way channel over TCP where either side can send at any moment.
The upgrade handshake. The client sends an ordinary HTTP/1.1 GET with these headers:
GET /ws HTTP/1.1
Host: chat.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://app.example.com
Cookie: session=...
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=The server proves it understood the WebSocket request by taking the client's random key, appending a fixed GUID defined in the RFC, hashing with SHA-1 and returning the result base64-encoded. This is not security; it stops a confused HTTP server or cache from accidentally accepting a WebSocket. After the 101 response, HTTP is finished and the same TCP connection carries WebSocket frames. Because the connection starts as HTTP, it can reuse existing machinery: cookies for authentication, the Origin header for checking which site opened it, TLS on port 443 (wss://), and normal routing by host and path at the load balancer.
Frames. Each message travels in one or more frames with a header of 2-14 bytes: a FIN bit (last fragment), an opcode (text, binary, close, ping, pong, continuation), a payload length and, for client-to-server frames, a 4-byte masking key. Client frames are masked (XORed with the key) so that malicious script in a browser cannot craft bytes that look like HTTP requests to a confused intermediate proxy and poison its cache. Compared with HTTP requests that carry hundreds of bytes of headers, a 2-byte frame header makes small, frequent messages very cheap.
Control frames. Ping and pong check liveness and keep middleboxes from closing an idle connection; servers commonly ping every 20-30 seconds and drop clients that do not answer. A close frame carries a status code (1000 normal, 1001 going away, 1008 policy violation, 1011 server error), so clients can tell a deliberate shutdown from a failure.
You design the application protocol. WebSockets only move bytes. You decide what messages mean, and that becomes the API you present in an interview:
{ "type": "send_message", "clientMsgId": "c-77", "roomId": "r7", "text": "hi" }
{ "type": "ack", "clientMsgId": "c-77", "messageId": 90211 }
{ "type": "message", "roomId": "r7", "messageId": 90212, "from": "u42", "text": "hello" }
{ "type": "typing", "roomId": "r7", "userId": "u42" }JSON is common and easy to debug; binary formats such as Protocol Buffers or MessagePack save bandwidth for high-rate traffic (games, trading). The Sec-WebSocket-Protocol header lets client and server agree on a named subprotocol and version. The optional permessage-deflate extension compresses messages, at a cost of memory per connection for compression state, which matters at millions of connections.
Authentication. Options are cookies sent with the handshake (check Origin to block cross-site WebSocket hijacking), a short-lived token in the URL query (it may end up in logs, so keep it single-use and brief), or an "auth" first message after connecting. Long-lived connections outlive token expiry, so servers must re-check permissions periodically or when a user is removed from a room, and close connections when access is revoked.
Every hop must cooperate. Firewalls, corporate proxies, load balancers and CDNs between the client and the server must all understand the upgrade and allow a long-lived connection. Using wss:// on port 443 avoids most interference, because middleboxes cannot see inside TLS. Teams that deploy WebSockets typically spend real time on idle timeouts, proxies that drop upgrades, and load balancers that need explicit configuration.
When WebSockets are worth it. High-frequency, two-way, low-latency traffic: chat with typing indicators and read receipts, multiplayer games, collaborative editors sending each keystroke, trading screens. When the client only needs to receive, SSE is simpler. When the client only asks and the server answers, plain HTTP is simpler still. Interviewers watch for candidates who reach for WebSockets without justifying them: stateful connections affect load balancing, deploys, scaling and failure handling, so name the reason first.
Webhooks#
A webhook is an HTTP callback between servers. You register a URL with a provider (a payment processor, Git host, SaaS tool); when an event happens, the provider sends a POST to that URL. Good webhook design includes:
- Retries with backoff when the receiver is down, so receivers must be idempotent (the same event may arrive twice). See Idempotency.
- Signatures: the provider signs the body with a shared secret (HMAC), and the receiver verifies it and a timestamp to reject forgeries and replays.
- Quick acknowledgement: return 2xx fast, then process asynchronously through a queue.
Webhooks in depth#
A webhook turns polling between companies upside down. Instead of your backend asking a payment provider "has payment 881 finished?" every few seconds, you register https://api.yourshop.com/hooks/payments and the provider calls you when it happens.
Signatures. The receiver's URL is public, so anyone could POST fake events to it. Providers sign each delivery: they compute an HMAC (a keyed hash) of the timestamp and raw body with a secret shared only with you, and put it in a header. The receiver recomputes and compares:
import { createHmac, timingSafeEqual } from "crypto";
function verify(rawBody: string, header: string, secret: string): boolean {
const [t, sig] = header.split(","); // e.g. "t=1767225600,v1=ab12..."
const ts = Number(t.slice(2));
if (Math.abs(Date.now() / 1000 - ts) > 300) return false; // reject replays
const expected = createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
const given = sig.slice(3);
return given.length === expected.length &&
timingSafeEqual(Buffer.from(given), Buffer.from(expected));
}Verify against the raw bytes, not re-serialised JSON (key order and whitespace change the hash), use a constant-time comparison, and reject old timestamps to block replays.
Retries and idempotency. Networks fail and receivers deploy, so providers retry failed deliveries with exponential backoff, commonly for hours or days. A delivery may also succeed at your end while the 200 is lost, so the provider sends it again. Every webhook must therefore be safe to process twice: store processed event IDs and skip duplicates. See Idempotency.
Ordering. Retries mean events can arrive out of order: "payment.succeeded" may arrive before "payment.created". Either make handlers tolerant (use timestamps or version numbers and ignore older states) or treat the webhook as a hint and fetch the object's current state from the provider's API.
Thin and fat events. A fat event carries the full object; a thin one carries only an ID and type, and the receiver calls the API for details. Thin events avoid acting on stale or reordered data and leak less if a delivery goes to the wrong place, at the cost of an extra call.
Reconciliation. Webhooks can be missed for good: the endpoint was misconfigured for a day, or retries ran out. Robust systems also run a periodic job that lists recent objects from the provider and fixes anything that was missed. Treat webhooks as the fast path, not the only path.
If you send webhooks (you are the provider): deliver from a queue with per-customer rate limits so one slow receiver does not block others; record every attempt and show customers a delivery log with a "resend" button; disable endpoints that fail for days; sign everything; and guard against server-side request forgery, because customers choose the URL, so block private and internal addresses such as the cloud metadata endpoint.
WebRTC for peer-to-peer media#
WebRTC lets browsers and apps send audio, video and data directly to each other, usually over UDP for low latency. A signalling server (often over WebSockets) helps peers exchange connection details. STUN servers help peers discover their public address behind NAT; when a direct path is impossible, a TURN server relays the traffic. Group calls typically use an SFU (selective forwarding unit) server that receives each participant's stream once and forwards it to the others.
WebRTC in depth#
WebRTC is a set of standards that lets two browsers or apps exchange audio, video and arbitrary data directly, usually over UDP. It is the only common browser technology here that uses UDP, which matters for media: a late video frame is useless, so it is better to skip a lost packet than to wait for a retransmission the way TCP would.
Why direct connections are hard. Most devices sit behind NAT (network address translation): a home router or carrier gateway gives many devices one public address, and drops inbound packets that do not match a connection started from inside. Two such peers cannot simply connect to each other. WebRTC solves this with several pieces:
- A signalling server, which you build yourself, often over WebSockets. Peers use it to find each other and exchange connection details. WebRTC does not define the signalling protocol.
- SDP offers and answers: text descriptions of what each peer can send and receive (codecs, media types, encryption fingerprints).
- ICE (Interactive Connectivity Establishment): each peer gathers candidate addresses (local, public as seen from outside, relayed), exchanges them through signalling, and tests pairs until one works.
- STUN servers tell a peer what its public address and port look like from the internet. Both peers then send packets to each other's public addresses at about the same time, which opens matching entries in their NATs ("hole punching").
- TURN servers relay all traffic when no direct path works, for example behind strict corporate firewalls or symmetric NATs. Relaying costs bandwidth on your servers, so TURN capacity is a real line item.
Security is built in. Media is encrypted with SRTP, and keys are negotiated with DTLS. Browsers ask the user before sharing camera or microphone. Data channels carry arbitrary messages over SCTP on top of DTLS, and can be reliable and ordered (like TCP) or unreliable (like UDP), which suits game state and file transfer.
Group calls: mesh, SFU, MCU. With N participants in a mesh, each uploads N-1 copies of its stream. At 1.5 Mbps per video stream, a 6-person mesh means each person uploads 7.5 Mbps, which home connections and phones cannot sustain. An SFU (selective forwarding unit) receives each participant's stream once and forwards copies, so each uploads 1.5 Mbps and downloads 7.5 Mbps; with simulcast, senders upload a few quality levels and the SFU sends each receiver the one that fits its bandwidth. An MCU (multipoint control unit) decodes all streams and mixes them into one, the cheapest for clients but very CPU-heavy on servers. Most modern conferencing uses SFUs.
When to use it. Audio and video calls and conferencing, where it is the standard answer. Peer-to-peer data for collaborative editing is possible (for example with CRDTs, data types that merge concurrent edits without conflicts), but most editors need a server anyway to store the document, check permissions and coordinate many clients, so WebSockets to a server are the usual choice. In interviews, keep WebRTC to calls and conferencing. Peer-to-peer designs are hard to get right, connections drop even in good implementations, and candidates who build a whole design around peer-to-peer when it is not needed usually lose time and clarity.
Comparison#
| Short polling | Long polling | SSE | WebSockets | Webhooks | WebRTC | |
|---|---|---|---|---|---|---|
| Direction | Client pulls | Server to client (via held request) | Server to client | Both ways | Server to server | Peer to peer |
| Latency | Up to the interval | Near real time | Near real time | Lowest (ms) | Seconds | Lowest, for media |
| Transport | HTTP | HTTP | HTTP (streaming) | TCP after HTTP upgrade | HTTP POST | UDP mostly |
| Complexity | Very low | Low-medium | Low | Medium-high | Medium (retries, signatures) | High |
| Infra cost | Many wasted requests | One held request per client | One open stream per client | One open socket per client, stateful | Low | Media servers, TURN relays |
| Reconnect / resume | N/A | Manual | Built in (Last-Event-ID) | Manual | Provider retries | Manual |
A decision flow#
The comparison table becomes a short sequence of questions. Ask them in order and stop at the first answer that fits; each step down adds infrastructure and operational cost.
Two notes. First, the choice is per feature, not per product. One app may use WebSockets for chat, SSE for an activity feed, polling for a slow export job, webhooks from its payment provider and push notifications for phones in pockets. Second, a WebSocket that is already open for one feature can carry other features' events cheaply. If chat already needs a socket, sending notifications over it is often simpler than adding an SSE stream, so the decision also depends on what connections the client already holds.
Choosing for common features#
| Feature | Good choice | Why |
|---|---|---|
| Chat and messaging | WebSockets | Frequent two-way messages, typing indicators, presence |
| Notifications and activity feeds | SSE (or long polling) | One-way, occasional, simple; mobile apps add push notifications |
| Live dashboards, scores, tickers | SSE | Server streams updates; client rarely talks |
| Collaborative editing, multiplayer | WebSockets | Low-latency two-way operations |
| Payment or CI status to your backend | Webhooks | Provider-to-server events |
| Video and voice calls | WebRTC (+ WebSockets for signalling) | Real-time media needs UDP and peer paths |
| Rare updates, simplest possible | Short polling | A job status page polled every 10 s is fine |
Choosing in detail#
Chat (WhatsApp, Slack style). WebSockets to a gateway tier; durable message store with per-conversation sequence numbers; presence registry plus pub/sub or targeted routing; push notifications for offline users; resume by cursor. Typing indicators and read receipts are ephemeral, so they are sent over the socket without being stored.
Notifications and feeds. Usually SSE or a WebSocket that is already open for other reasons. Updates are one-way and infrequent. Store notifications, push a small "new item" event, and let the client fetch details. On mobile, platform push notifications carry most of the load.
Live dashboards, scores, auctions, tickers. SSE, or short polling of a CDN-cached endpoint when millions watch the same data. Coalesce rapid changes into the latest value every few hundred milliseconds. For an auction, the bid itself is a normal HTTP POST that is validated and stored, and the new price is broadcast over SSE.
Collaborative editing and multiplayer. WebSockets, with every participant of one document or game routed to the same server (consistent hashing on the document or room ID), so the server orders operations in memory. Operational transformation or CRDTs merge concurrent edits. WebRTC data channels are an option for small peer groups.
Ride-hailing locations. Drivers send GPS updates every few seconds (HTTP or a socket); riders watching one trip receive their driver's position over a WebSocket or SSE. The server throttles location pushes to a few per second.
AI chat assistants. SSE, or streamed HTTP responses, carry tokens as they are generated. This is a classic one-way stream: the prompt is a normal POST, and the answer streams back.
Server-to-server events. Webhooks between companies; inside one company, a message queue or event stream is usually better than webhooks (see Real-time Updates pattern).
Load balancers and connection limits#
Long-lived connections change scaling:
- Each connection costs memory (often tens of KB including buffers), so one well-tuned server holds roughly 100,000 or more idle connections, limited by memory, file descriptors and kernel settings.
- The load balancer must support it: WebSocket upgrade, long idle timeouts (or heartbeats every 20-30 seconds to keep connections alive), and enough connection capacity.
- Balancing is by connection, not message, so after a deploy or scale-up, load is uneven until clients reconnect. Use least-connections balancing.
- Routing messages to users: user A on server 1 sends to user B on server 7. You need a registry of which server holds which user, or a pub/sub layer (Redis Pub/Sub, Kafka, NATS) that all servers subscribe to. See Pattern: Real-time Updates.
- Reconnect storms: if a server dies, its 100,000 clients reconnect at once. Clients must use exponential backoff with jitter.
Hop two: getting events to the right connection server#
Suppose 10 million users are connected across 200 connection servers (gateways). User A, on gateway 17, sends a message to user B. Which gateway holds B, and how does the message get there? There are three broad answers.
1. Pull: gateways poll the source. Each gateway periodically queries the database or an event log for news about its connected users ("any new messages for these 50,000 users since my last check?"). This is simple and needs no extra infrastructure. But it adds the poll interval to latency, and 200 gateways each polling for 50,000 users puts heavy, mostly empty read load on the database. It fits low-rate updates such as a job dashboard, or a gateway reading a partitioned log such as Kafka, where "polling" is a cheap sequential read.
2. Push with consistent hashing: route users to known gateways. Decide which gateway owns each user (or each room or document) with a consistent hash of its ID. Clients are directed to their owning gateway at connect time, through a lookup service or a load balancer that hashes on the ID. Any service that wants to reach user B computes the same hash and sends the event straight to that gateway. This is efficient: one hop, no broadcast, and all collaborators on a document land on the same server, which makes ordering and in-memory state easy. The costs: when gateways are added or removed, some users must move and reconnect; a hot room or celebrity concentrates on one server; and you need a coordination service (such as ZooKeeper or etcd) so everyone agrees on the hash ring. See Consistent Hashing.
3. Push via pub/sub: gateways subscribe to topics. Each gateway subscribes to a channel per connected user or room on a pub/sub system (Redis Pub/Sub, NATS, or Kafka with a consumer per gateway). Publishers write to channel user:B without knowing where B is; the pub/sub layer delivers to whichever gateway subscribed. Clients can connect to any gateway, so plain least-connections balancing works, and gateways stay stateless apart from their sockets. The costs: an extra hop, a pub/sub cluster that must scale with the total message rate, and the fact that Redis Pub/Sub is fire-and-forget, so a gateway that is briefly disconnected misses messages. This is why durable storage plus resume-by-ID is still needed.
| Approach | Latency | Infra | Balancing | Best for |
|---|---|---|---|---|
| Gateways poll the source | Poll interval | None extra | Any | Low-rate updates, log-based sources |
| Consistent hashing | Lowest, one hop | Ring coordination | By user or room ID | Collaborative docs, game rooms, stateful sessions |
| Pub/sub | Low, one extra hop | Pub/sub cluster | Any, least connections | Chat, notifications, general fan-out |
Many large systems combine them. A presence registry (user to gateway, kept in Redis with a TTL that heartbeats refresh) gives targeted delivery for one-to-one messages. Pub/sub topics per room handle group fan-out, and consistent hashing places stateful rooms or documents.
Where the events come from. Hop two starts at the source, and the source is often a database write rather than a message service. Having every service remember to publish an event after each write is fragile: a crash between the database commit and the publish loses the event. Two safer options are change data capture, which reads the database's own change log (for example with Debezium into Kafka), and the outbox pattern, which writes the event into an outbox table in the same transaction as the data and has a relay publish it afterwards. Either way, every committed change produces exactly one event for the real-time tier to fan out. See Change Data Capture and the Outbox Pattern.
Fan-out to millions: the celebrity problem#
What happens when one event must reach millions of connected users, such as a goal in a World Cup match, a celebrity's live stream comments, or a price tick on a popular stock? Sending 5 million individual messages through pub/sub, one per user channel, overwhelms the publisher and the pub/sub layer.
The standard fixes:
- Fan out to gateways, not users. Publish once to a topic for the match. Each of the 500 gateways subscribes once and delivers locally to its own connected viewers. The pub/sub layer handles 500 deliveries instead of 5 million; each gateway writes to its 10,000 sockets from memory.
- Fan-out trees. With very many gateways, add relay tiers: the source sends to 20 relays, each relays to 25 gateways. Each layer multiplies reach while keeping each node's fan-out bounded.
- Coalesce and sample. Viewers do not need every one of 50,000 comments per second. Send a sample, batch updates into one frame every 100-500 ms, or send only the latest value (the current score, not every intermediate change).
- Cache instead of push. For updates that are the same for everyone and can tolerate a second of staleness, push a tiny "something changed" signal and let clients fetch the content from a CDN, or simply let clients poll a cached endpoint. A CDN absorbs millions of identical requests easily.
- Jitter the reactions. If a push makes every client fetch something, spread the fetches with random delays so they do not hit the backend in the same millisecond.
Message ordering across servers#
Users expect messages in a conversation to appear in the same order for everyone. With many servers this is not free:
- Assign order at one place per conversation. Route all writes for a chat room through the room's owner (by consistent hashing), or use a database sequence or a per-conversation counter, so each message gets a monotonically increasing sequence number. Kafka gives ordering within a partition, so partitioning by conversation ID orders each conversation.
- Do not trust client clocks. Phones' clocks drift; order by server-assigned sequence or time, and use the client's timestamp only for display.
- Clients reorder and fill gaps. If a client has message 41 and receives 43, it knows 42 is missing, waits briefly, then fetches it. Messages carry a client-generated ID too, so a retried send is deduplicated rather than shown twice.
- Global order is rarely needed. Order matters within a conversation or document, not across all of them, and per-conversation ordering scales far better.
Reconnection, without losing messages#
Connections break all the time: phones switch between Wi-Fi and mobile data, laptops sleep, gateways deploy. A robust design assumes it:
- Store before sending. Write each message to durable storage with its sequence number, then push it. The live connection is a fast path, not the system of record.
- Resume from a cursor. On reconnect the client sends its last sequence number per conversation (or one global cursor), and the server sends everything after it, or tells the client to do a full sync if it was away too long.
- Back off with jitter. Retry after roughly 0.5, 1, 2, 4 seconds, up to about 30 seconds, each multiplied by a random factor, so a gateway crash does not turn 100,000 clients into a synchronised reconnect storm.
- Detect dead connections. TCP may not notice for minutes that a phone vanished. Application heartbeats (ping every 20-30 seconds, close after two missed) keep presence accurate and free resources.
- Drain gracefully on deploy. Tell clients to reconnect elsewhere in small batches over a few minutes, instead of closing all sockets at once.
- Offline users get push notifications. When the presence registry says a user has no live connection, deliver through APNs (Apple) or FCM (Google). Mobile operating systems suspend background apps' sockets, so platform push is the only reliable path to a phone in a pocket.
Sizing a connection tier, worked example#
A chat app has 50 million daily users, and at peak 10 million are connected at once. Each connected user receives about one message every 10 seconds and sends one every 60 seconds.
- Connections. Assume a tuned gateway holds 100,000 connections comfortably, leaving headroom. 10,000,000 ÷ 100,000 = 100 gateways. Add 30-50% headroom for losing a zone and for reconnect bursts: about 140 gateways.
- Memory. At roughly 20-50 KB per connection (kernel socket buffers, TLS state, application state), 100,000 connections need 2-5 GB, well within a typical server.
- Message rate. Inbound: 10 M ÷ 60 s, about 170,000 messages per second. Outbound: 10 M ÷ 10 s = 1 million deliveries per second, about 7,000 per gateway, which is easy.
- Heartbeats. A ping every 25 seconds per connection is 400,000 pings per second across the fleet, more than the real messages. Heartbeat cost is a real part of the budget; longer intervals save it but detect dead clients later.
- Reconnect storm. If one gateway dies, 100,000 clients reconnect. Without jitter they arrive within a second, and each reconnect costs a TLS handshake and an authentication check. With jitter spread over 30 seconds that is about 3,300 per second, which the other gateways absorb.
The same arithmetic shows why polling is costly here: 10 million clients polling every 5 seconds is 2 million requests per second, each with full HTTP and authentication overhead, mostly returning nothing.
Running long-lived connections in production#
Operating-system limits. Each connection uses a file descriptor, so raise the per-process limit (ulimit -n, LimitNOFILE in systemd) far beyond the default of 1,024. Tune kernel socket buffer sizes, because default buffers multiplied by a million connections can use many gigabytes. On the load balancer or proxy side, each upstream connection uses a local port. One source IP talking to one backend IP and port has roughly 28,000-64,000 ephemeral ports, so proxies holding many connections to a few backends need several source IPs or several backend ports. Stateful firewalls and NAT gateways have connection-tracking tables that can fill up too.
Event-driven servers. One thread per connection does not scale to 100,000 connections, because thread stacks and context switches dominate. Gateways use event loops built on epoll (Linux) or kqueue (BSD and macOS): one thread watches thousands of sockets and handles only those with data. Node.js, Go, Netty (Java), Elixir and Erlang on the BEAM VM, and Rust's tokio all work this way. Public examples show what is possible: the Phoenix framework team reported 2 million WebSocket connections on a single large server in 2015, and WhatsApp described over 2 million TCP connections per server on Erlang and FreeBSD in 2012. Real deployments run far below such limits to leave headroom.
Load balancer settings. Use L4 balancing, or L7 with WebSocket support. Set idle timeouts above the heartbeat interval. Use least-connections balancing so new connections go to the emptiest gateway. Remember that a newly added gateway gets no existing connections until clients reconnect. Some systems deliberately recycle connections every few hours (the server closes them and clients reconnect elsewhere) to rebalance load and pick up new deployments.
Deploys. A gateway deploy closes every socket on that machine. Use rolling deploys with draining: stop sending new connections to the old instance, ask its clients to reconnect over a few minutes, then stop it. Keep gateways thin (authentication, routing, fan-out) so they rarely need deploying, and put business logic in stateless services behind them.
Observability. Track connections per gateway, connect and disconnect rates, reconnect reasons (close codes), message delivery latency from send to receive (end-to-end, measured with timestamps in messages), per-connection send-buffer sizes (a growing buffer is a slow consumer) and pub/sub lag.
When to Use It#
- Short polling for rare updates where seconds of delay are fine.
- Long polling when you need near real-time but cannot use streaming (restrictive networks, legacy clients).
- SSE for one-way live updates to browsers.
- WebSockets for interactive two-way features.
- Webhooks to receive or deliver events between companies' systems.
- WebRTC for real-time audio, video or peer data.
When NOT to Use It#
- Do not use WebSockets for a status that changes once a minute; polling or SSE is cheaper.
- Do not use these for mobile apps in the background; the OS suspends connections, so use platform push notifications (APNs, FCM).
- Do not rely on a live connection as the only delivery path; store messages so clients can fetch what they missed.
How to Implement It#
- Pick the mechanism from direction, frequency and latency needs.
- Separate the connection tier (WebSocket/SSE gateways) from business services, so it scales on connection count.
- Add a pub/sub layer and a presence registry to route messages to the right gateway.
- Persist messages and give each an ID, so clients resume from the last ID after reconnecting.
- Configure LB timeouts and heartbeats, and make clients reconnect with backoff and jitter.
- For webhooks: sign payloads, retry with backoff, and make receivers idempotent.
// Client: resilient WebSocket with backoff and resume
let attempt = 0, lastId = 0;
function connect() {
const ws = new WebSocket(`wss://chat.example.com/ws?after=${lastId}`);
ws.onopen = () => { attempt = 0; };
ws.onmessage = (e) => { const m = JSON.parse(e.data); lastId = m.id; render(m); };
ws.onclose = () => {
const delay = Math.min(30000, 500 * 2 ** attempt++) * (0.5 + Math.random());
setTimeout(connect, delay); // exponential backoff with jitter
};
}
connect();| Technology | Fits when |
|---|---|
| Socket.IO, ws (Node), Centrifugo | Building WebSocket servers with rooms and fallbacks |
| AWS API Gateway WebSockets, Azure Web PubSub, Ably, Pusher | Managed real-time connections |
| Redis Pub/Sub, NATS, Kafka | Fan-out between connection servers |
| mediasoup, Janus, LiveKit | WebRTC SFUs for group calls |
| coturn | STUN/TURN for NAT traversal |
Trade-offs#
| Mechanism | Gain | Cost | Pick when |
|---|---|---|---|
| Short polling | Simplest, stateless, cacheable | Wasted requests, delay | Rare updates |
| Long polling | Near real-time over plain HTTP | Reconnect per message, held requests | Fallback, restrictive networks |
| SSE | Simple streaming, auto-reconnect | One-way, text only | Feeds, dashboards, notifications |
| WebSockets | Lowest latency, two-way | Stateful servers, custom reconnect logic | Chat, games, collaboration |
| Webhooks | No polling between companies | Retries, idempotency, security work | Server-to-server events |
| WebRTC | Real-time media, peer-to-peer | NAT traversal, media servers | Calls and live media |
| Pub/sub routing | Clients connect anywhere, simple balancing | Extra hop, pub/sub cluster, not durable by itself | Chat, notifications, general fan-out |
| Consistent-hash routing | One hop, room state in one place | Rebalancing on scale events, hot rooms | Collaborative docs, game rooms |
| Platform push (APNs, FCM) | Reaches suspended mobile apps | Delays, payload limits, no delivery guarantee | Offline users, background alerts |
Common Pitfalls#
- Holding all users' connections with no pub/sub, so messages only reach users on the same server.
- No resume mechanism, so messages sent during a reconnect are lost.
- Load balancer idle timeouts (often 60 s) silently dropping quiet connections.
- Reconnect storms after a deploy, because every client retries immediately.
- Webhook receivers that do slow work before replying, causing timeouts and duplicate deliveries.
- Sending events over the socket without storing them first, so a reconnect loses them.
- Ignoring hop two, so a message only reaches users connected to the same server.
- Leaving SSE behind a buffering proxy or compressor, so events arrive in one late lump.
- Broadcasting to millions of user channels individually instead of once per gateway.
- Accepting unauthenticated WebSocket connections that hold server memory indefinitely.
- Verifying webhook signatures against re-serialised JSON instead of the raw body.
Real-World Examples#
Slack has publicly described using WebSockets for its real-time messaging, with clients connecting to gateway servers that receive messages from backend services.
Stripe sends webhooks for payment events, signs them with a per-endpoint secret, and retries failed deliveries over several days, so receivers are expected to verify signatures and handle duplicates.
Facebook described its original web chat (2008) as long polling against Erlang servers, and later used MQTT for Messenger's mobile client. WhatsApp's Erlang servers were reported in 2012 to hold over 2 million connections each. Zoom, Google Meet and most conferencing products route group calls through SFU-style media servers rather than full peer-to-peer meshes.
In the Interview#
How to present real-time updates in an interview#
Interviewers like a clear structure here, because many candidates have never built real-time systems themselves:
- Justify real-time. Say which requirement needs it ("riders must see the driver move", "bidders must see a new price within a second") and how fresh it must be. If seconds are fine, say polling is enough and move on.
- Pick hop one by direction and frequency. One-way and occasional: SSE or long polling. Two-way and frequent: WebSockets. Media: WebRTC. Server to server: webhooks or a queue.
- Design hop two explicitly. "Gateways register users in a presence store and subscribe to per-user channels on Redis Pub/Sub" or "documents are consistently hashed to editing servers". This is where strong answers stand out.
- Cover failure. Messages are stored with sequence numbers, clients resume from their last ID, reconnects back off with jitter, and offline users get push notifications.
- Give the scale numbers. Concurrent connections, connections per gateway, gateway count, messages per second.
Common scenarios where this comes up: chat (WhatsApp, Messenger), live comments on streams, collaborative documents (Google Docs), ride-hailing (Uber), live auctions, stock tickers (Robinhood), ticket queues (Ticketmaster), online games such as chess, fitness tracking with live friends' activity (Strava), flash sales and AI chat streaming.
When not to use real-time pushes: updates that are rare or can wait, data that changes constantly but nobody watches live, and systems where a simple refresh is acceptable. Adding WebSockets to a design that does not need them costs you credibility.
Follow-up questions to expect#
- "A user is connected on a phone and a laptop." The presence registry maps a user to a set of connections; deliver to all of them and sync read state between devices.
- "How do you handle a celebrity with 10 million live viewers?" Fan out to gateways, not users; coalesce or sample updates; consider CDN-cached polling for identical data.
- "What if Redis Pub/Sub drops a message?" It is not durable, so the store is the source of truth; clients detect gaps by sequence number and fetch missing messages.
- "How do you know a user is online?" Heartbeats refresh a presence entry with a TTL of about two heartbeat intervals; when it expires the user is offline. Broadcast presence changes lazily, because presence fan-out for large friend lists is expensive.
- "Why not just use HTTP/2 server push?" HTTP/2 server push was designed to send resources the browser will need for a page, not application events, and major browsers have removed support for it. SSE over HTTP/2 is the right tool for streaming events.
Deep Dive: Delivery guarantees, backpressure and scaling to millionsShow
Connections do not guarantee delivery. A message written to a socket can be lost if the connection drops before the client processes it. Reliable systems store messages with sequence numbers, let clients acknowledge them, and resend unacknowledged ones on reconnect. That gives at-least-once delivery; clients deduplicate by message ID.
Backpressure. A slow client (bad mobile network) cannot read as fast as the server sends. If the server buffers without limit, memory grows until it crashes. Set per-connection buffer limits, and drop, coalesce (send only the latest score) or disconnect slow consumers.
Scaling to millions of connections. Gateways are sized on connections and messages per second, not on CPU for business logic. Large systems shard users across gateway clusters, keep gateways thin (auth, routing, fan-out only), and keep presence data in a fast store with TTLs so dead entries expire. Graceful drains during deploys (tell clients to reconnect elsewhere in batches) prevent reconnect storms.
HTTP/2 and HTTP/3 change the picture. SSE over HTTP/2 avoids the old browser limit of ~6 connections per domain. WebTransport, built on HTTP/3, offers bidirectional streams and unreliable datagrams in browsers, and may replace some WebSocket and WebRTC data-channel uses over time.
Deep Dive: Inside a WebSocket gateway at scaleShow
Thin gateways. Large systems split the real-time path into gateways that only terminate connections (TLS, WebSocket framing, authentication, heartbeats, per-connection buffers) and backend services that own the logic. Gateways can then be scaled on connection count and restarted rarely, while services deploy freely. Slack, for example, has described a design with gateway servers holding client WebSockets and separate channel servers, located by consistent hashing, that hold channel state and fan messages out to the gateways.
Memory per connection. On Linux, each TCP socket has receive and send buffers that grow automatically up to configured limits; idle sockets use little, busy ones much more. TLS adds state for the session, and compression adds per-connection context (permessage-deflate with default settings can cost tens of KB per connection, so large fleets often disable it or limit its window size). Application state (user ID, subscriptions, a small outbound queue) adds the rest. Measuring real memory per connection under load is more reliable than estimates.
Slow consumers and backpressure. When a client reads more slowly than messages arrive, the kernel's send buffer fills, then the application's outbound queue grows. A safe gateway caps each connection's queue (by messages or bytes), and when it is exceeded either drops low-value messages (typing indicators, intermediate positions), collapses updates to the latest state, or closes the connection with a "too slow" code so the client reconnects and resyncs from the store. Without a cap, one region with a bad mobile network can push gateways out of memory.
Head-of-line blocking. A WebSocket runs over one TCP connection, so one lost packet delays every message behind it until it is retransmitted. For chat this is fine. For games and live media, where only the newest data matters, UDP-based transports (WebRTC data channels in unreliable mode, or WebTransport over HTTP/3 and QUIC) avoid it.
Fairness and abuse. Rate-limit messages per connection and per user, limit subscriptions per connection, cap message sizes, and authenticate before allocating expensive state. A WebSocket endpoint is a long-lived resource, so a flood of idle connections is a cheap denial-of-service attack unless connections must authenticate within a few seconds.
Zone and region failure. Spread gateways across zones; when a zone fails, its clients reconnect to the others, so plan capacity for N-1 zones. Across regions, connect users to the nearest region and replicate messages between regions asynchronously, accepting a short cross-region delay for users talking across continents.
Deep Dive: Delivery semantics, presence and newer transportsShow
Exactly-once is an illusion on the wire. A sender cannot tell whether a lost acknowledgement means the message was lost or the ack was. So real-time systems use at-least-once delivery plus deduplication: every message has an ID (client-generated for sends, server sequence for receipt), and both sides ignore duplicates. The result looks exactly-once to users. See Delivery Semantics.
Acknowledgement levels. Chat apps typically show three: sent (the server stored it), delivered (a recipient's device received it) and read (the recipient opened it). Each is a small message flowing back to the sender, so acknowledgements roughly triple the message count, which matters when sizing.
Presence is expensive. If each of 10 million online users has 200 friends, broadcasting every online or offline change means up to 2 billion notifications as people come and go. Systems reduce this by fetching friends' presence only when a contact list is open, batching changes, delaying "offline" for a grace period so brief disconnects do not flicker, and limiting presence to small groups.
Long polling, SSE and WebSockets over HTTP/2 and HTTP/3. SSE benefits most from HTTP/2: many streams share one connection, removing the 6-per-host limit. RFC 8441 (2018) defines how to carry WebSockets over HTTP/2 streams, and RFC 9220 (2022) over HTTP/3, though support across servers and proxies is uneven. WebTransport, built on HTTP/3 and QUIC, gives browsers multiple reliable streams without head-of-line blocking between them, plus unreliable datagrams, a combination that previously needed WebRTC.
MQTT and mobile. For IoT devices and some mobile apps, MQTT, a lightweight publish/subscribe protocol over TCP (or over WebSockets in browsers), is common. It has small headers, three delivery levels (QoS 0 at most once, 1 at least once, 2 exactly once between client and broker) and retained messages. Facebook Messenger was described as using MQTT for its mobile client in 2011 to save battery and bandwidth.
Key Takeaways#
- HTTP cannot push, so use polling, long polling, SSE, WebSockets, webhooks or WebRTC depending on direction and latency.
- SSE is the simplest choice for one-way live updates; WebSockets for frequent two-way messaging.
- Webhooks push events between servers and need retries, signatures and idempotent receivers.
- WebRTC carries real-time media peer to peer, with STUN/TURN for NAT and SFUs for groups.
- Long-lived connections need a connection tier, pub/sub routing, heartbeats, resume by message ID and backoff on reconnect.
- Split every real-time feature into hop one (server to client) and hop two (source to the right server), and design both.
- Short polling is fine for rare updates; long polling and SSE handle one-way updates over plain HTTP; WebSockets are for frequent two-way traffic.
- Store messages with sequence numbers before pushing, and resume by cursor after reconnects.
- Fan out once per gateway, coalesce rapid updates and use CDN-cached polling for identical data watched by millions.
- WebRTC is for calls and conferencing, with STUN, TURN and SFUs; webhooks need signatures, retries, idempotency and reconciliation.