System Design

Core Concepts

WebSockets, SSE and Polling

A push connection makes delivery fast and never makes it reliable. Connections break many times a day, so the design question is what the client asks for when it comes back. Answer that, and the choice of transport mostly makes itself.

Why you are doing this at all

If you ask how a phone hears about a new message, "WebSockets" usually comes back before the question is finished. It's often the right answer, but it answers the easy half. The transport decides how fast an event arrives while the connection is up. Most of the design is about the time when it isn't.

Connections go down all the time, for ordinary reasons. Every deploy restarts the servers that hold them, and Cloudflare's documentation says its own releases may restart servers, "which terminates WebSockets connections." An AWS Application Load Balancer (ALB) closes any connection that has been quiet for 60 seconds by default. Phones switch networks, and apps go into the background. None of these is a bug in your code.

Each one leaves a gap. An event that happens during the gap can't be pushed, because there's nothing to push it down. When the client comes back, either it asks for what it missed, or it never sees those events.

A push connection makes delivery fast. It never makes it reliable. Reliability comes from a resume request that the client starts after every gap, asking for everything after the last position it saw. That request works like a poll, so every push design still contains one. The only exceptions are the streams you decide are allowed to lose events, and that is a decision you make out loud.

One client's connection over an afternoon
The top row is events the server produces for one client, numbered by position. The middle row is the client's connection, which drops three times: a deploy, a switch from Wi-Fi to mobile data, and a load balancer closing it after 60 quiet seconds. Events while it is up arrive by push, in green. Events in a gap, in blue, arrive only because the client reconnects and asks for everything after the last position it saw (1, 2, 3).The top row is events the server produces for one client, numbered by position. The middle row is the client's connection, which drops three times: a deploy, a switch from Wi-Fi to mobile data, and a load balancer closing it after 60 quiet seconds. Events while it is up arrive by push, in green. Events in a gap, in blue, arrive only because the client reconnects and asks for everything after the last position it saw (1, 2, 3).
Push carries the events while the connection is up. A resume request carries the rest. The top row is events the server produces for one client, numbered by position. The middle row is the client's connection, which drops three times: a deploy, a switch from Wi-Fi to mobile data, and a load balancer closing it after 60 quiet seconds. Events while it is up arrive by push, in green. Events in a gap, in blue, arrive only because the client reconnects and asks for everything after the last position it saw (1, 2, 3).

What push buys you

Push buys two things: a shorter delay between an event and the client seeing it, and no requests that come back empty. It costs one held connection per client, which is state on your server. A client polling every 10 seconds sees an event up to 10 seconds late, 5 on average, and pays a full request for every poll that finds nothing.

Whether that matters comes down to two durations for one client: the time between updates, and the delay the client can accept.

  • Updates further apart than the accepted delay. Most polls come back empty. In the WhatsApp breakdown, a phone gets a message about every 28 seconds and needs it within half a second, so 98 percent of polls would find nothing. Push wins.
  • Updates closer together than the accepted delay. Every poll carries something, often several updates in one response. Polling now sends fewer messages than push would, and it batches for free.

Push when updates are rarer than the delay you can accept. Poll when they are more frequent.

That rule counts messages only, so treat it as a first estimate. A poll also carries about a kilobyte of headers where a push frame carries 2 to 14 bytes, and a held connection carries heartbeats. For a client that gets an update every 30 seconds, a heartbeat every 30 seconds moves the crossing point from 30 seconds to 15.

Messages a second for 100,000 clients
Each client gets one update every 30 seconds. Push sends one message per update, 3,333 a second, the solid purple line, whatever delay you accept. Polling sends one request per client per interval, the blue line. At a 1 second delay that is 100,000 a second, 30 times push. The lines cross at 30 seconds. Add a heartbeat every 30 seconds to every push connection, the dashed purple line, and push sends 6,667 a second, so the lines cross at 15 seconds. Both axes are logarithmic.Each client gets one update every 30 seconds. Push sends one message per update, 3,333 a second, the solid purple line, whatever delay you accept. Polling sends one request per client per interval, the blue line. At a 1 second delay that is 100,000 a second, 30 times push. The lines cross at 30 seconds. Add a heartbeat every 30 seconds to every push connection, the dashed purple line, and push sends 6,667 a second, so the lines cross at 15 seconds. Both axes are logarithmic.
The lines cross where the accepted delay equals the time between updates, or half that once heartbeats count. Each client gets one update every 30 seconds. Push sends one message per update, 3,333 a second, the solid purple line, whatever delay you accept. Polling sends one request per client per interval, the blue line. At a 1 second delay that is 100,000 a second, 30 times push. The lines cross at 30 seconds. Add a heartbeat every 30 seconds to every push connection, the dashed purple line, and push sends 6,667 a second, so the lines cross at 15 seconds. Both axes are logarithmic.

