Sub topic 13
Syncing multiple devices and loading history
This chapter assumes you have read the chapters on message ordering and on storage for chat history. You should know that each chat has a server-assigned sequence number (seq) and that messages are stored by (chat_id, seq). You should also be comfortable reading short Python and JavaScript snippets.
The problem
Most users do not have one device. A person might use a phone, a laptop, and a tablet. Each device connects and disconnects on its own schedule. The laptop may be closed for a week, and the phone may lose signal in a tunnel.
The system has to satisfy four requirements:
- Every device eventually shows the same messages in the same order.
- Messages the user sends from one device appear on the others.
- A device that was offline can catch up without downloading everything again.
- A new device can load recent history and scroll back through older messages.
The tool that solves all four is the per-chat sequence number. It gives each device a cursor into each chat's log.
Devices as cursors
Each chat is an append-only log. Message seq = 41 always comes after seq = 40, and every device sees the same numbering. A device only needs to remember one number per chat: the highest seq it has applied without gaps.
To sync, the device asks the server for everything after that number. The request is "chat c1, after seq 100, limit 50". The server needs no per-device state to answer it. This keeps the sync API stateless, so any API server can handle it.
The server still needs to know which devices are connected so it can push live messages. That is a routing concern, covered in the chapter on scaling connection servers. For this chapter, assume the server can look up all live sessions for a user.
Fan-out to every device
When a message is accepted, the server pushes it to every live session of every participant. That includes the sender's other devices. If Alice sends from her phone, her laptop should show the message without a refresh. The sending device also receives the stored message back. It matches the message to its pending entry by clientMsgId and replaces the local draft with the final seq.
Devices that are offline get nothing now. They catch up when they reconnect. The push-notification chapter covers waking them.
Fetching history in two directions
A device pages through the log in two directions:
- Forward (after a cursor). Used for catch-up. The query is
seq > last_seq, ordered ascending. - Backward (before a cursor). Used for scrolling up. The query is
seq < oldest_seq, ordered descending, then reversed for display.
Both are keyset pagination. The cursor is a seq value, not a page number. Offset pagination (OFFSET 5000) breaks when new messages arrive, because every offset shifts. It also gets slower as the offset grows. A seq cursor stays valid, and the lookup is a range scan on the primary key (chat_id, seq).
from collections import defaultdict
class HistoryStore:
def __init__(self):
# chat_id -> list of messages; message with seq n is at index n - 1
self.messages = defaultdict(list)
def append(self, chat_id, text):
seq = len(self.messages[chat_id]) + 1
msg = {"chat_id": chat_id, "seq": seq, "text": text}
self.messages[chat_id].append(msg)
return msg
def after(self, chat_id, last_seq, limit=50):
"""Messages with seq > last_seq, oldest first."""
return self.messages[chat_id][last_seq:last_seq + limit]
def before(self, chat_id, oldest_seq=None, limit=50):
"""Messages with seq < oldest_seq, oldest first. None means latest."""
log = self.messages[chat_id]
end = len(log) if oldest_seq is None else oldest_seq - 1
return log[max(0, end - limit):end]
def catch_up(store, chat_id, last_seq, page=50):
"""Fetch pages until the device has everything. Returns (messages, new_last_seq)."""
collected = []
while True:
batch = store.after(chat_id, last_seq, page)
if not batch:
return collected, last_seq
collected.extend(batch)
last_seq = batch[-1]["seq"]
store = HistoryStore()
for i in range(1, 121):
store.append("c1", f"message {i}")
missed, new_last = catch_up(store, "c1", last_seq=100)
assert [m["seq"] for m in missed] == list(range(101, 121))
assert new_last == 120
older = store.before("c1", oldest_seq=101, limit=50)
assert [m["seq"] for m in older] == list(range(51, 101))
latest = store.before("c1", None, limit=30)
assert latest[0]["seq"] == 91 and latest[-1]["seq"] == 120A brand-new device has no cursor, so it skips forward catch-up. It calls before(chat, None) to get the latest page for each visible chat and loads older pages on demand.
Detecting gaps on the client
Live pushes and catch-up fetches overlap, and some pushes are lost. The client therefore treats the sequence number as a contiguity check:
seq <= last: a duplicate. Ignore it.seq == last + 1: the next message. Apply it.seq > last + 1: a gap. Fetch the missing range.
const lastSeq = new Map(); // chatId -> highest contiguous seq applied
const localLog = new Map(); // chatId -> array of messages
function applyMessage(msg) {
const last = lastSeq.get(msg.chatId) ?? 0;
if (msg.seq !== last + 1) return false;
if (!localLog.has(msg.chatId)) localLog.set(msg.chatId, []);
localLog.get(msg.chatId).push(msg);
lastSeq.set(msg.chatId, msg.seq);
return true;
}
async function syncChat(chatId) {
for (;;) {
const last = lastSeq.get(chatId) ?? 0;
const res = await fetch(
`/chats/${encodeURIComponent(chatId)}/messages?after=${last}&limit=100`
);
const batch = await res.json();
if (batch.length === 0) return;
for (const m of batch) applyMessage(m);
}
}
async function onLiveMessage(msg) {
if (applyMessage(msg)) return;
const last = lastSeq.get(msg.chatId) ?? 0;
if (msg.seq > last + 1) await syncChat(msg.chatId); // gap: fetch the missing range
}Because applyMessage only accepts the exact next number, the order of arrival does not matter. A live push and a fetched batch can both contain seq = 121, and the second one is dropped.
What to sync besides messages
Messages are only part of the state. Devices should also agree on the following.
- Read position. Store one
last_read_seqper user per chat on the server. Only ever move it forward (max(old, new)). Then reading on the phone clears the unread badge on the laptop, and two devices racing cannot move it backward. - Edits and deletes. The log is append-only, so a new
seqcan mean "message 40 was edited". A simpler option is to give each message aversionand update it in place. A deleted message becomes a tombstone (a record that says it was deleted). If you removed the row instead, an offline device could never learn that the message is gone. - The chat list. A device also needs to learn about new chats. Keep a per-user list of chats with the latest
seqfor each. On connect, compare it with local cursors to see which chats need a sync.
Choosing the cursor scope
| Approach | Cursor | Strength | Weakness |
|---|---|---|---|
| Per-chat cursor | One `seq` per chat | Reuses the chat's ordering. Simple. | Many chats means many requests after a long absence. |
| Per-user feed | One number for the whole inbox | A single request returns all changes, including edits and read state. | Needs a second sequence per user and extra writes per message. |
Per-chat cursors are enough for most designs. Switch to a per-user feed if users belong to thousands of chats, or if you need one ordered stream of every change.
Edge cases and limits
- Very long absence. If a device is months behind in a busy chat, pulling every message is wasteful. Set a threshold. Past it, the server returns the latest page and marks the range as "not loaded". The client fills it in on demand when the user scrolls.
- Retention. If the server prunes old messages, a cursor that points below the retention floor must get a "reset" response. The client then discards its local copy of that chat and reloads.
- Page size. Cap
limiton the server, for example at 100. A client must not be able to request a million rows. - Authorization. Each fetch must check that the user is a member of the chat, and was a member at those
seqvalues if you hide pre-join history. - Timestamps. Never use them as cursors. Device clocks differ, and the server's own clocks can too.
seqis the only reliable position. - End-to-end encryption. If the server cannot read messages, a new device cannot get old messages from the server alone. You need an encrypted backup or a transfer from an existing device.
Exercise
A laptop has lastSeq = 200 for chat c1. It receives a live push with seq = 205. What should it do, and why is dropping the message wrong?
Show answer
It should fetch messages after seq 200 (201 to 204, and then 205 if not yet applied) and apply them in order. Applying 205 directly would leave a hole in the local log, and lastSeq would then claim the device has everything up to 205. Dropping the message is also wrong, because the live push may be the only copy the device gets. The fetch recovers 205 along with the missing messages.
Exercise
Why is "load 50 messages starting at offset 1000" a poor way to page through a chat that receives new messages while the user scrolls?
Show answer
New messages shift every offset, so the page contents change between requests. The user sees duplicates or skips messages. Offsets also get slower as they grow. A seq-based cursor ("seq < 951, limit 50") stays correct when new messages arrive, and it is a fast range scan on the (chat_id, seq) key.
Exercise
A user reads a chat on the phone up to seq 90, and at the same moment the laptop reports it has read up to seq 85. What should the stored lastreadseq be, and why?
Show answer
It should be 90. The server stores max(old, new), so the value only moves forward. A late or out-of-order update from the laptop cannot move the read position backward and bring back unread badges the user has already cleared.