ealeng

Episode 35 of 55 · Real-time

Reconnects and missed notifications: a server died, reconnecting lost 195, and sequence numbers lost none

A notification server was killed with 1,000 of 3,000 WebSocket clients connected to it. Reconnecting and asking for nothing lost 195 notifications for 183 users. Resending after the last acknowledgement lost none, but showed 1,540 notifications twice to 805 users, because nobody had acknowledged anything yet. Numbering each message, with an inbox to replay from, lost none and repeated none. Then presence: a phone that vanishes without saying goodbye stayed online for a median of 2.4, 12.3 or 37.4 seconds, depending on how often it sent a heartbeat, and why accurate presence costs a heartbeat a second per user.

Lab 15 · Real-Time Delivery and Fan-out11 min read
Video transcript9:16

0:00Cold open

0:01

I killed a notification server, with a thousand users connected to it. Their apps reconnected on their own.

0:09

Just reconnecting, a hundred ninety-five notifications vanished, for a hundred eighty-three users.

0:17

Asking the server to resend everything after the app’s last acknowledgement, its last got-it: none lost. But nobody had sent a got-it yet, so one thousand five hundred forty were shown twice.

0:31

Numbering every notification: zero lost, and zero shown twice.

0:37

So how does a reconnecting app get everything exactly once? And how does a server know you’re really gone?

0:46Intro

0:47

Hands-on system design, part thirty-five.

0:51

Today: reconnecting without losing or repeating messages, and the green online dot.

0:58Meet Lucía

0:59

I’m Lucía, a platform engineer.

1:02

These aren’t real phones. A load tester opens three thousand WebSocket connections, all on one laptop. A WebSocket is a connection that stays open, so the server can push messages down it.

1:17

They’re spread over three notification servers, behind HAProxy, a load balancer. A publisher sends notifications to random users for forty seconds: only about four per user in the whole run.

1:31

Think of a radio show. A live connection is listening to the broadcast. Reconnecting is stepping out of the room. Unless the station keeps recordings, what played meanwhile is gone.

1:4501 · What you need

1:47

To run it yourself: Docker, for the servers, HAProxy and Redis. The quick tests run in a couple of seconds, without Docker.

1:56

No cloud, and nothing to pay for.

2:0102 · One notification

2:03

First, how one notification travels. The publisher runs one small script in Redis, a fast shared message board, for each one.

2:12

It gives the message the user’s next sequence number: one, two, three, and so on.

2:19

It keeps a copy in the user’s inbox, which holds the last two hundred.

2:25

And it publishes it on the user’s channel. Whichever server holds that user’s connection is listening on that channel, and passes it on.

2:35

But a channel reaches only whoever is listening right now. Like the live broadcast.

2:4303 · Just reconnect

2:44

Fifteen seconds in, I killed one of the three servers without warning. It held a third of the clients: a thousand. Its restart loop brought it back, and they reconnected through HAProxy, which picks a server for each.

2:59

First, the plain way: reconnect, and ask for nothing. A hundred ninety-five notifications were lost, for a hundred eighty-three users.

3:09

Why? Those thousand users get a third of the notifications: about a hundred a second between them. So a hundred ninety-five means each was away about two seconds, on average. That’s my estimate: the time away wasn’t measured.

3:2604 · Resend

3:27

Second try. The app keeps a bookmark: the last message it acknowledged with a got-it. It sends a got-it once every ten messages. On reconnect, it asks for everything after that bookmark.

3:41

How many lost this time? And how many shown twice?

3:47

None lost. But one thousand five hundred forty shown twice, to eight hundred five users.

3:54

Why so many? Before the kill, each user had received only about one and a half notifications. Almost certainly nobody had reached ten, so nobody had sent a got-it, and the server resent everything they’d already seen. That’s how this test was set up: with busier users, the repeats would be at most the last nine.

4:15

And the app had no way to tell a repeat from a new one.

4:2105 · Numbered

4:22

Third try: the app remembers the sequence numbers it has. On reconnect it says: I have everything up to thirty-seven. Like asking the station for episode thirty-eight onwards.

4:35

Zero lost, and zero shown twice, out of eleven thousand nine hundred ninety-nine.

4:42

The price is time. Of everything sent roughly after the kill, the slowest one in a hundred took under a second with a replay,

