Realtime Updates

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.

Deliver one stream to a million

2

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

One Write, a Million Reads

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.

Multiply one write by the room

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.

40
1,000,000

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.

Say it aloud

B equals eight times s times lambda times N.

B
B the egress bandwidth: bits a second that leave the servers.
8
eight the bits in one byte.
s
s the bytes in one delivered comment, 150 here.
λ
lambda the comments a second on this stream, 40 at a hype moment.
N
N the viewers connected now, 1,000,000.
In plain words

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 numbers

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.

  1. Short polling: every browser asks on a timer, and most answers are empty.
  2. Long polling: the server holds the question open, and pays for it at high rates.
  3. Server-Sent Events: one response that never ends, with resume built in.
  4. WebSockets: a two-way connection, and the heartbeat that keeps it alive.
  5. Choosing a protocol: three questions that pick the cheapest one that works.
  6. Pub/sub: how the server that saved a comment reaches the servers that hold the viewers.
  7. The connection tier: how many viewers fit on one box, and which limit binds.
  8. Reconnection storms: what happens when 100,000 viewers drop at once.
  9. The field guide: numbers, checklist, code and links.
A stream has 500,000 viewers and 20 comments a second of 150 bytes each. What egress bandwidth does it need?

Chapter 1

Short Polling: Ask on a Timer

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.

Say it aloud

Q equals N over T.

Q
Q the poll requests a second that reach the servers.
N
N the viewers with the page open, 1,000,000.
T
T the poll interval: seconds between two asks from one browser.
In plain words

Each viewer sends one request every T seconds. N viewers send N divided by T each second.

With numbers

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.

Say it aloud

p-zero equals e to the minus lambda T.

p0
p-zero the chance that no comment arrived during one interval, so the poll comes back empty.
e
e the number 2.718, the base of natural growth and decay.
λ
lambda the comments a second.
T
T the poll interval in seconds.
In plain words

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.

With numbers

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.

Set the poll timer

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.

2 s

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.

200,000 viewers poll every 4 seconds. A comment arrives about once every 10 seconds. About how many polls a second come back empty?

Chapter 2

Long Polling: Hold the Question Open

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.

Say it aloud

r equals N over the sum of d and W.

r
r the long-poll requests a second that reach the servers.
N
N the viewers, 1,000,000.
d
d one network round trip, 0.1 s here.
W
W the average time the server holds a request before it answers.
In plain words

One viewer finishes a cycle every d plus W seconds. N viewers send N divided by that each second.

With numbers

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.

Release every held request at once

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.

0.1

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).

A busy stream has 20 comments a second and long polling with a 0.1 s round trip. Why does the request rate go up, not down?

Chapter 3

Server-Sent Events: A Response That Never Ends

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.

Say it aloud

K equals lambda times g.

K
K the events a viewer missed, which the buffer must still hold.
λ
lambda the comments a second on the stream.
g
g the gap: seconds from the drop to the resume.
In plain words

Multiply the rate lambda by the gap g. Keep at least K events for each stream.

With numbers

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.

Drop the stream, then resume

Set how long the viewer is gone, then press Drop. Teal events come back from the buffer; red ones fell out of it.

10 s

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.

A stream runs at 25 comments a second. Viewers can be gone for up to 20 s. How many events must the buffer hold per stream?

Chapter 4

WebSockets and the Heartbeat

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.

Keep the connection alive

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.

25 s

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.

Say it aloud

H equals N times b over h.

H
H heartbeat bytes a second across the whole fleet.
N
N open connections, 1,000,000.
b
b bytes on the wire for one ping and its pong, headers included.
h
h the heartbeat interval in seconds.
In plain words

Each connection spends b bytes every h seconds. Multiply by the N connections and divide by h.

With numbers

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.

A path has two boxes in it: one closes idle connections after 60 s, the other after 45 s. Which heartbeat interval is safe?

Chapter 5

Choosing a Protocol

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.

OptionRequests a second, quietRequests a second, hypeOpen connectionsDirectionTypical delay
Short poll, T = 2 s500,000500,000almost nonebrowser asksabout 1 s
Long poll, 30 s cap104,0008,000,000about one per viewerbrowser asksone network trip
SSEreconnects onlyreconnects onlyone per viewerserver to browserone network trip
WebSocketreconnects onlyreconnects onlyone per viewerboth waysone network trip

