1. What It Is
Some features cannot wait for the client to ask. A chat message, a new comment, a driver's position or a score change should reach the screen in about a second, so the server has to push. Real-time delivery covers the four transports that do this and the machinery around them that makes a million connections survivable.
What:
Short polling, long polling, Server-Sent Events (SSE) and WebSocket as ways to move a server event to a client, plus a gateway tier, a user to gateway routing map, heartbeats, reconnect with backoff, resume by sequence number and a mobile push fallback.
Primary purpose:
Deliver events with low latency and low per-event cost while every individual connection is allowed to die at any moment without losing or duplicating visible data.
Usually used for:
Chat, live comments and reactions, presence, live dashboards, vehicle tracking, notifications and any feature where freshness is measured in seconds.
2. Core Mental Model
Answer three separate questions. Transport is how a frame travels, routing is which machine holds this user's connection, and recovery is what happens when that connection dies. Most candidates answer only the first, and the interview is decided on the other two.
π‘ Transport is the easy part
Pick the cheapest option that meets the direction and latency need. Polling asks, SSE streams one way, and WebSocket talks both ways on one socket.
π§ Routing is the hard part
A connection is state that lives on exactly one gateway. To reach a user you must find that gateway, which is a directory lookup or a topic subscription.
π©Ή Recovery makes it real
Sockets drop constantly. Every frame carries a per-stream sequence number, the client acknowledges, and a reconnect resumes from the last number applied.
In the room
Say it in one breath: clients hold a WebSocket to a thin gateway tier, a user to gateway map in Redis tells us where to publish, every frame carries a per-stream sequence number, and when the socket is gone we send a push and let the client resume from its last number.
3. Why It Matters in HLD
The first number an interviewer expects is what polling costs, because it shows why persistent connections exist. Here is the arithmetic for one million online users:
| Approach | Math | Result |
|---|---|---|
| Short polling every 5 s | 1,000,000 online users / 5 s | 200,000 requests per second, nearly all empty, and an event waits 2.5 s on average (T / 2) |
| Long polling with a 30 s hold on a quiet stream | 1,000,000 users / 30 s | about 33,333 requests per second, plus 1,000,000 requests parked on the servers |
| SSE or WebSocket | 1,000,000 open connections x 64 KB planning budget | about 64 GB of connection memory, one frame per event and no empty requests |
Persistent connections win on request volume and latency, and they pay for it with state. Three lenses:
Needed When:
Freshness is measured in seconds, many viewers watch the same stream, or the client and server both talk often, as in chat, comments, presence and live maps.
Avoids:
Millions of empty poll requests, stale screens, messages lost across a disconnect, and reconnect storms that take down the fleet that survived the first failure.
Optimizes For:
Latency per event, request overhead, mobile battery and the ability to recover a client without a manual refresh.
4. Architecture & Data Flow
Walk the diagram in order. Setup: a client opens a socket through an L4 balancer, and its gateway verifies the token and writes a user to gateway entry with a TTL. Steps 1 to 4 (send): the sender's gateway hands the frame to a stateless service that assigns the next sequence number, appends it to a durable log and confirms, and only then is the sender acknowledged. Steps 5 and 6 (route): the gateway looks up the recipient's gateway and publishes the frame to that gateway's channel. Steps 7 and 8 (deliver): the recipient's gateway writes the frame to its socket and the client acknowledges the sequence number. Fallback: if no live session exists, a push goes out and the client resumes from the log when it returns.
Why the gateway is its own tier
A gateway terminates TLS, checks the token, parses frames, tracks heartbeats, keeps the subscription registry and owns each connection's buffers, and it does nothing else. It scales on connections and memory while business services scale on CPU and requests, so the two fleets need different sizes. Every restart of a gateway drops its sockets, so it should change rarely and deploy slowly, whereas business code ships daily. Keeping them apart also means a bug in message handling cannot disconnect 100,000 users, and the stateless services behind the gateway keep ordinary load balancing and retries.
Frames and routing keys
interface ServerFrame {
streamId: string;
seq: number; // dense per-stream counter from the stream's sequencer
messageId: string; // stable id so replays and retries can be deduped
payload: unknown;
}
interface ClientResume { type: "resume"; streamId: string; lastSeq: number } // lastSeq = applied, not just received
interface ClientAck { type: "ack"; streamId: string; upToSeq: number } // cumulative# connect and every heartbeat: 90 s is three missed 30 s heartbeats (per device keys avoid one phone keeping a dead laptop alive)
# the chat problem uses a longer 5 minute TTL on its own session map, which only changes how long a dead entry lingers
SET ws_location:u42:device-7 gateway-G2 EX 90
SADD user_devices:u42 device-7
# the sender's gateway finds every live device of the recipient (a nil result means that device is offline)
SMEMBERS user_devices:u42
MGET ws_location:u42:device-7 ws_location:u42:device-9
# each gateway listens on its own channel, and the sender's gateway publishes to the recipient's
SUBSCRIBE gw:G2
PUBLISH gw:G2 "frame for u42, stream chat:c9, seq 118"In the room
Draw the gateway as a separate box before you draw anything else, then say that the log is the source of truth and the socket is only a fast path. That one sentence answers most follow-up questions about lost messages.
5. Key Characteristics
The four transports differ on the dimensions an interviewer will probe, so compare them on direction, protocol, proxy behaviour, reconnect, HTTP/2 and battery:
| Dimension | Short polling | Long polling | SSE | WebSocket |
|---|---|---|---|---|
| Direction | Client asks and the server answers | Client asks and the server answers when it has something | Server to client only, and upstream data goes over ordinary HTTP requests | Full duplex, so either side can send at any time |
| Protocol | Plain HTTP request and response | Plain HTTP, with the response held until an event or a timeout | One long HTTP response of type text/event-stream, UTF-8 text only | HTTP Upgrade handshake, then RFC 6455 frames on one TCP connection, text or binary |
| Proxies and load balancers | Works everywhere and balances per request | Works everywhere, but every idle timeout must exceed the hold time | Works through most HTTP infrastructure, but a proxy or CDN that buffers responses delays events | Needs Upgrade support end to end, long idle timeouts and a connection aware balancer |
| Reconnect behaviour | Nothing to reconnect, every poll is a fresh request | Client reissues the request after each response or timeout | Browser EventSource retries on its own and sends Last-Event-ID if the server set event ids | None built in, so you write backoff, jitter and resume yourself |
| HTTP/2 multiplexing | Many polls share one connection | Each parked request is a stream on a shared connection | Streams share one connection, which removes the HTTP/1.1 browser limit of about 6 connections per host | Usually its own TCP connection, and WebSocket over HTTP/2 exists but is less widely deployed |
| Mobile battery | Worst, because every poll can wake the radio | Better, though each reissue still costs a request | Fine in the foreground, one connection with a sparse keepalive | Same as SSE, and the OS suspends it in the background |
Scaling persistent connections
Two per-connection memory figures appear on this site, and they answer different questions. The Network Protocols page quotes about 10 to 20 KB, which is the floor for one idle socket in a lean event-driven runtime. The chat problem budgets 64 KB of kernel and user-space buffers per connection, a deliberately generous planning figure that leaves room for TLS state, send and receive buffers (a TLS record carries up to 16 KB of plaintext) and a short outbound queue. Use 10 to 20 KB to reason about what an idle connection costs at minimum and 64 KB to provision a gateway. At 100,000 sockets that is 100,000 x 64 KB = 6.4 GB against 1 to 2 GB at the idle floor. This page sizes with 64 KB so its numbers match the chat problem, and a real fleet should be measured under load because buffers grow when clients are slow. The 100,000 sockets per gateway is likewise a chosen memory budget and blast radius rather than a kernel limit, since well tuned servers can hold several times that, but one crash then drops all of them at once.
Every socket is also a file descriptor, so the process limit must be raised far above its default. Inbound connections to a gateway do not hit a port limit, because each client brings its own address and port while the server keeps listening on one port such as 443. The limit bites on a hop where one machine opens many outbound connections to the same destination address and port, such as a proxy that opens one upstream connection per client. Each of those needs its own source port, and the Linux default ephemeral range of 32768 to 60999 allows only about 28,000. Widening the range raises that to at most about 64,000 per source address, destination address and destination port, so that hop needs several source addresses or a pass-through L4 balancer that opens no second connection. At steady state connections are nearly idle, so memory and descriptors run out long before CPU does, and CPU only spikes during TLS handshakes in a reconnect wave.
The worked sizing below uses 10 million concurrent connections, the same scale as the chat problem:
| Step | Calculation | Result |
|---|---|---|
| Memory per gateway | 100,000 connections x 64 KB = 6,400,000 KB | about 6.4 GB, the same figure the chat problem uses. At the 10 to 20 KB idle floor it would be 1 to 2 GB, so 64 KB is the safe provisioning budget |
| Gateways if packed full | 10,000,000 / 100,000 | 100 gateways with no spare capacity |
| Gateways with zone headroom | 3 zones, and losing one zone pushes its third onto the other two. Fill each gateway to 2/3, about 66,667 connections, so 10,000,000 / 66,667 | 150 gateways, 50 per zone |
| Fleet connection memory | 10,000,000 x 64 KB = 640,000,000 KB | about 640 GB in total, or about 4.3 GB per gateway at 66,667 connections |
| File descriptors | One per socket, so at least 100,000 per process plus headroom for logs and upstream sockets | raise the open file limit far above 100,000, since Linux often ships a soft limit of 1,024 |
| Heartbeat load | 10,000,000 / 30 s = 333,333 pings per second, then / 150 gateways | about 2,222 pings per second per gateway, which is small |
| Zone loss reconnect wave | 50 gateways x 66,667 = 3,333,350 connections. Spread over 60 s of jitter: 3,333,350 / 60 | about 55,600 new connections per second across 100 survivors, or about 556 each, and every survivor ends at 100,000 connections, which is why the headroom was needed |
Heartbeats and liveness
TCP cannot tell you that a phone left coverage or a NAT mapping expired, because no FIN or RST ever arrives. TCP keepalive is off unless the application enables it, and where it is on, the Linux default idle time is two hours. Proxies, NATs and balancers also close silent connections. Their idle timeouts start at about a minute (the default for an AWS Application Load Balancer and for nginx proxy_read_timeout) and run to several minutes (350 seconds for a Network Load Balancer TCP flow), so heartbeats double as keepalives and must arrive more often than the shortest timeout on the path. The standard design is a ping every 30 seconds, which stays under a 60 second timeout, and a cutoff after two or three missed intervals, which means 60 to 90 seconds. The chat problem pings every 30 seconds and cuts at 90, and the presence problem refreshes a 60 second TTL every 30 seconds.
Browsers cannot send WebSocket ping frames from JavaScript, so web clients send an application level heartbeat message while the server uses protocol pings, which browsers answer on their own. Each heartbeat also refreshes the routing entry, so a dead gateway or client stops attracting traffic. A shorter interval detects faster but costs battery and load, because 10,000,000 / 10 s is 1,000,000 pings per second against 333,333 at 30 seconds.
6. Strategic Tradeoffs
Persistent connections trade request volume for state, so we state both sides:
| Benefit | Cost |
|---|---|
| Low latency push (an event reaches the client in about one network trip with no request overhead per event) | A stateful tier (every connection pins memory and a file descriptor, and every deploy or crash forces a reconnect wave) |
| Cheap at high fan-out (one open socket replaces thousands of empty polls per user per day) | A routing problem (something must know which gateway holds each user, and keep that map fresh) |
| Server controls pacing (batching, sampling and coalescing happen before the socket write) | Protocol work you own (heartbeats, backoff, resume, dedupe and slow consumer handling are all yours) |
Routing: stateless gateways versus sticky routing
Routing decides how a message finds the one gateway holding the socket. The chat and presence problems keep gateways stateless and use a directory in Redis, the live comments and reactions problems subscribe each gateway to a stream channel, and sticky hashing suits only small fleets or rooms pinned to one node. Pub/sub is a fast path rather than a guarantee, so every style needs the resume path from section 11 to repair a missed delivery.
| Routing style | Mechanic | Good when | Breaks when |
|---|---|---|---|
| Stateless gateways with a directory | Any gateway accepts any client. A fast store maps user to gateway with a TTL, and the sender looks up the entry then publishes to that gateway's channel | Messages are addressed to specific users, as in chat, notifications and presence | The map is stale or the store is down, so the first delivery misses and the resume path repairs it |
| Topic subscription | Each gateway subscribes once to a stream channel and loops over its local sockets | The audience is defined by a topic, as in live comments, reactions and a map viewport | Pub/sub drops a message, so clients must detect a gap and replay |
| Sticky routing by hash | The balancer hashes user id or room id to a gateway, so the owner is computed and no lookup is needed | A small fleet, or a room that must live on one node such as a game room or shared document | A resize or failure remaps many users at once, and one hot room cannot spread out |
7. Failure / Bottleneck Awareness
Connections die constantly, so volunteer these failure modes before the interviewer asks:
Problem: A gateway crash, a deploy or a lost zone drops thousands of sockets at once, and every client retries on the same fixed schedule. TLS handshakes, token checks and resume reads hit the survivors together, and the second failure is worse than the first.
Mitigation: Exponential backoff with full jitter on the client, a per-gateway accept rate limit that answers with a retry hint, tokens that a gateway can verify locally, bounded resume reads, and deploys that drain a few gateways at a time.
Problem: A phone loses signal without a FIN, so the gateway still believes the socket is live. It holds memory and the routing map keeps sending frames into a void.
Mitigation: Heartbeats with a cutoff of two or three missed intervals, a routing TTL refreshed by each heartbeat, and no delivery marked complete until the client acknowledges the sequence number.
Problem: One client reads slowly, its send buffer fills and the gateway queues frames for it without limit. Memory climbs, and a fan-out loop that blocks on that socket delays everyone else.
Mitigation: Non-blocking writes with a bounded queue per connection, then coalesce, drop or disconnect according to the stream type, as in Backpressure and Load Shedding.
Problem: Pub/sub is fire and forget, and a routing entry can point at a gateway the user already left. The socket is healthy and a frame silently never arrives.
Mitigation: A dense per-stream sequence number lets the client see the gap, and it replays from the log or fetches a snapshot. The log, not the socket, is the source of truth.
8. Common HLD Usage
Eight problems on this site lean on this page, and each uses a different slice of it:
| Problem | Transport and scale | How this concept shows up |
|---|---|---|
| Design a Real-Time Chat Application | WebSocket, about 10M concurrent sockets at about 100,000 per gateway | A sessions:{user_id} map in Redis, Pub/Sub to the recipient's gateway, a 30 s heartbeat with a 90 s timeout, a per-conversation conversation_seq for resume sync, and APNs or FCM when no session exists. |
| Design a Live Comments System | WebSocket, 100 gateways x 100,000 viewers on one stream | Each gateway subscribes once to the stream channel. A crashed gateway's clients back off with jitter, send last_seen_comment_id, and the new gateway subscribes first, replays the gap, drains its buffer and the client dedupes. |
| Design Live Likes and Reactions | WebSocket frames every 500 ms | One batched delta per content_id per window, stamped with window_seq. Clients drop duplicates, detect a gap and fetch a fresh count snapshot. |
| Design a User Presence System | WebSocket with a 30 s heartbeat and a 60 s TTL | A killed app sends no logout frame, so the missed heartbeat expires the key. A per-device ws_location entry routes pushes to the right gateway. |
| Design a Real-Time Vehicle Tracking System | MQTT from vehicles, WebSocket to dashboards | Dashboards subscribe to geohash scoped channels, and a reconnecting client reloads current state over REST because only the latest position matters. |
| Design a Real-Time Dashboard and Metrics System | WebSocket push replacing 30 s client polling | One backend query serves every viewer sharing a context, heartbeats prune stale connections, and a reconnect receives a full snapshot. |
| Design a Notification System | Mobile push through APNs and FCM | The delivery path when no socket exists. Delivery is at-least-once with a 24 hour idempotency key, so a duplicate nudge is harmless. |
| Design a Video Conferencing System | WebSocket for signaling, UDP and SRTP for media | The socket carries join, SDP and ICE traffic, media avoids TCP head of line blocking, and a missed heartbeat reveals a dead SFU in under 3 s. |
9. Decision Signals
Choose the cheapest transport that meets the direction and latency need, and say the decision rule out loud:
| Situation | Pick | Why |
|---|---|---|
| Updates every minute or slower, or a few seconds of staleness is fine | Short polling | No connection state, cacheable at a CDN and trivially balanced. The early phase of the dashboard problem polls every 30 seconds |
| Events are occasional and the network or proxies are restrictive | Long polling | Plain HTTP survives almost any proxy, which is why some WebSocket libraries keep it as a fallback transport |
| Server to client only, browser clients, ordered text events | SSE | Native reconnect and Last-Event-ID, plain HTTP and the easiest to operate. It fits comment feeds, score tickers and token streaming |
| The client also sends often, both directions need low latency, or payloads are binary | WebSocket | One full duplex socket. It fits chat, typing indicators, collaborative editing and presence |
| Audio and video media | WebRTC over UDP | TCP head of line blocking stalls media, so a socket carries only signaling, as in the video conferencing problem |
| The mobile app is in the background | Mobile push (APNs, FCM) | The OS suspends sockets, so the connection serves only the foreground app |
Then add each recovery layer when its failure becomes visible to a user:
- A gateway tier and routing map as soon as the sockets no longer fit on one machine.
- Sequence numbers and resume as soon as a missed message is visible to the user.
- Mobile push whenever the app can be backgrounded or the user can be offline.
- One machine holds every socket, so an in-memory map replaces the Redis directory.
- Only the latest value matters, such as a map position or a total, so skip replay and send a snapshot on reconnect.
- Updates are not time critical, so push notifications or plain polling are enough.
- The payload is real-time media, which belongs on WebRTC and UDP rather than on a socket.
In the room
Expect the follow-ups to be what happens when a gateway dies, how you avoid a reconnect storm, how a client catches up and how you know a user is offline. The classic mistakes are saying WebSocket for everything, skipping heartbeats, using one global sequence, leaving per-connection queues unbounded, treating push as reliable delivery and retrying without jitter.
11. Deep Dive (Optional)
Reconnect with exponential backoff and full jitter
The delay before attempt n is a random number between 0 and min(cap, base x 2^n). With a base of 1 s and a cap of 30 s the ceilings are 1, 2, 4, 8 and 16 s, and then 30 s because 32 s is capped, so the mean delay is half of each ceiling. Reset the attempt counter only after the new connection has stayed healthy for a while, otherwise a server that accepts and then drops clients creates a tight retry loop.
function nextDelayMs(attempt: number, baseMs = 1000, capMs = 30000): number {
const ceiling = Math.min(capMs, baseMs * 2 ** attempt);
return Math.random() * ceiling; // full jitter, uniform in [0, ceiling)
}The window width is the knob that matters in a mass disconnect. If one gateway holding 100,000 sockets dies, 99 gateways remain. With no jitter, 100,000 / 99 is about 1,010 handshakes per survivor in the same instant. The 0 to 500 ms jitter in the live comments problem gives 100,000 / 0.5 s = 200,000 attempts per second, about 2,020 per survivor, which that fleet tolerates. A first window of 5 s gives 100,000 / 5 s = 20,000 per second, about 202 per survivor. A base of 1 s makes the first window only 1 s wide, so for a large fleet the server should send a wider retry hint, and each gateway should cap how many handshakes it accepts per second.
Resume, ordering and dedupe
Sequence numbers are per stream, such as per conversation or per content id, and dense, so a missing number is a visible gap. One sequencer per stream assigns them, and a global sequence is unnecessary and would become the bottleneck. A Snowflake id works as a resume cursor, as in the live comments problem, but it cannot reveal a gap, so use a dense counter when gap detection matters, as the reactions problem does with window_seq. The server must subscribe to live frames before it reads the log, because anything published between the read and the subscription would otherwise be lost.
Delivery is at-least-once, because an acknowledgement can be lost and a replay overlaps live frames, so the client dedupes by sequence number. Order holds within a stream because one sequencer numbers it, but a live frame can arrive before the replay, so the client orders by seq rather than by arrival. If the client's last number is older than the log retains, the server answers with a resync instruction and the client loads a snapshot. This is the effectively-once pattern from Idempotency & Exactly-Once Effects, applied at the edge.
function onFrame(f: ServerFrame, s: StreamState): void {
if (f.seq <= s.lastApplied) return; // duplicate from replay or retry
s.pending.set(f.seq, f);
while (s.pending.has(s.lastApplied + 1)) { // apply strictly in order
const next = s.pending.get(s.lastApplied + 1)!;
s.pending.delete(next.seq);
render(next);
s.lastApplied = next.seq;
}
if (s.pending.size > 0) scheduleGapRepair(s); // a hole remains, so ask for replay after a short wait
ackLater(s.streamId, s.lastApplied); // cumulative ack, batched
}Slow consumers and per-connection buffers
A successful socket write only copies bytes into the kernel send buffer, so it does not mean the client received anything. If the client cannot keep up, that buffer fills and a blocking write stalls the fan-out loop, so use non-blocking writes and a bounded queue per connection. The cap must appear in the sizing. If each queue may hold 256 KB, then 66,667 connections x 256 KB is about 17 GB in the worst case, four times the 4.3 GB baseline, so also set a gateway wide memory budget. What happens at the cap depends on the stream. Latest-state streams such as positions and counts coalesce to the newest value per key. Lossy feeds such as sampled comments drop the oldest frames. Must-deliver streams such as chat disconnect the slow client and let it resume from the log, so the gateway never stores unbounded history.
Falling back to mobile push
When the session lookup finds no live entry, or a frame stays unacknowledged past a deadline, publish a push job to APNs or FCM. A push is a nudge and not the data. It is best effort, can be delayed or dropped, has no ordering guarantee and should carry little content, so the durable log still holds the message and the app sends a resume with its last number when it opens. If the user reconnects between the lookup and the push, the result is a harmless extra nudge. Collapse many pending messages into one notification and rate limit per user, as the notification problem does. Choose by session presence rather than by device type, since a foreground app has a socket and a backgrounded one usually does not.
Review
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Discussion
Share your thoughts, ask questions, or help others.