4:51

against a few milliseconds without, because without a replay, the messages that would have been slow were simply lost. The replayed ones had waited in the inbox while the app reconnected.

5:0406 · In code

5:06

In code. When a client connects, the server starts listening on the user’s channel first.

5:13

Then it replays the inbox after the number the client sent. Only then does it forward live messages.

5:21

That order matters. If it replayed first and started listening after, a message sent in between would be missed. This way, it may arrive twice instead,

5:32

and the app drops any number it has already seen.

5:36

The number the app sends is the highest one with no gaps before it. If it has one, two, three and five, it says after three, so four comes again.

5:47

One limit: the inbox keeps two hundred. A phone that fell further behind than that can’t be replayed. A real system has to say so, and the app reloads everything. This demo doesn’t do that part, and this run never got close.

6:0407 · Who’s online?

6:05

Now presence: the green dot that says who’s online. How does a server know?

6:11

Each connected app sends a heartbeat, a tiny message, every few seconds. Each one sets online in Redis, with a timer three heartbeats long.

6:22

Close the app properly, and the server deletes it at once.

6:27

But a phone that loses signal never says goodbye. Its connection just goes quiet, and it stays online until the timer runs out: three heartbeats after its last one, so two to three heartbeats after it went quiet. Like a hallway light on a timer.

6:45

A new test, separate from the first: two thousand clients. Twenty seconds in, ten percent go silent: no more heartbeats, but no goodbye either. And ten percent close properly. An observer checks everyone four times a second.

7:0208 · Shown offline

7:03

With a heartbeat every second, a vanished user still showed online for about two point four seconds. Expected: two to three.

7:13

With a heartbeat every five seconds: about twelve seconds.

7:19

Every fifteen seconds: about thirty-seven, and up to forty-five.

7:24

A clean close showed offline at the observer’s next check, under a quarter of a second, in every run.

7:32

The spread comes from timing. A phone vanishes at a random moment between two heartbeats, so its timer has anywhere from two to three heartbeats left. And I time it to the last check that still saw the user online, a quarter-second apart, so the shortest, one point nine, is just under two.

7:5309 · The cost

7:54

What does it cost? This part isn’t measured, it’s arithmetic: every online user sends one heartbeat per interval.

8:03

At a million users, two to three second presence costs a million heartbeats a second, each one a write to Redis. Thirty to forty-five seconds: about sixty-seven thousand.

8:16

Halve the delay, and you double the heartbeats, for everyone online. That’s one reason many apps show last seen, instead of a live dot.

8:26Back to Lucía

8:28

So, three lessons.

8:30

A live channel forgets. Keep an inbox, and let a reconnecting app resume.

8:37

Number every message. The app says how far it got, the server starts listening first and then replays, and the app drops repeats.

8:47

And presence is a timer. Making it faster is paid for by everyone online.

8:53

Next time: one post, and tens of thousands of followers. Copy it into every feed, or gather it when each feed is read?

9:03

For today: number your messages.Lucía: Number your messages.

9:06Summary

9:08

Keep an inbox, resume by sequence number, and pay for presence with heartbeats.

Key takeaways

  • ✓A live connection forgets: when the server holding 1,000 clients was killed, reconnecting and asking for nothing lost 195 of 11,999 notifications, for 183 of those users, because a channel delivers only to whoever is listening at that moment.
  • ✓Resending after the last acknowledgement lost none, but it showed 1,540 notifications twice to 805 users: acks went out in batches of ten, and before the kill each user had received only about 1.5 notifications, so no batch had completed and the server resent everything.
  • ✓Numbering each notification per user and keeping the last 200 in an inbox lost 0 and repeated 0 of 11,999, at a price: the replayed notifications were slower: the slowest one in a hundred (the p99) took 750 ms after the kill, against 3.7 ms for the ones that arrived without a replay.
  • ✓The client asks for everything after the highest number it has with no gap before it, and the server starts listening before it replays, so a notification sent during the replay arrives twice rather than not at all; the client drops the second copy.
  • ✓Presence is a timer that each heartbeat resets: a client that vanished silently stayed online for a median of 2.4 s with a heartbeat every second, 12.3 s every five seconds and 37.4 s every 15 seconds, each inside its predicted window of 2–3, 10–15 and 30–45 seconds, while a clean close showed offline within one quarter-second check.
  • ✓Faster presence costs the same at every user: at one million users, a 2–3 second window means 1,000,000 heartbeats a second, and a 30–45 second window means 66,667, which is arithmetic from the heartbeat rule, not something the lab measured.