Polling has strengths of its own. Each request stands alone, so any server can answer it and a deploy breaks nothing. A cache or a content delivery network (CDN) can answer identical polls.

The price shows up at scale. Uber's apps polled, and at one point 80 percent of the requests reaching Uber's API gateway were polling calls.

The toolkit

Four transports, side by side

There are four ways to get an event from a server to a client.

transportwho can senddelay it addscost per messagewhat the server holdscatching up after a gap
short pollingthe client, on a timerup to one intervala full request and responsenothing between requestsbuilt in: each request carries the last position
long pollingthe client asks, and the server answers when it has somethingabout one network trip, up to threea full request and responseone open request per clientbuilt in, the same way
server-sent eventsthe server; the client uses ordinary requestsclose to nonea few bytes of text framingone open response per clientbuilt in: Last-Event-ID on reconnect
WebSocketboth, at any timeclose to none2 to 14 bytes of framingone open socket per clientnone: you build it

Short polling

The client asks on a timer: GET /orders/board?since=4411. The since value is the position of the last update it has, so polling has catch-up built in. A client that was offline for an hour sends the same request it always sends.

Two details keep it cheap. A conditional request makes the empty answer small. The client sends the version tag it last saw in If-None-Match, and the server replies 304 Not Modified with no body.

The timer also needs a random offset. If every client restarts its timer when the same outage ends, they all poll in the same second, every interval, from then on. A random offset of up to one interval spreads them out.

Long polling

The client asks, and the server holds the request open until it has something to send or a timeout passes. Then it answers, and the client asks again straight away. It needs nothing but ordinary HTTP, so it's still the usual fallback. Socket.IO, a real-time library, starts every connection with long polling and upgrades to WebSocket afterwards. A WebSocket sometimes can't be opened at all behind a corporate proxy, a firewall or antivirus software.

It has two costs. The first is a blind spot after every answer. RFC 6202, on long polling's known issues, points out that once the server answers, it can't send anything until the next request arrives. An event that lands just after a response waits while that response reaches the client, the new request comes back, and the next response goes out. That is three network trips in the worst case, against about one on average.

The worst case for long polling
Time runs left to right, with the client on top and the server below. The server answers the held request with event 41 (1). Event 42 arrives a moment later, but no request is open, so it waits, the orange stretch, while 41 travels to the client and the next request travels back (2). Only then can 42 go out (3).Time runs left to right, with the client on top and the server below. The server answers the held request with event 41 (1). Event 42 arrives a moment later, but no request is open, so it waits, the orange stretch, while 41 travels to the client and the next request travels back (2). Only then can 42 go out (3).
An event that just misses a response waits three network trips. Time runs left to right, with the client on top and the server below. The server answers the held request with event 41 (1). Event 42 arrives a moment later, but no request is open, so it waits, the orange stretch, while 41 travels to the client and the next request travels back (2). Only then can 42 go out (3).

The second is a full request and response for every event. When events are frequent, the request rate rises to match the event rate, and long polling turns back into polling.

Server-sent events

Server-sent events (SSE) use an HTTP response that the server never finishes. The client makes one GET. The server replies with Content-Type: text/event-stream, then writes events into the response as they happen:

id: 4412
event: offer
data: {"trip": "t_19", "expires_in": 15}

: keepalive

id: 4413
data: {"trip": "t_19", "status": "taken"}

Each event is a few field: value lines followed by a blank line. A line that starts with a colon is a comment, and the browser ignores it. Two things to note in that stream.

The id field is the position. The browser's EventSource remembers the last id it received. If the connection drops, it reconnects by itself and sends that value in a Last-Event-ID header, so the server knows where to resume. This is the resume request, built into the protocol. Keeping and replaying the events is still your job.

The comment line keeps the connection alive. The standard warns that some proxies drop HTTP connections after a short idle period, and suggests a comment line "every 15 seconds or so."

The automatic reconnect has a limit. The browser only retries after a network error. A response that isn't a 200, or has the wrong Content-Type, fails the connection for good, so a 502 from a proxy during a deploy ends the stream. Production clients watch for that, create a new EventSource themselves, and pass the last id in the URL.

SSE also only goes from server to client, so the client sends with ordinary HTTP requests. And it's text only, always UTF-8, so binary data has to be encoded.

WebSocket

A WebSocket starts as an HTTP request that asks to switch protocols:

GET /live HTTP/1.1
Host: rt.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

After the 101, both sides send frames on the same TCP connection whenever they like. RFC 6455, the WebSocket standard, gives a short frame from the server a 2-byte header, plus up to 8 bytes of length for a large one. Client frames add a 4-byte mask key. So framing runs 2 to 14 bytes.