Answer three questions

The tree asks in order and stops at the first answer that decides. Flip the answers and watch the path move.

1. Does the browser send small messages often?
2. Can the servers hold one open connection per viewer?
3. Must an update arrive within a second?

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.

A stock ticker pushes prices to 300,000 viewers. Viewers never send anything back, and the servers can hold the connections. What does the tree pick?

Chapter 6

Pub/Sub: From the Writer to the Socket Holders

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.

Two-level fan-out, illustrative
broker copies = λ × servers = 40 × 50 = 2,000 a second
each server loops over its own 1,000,000 / 50 = 20,000 sockets, in memory
2,000 × 20,000 = 40,000,000 socket writes a second, the same as Chapter 0

Split the fan-out in two

Purple copies leave the broker, one per server. Each server then fans out locally. Drag the server count, then switch to one global topic.

50

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.

A stream of 30 comments a second has viewers on 80 connection servers. How many copies a second does the broker send for it?

Chapter 7

The Connection Tier: Which Limit Binds

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.

  1. File descriptors. Each socket is one open file. Many Linux systems start a process with a soft limit of 1,024. You raise it in config; it is not hardware.
  2. Memory. Kernel buffers, TLS state and your own objects. At an illustrative 28 KB per idle connection, 16 GB holds 571,000.
  3. CPU. At a hype moment, every socket gets a write for every comment.

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.

Say it aloud

n equals C times u over lambda times c.

n
n the connections one box can serve on CPU.
C
C the CPU cores in the box.
u
u the share of CPU kept for fan-out, from 0 to 1.
λ
lambda the messages a second sent down each connection.
c
c the CPU seconds that one socket write costs.
In plain words

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 numbers

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.

Find the limit that bites

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.

10 μs
16
40

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.

A 32-core box keeps half its CPU for fan-out. Each write costs 10 μs and each socket gets 40 messages a second. How many connections fit on CPU?

Chapter 8

Reconnection Storms and Jitter

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.

Say it aloud

A equals K over w.

A
A the reconnect attempts a second offered to one box.
K
K the clients that retry against that box, 2,222 here.
w
w the window: seconds over which their attempts spread.
In plain words

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 numbers

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.

Survive the storm

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 lostClients per survivorFixed 1 sFull jitter, first window
1 of 504084.1 ×0.20 ×
5 of 502,22222 ×1.11 ×
10 of 505,00050 ×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.

A box can finish 2,000 handshakes a second. 3,000 clients retry against it with full jitter over a 2 s window. What is the offered rate?

Chapter 9

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Fan-outreaders one write must reach1,000,000; B = 8 · s · λ · N = 48 Gbps
Short pollingask every T secondsQ = N/T = 500,000 a second; 82% empty when quiet
Long pollingserver holds the ask until news104,000 a second quiet; 8,000,000 at hype
SSEone HTTP response that never endsbuffer K = λ · g = 400 events for a 10 s gap
WebSocketupgraded two-way connection101 Switching Protocols; 2-byte frame header
Heartbeatping and pong that reset idle timersevery 25 s under a 60 s timeout; about 50 Mbps fleet-wide
Two-level fan-outbroker copies, then local loops2,000 copies a second, 20,000 sockets per server
CPU ceilingn = C · u / (λ · c)20,000 per box, 50 boxes
Full jitterwait random(0, min(cap, base · 2a))22 times capacity falls to 1.11 times

Checklist

  1. Compute the peak lambda times N, not the write rate.
  2. Pick the protocol with the three questions; add a fallback.
  3. Give every event an id, and keep a replay buffer for the longest gap you promise.
  4. Set a heartbeat under half the shortest idle timeout on the path.
  5. Use one topic per stream; remember Redis Pub/Sub is at most once.
  6. Size connection servers by CPU at the peak rate, and batch messages.
  7. Use full jitter in the client and load shedding at the server.
  8. Watch: deliveries a second, CPU per box, connection lifetimes, handshakes a second, resume misses.

The core as code

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
  }
}

Keep going

The takeaway. Realtime is one multiplication, lambda times N, paid somewhere. Push pays it with open connections instead of requests. Pub/sub moves it into local loops. CPU sets how many viewers fit on a box. Jitter and a resume id keep a failure from becoming a storm.

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.

Realtime Updates
RFC 6455 · Server-sent events · RFC 6202 · Back to Gleams