A server with a thousand clients on it was killed in the middle of a run. Reconnecting lost 195 notifications. Asking the server to resend everything after the last acknowledgement lost none, but showed 1,540 notifications twice. Numbering every notification lost none and showed none twice. This chapter takes the three reconnect strategies apart, then asks how a server knows a phone has gone, and what that knowledge costs.

The examples come from Lab 15 (Real-Time Delivery and Fan-out) of the system design labs: script 03_restart.py for the server kill, with the client logic in delivery.py, and script 05_presence.py for the online dot. Both run on the same laptop setup as the earlier chapters, an Apple M4 Max with Docker Desktop and 16 virtual CPUs. The servers, the HAProxy load balancer and Redis all ran in Docker, and a separate client container simulated the users. Each configuration is one recorded run. The README puts the whole lab at about 35 minutes.

What a reconnect loses

A WebSocket is a connection that stays open, so the server can push a message down it the moment it arrives. The server gets each notification through Redis, a fast shared store that also carries a publish-subscribe channel: one channel per user, named u:<user> in the lab. Whichever server holds the user's connection listens on that channel and passes the message on.

A channel reaches only whoever is listening right now. A client that is reconnecting is not listening, so what is published in the gap is gone. Think of a live radio broadcast: step out of the room, and what played meanwhile is gone unless the station keeps recordings.

The first test kills a server and does nothing else. In the lab, 3,000 clients were spread across three servers behind HAProxy, a load balancer, and a publisher sent 300 notifications a second for 40 seconds. Fifteen seconds in, one server (ws2) was killed. It held a third of the clients, 1,000 of them, and they reconnected through HAProxy, which picks a server for each.

  • Reconnect and ask for nothing: 195 of 11,999 notifications were lost, for 183 users.

Those 1,000 users received about 100 notifications a second between them. 195 lost is therefore about two seconds' worth each, on average. That is an estimate. The time away was not measured.

Sequence numbers: ask for what you missed

The second strategy is the one most apps reach for first: remember the last message you acknowledged, and ask for everything after it. In the lab, the client acknowledges every ten messages, so the acknowledgement is a bookmark that moves in steps of ten.

  • Resend after the last ack: none lost, but 1,540 notifications were shown twice, to 805 users.

Why so many repeats? Before the kill, each user had received only about 1.5 notifications, so almost none had reached the tenth message that triggers an acknowledgement. Nobody had moved the bookmark, and the server resent everything the users had already seen. The client had no number to tell a repeat from a new message, so it showed them all. This is how the test was set up. With busier users, the repeats would be at most the last nine, because the bookmark would have moved most of the way.

The third strategy gives every message a number. The server assigns each user's notifications the next sequence number, one, two, three, and so on, and keeps the last 200 in an inbox: a per-user list in Redis (inbox:<user>). The client remembers the numbers it has. On reconnect, it says what it has, not what it hasn't: "I have everything up to 37." The client sends the highest number it holds with no gap before it, so if it holds 1, 2, 3 and 5, it says 3, and 4 comes again. The client drops repeats by number.

  • Sequence numbers with an inbox: 0 lost and 0 shown twice, out of 11,999.
Try it · A server dies with 1,000 clients on itrecorded run, 03_restart.py

The client reconnects and asks for nothing. Whatever was published while it was away is gone.

Lost
195
Shown twice
0
Users affected
183
p99 after the kill
4 ms
Lost, of 200
Repeats, of 1,600

Published 11,999 notifications over 40 s; 11,804 arrived. Median delivery 1.2 ms in every mode. One run per mode.

The price is time. Messages that were replayed from the inbox had waited while the client reconnected. Their p99 latency after the kill was 750 ms, against 3.7 ms for messages that arrived without a replay. The fast figure is not a fair comparison, because the messages that would have been slow in the first strategy were the ones lost.

Replay order, and the window it covers

The order of operations in the server matters. On connect, the server must start listening on the user's channel first, then replay the inbox after the client's number, and only then forward live messages. If it replayed first and started listening afterwards, a notification published in between would be missed. Listening first means the same notification may arrive twice, and the client drops the second copy.