A Ping must be answered with a Pong, and serves "either as a keepalive or as a means to verify that the remote endpoint is still responsive." A Close frame carries a code, such as 1001 for "going away" when a server shuts down.

The standard has no acknowledgements, so you can't tell whether the client read a frame you wrote. It has no position and no resume either, so a reconnect starts from nothing. It does say how to reconnect: back off, and delay the first attempt by a random amount.

Libraries don't add acknowledgements or positions by default. Socket.IO's documentation promises "an at most once guarantee of delivery." Its recommended fix is a position: store events with ids, and have the client send the offset of the last one it received when it reconnects.

What sits between the client and your server

A connection passes through boxes that each keep their own timer: load balancers, reverse proxies, CDNs, and the network address translation (NAT) in home routers and mobile networks. Each one closes a connection, or forgets it, after a stretch of silence.

on the pathdefault idle limit
AWS Application Load Balancer60 s, settable from 1 to 4,000 s
AWS Network Load Balancer, TCP listener350 s, settable from 60 to 6,000 s
nginx proxying a WebSocket60 s with no data from the server
Heroku router55 s with no data, after the first byte

The shortest timer on the path is the one that applies, and you never see the whole path. A mobile carrier's NAT and a corporate proxy have timers nobody publishes. So send something more often than the shortest timer you do know, with a margin. An interval of 25 to 30 seconds clears every number in this table.

A close that both ends hear about is the easy case. In the harder case, a box in the middle forgets the connection and tells nobody. The server's next write lands in a kernel buffer and reports no error, and the client takes the silence for a quiet stream. Uber's write-up draws the conclusion: because of "large buffers at various network proxies and lossy mobile networks, the only way to know if a connection is broken is heartbeats."

A connection that is up at both ends and dead in the middle
A box in the middle forgets the connection without telling anyone, the red cross. The server writes event 43, and its kernel accepts the bytes into a buffer, so nothing reports an error (1). The client hears nothing, which looks like a quiet stream. The next heartbeat never arrives (2), so after the grace period the client reconnects and sends its last position, 42 (3). The server replays 43 (4).A box in the middle forgets the connection without telling anyone, the red cross. The server writes event 43, and its kernel accepts the bytes into a buffer, so nothing reports an error (1). The client hears nothing, which looks like a quiet stream. The next heartbeat never arrives (2), so after the grace period the client reconnects and sends its last position, 42 (3). The server replays 43 (4).
Neither end hears about a silent drop. Only a missing heartbeat shows it. A box in the middle forgets the connection without telling anyone, the red cross. The server writes event 43, and its kernel accepts the bytes into a buffer, so nothing reports an error (1). The client hears nothing, which looks like a quiet stream. The next heartbeat never arrives (2), so after the grace period the client reconnects and sends its last position, 42 (3). The server replays 43 (4).

Heartbeats, and what they detect

A heartbeat is a small message sent on a timer, and it does two jobs. It keeps the idle timers on the path from firing, and it tells each end that the other is still there. Only the second job needs a reply.

The interval decides how fast you notice a dead connection. Uber's push platform sent a one-byte heartbeat every 4 seconds, and its client reconnected after 7 seconds of silence.

Discord's gateway tells each client its interval, 45 seconds in the documentation's example, and acknowledges every heartbeat. A missing acknowledgement "may be due to a failed or 'zombied' connection", so the client closes the connection and resumes.

Back of envelopeWhat a heartbeat costs, and what it buys
The question is how short the interval can be. Price
it on the server first, then on the phone.

One server, 1M connections, ~100 B a heartbeat
with TCP and encryption
  every 30 s   1,000,000 / 30 s × 100 B      ≈ 3.3 MB/s
  every 4 s    1,000,000 / 4 s × 100 B       ≈ 25 MB/s

Time to notice a dead connection
  every 30 s, with a 10 s grace              up to 40 s
  every 4 s, reconnect after 7 s
  of silence (Uber)                          up to 7 s

On a phone. Android's documentation, for a typical 3G
radio, says each transfer keeps the radio drawing power
for at least 18 s
  every 30 s     18 / 30                     = on 60% of the time
  every 4 s      the next one comes first    = on all the time
  ──────────────────────────────────────────────────────
At 30 s the server rarely limits the interval. Detection
time and the phone's battery do. Pick the slowest
heartbeat that notices a dead connection fast enough,
and keep it under the shortest idle timer on the path.

That is why intervals in practice sit so far apart. A trip offer is useful only briefly, so Uber paid for a 4 second heartbeat. The WhatsApp breakdown settles on a keepalive every few minutes, which only works where you set every timer on the path yourself.

Positions, and catching up after a gap

