One live comment must reach 1,000,000 open browsers within a second. Polling makes every browser ask, up to 500,000 times a second. Push keeps one connection open per viewer and sends the comment down it.
Pick a way to deliver, then drag the comment rate. Watch one viewer's timeline and the load on the servers. Then we build each piece: polling, long polling, Server-Sent Events, WebSockets, pub/sub, the connection tier and the reconnect storm.
You need to know what an HTTP request is and a little Python. We build the rest from zero.
An illustrative stream: 1,000,000 viewers, a 0.1 s network round trip, 800 bytes of headers per HTTP request and reply. Comment times on the timeline are random, drawn at the rate you set. The formulas behind each meter come in Chapters 1 to 4.
Chapter 0
Count what one comment costs when a million people watch the same stream
It is the tenth round of a boxing stream. A knockdown lands. One viewer types "HE'S DOWN!!" and presses send. That comment must appear, within about a second, in the browser of each of 1,000,000 viewers. None of them asked for it.
Saving the comment is one database write. Showing it is a million deliveries. The ratio between the two is the fan-out: the number of readers that one write must reach. A normal API call has a fan-out of one. This stream has a fan-out of a million.
Each teal pulse is one comment going to every viewer. Drag the comment rate and the audience, and read the bandwidth that leaves the servers.
Illustrative stream. Each dot stands for an equal share of the audience. A delivered comment is about 93 bytes of JSON. Framing and TLS add about 30 more. We round up to 150 bytes for longer comments.
How many bits leave the servers each second? Call the comment rate λ (lambda), in comments a second. Call the number of viewers N. Call the size of one delivered comment s, in bytes. Network makers rate links in bits, so multiply by 8. Call the result B.
B equals eight times s times lambda times N.
Multiply the comment rate lambda by the viewers N to get deliveries a second. Multiply that by the size s and by 8. The result is B.
With made-up numbers: lambda = 40, N = 1,000,000, s = 150. Deliveries are 40 × 1,000,000 = 40,000,000 a second. B = 8 × 150 × 40,000,000 = 48,000,000,000 bits a second, 48 Gbps. One 10 Gbps network card cannot carry that.
Each factor multiplies. Double the rate or the audience and B doubles. A title fight with 3,000,000 viewers needs 144 Gbps at the same rate.
Failure. Symptom: the comment box freezes at the big moments and works in quiet ones. Measure: plot deliveries a second, not writes a second. Fix: size for the peak product of lambda and N.
Chapter 1
Count the requests that a timer sends, and the share that come back empty
The simplest plan: each browser asks "anything new since comment 8214?" every few seconds. This is short polling. Each ask is a full HTTP request with headers and a cookie, and the server answers at once, even with nothing.
How many requests does that make? Call the number of viewers N and the poll interval T, in seconds. Call the requests a second that reach the servers Q.
Q equals N over T.
Each viewer sends one request every T seconds. N viewers send N divided by T each second.
N = 1,000,000 and T = 2 s give Q = 500,000 requests a second. Q does not depend on how many comments there are.
In a quiet stretch, most answers are empty. Comments arrive at random times, so we use the Poisson model: arrivals at an average rate λ, each one independent of the last. Call the share of polls that find nothing p0.
p-zero equals e to the minus lambda T.
Multiply lambda by T to get the average number of comments in one interval. Raise e to minus that number. The result is p-zero.
A quiet stretch: lambda = 0.1 and T = 2, so lambda T = 0.2 and p-zero = 0.82. Of 500,000 requests, 409,000 a second carry nothing. At 800 bytes of headers each, that is 2.6 Gbps of empty answers.
Teal marks are comments. Blue ticks are polls: hollow when empty. Yellow lines show how long each comment waited. Change the interval and the comment rate.
Comment times are random at the rate you pick. Fleet numbers use N = 1,000,000 and the formulas above; 800 bytes of headers per poll is an illustrative figure.
Each comment waits for the next poll. On average that is T/2, so T = 2 s means about 1 s of delay. A shorter T cuts the delay and raises Q in the same step.
Failure. Symptom: unrelated API calls slow down, because polls share their servers. Measure: requests a second by endpoint, and the share with empty bodies. Fix: poll idle tabs less often, or move to push.
Chapter 2
See why holding each request until news arrives saves requests when it is quiet and multiplies them when it is busy
In long polling the browser asks, and the server does not answer until a comment arrives or a timeout passes. Then the browser asks again at once. RFC 6202 reports timeouts up to 120 seconds working, but calls 30 seconds the safer value. We use 30.
One cycle is one network round trip d plus a wait. Call the average wait W: the time to the next comment, cut off at the timeout T. For random arrivals, W = (1 − e−λT)/λ. Call the requests a second r.
r equals N over the sum of d and W.
One viewer finishes a cycle every d plus W seconds. N viewers send N divided by that each second.
Quiet, lambda = 0.1: W = 9.5 s, so r = 1,000,000 / 9.6 = 104,000 a second, a fifth of short polling. Hype, lambda = 40: W = 0.025 s, so r = 1,000,000 / 0.125 = 8,000,000 a second, sixteen times worse.
At a high rate, long polling turns into polling at the speed of the network. Worse, the replies come in lockstep. One comment releases every held request in the same instant, and a million new requests arrive one round trip later.
Pink bars show held requests. Each teal line is a comment that answers all of them. Drag the rate, then turn on a batch window.
Illustrative: 30 s timeout, 0.1 s round trip, N = 1,000,000. The batch window makes the server wait 1 s after the first comment so that one reply carries several.
Little's law says the average number of requests in a system is the arrival rate times the time each stays. Quiet: 104,000 × 9.5 s ≈ 990,000 held requests. So long polling holds about one open request per viewer, the cost of push, and still pays 800 bytes of headers per reply.
Failure. Symptom: request spikes that line up with comment bursts. Measure: requests a second at one-second resolution beside the comment rate. Fix: a batch window, or a connection that stays open (Chapter 3).
Chapter 3
Keep one response open, write each comment into it, and resume from the last id after a drop
Why close the response at all? With Server-Sent Events (SSE), the server keeps one HTTP response open and writes each event into it. The content type is text/event-stream. In the browser, the EventSource object reads it.
httpGET /stream/42 HTTP/1.1 Accept: text/event-stream HTTP/1.1 200 OK Content-Type: text/event-stream id: 8214 data: {"u":"ringside_fan_88","t":"HE'S DOWN!!"} id: 8215 data: {"u":"corner_cam","t":"get up get up"} the response stays open
The parser knows four fields: data, id, event and retry. It ignores the rest. The stream is always UTF-8 text, and it goes one way only, server to browser.
SSE has resume built in. After a drop, the browser waits a reconnection time, then reconnects with a Last-Event-ID header that holds the last id it saw. The spec leaves the default wait to the browser, "in the region of a few seconds"; the server can set it with retry:. The server replays what came after that id, from a buffer.
How big must the buffer be? Call the comment rate λ and the gap between drop and resume g, in seconds. Call the number of events the server must keep K.
K equals lambda times g.
Multiply the rate lambda by the gap g. Keep at least K events for each stream.
With made-up numbers: lambda = 40 and g = 10 s give K = 400 events. At 150 bytes each, that is 60 KB per stream. A 90 s outage needs 3,600.
Set how long the viewer is gone, then press Drop. Teal events come back from the buffer; red ones fell out of it.
Illustrative: 40 comments a second and a buffer of 400 events per stream. We invented the ids.
One limit bites: over HTTP/1.1, browsers allow about 6 open connections per domain (MDN). A seventh tab's stream waits. HTTP/2 multiplexes streams on one connection, 100 by default.
Failure. Symptom: a viewer back from a tunnel sees a hole in the feed. Measure: count resumes whose Last-Event-ID is older than the buffer's oldest. Fix: size the buffer for the longest gap you promise.
Chapter 4
Upgrade one HTTP request into a two-way connection, then keep it alive through silent boxes
The comment box gets a "3 people typing" line. Now each browser sends small messages up, several times a second. SSE goes one way, so it cannot carry them. A WebSocket (RFC 6455) can.
httpGET /stream/42 HTTP/1.1 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== # a random nonce Sec-WebSocket-Version: 13 HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= # base64(SHA-1(key + fixed GUID))
It starts as an HTTP request that asks to upgrade. The server answers 101 Switching Protocols and proves it read the key. After that, the TCP connection carries frames both ways. A short frame has a 2-byte header. The client must mask its frames with a 4-byte key; the server must not.
Now the quiet killer. A load balancer or proxy closes a connection that stays silent too long, and it tells nobody. An AWS Application Load Balancer closes after 60 s idle by default. Nginx closes a proxied connection after 60 s with no data.
The fix is a heartbeat: the server sends a ping control frame, and the browser answers with a pong. RFC 6455 says a ping may serve as a keepalive or as a check that the other end still answers.
The yellow sawtooth is the idle timer in the box between viewer and server. Each ping resets it. If it reaches the timeout, the box closes the connection. Set both.
The 60 s timeout is the documented default of AWS ALB and of nginx proxying. The 30 s and 350 s boxes are illustrative. Fleet cost uses the formula below.
What do heartbeats cost the fleet? Call the open connections N, the bytes one ping and pong cost on the wire b, and the heartbeat interval h. Call the heartbeat bytes a second H.
H equals N times b over h.
Each connection spends b bytes every h seconds. Multiply by the N connections and divide by h.
The ping frame is 2 bytes and the masked pong 6. Each rides its own packet with about 74 bytes of TCP, IP and TLS headers, so b ≈ 156. With h = 25 s: H = 1,000,000 × 156 / 25 = 6.24 MB a second, about 50 Mbps, 0.1% of 48 Gbps.
Failure. Symptom: viewers stop getting comments after a quiet minute, with no error. Measure: a histogram of connection lifetimes; a spike at 60 s is an idle timeout. Fix: a heartbeat under half the shortest timeout on the path.
Chapter 5
Ask three questions in order and take the cheapest option that answers all of them
An admin dashboard with 40 users that polls every 10 s sends 4 requests a second. Nobody should build push for that. A million viewers at a hype moment is a different problem. The right protocol depends on the client, the scale and the deadline.
| Option | Requests a second, quiet | Requests a second, hype | Open connections | Direction | Typical delay |
|---|---|---|---|---|---|
| Short poll, T = 2 s | 500,000 | 500,000 | almost none | browser asks | about 1 s |
| Long poll, 30 s cap | 104,000 | 8,000,000 | about one per viewer | browser asks | one network trip |
| SSE | reconnects only | reconnects only | one per viewer | server to browser | one network trip |
| WebSocket | reconnects only | reconnects only | one per viewer | both ways | one network trip |
The tree asks in order and stops at the first answer that decides. Flip the answers and watch the path move.
The tree is a rule of thumb for this lesson, not a standard. The request rates in the table come from Chapters 1 and 2 with N = 1,000,000.
Our stream answers yes to the first question, because of the typing line. So it uses WebSockets, and the rest of the lesson builds on that.
Plan for networks that block the upgrade. Nginx documents that Upgrade is a hop-by-hop header. A proxy drops it unless you tell the proxy to pass it on. A good client tries WebSocket for 3 s, then falls back to SSE, then to long polling.
Migrate in steps. Ship a client that speaks both protocols, then switch 1%, 10%, 50% and 100% of viewers, with a pause at each step. A million viewers that move over minutes do not form the storm of Chapter 8.
Failure. Symptom: users on one office network never see live comments. Measure: upgrade failures by network, and how long each attempt waits. Fix: a short upgrade timeout with a fallback.
Chapter 6
Split the fan-out into a few network hops and many local loops
The API server that saved the comment holds no viewer sockets. Those live on a separate fleet of connection servers, say 50 of them. How does the comment reach all 50?
Through a broker. A publisher sends a message to a named topic, and the broker gives a copy to each subscriber of that topic. Each connection server subscribes to stream:42:comments while it holds at least one viewer of stream 42.
Purple copies leave the broker, one per server. Each server then fans out locally. Drag the server count, then switch to one global topic.
Illustrative platform: this stream has 40 comments a second; all 10,000 streams together have 500.
Topic design matters. Name one topic per stream, such as stream:42:comments. With one global topic, a server that holds viewers of only this stream still receives all 500 comments a second. It throws away 460 of them, 92%. That is 12.5 times the inbound traffic it needs.
Know what the broker promises. The Redis docs say its Pub/Sub delivers at most once. If a subscriber loses its connection, it never gets that message. Each subscriber gets messages in the order the publishers sent them. Redis Streams keep messages for later reads, so a server can catch up.
Failure. Symptom: after a connection server restarts, its viewers miss comments from the restart window. Measure: compare published ids with delivered ids per server. Fix: replay from a durable log, keyed by Last-Event-ID.
Chapter 7
Size a connection server by three limits and find the one that bites first
How many viewers fit on one connection server? Check three limits.
Call the cores C and the share of CPU you give to fan-out u. Call the messages a second per connection λ, and the CPU time of one socket write c. Call the connections one box can serve n.
n equals C times u over lambda times c.
C times u is the CPU time you can spend each second. Each connection costs lambda times c of it. Divide the first by the second.
With made-up numbers: C = 16, u = 0.5, lambda = 40, c = 10 μs. n = 8 / (40 × 0.00001) = 8 / 0.0004 = 20,000. So 1,000,000 viewers need 50 servers.
The shortest bar is the real capacity of the box. Drag the write cost, the cores and the comment rate, and watch the fleet size.
Illustrative box: file descriptor limit raised to 1,048,576, 16 GB of RAM for connections at 28 KB each, half the CPU for fan-out. Measure c on your own servers.
Memory allowed 571,000; CPU allows 20,000, which is 28 times tighter. Each box then sends 20,000 × 40 × 150 × 8 bits, about 0.96 Gbps, well inside a 10 Gbps card.
Assign streams to servers with consistent hashing: place servers and stream shards on a ring and give each shard to the next server clockwise. Growing from 50 to 51 servers moves about 1/51 of shards, 2%. Plain "hash mod N" moves 98%.
Failure. Symptom: CPU at 100% during bursts while memory sits at 10%. Measure: CPU per box in the busiest minute. Fix: size by CPU, and batch several comments into one frame to cut lambda per socket.
Chapter 8
Spread the retries of 100,000 dropped viewers so the servers that survive can take them
A deploy goes wrong. Five of the 50 connection servers die within a few seconds. Their 100,000 viewers drop at once. The hash ring spreads them over the 45 survivors: 2,222 each. A reconnect costs a TCP and TLS handshake, the upgrade and a new subscription. Say a box can finish 2,000 a second.
Call the clients that retry against one box K, and the seconds over which their attempts spread w. Call the attempts a second that reach the box A.
A equals K over w.
Spread K attempts evenly over w seconds. Each second gets K divided by w. Compare A with the 2,000 the box can finish.
With made-up numbers: everyone retries after exactly 1 s, all within 50 ms. A = 2,222 / 0.05 = 44,444 a second, 22 times capacity. Random delays over a full second give A = 2,222 / 1 = 2,222, only 1.11 times.
The fix is exponential backoff with full jitter. On retry number a, wait a random time between 0 and min(cap, base × 2a). The AWS Architecture Blog post "Exponential Backoff And Jitter" also tests equal jitter: half the window, plus a random half. It finds equal jitter the worst of the jittered kinds.
Bars are attempts reaching one surviving box; red is above what it can finish. The green line is the share of viewers back online. Pick a retry rule and a failure size, then press Run.
An illustrative simulation of one surviving box: 2,000 handshakes a second, drops spread over 50 ms, base 1 s, cap 30 s. Without shedding, an overloaded box also burns CPU on handshakes it cannot finish, so it completes fewer (a made-up model). With shedding on, it answers attempts above 1,600 a second with a cheap 503.
| Boxes lost | Clients per survivor | Fixed 1 s | Full jitter, first window |
|---|---|---|---|
| 1 of 50 | 408 | 4.1 × | 0.20 × |
| 5 of 50 | 2,222 | 22 × | 1.11 × |
| 10 of 50 | 5,000 | 50 × | 2.5 × |
The resume token from Chapter 3 closes the gap. If the slowest client waits 8 s, it missed 8 × 40 = 320 events, inside a 400-event buffer.
Failure. Symptom: survivors fall one by one after the first failure. Measure: handshake attempts a second per box against capacity. Fix: full jitter in the client, and shed load at the server.
Chapter 9
Keep the numbers, the checklist and the code for the next realtime feature you build
One comment travels like this. The browser sends it up its WebSocket. A stateless API server saves it and publishes it to the stream's topic. The broker copies it to each connection server that holds a viewer. Each server writes it to its own sockets. If a server dies, its viewers reconnect with jitter and resume from their last id.
| Term | What it is | This lesson's number |
|---|---|---|
| Fan-out | readers one write must reach | 1,000,000; B = 8 · s · λ · N = 48 Gbps |
| Short polling | ask every T seconds | Q = N/T = 500,000 a second; 82% empty when quiet |
| Long polling | server holds the ask until news | 104,000 a second quiet; 8,000,000 at hype |
| SSE | one HTTP response that never ends | buffer K = λ · g = 400 events for a 10 s gap |
| WebSocket | upgraded two-way connection | 101 Switching Protocols; 2-byte frame header |
| Heartbeat | ping and pong that reset idle timers | every 25 s under a 60 s timeout; about 50 Mbps fleet-wide |
| Two-level fan-out | broker copies, then local loops | 2,000 copies a second, 20,000 sockets per server |
| CPU ceiling | n = C · u / (λ · c) | 20,000 per box, 50 boxes |
| Full jitter | wait random(0, min(cap, base · 2a)) | 22 times capacity falls to 1.11 times |
python# connection server: one topic per stream, local fan-out, replay on resume import asyncio, collections BUFFER = 400 # K = lambda * g = 40 * 10 recent = collections.defaultdict(lambda: collections.deque(maxlen=BUFFER)) sockets = collections.defaultdict(set) # stream_id -> open WebSockets async def on_broker_message(stream_id, event): # event: {"id": 8215, "data": "..."} recent[stream_id].append(event) frame = event["data"] for ws in list(sockets[stream_id]): # ~20,000 writes, in memory try: await ws.send(frame) except ConnectionError: sockets[stream_id].discard(ws) async def on_connect(ws, stream_id, last_id): for ev in recent[stream_id]: # replay what the viewer missed if ev["id"] > last_id: await ws.send(ev["data"]) sockets[stream_id].add(ws)
javascript// browser: reconnect with full jitter and resume from the last id async function connectForever(streamId) { let attempt = 0, lastId = 0; const base = 1000, cap = 30000; // milliseconds for (;;) { try { await openSocket(streamId, lastId, ev => { lastId = ev.id; attempt = 0; }); } catch (e) { /* dropped or refused */ } const win = Math.min(cap, base * 2 ** attempt++); await sleep(Math.random() * win); // full jitter } }
Now press Present or Teach and explain five things from memory. Explain the fan-out product, why long polling fails at high rates, how SSE resumes, why heartbeats exist, and how full jitter tames a storm. Then go back to the hero and set the comment rate to 40 with long polling on.