download

A chat app reconnects. Which messages should it ask for?

System design~15 minReviewed 29 Oct 2026Free · No sign-in

Question

In a chat app, the server numbers each conversation's messages 1, 2, 3 and so on, with no gaps. The phone saves every message it gets. After a reconnect, it asks the server for all messages after its cursor.

The phone has saved messages 1 to 20. Then 22 and 23 arrive, but 21 is late, and the connection drops before it comes.

  1. With the code below, what does the phone ask for after the reconnect? What is lost?
  2. Fix on_message. No message may be lost, and a repeated message must be saved only once.
"CODE · PYTHON"
class ChatSync:
    def __init__(self):
        self.saved = {}  # message number -> text, stored on the phone
        self.cursor = 0  # after a reconnect, ask for messages after this

    def on_message(self, seq, text):  # seq: the message number
        self.saved[seq] = text
        self.cursor = max(self.cursor, seq)
Show hints (3)
  1. "FOLLOW THE CURSOR"

    Write down the cursor after 22 and after 23. The server sends only messages with a higher number. Who will ever send 21?

  2. "WHAT IT PROMISES"

    Let the cursor mean: every message up to here is saved. Is that true for the highest number seen?

  3. "MOVE IT CAREFULLY"

    Keep 22 and 23, but move the cursor only while the next number is already saved. Storing messages by number makes a repeat harmless.

Show checked explanation

It asks for messages after 23, so the late 21 is never fetched. The cursor must be the last number with no gap before it, not the highest seen. Keep 22 and 23, leave the cursor at 20, ask after 20, and skip repeats.

"SOLUTION · PYTHON"
class ChatSync:
    def __init__(self):
        self.saved = {}  # message number -> text, stored on the phone
        self.cursor = 0  # every message up to here is saved

    def on_message(self, seq, text):
        self.saved.setdefault(seq, text)  # a repeat changes nothing
        while self.cursor + 1 in self.saved:
            self.cursor += 1


sync = ChatSync()
for seq in [*range(1, 21), 22, 23]:
    sync.on_message(seq, f"msg {seq}")
print("after the reconnect, ask after", sync.cursor)
for seq in [21, 22, 23]:  # the server's answer
    sync.on_message(seq, f"msg {seq}")
print("cursor", sync.cursor, "saved", len(sync.saved))
"OUTPUT"
after the reconnect, ask after 20
cursor 23 saved 23

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

The bug is what the cursor means. The server answers "after N" with every message numbered above N. That is safe only if the phone really has everything up to N.

eventsaved on the phonehighest seenlast with no gap
start1 to 202020
22 arrives1 to 20, 222220
23 arrives1 to 20, 22, 232320
reconnectsameasks after 23, gets nothingasks after 20, gets 21, 22, 23
answer saved1 to 232323

With the highest number, 21 sits behind the cursor, and nobody sends it again. With the last number before the gap, the phone asks after 20. It gets 21, plus 22 and 23 a second time. Those are already saved under their numbers, so the repeats change nothing. Then the cursor moves from 20 to 23.

Why can 22 come before 21? Inside one WebSocket connection, messages arrive in the order the server sent them. But in a group chat, two server workers may number two messages, 21 and 22, and the second one sends first. Loading history while listening for new messages also gives two streams that can overlap.

The server must do two things: number each conversation with no gaps, and keep messages long enough to send any number again.

Common mistakes

  • Asking for a few extra messages, like everything after 13 instead of 23. A message that is later than your margin is still lost.
  • Using the time of the last message as the cursor. Two messages can share a millisecond, and server clocks drift. Use the conversation's message number.
  • Saving the new cursor before the messages. If the app crashes in between, the cursor points past messages that were never stored. Save both in one local database transaction.
  • Deleting a message by dropping its number. The phone waits for that number forever. Keep the number and send a "deleted" marker in its place.

Follow-up questions

  • "21 never arrives. What now?" Don't wait forever: after a few seconds, ask the server for 21 by number. If the phone is far behind, say 5,000 messages after a week offline, load the newest 50 first. Mark the 4,950 older ones as missing and fetch them as the user scrolls up.
  • "Can the phone send a read receipt when the cursor moves?" No. The cursor means the messages are stored on the phone: "delivered". "Read" means the user saw them. Send a separate read event with the number of the last message shown on screen.
  • "Your message ids are global, like 1001, 1005, 1012. Does this still work?" Not as it is. With global ids, missing numbers are normal, so a gap tells you nothing. Add a gap-free number per conversation, or let the server return a resume token it knows how to continue from.

What a strong answer covers

Shows that the highest number seen skips a late message. Uses the last number with no gap before it, keeps out-of-order messages and skips repeats. Says the server must number each conversation without gaps.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from System Design Interview: An Insider's Guide (Alex Xu, 2020); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.