A reconnecting client asks for what it missed. For that, every event needs a position: a number that only goes up, assigned by the server, per stream. If each client has a single delivery stream, the reconnect carries one number. Discord does this with one session per connection, and the WhatsApp breakdown with one spool per device. Without it, a client in 40 conversations would have to send back 40 positions.

The client keeps the highest position it has seen. When it reconnects, it sends that number, and the server gives one of three answers.

  • Replay. The server still holds every event after that position, so it sends them and carries on live.
  • Snapshot. The gap goes back further than anything the server kept, so it sends the current state, and the client replaces what it has.
  • Nothing. The stream is allowed to lose events, so the client starts from now.

It's the same idea as a consumer's offset in a log, described in message queues against event streams.

The replay buffer can't live on the connection server. The restart that caused the reconnects has just deleted it, and the clients land on other servers anyway. Keep it in a shared data store, keyed by stream. A later version of Uber's push platform stored messages in Cassandra, with Redis as a cache in front.

On reconnect, the new server subscribes the client to live events first, then replays from the buffer, then drops anything at or below a position it has already sent. In the other order, an event published between the replay and the subscribe is lost.

Three answers to a reconnect
A shared data store keeps the last 10 minutes of each stream, the orange band. A client back after 1 minute sends position 4,412, which is inside the band, so the new server replays from there, in green. A client back after 3 hours sends a position the band no longer holds, so it gets the current state as a snapshot, in blue. A stream marked as allowed to lose events, in grey, gets nothing back and carries on from now.A shared data store keeps the last 10 minutes of each stream, the orange band. A client back after 1 minute sends position 4,412, which is inside the band, so the new server replays from there, in green. A client back after 3 hours sends a position the band no longer holds, so it gets the current state as a snapshot, in blue. A stream marked as allowed to lose events, in grey, gets nothing back and carries on from now.
How far back the shared buffer goes decides which answer a client gets. A shared data store keeps the last 10 minutes of each stream, the orange band. A client back after 1 minute sends position 4,412, which is inside the band, so the new server replays from there, in green. A client back after 3 hours sends a position the band no longer holds, so it gets the current state as a snapshot, in blue. A stream marked as allowed to lose events, in grey, gets nothing back and carries on from now.

Published systems use the first two answers. Uber's clients reconnected "with the largest sequence number it has seen", and the server resent what came after. Discord replays missed events, and when a session is too old, the client starts again and downloads its full state. Figma's multiplayer editor always takes the snapshot: a client back online "downloads a fresh copy of the document" and reapplies its offline edits.

The buffer costs memory, but full state is far bigger than what a short gap misses. Discord's write-up on compression measured one READY payload, the full state a client receives on a fresh start, at 307 KB compressed.

Back of envelopeReplay against reload, for 1 million reconnects
A server restart sends 1M clients back at once. Decide
what each one downloads, then how much buffer replay
needs.

Each client's stream
  one event every 30 s, ~1 KB each
  a 60 s gap misses             60 / 30      = 2 events

Reload the full state on every reconnect
  ~300 KB each, about one Discord READY, compressed
  1M × 300 KB                                = 300 GB

Replay from the last position
  1M × 2 events × 1 KB                       = 2 GB

The buffer that makes replay possible
  keep 10 minutes      600 / 30              = 20 events
  20 × 1 KB × 1M streams                     = 20 GB
  keep 24 hours        86,400 / 30           = 2,880 events
  2,880 × 1 KB × 1M streams                  ≈ 2.9 TB
  ──────────────────────────────────────────────────────
Replay moves a 150th of the data reload does. A buffer
of minutes covers deploys and network switches, and it
fits in memory. Anything older gets the snapshot, which
is rare enough to afford.

Some streams should take the third answer on purpose. A typing indicator, presence or a like is worthless a few seconds late. LinkedIn's platform for likes on live video doesn't guarantee delivery. Name the streams that may lose events, and keep positions for the rest.

How many connections one server holds

Published figures range over a factor of ten. LinkedIn ran 100,000 per node for messaging in 2016, Netflix's Pushy averaged 200,000 per node in 2024, and WhatsApp ran 1 million per server in 2014.

The cost of a restart should decide it, because every client on that server reconnects. Netflix's push team put it as "More number of smaller servers >> few BIG servers". Its slides also say to autoscale "on number of open connections per box", not on requests or CPU. The WhatsApp breakdown works through 250,000 connections a server against 1 million.

The method

1. Write down the delay the client can accept, in seconds, and who sends. One number per stream.

2. Price polling at that delay. Clients divided by the interval is the request rate. If updates come more often than the delay, or the request rate is small, poll and stop here.