The replay window is the inbox. The lab keeps the last 200 notifications per user, and a client that has fallen further behind than that cannot be replayed. It must be told to resynchronize: reload the full state, the way a station with no archive would tell a listener to fetch the current schedule instead. The lab does not implement this step. Its test clients never got close to the limit: over the whole 40-second run each user received about four notifications, far below 200. The README lists the resync path as an exercise, and any real system needs it, because a phone that is off for a day will hit the limit.

Presence: knowing who is online

The green dot needs the server to know which clients are still there. A client that closes its connection cleanly says goodbye, and the server can remove it at once. A phone that loses signal never says goodbye. Its connection just goes quiet.

So the lab uses heartbeats. Each connected client sends a small message on its connection every few seconds. The server handles each one by writing a key for that user, presence:<user>, in Redis, with a time-to-live (TTL): a timer that deletes the key when it runs out. Each heartbeat resets the timer, and the lab sets the TTL to three heartbeat intervals.

Think of a hallway light on a timer: each motion turns it on for three minutes, and it goes off after the last motion when nobody moves again. A clean close is someone turning the light off by hand. A silent phone is someone walking off without touching the switch.

The timing follows from the rule. A phone vanishes at a random moment between two heartbeats, so its timer has somewhere between two and three intervals left. A closed connection is removed immediately; a silent one is seen as online until the timer runs out.

Try it · How long a vanished user still shows onlinerecorded run, 05_presence.py
Heartbeat every 1 s, timer 3 smedian 2.4 s (1.9–2.9)
0 s25 s50 s
Heartbeat every 5 s, timer 15 smedian 12.3 s (10.0–14.8)
0 s25 s50 s
Heartbeat every 15 s, timer 45 smedian 37.4 s (30.0–44.8)
0 s25 s50 s
Shaded: the predicted window, 2–3 times the heartbeat interval. Dot: the recorded median. Line: the fastest and slowest of 200 vanished clients.
A clean close showed offline at the next observer check, under a quarter of a second, in every run.
HeartbeatHeartbeats/s, 2,000 usersAt 1M users (arithmetic)
every 1 s2,0001,000,000
every 5 s400200,000
every 15 s13366,667

The workflow and the results

Reconnects. The 03_restart.py script starts 3,000 WebSocket clients through HAProxy, starts publishing 300 notifications a second, waits 15 seconds, and then kills ws2. It runs three times, once per client mode, and counts what each client received against what was published. Each user's notifications are numbered, so the script can match them exactly and count losses and repeats.

Client mode Published Delivered Lost Shown twice Users affected p50 p99 after the kill
Reconnect, ask for nothing 11,999 11,804 195 0 183 1.2 ms 3.7 ms
Resend after the last ack 11,997 13,537 0 1,540 805 1.2 ms 621 ms
Sequence numbers and inbox 11,999 11,999 0 0 0 1.1 ms 750 ms

Presence. The 05_presence.py script starts 2,000 clients, each heartbeating every 1, 5 or 15 seconds, with a TTL of three intervals. At 20 seconds in, 10% of them go silent (no more heartbeats, but the connection stays open) and 10% close cleanly. An observer asks Redis who is online four times a second. The script records, for each vanished client, how long after going silent it was last seen online.

Heartbeat every TTL Predicted window Vanished, last seen online: median (range) Clean close Heartbeats/s, 2,000 users
1 s 3 s 2–3 s 2.4 s (1.9–2.9) within one check 2,000
5 s 15 s 10–15 s 12.3 s (10.0–14.8) within one check 400
15 s 45 s 30–45 s 37.4 s (30.0–44.8) within one check 133

Every vanished client went offline inside its window, and a clean close showed offline at the next quarter-second check. The 1 s row's shortest value, 1.9 s, is just under two seconds because the observer checks every 0.25 s and records the last check that still saw the client online.

What presence costs

Accuracy is paid for by everyone online. Every online user sends one heartbeat per interval, and each heartbeat is a write to Redis. Halve the detection time and you double the heartbeats, for every connected user at once.

At one million users, a 2–3 second window means one million heartbeats a second. A 30–45 second window means about 67,000. This is arithmetic from the rule (users divided by interval), and the lab did not load a million clients to measure it. It is also why many apps show "last seen" rather than a live dot: the cost of a fast dot falls on every user, including the ones not looking at it.

