Sub topic 13
Syncing Multiple Devices and Loading History
This chapter assumes you know how per-chat sequence numbers work (see ordering and IDs) and how chat history is stored, partitioned by chat and ordered by sequence. Here you will see how a user's phone, laptop, and tablet stay consistent, and how a client loads history without fetching everything.
The problem
A user can be logged in on several devices at once. Each device needs every message, in the same order, even if it was offline for hours. The server cannot track "which messages did this device see" by pushing alone, because pushes are lost when connections drop.
The fix is to make the client responsible for knowing where it is. Each device remembers the highest sequence number it has received for each chat. This number is the device's cursor.
Cursors and catch-up
When a device connects, it reports its cursors. The server returns every message with a higher sequence number. Because sequence numbers are dense and per-chat, the client can also detect gaps: if it holds 41 and receives 43, it knows 42 is missing and asks for it.
def sync(log_messages, cursors):
"""log_messages: {chat_id: [msg, ...]} ordered by seq.
cursors: {chat_id: last_seq_seen_by_this_device}."""
updates = {}
for chat_id, msgs in log_messages.items():
last = cursors.get(chat_id, 0)
new = [m for m in msgs if m["seq"] > last]
if new:
updates[chat_id] = new
return updates
log = {"c1": [{"seq": 1, "text": "hi"}, {"seq": 2, "text": "yo"}, {"seq": 3, "text": "ok"}]}
assert sync(log, {"c1": 1}) == {"c1": [{"seq": 2, "text": "yo"}, {"seq": 3, "text": "ok"}]}
assert sync(log, {"c1": 3}) == {}In production, the server reads from storage with a range query ("chat c1, seq greater than 1") instead of scanning a list.
Delivering to every device
The server tracks the user's active connections, one per device. When a message arrives for a user, it goes to every connection that user has. The sender's other devices also receive it, so the message appears in their view of the conversation.
Each device acknowledges independently. A phone that is offline does not block the laptop, and the phone catches up by cursor when it reconnects.
placeholderLoading history
Opening a chat should not download its whole history. Clients load a page at a time, newest first, and fetch older pages as the user scrolls up. Paging by sequence number is better than paging by offset, because new messages shift offsets but never change sequence numbers.
def load_page(msgs, before_seq=None, limit=50):
"""Return up to `limit` messages older than before_seq, oldest first."""
if before_seq is None:
before_seq = msgs[-1]["seq"] + 1 if msgs else 1
older = [m for m in msgs if m["seq"] < before_seq]
return older[-limit:]
msgs = [{"seq": i} for i in range(1, 121)]
page1 = load_page(msgs)
page2 = load_page(msgs, before_seq=page1[0]["seq"])
assert page1[0]["seq"] == 71 and page2[-1]["seq"] == 70The client passes the oldest sequence number it holds, and the server returns the page before it.
Common errors
- Using timestamps as cursors. Clocks differ between servers, and two messages can share a timestamp. Use sequence numbers.
- Sharing one cursor per user. One device's progress would hide messages from another. Keep cursors per device and per chat.
- Loading everything on connect. With many chats, send only unread counts and the latest message per chat, then load details when a chat is opened.
- Ignoring gaps. If the client only appends what arrives, a lost push leaves a permanent hole.
Exercise
A laptop has cursor 120 for chat c7 and receives a pushed message with seq 123. What should it do, and why?
Show answer
It should request messages 121 and 122 from the server, then apply 123. Cursors are only safe to advance when there are no gaps, so a jump from 120 to 123 means two messages were lost and need to be fetched.
Exercise
Why is "give me messages after seq 70, limit 50" better than "give me page 2" for loading history?
Show answer
Offsets change when new messages arrive, so page 2 can repeat or skip messages. A sequence number refers to the same message forever.