3. Pick the lightest transport that carries the traffic. Use SSE when only the server pushes and doesn't need to know each event arrived. Use WebSocket, or a gRPC bidirectional stream in a native app, when the client sends often or the server needs an acknowledgement per message. Keep long polling as the fallback.

4. Give every event a position, and pick an answer for each stream. Replay from a buffer in a shared data store, snapshot when the gap is older than the buffer, or let the stream lose events. Size the buffer in minutes.

5. Size the connection tier by connections. Divide peak concurrent clients by connections per server, and choose the per-server number by what one restart can absorb.

6. Set the heartbeat. Keep it under the shortest idle timer on the path, and fast enough to notice a dead connection within the time the product can tolerate.

7. Plan how connections end. After a failure, clients back off with jitter, a random extra delay. Add a drain that asks clients to leave, a maximum lifetime so new servers fill up, and platform push notifications for apps in the background.

Worked examples, start to finish

Here are four systems. In each one the obvious design fails in a different way.

A dashboard that changes every few seconds

Staff and customers keep 200,000 browser tabs open on warehouse order boards. Each board changes about every 3 seconds, and the people watching are happy if it is 30 seconds old. The word "live" is in the product brief, so the obvious design is a WebSocket per tab, with every change pushed.

Back of envelopePolling the boards, against pushing them
200,000 open tabs. Each shows one warehouse board that
changes about every 3 s, and 30 s of delay is fine.
Price both ways of keeping the tabs current.

Poll every 30 s, with a random offset
  requests     200,000 / 30 s                ≈ 6,700/s
  each poll returns the latest board

Push every change
  messages     200,000 / 3 s                 ≈ 67,000/s
  plus 200,000 held connections, heartbeats and drains
  the tab needs one board every 30 s, and gets 10

Poll every 1 s, if the product changes its mind
  requests     200,000 / 1 s                 = 200,000/s
  ──────────────────────────────────────────────────────
At 30 s, polling sends a tenth of the messages and holds
no connections. At 1 s it sends three times as many as
push, and push becomes the cheaper design.

The reason is the kind of data. The board is state, not a list of events. A tab needs the latest board, not every board in between. Polling skips the in-between versions by itself. Push delivers all of them, and the tab renders nine versions in every ten that nobody needed.

So the decision is to poll every 30 seconds, with a random offset on each tab's timer. Each poll sends the board's version tag, its ETag, so a quiet warehouse costs a 304.

A trip offer the server must know arrived

A ride-hailing app sends a trip offer to a driver, who has a short time to accept it. If the offer doesn't arrive, the server should offer the trip to another driver straight away. The server does all the sending here, so the obvious transport is one-way push.

Uber built exactly that. Its push platform, RAMEN, streamed messages over SSE, and the app sent acknowledgements separately, calling /ramen/ack every 30 seconds. Uber's later write-up names the cost: "The delivery state of a message is unknown for up to 30 seconds after it is written to a RAMEN connection." That gap, it says, "prevents us from resending critical push messages like driver offers."

When the server learns an offer arrived
Top: the offer goes down the SSE stream at 0 seconds (1), and the acknowledgement rides the next batched call, up to 30 seconds later (2). An offer lost at 0 seconds looks the same as one that arrived, in red, until the batch is due. Bottom: on a bidirectional stream, the app acknowledges the offer on the same connection within one round trip (3), so a missing acknowledgement can trigger a second driver within seconds, in green.Top: the offer goes down the SSE stream at 0 seconds (1), and the acknowledgement rides the next batched call, up to 30 seconds later (2). An offer lost at 0 seconds looks the same as one that arrived, in red, until the batch is due. Bottom: on a bidirectional stream, the app acknowledges the offer on the same connection within one round trip (3), so a missing acknowledgement can trigger a second driver within seconds, in green.
With batched acknowledgements, the server is unsure for up to 30 seconds. Top: the offer goes down the SSE stream at 0 seconds (1), and the acknowledgement rides the next batched call, up to 30 seconds later (2). An offer lost at 0 seconds looks the same as one that arrived, in red, until the batch is due. Bottom: on a bidirectional stream, the app acknowledges the offer on the same connection within one round trip (3), so a missing acknowledgement can trigger a second driver within seconds, in green.

The heartbeat closes only part of that gap. After 7 seconds of silence the app reconnects, and its sequence number tells the server where it stopped. But the server learns this late, and never if the phone has gone dark.

Uber rejected an HTTP acknowledgement per message, because "This results in a larger amount of data being uploaded due to headers." It moved RAMEN to gRPC bidirectional streams, so the app acknowledges each message on the stream it arrived on.

The direction depends on who sends the data, and also on who needs to know it arrived. When the server acts on delivery, the acknowledgement has to come back quickly and cheaply. In practice that means on the same connection, even though the data only flows one way.

Live comments for a million viewers