Lab 15 does not test fan-out of presence to friends. Pushing every change to every friend is the same fan-out problem as the feed, which the next episode of this track (part 36) takes up.

Caveats

  • One run per mode, and the numbers are small. The three reconnect runs and the presence runs are single recordings. The published count differs slightly between runs (11,997 in the resend run, 11,999 in the others), because the publisher's random sequence differs.
  • Time away was not measured. The "about two seconds away" figure is an estimate from the loss rate. HAProxy's least-connections balancing can also send reconnects to the dead server until its health check marks it down, which adds to the time away.
  • The p99 "after the kill" figures are approximate. They mix all 3,000 users. The kill time is taken on the host's clock and the message times come from the client container's clock, so read them as orders of magnitude, not exact milliseconds.
  • The resend result depends on the setup. The lab's README says the repeats are "up to nine" messages per client, which is true in general. In this run, each user had about 1.5 messages before the kill, so the server resent everything, and the 1,540 is a feature of the test, not of the strategy.
  • No resync was tested. Inbox overflow never happened (200 per user, about four per user over the run), so the "too far behind" path is untested.
  • Presence was tested on one laptop with 2,000 clients. The observer's quarter-second check sets the resolution, and the clean-close times in the results are negative because they are measured against the close time, which sits just after the observer's last online check. The heartbeat rates at a million users are arithmetic, not a load test.
  • Not covered: multi-region routing, TLS, the cost of heartbeats on Redis under load, and presence fan-out to friends. The lab lists fan-out to friends as an exercise.

The checklist

  1. Assume a live connection forgets. Keep an inbox per user for the last N messages, and let a reconnecting client replay from it.
  2. Number every message per user. The client says the highest number it has with no gap before it, and drops any number it has already shown.
  3. Listen first, then replay. A notification sent during the replay is then delivered twice, never zero times, and the client drops the second copy.
  4. Size the inbox from how long a phone can be away, and have an answer for a client that is older than the inbox: resynchronize from full state, never skip silently.
  5. Treat presence as a timer, and price its heartbeats. The detection time you pick is paid for by every connected user, every interval.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.A client drops its connection when its server dies, reconnects a moment later and asks for nothing. What happens to the notifications published while it was away?

  2. 2.Resending after the last acknowledgement lost nothing, yet 1,540 notifications were shown twice. What explains the repeats?

  3. 3.A client has numbers 1, 2, 3 and 5 when it reconnects. What should it ask for, and why?

Check your understanding

Try each question before opening its answer.

Why did "resend after the last ack" show 1,540 notifications twice, when the lab's acknowledgements were sent every 10 messages?

Because before the kill, each user had received only about 1.5 notifications, so almost no client had reached the tenth message that triggers an acknowledgement. The server had no bookmark and resent everything. The client had no sequence number to recognize a repeat, so it showed them again. With busier users, the repeats would have been at most the last nine.

The server starts listening before it replays the inbox. What goes wrong if it replays first?

A notification published between the end of the replay and the start of listening is missed, because it was neither in the replay nor sent live. Listening first can deliver a notification twice, once in the replay and once live, but the client drops the second copy, so nothing is lost.

A client has notifications 1, 2, 3 and 5. What does it ask for, and what does the server send back?

It asks for everything after 3, the highest number with no gap before it. The server replays 4 and 5, and the client drops the 5 it already has. Asking after 5 would never produce 4.

A phone's signal drops, and its presence timer has three heartbeats of TTL. Why did the 1-second heartbeat show it online for between 1.9 and 2.9 seconds, not exactly 3?

The timer is reset by each heartbeat, so when the phone goes silent it has between two and three intervals left, depending on where in the interval it went quiet. The observer checks every 0.25 seconds, so the recorded last-online time is the last check that still saw the phone online, which is also quantized.

Presence at 2 to 3 seconds costs a million heartbeats a second at a million users. Why is that the wrong place to put the cost in most apps?

Because the cost falls on every connected user, including the ones who never look at the dot. Most people only need to know whether a friend is online when they open a conversation. Fetching presence for the friends on screen costs one request, and fast updates can be pushed only for the conversation that is open.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.