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.
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.
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.
| transport | who can send | delay it adds | cost per message | what the server holds | catching up after a gap |
|---|---|---|---|---|---|
| short polling | the client, on a timer | up to one interval | a full request and response | nothing between requests | built in: each request carries the last position |
| long polling | the client asks, and the server answers when it has something | about one network trip, up to three | a full request and response | one open request per client | built in, the same way |
| server-sent events | the server; the client uses ordinary requests | close to none | a few bytes of text framing | one open response per client | built in: Last-Event-ID on reconnect |
| WebSocket | both, at any time | close to none | 2 to 14 bytes of framing | one open socket per client | none: 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 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 path | default idle limit |
|---|---|
| AWS Application Load Balancer | 60 s, settable from 1 to 4,000 s |
| AWS Network Load Balancer, TCP listener | 350 s, settable from 60 to 6,000 s |
| nginx proxying a WebSocket | 60 s with no data from the server |
| Heroku router | 55 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."
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.
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.
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.
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.
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."
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.
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.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.
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.
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.
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.
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?
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.
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.
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.
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.
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
| fact | why it matters |
|---|---|
| Push makes delivery fast, never reliable | after every gap, the client resumes from its last position |
| Push when updates are rarer than the accepted delay, poll when they are more frequent | a first estimate; heartbeats move the line toward polling |
| Long polling's worst case is three network trips | an event just after a response waits for the next request |
SSE has Last-Event-ID. WebSocket has nothing | with WebSocket you build the position yourself |
| The shortest idle timer on the path applies, 60 s on an ALB and on nginx | heartbeat every 25 to 30 seconds, and expect a reply |
| Keep the replay buffer in a shared data store, and snapshot anything older | 2 GB against 300 GB for 1 million reconnects |
| On reconnect, subscribe first, then replay, then drop duplicates by position | the other order loses events |
| A connection drain never finishes by itself | close with 1001, and give connections a maximum lifetime |
| If the server must know a message arrived, the acknowledgement has to come back quickly and cheaply | in 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.
- RFC 6455: the WebSocket handshake, framing, Ping and Pong, close codes and reconnect delay.
- WHATWG, Server-sent events, and MDN, Using server-sent events:
Last-Event-ID, when the browser gives up, and the 6 connection limit. - RFC 6202: long polling's three network trips.
- Uber, Real-Time Push Platform and Next Gen Push Platform on gRPC: polling load, sequence-number resume, heartbeats and acknowledgements.
- Discord, Gateway documentation and How Discord Reduced Websocket Traffic by 40%: heartbeats, resume and
READYsize. - Slack, Websockets to Envoy, Flannel and Real-time Messaging: long drains, reconnect storms and connection setup.
- Netflix, Scaling Push Messaging, Zuul's PushRegistrationHandler and InfoQ on Pushy: connection lifetimes and connections per node.
- LinkedIn, Instant Messaging and Streaming a Million Likes/Second: connections per node and the dispatcher fanout.
- High Scalability, How WhatsApp Grew: connections per server and peak logins.
- Idle timers from the AWS ALB, AWS NLB (idle timeout, keepalive), nginx, Heroku and Cloudflare documentation.
- Linux tcp(7) and Android's network access guide: keepalive defaults and radio tail time.
- Socket.IO, How it works and Delivery guarantees: the long-polling start and at-most-once delivery.
- Figma, How Figma's multiplayer technology works: the snapshot on reconnect.
- RFC 8216, the Low-Latency HLS draft and CloudFront Origin Shield: polling players, held requests and collapsed origin fetches.