The question is how 200 comments a second reach 1 million viewers of the same live stream. Chat is the familiar model, so the obvious design is a connection per viewer, with each comment sent as it arrives.

Back of envelopeOne stream, 1 million viewers, 200 comments a second
The audience and the comment rate are assumptions. Count
the frames each design writes, then the servers that
hold the connections.

One frame per comment per viewer
  frames       1M × 200                      = 200M/s

One batch per viewer per second
  frames       1M × 1                        = 1M/s
  servers      1M / 100,000 per server       = 10
               (LinkedIn's live video experiment)
  ──────────────────────────────────────────────────────
Batching cuts the frames 200 times. It still leaves a
connection tier sized for the largest audience.
Naive

A WebSocket per viewer, one frame per comment

A viewer receives far more than it sends, and posting a comment is one ordinary request, so a bidirectional socket buys nothing over SSE. The cost that rules it out is 200 million frames a second, each a separate write into a separate socket.

Senior

SSE per viewer, through a fanout tier that batches

LinkedIn built this for likes on live video. Each viewer's connection lands on a frontend server, which keeps an in-memory table of which of its connections watch which video. Frontends subscribe to dispatcher nodes for those videos, so a dispatcher sends each event once per frontend, not once per viewer. In an experiment, LinkedIn fit 100,000 connections on one frontend.

Fanout through frontends that batch
A comment reaches a dispatcher (1), which sends it once to each frontend with viewers of that video (2). Each frontend holds 100,000 SSE connections and an in-memory table of who watches what. It gathers a second's comments and writes one batch to each viewer (3).A comment reaches a dispatcher (1), which sends it once to each frontend with viewers of that video (2). Each frontend holds 100,000 SSE connections and an in-memory table of who watches what. It gathers a second's comments and writes one batch to each viewer (3).
Each comment is sent once per frontend, then once per second per viewer. A comment reaches a dispatcher (1), which sends it once to each frontend with viewers of that video (2). Each frontend holds 100,000 SSE connections and an in-memory table of who watches what. It gathers a second's comments and writes one batch to each viewer (3).

With one batch per viewer per second on each frontend, 200 million frames a second become 1 million, on about 10 frontends. This is the standard design. Its cost is a connection tier sized for the largest audience, holding connections that must survive deploys and all carry the same bytes.

Staff

Every viewer gets the same bytes, so serve them like video

Question the premise that each viewer needs their own stream. Every viewer sees the same comments in the same second, and nothing in a batch is personal. So publish each second's comments as one small object that never changes, at a URL such as /live/v_77/comments/1730457307. Viewers fetch them through the CDN's points of presence (PoPs), the locations it serves users from.

Live video already works by polling. An HTTP Live Streaming (HLS) player "MUST periodically reload" its playlist under RFC 8216, so a live HLS stream with 1 million viewers is 1 million clients polling a CDN.

Two details make it work. First, a viewer shouldn't guess which second to ask for. A second that doesn't exist yet misses at every PoP and reaches the origin as a 404. So either the viewer reads a small latest object, cached for about a second, that names the newest finished second, or the origin holds the request until that second exists. Low-Latency HLS works the second way: the server holds a request until the segment it asks for exists. Either way, the client takes the time from the server, never from its own clock.

Second, "once per PoP" needs the CDN to collapse simultaneous misses for the same object into one origin request. CloudFront's Origin Shield, for example, does this so that "as few as one request" reaches the origin.

Comments as one-second objects at the edge
The publisher writes each second's comments as one object that never changes, and updates a small latest object that names the newest second (1). Viewers read latest, then ask their nearest CDN location for the next second (2). Each location collapses simultaneous misses into one origin fetch per object (3), then serves it to every viewer near it.The publisher writes each second's comments as one object that never changes, and updates a small latest object that names the newest second (1). Viewers read latest, then ask their nearest CDN location for the next second (2). Each location collapses simultaneous misses into one origin fetch per object (3), then serves it to every viewer near it.
Origin load is set by the number of PoPs, not the number of viewers. The publisher writes each second's comments as one object that never changes, and updates a small latest object that names the newest second (1). Viewers read latest, then ask their nearest CDN location for the next second (2). Each location collapses simultaneous misses into one origin fetch per object (3), then serves it to every viewer near it.

In numbers: 1 million requests a second at the edge, and at the origin about one request per PoP per object. With, say, 300 PoPs, that is 300 requests a second, whether the audience is 10,000 or 10 million. A client that missed a second asks for that second's object, so the timestamp in the URL is its position.

What you give up:

A comment can arrive up to about 2 seconds after it was posted, against about 1 second with per-second batching. The edge bill is 1 million requests a second. Nothing can be personal: a viewer's own comment has to be drawn locally, and hiding a comment from one viewer can't use the shared object. For a broadcast, that trade is usually right. For anything per user, it isn't.

A deploy across the connection fleet

The load balancing page drains an HTTP server by taking it out of rotation and waiting for in-flight requests to finish, which takes seconds. A WebSocket connection has no natural end. After every configuration reload, Slack's HAProxy tier kept its old processes running "for many hours to allow long-lived websocket connections to drain". Slack had to limit how often it reloaded.

So the question has two parts. How do you restart 100 servers that each hold 1 million connections? And how do connections reach a server you have just added?

Naive

Restart the server, and let the clients reconnect

Each restart drops 1 million clients, and they all come back at once. The WhatsApp breakdown puts the peak near 500,000 logins a second for one server with no backoff. Each reconnect also downloads what it missed or, without positions, everything. Slack built an edge cache, Flannel, partly because "the combined weight of those requests manifest as slower connections," which leads to more reconnects, failures and retries.

Senior

Drain by asking clients to leave, and make each reconnect a resume

The server stops accepting new connections. Then it closes its existing ones over a window of a few minutes, with close code 1001, "going away". Clients reconnect with exponential backoff and a random first delay, land on other servers, and resume from their last position in the shared buffer. With replay, each reconnect costs a couple of events instead of the full state.

This is the standard answer. Two costs are left. The fleet needs headroom for the connections of every server draining at the same time. And adding servers moves nobody, because a new server only gets connections opened after it starts. Clients that stay connected for hours, such as desktop and TV apps, keep the old servers full.

Staff

Give every connection a maximum lifetime, with a random spread

Question the premise that a connection should last as long as possible. Netflix's push team ended connections on purpose. Its slides say to "Recycle connections after tens of minutes" and "Randomize each connection's lifetime." By default, Netflix's push server, Zuul Push, asks each client to close after 30 minutes, minus a random 0 to 3 minutes.

Every connection now ends on a schedule, and its reconnect goes wherever the load balancer sends it. A scheduled close isn't a failure, so the client skips the backoff and reconnects at once. The random spread already keeps reconnects apart. A new server fills within one lifetime, and a server you retire empties within one lifetime without forcing anyone off.

Back of envelopeWhat a 30 minute lifetime costs, all day
Every connection now ends on a schedule. Price the
reconnect rate that creates, every second of every day.

One server, 1M connections, 30 minute lifetime
  reconnects    1,000,000 / 1,800 s          ≈ 560/s

A fleet of 100M connections
  reconnects    100,000,000 / 1,800 s        ≈ 56,000/s
  WhatsApp's measured peak of logins         230,000/s
  share of that peak, always on              ≈ 24%

A 2 hour lifetime instead
  reconnects    100,000,000 / 7,200 s        ≈ 14,000/s
  ──────────────────────────────────────────────────────
The lifetime trades rebalancing speed for a constant
login load. New servers fill within one lifetime, and
every reconnect has to be a cheap resume, not a reload.

What you give up:

You pay for a constant stream of reconnects, each with a Transport Layer Security (TLS) handshake, an authentication check and a resume. Phones spend more data and battery.

Connections per server after adding five
Ten servers hold 100,000 connections each, and five empty ones are added at time 0. With no maximum lifetime, in red, the new five get only connections opened after they start, and the old ten stay near 100,000. With a 30 minute lifetime spread at random, in green, the old servers fall and the new ones rise until all 15 sit near 67,000 by about 30 minutes. These shapes hold for long-lived desktop and TV clients. On mobile, users closing and reopening the app do part of the rebalancing anyway.Ten servers hold 100,000 connections each, and five empty ones are added at time 0. With no maximum lifetime, in red, the new five get only connections opened after they start, and the old ten stay near 100,000. With a 30 minute lifetime spread at random, in green, the old servers fall and the new ones rise until all 15 sit near 67,000 by about 30 minutes. These shapes hold for long-lived desktop and TV clients. On mobile, users closing and reopening the app do part of the rebalancing anyway.
With no lifetime, new servers stay empty. With one, they fill within a lifetime. Ten servers hold 100,000 connections each, and five empty ones are added at time 0. With no maximum lifetime, in red, the new five get only connections opened after they start, and the old ten stay near 100,000. With a 30 minute lifetime spread at random, in green, the old servers fall and the new ones rise until all 15 sit near 67,000 by about 30 minutes. These shapes hold for long-lived desktop and TV clients. On mobile, users closing and reopening the app do part of the rebalancing anyway.

Where it goes wrong

These are ordered by how often they turn up.

1. Naming the transport before the delay

"We use WebSockets" in the first minute is the opening example in opening with the conclusion, the second of the ten most common ways candidates fail. It's often the right answer. But with no reasoning behind it, the interviewer can't tell it from a memorised one. State the delay in seconds and who sends, price polling at that delay, then step up only as far as the numbers force you.

2. A reconnect that starts from nothing

With no positions, a reconnect either loses the events from the gap or reloads the whole state. Both look fine in testing, where connections rarely drop. In production, the first loses messages without any error, and the second turns every deploy into a download of the full state for every client. Give each event a position, keep a few minutes of replay in a shared data store, and fall back to a snapshot.

3. A heartbeat slower than the shortest idle timer

Connections that die after exactly 60 seconds of quiet are an ALB or an nginx default doing its job. Send a heartbeat at least every 25 to 30 seconds, and expect a reply, so a dead connection is noticed as well as kept open.

4. Every client reconnecting in the same second

When a server fails, 1 million clients reconnecting at once are a load spike on the servers that survived. RFC 6455 asks for a random first delay, suggesting 0 to 5 seconds, and longer delays after each failure. The circuit breakers page makes the same point about recovery.

5. Draining as though connections end

A 30 second drain copied from an HTTP service either kills every connection at the deadline, which is the spike in item 4, or waits for hours. Close connections on purpose over a window, and give them a maximum lifetime.

6. Checking identity only at the handshake

A connection can outlive the token that opened it by hours. In browsers, neither the WebSocket nor the EventSource constructor can send an Authorization header, so tokens end up in the URL, and proxies write URLs to their logs. Fetch a short-lived, single-use ticket over a normal HTTPS request just before connecting, as Slack's client fetches "websocket connection setup information" first. Then have the server close a connection when its session is revoked or its token expires.

7. State on the connection server that must outlive the connection

LinkedIn's dispatchers kept their table of which frontends want which video in memory at first. Once there were several dispatchers, LinkedIn moved it into a shared key-value store, naming Couchbase and Redis as options, so losing one dispatcher would not lose it. State that must outlive a restart can't live on a server that every deploy restarts.

If you memorise nothing else

factwhy it matters
Push makes delivery fast, never reliableafter every gap, the client resumes from its last position
Push when updates are rarer than the accepted delay, poll when they are more frequenta first estimate; heartbeats move the line toward polling
Long polling's worst case is three network tripsan event just after a response waits for the next request
SSE has Last-Event-ID. WebSocket has nothingwith WebSocket you build the position yourself
The shortest idle timer on the path applies, 60 s on an ALB and on nginxheartbeat every 25 to 30 seconds, and expect a reply
Keep the replay buffer in a shared data store, and snapshot anything older2 GB against 300 GB for 1 million reconnects
On reconnect, subscribe first, then replay, then drop duplicates by positionthe other order loses events
A connection drain never finishes by itselfclose with 1001, and give connections a maximum lifetime
If the server must know a message arrived, the acknowledgement has to come back quickly and cheaplyin practice, on the same connection

What is expected at each level

Mid-level

Know the four transports and what each one costs, and walk from polling to push with a reason for each step. You aren't expected to raise idle timers, replay buffers or connection lifetimes unprompted, but you should answer sensibly when asked. If the interviewer says "the connection drops for a minute, what happens?", a good mid-level answer is "the client reconnects and asks for everything after the last message it got."

Senior

You lead this part of the discussion, and three things must come up without prompting.

Positions and resume. What the client sends when it reconnects, where the buffer that answers it lives, and what happens when the gap is older than the buffer.

How a connection dies. A heartbeat under the shortest idle timer, backoff with jitter, and a drain that closes connections on purpose.

Acknowledgements where delivery matters. How the acknowledgement gets back, and how fast.

Two things are disqualifying: a design where a reconnect loses events that matter without any error, and a reconnect path with no backoff.

Staff+

A correct design is still the bar. The difference is in deciding which connections, events and guarantees the product needs.

Decide per stream whether it may lose events. Messages need positions and replay. Typing, presence and likes don't.

Treat the reconnect as the normal path, and price it. Give connections a maximum lifetime, and size the reconnect rate it creates against your login capacity.

Question the per-client connection for broadcast data. When every viewer gets the same bytes, a one-second object behind a CDN replaces the whole connection tier, at the cost of about a second more delay.

Choose connections per server by what a restart costs, not by how many the hardware can hold.

And say what you would not build. Each of these can cost a team a quarter.

A WebSocket tier for a dashboard that is fine at 30 seconds old. An exactly-once protocol on top of WebSocket, when positions plus an id per send already cover it. A replay buffer measured in days, when a snapshot covers the rare long gap. A per-viewer fanout tier for a broadcast that a CDN could serve. A hand-built resume protocol for a one-way stream, when SSE's Last-Event-ID already does it.

Sources

The protocol details come from the standards, and every production number from the company that published it.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.