Chapter 6
Offline sync
Ben’s phone was offline for 10 minutes, and he is in 200 conversations. When it reconnects, what should it ask the server?
This chapter is a first draft. The author is still checking it, and its text and numbers may change.
Ben spent 10 minutes on the underground with no signal. Out of the station, his phone reconnects to the server. None of the messages sent to him in those 10 minutes were pushed to him.
While the connection is up, a push brings the message and its seq (the message’s number within its conversation, 1, 2, 3…, chapter 5) straight to the phone. When chapter 2 said “a push is only a hint”, it meant the case where the connection has quietly died: pushes get lost, and a pull has to make up for them. This is that case.
Up to chapter 5, the phone reconnects with chapter 1’s after=<id>: “give me everything with an id bigger than the biggest I have.” It has a hole: an id is assigned at insert time, but the commit can come later; if 102 commits before 101, a phone that recorded after=102 skips 101 for good. Nor can it say which conversation is missing what. Chapter 5 gave each conversation a contiguous seq, and within a conversation the seq order is the commit order: the next message cannot get its number until the one before has committed. So asking “the hiking group after seq 4” can never miss a smaller number that shows up a moment later; there is no such hole.
Ben is in 200 conversations. This chapter decides what the phone asks with when it comes back, and what the server stores for it.
1. The simplest idea: compare numbers
The premise is chapter 5’s: each message is stored once on the server, in its conversation, with that conversation’s seq. So every conversation has a latest seq, the number of its last message. The phone, too, keeps the last seq it has for each conversation.
So on return, compare: ask the server for the latest seq of these 200 conversations (the latest-seq sweeplatest-seq sweep最新 seq 一览On return the phone asks for the latest seq of all its conversations at once; the server reads them from a cache in one batch, one key per conversation. Any conversation whose seq is above the phone’s has new messages. Its reads grow with the number of conversations, not with the number of new messages.See the glossary), pair them with the phone’s 200, and wherever the server’s is bigger, that conversation is behind; pull those. From here on this is asking every conversation. Each conversation takes 12 bytes (conversation ID 8 bytes, seq 4 bytes), 2.4 KB for 200.
In the simulator below, Ben’s 200 conversations are laid out as a grid, most active at the top left; the darker a cell, the more messages came while he was away.
Ben comes back after 10 minutes offline, and his phone asks for the latest seq of all 200 conversations at once. How many of them have something new?
new messages (darker: more)the server read this conversation’s latest seq
–
- Conversation records changed–
- Latest seqs–
- Newest message of each conversation behind–
| Ask every conversation | A per-user inbox | |
|---|---|---|
| Requests | – | – |
| Phone sends | – | – |
| Phone receives | – | – |
| Server reads | – | – |
| Extra rows | – | – |
| Left for later | – | – |
In the default run, Ben was away 10 minutes and 2 messages came, in 2 conversations. Of the 200 numbers compared, 198 had not changed.
2. The missing piece: conversation records
Comparing numbers misses one case: Ben was added to a new group while away (tick it in the simulator). The phone has no such conversation; it is not among the 200. So the server keeps, for each person, a list of “the conversations I am in”, and it must be able to answer “what changed since last time”.
- Conversation recordconversation record会话记录One row per person per conversation: pinned, muted, the conversation’s latest seq, and later how far they have read. Written on join, leave or a settings change, and from chapter 11 on also when a message arrives (with the latest seq). Each change bumps that person’s record version. The messages are not here.See the glossary: one row per person per conversation, holding pinned and muted (and later how far they have read, chapter 14). Written only on join, leave or a settings change; never when a message arrives.
- Record versionrecord version记录版本A per-person number that goes up with each change to their conversation records; it is taken under a lock on that person’s users row, so version order is commit order. The phone keeps the version it has and asks “what changed after this” on return; a group it was added to, or a chat with new messages, shows up here.See the glossary: one number per person, bumped by one each time any of their records changes; the changed row stores the new version.
One of Ben’s rows, for example: (user Ben, conversation hiking group, pinned no, muted yes, version 57): he is in the hiking group, has it muted, and this was his 57th change.
When the phone comes back, three steps:
- Ask “what changed in my conversation records after version v”. Usually nothing; a group he was added to shows up here.
- In the same request, get the latest seq of all its conversations and compare with the phone’s to find those behind.
- In one more request, pull the newest message of each conversation behind, enough to lay out the conversation list; the rest waits until Ben opens that chat.
3. The other way: an inbox per person
There is another way that also catches up completely: an inboxinbox信箱A per-person index of “new messages for you”, with its own per-user sequence. Write fan-out writes it, and devices pull after their position in it. Chapters 6 and 10 weigh it against asking every conversation; this series’ v2 does not use it.See the glossary per person. When a message is stored, each recipient’s inbox also gets an entry “conversation X has seq s” (a small 32-byte pointer), and the inbox has its own contiguous number. The phone keeps one number: how far it has synced its inbox. Coming back, it asks: “everything in my inbox after 7,345.”
At v1’s scale neither breaks. The difference fits in one line: pay when reading, or pay when writing. Asking every conversation is read fan-outread fan-out读扩散Keep one copy in the conversation’s timeline, and each reader fetches it from there. Few writes, more reads; suits big groups. All of v1’s and v2’s messages are kept this way (chapters 6, 10); it needs the server to build the chat list and devices to sync it.See the glossary: a message is stored once, and every sync reads 200 numbers, most of them unchanged; reads grow with the number of conversations. The inbox is write fan-outwrite fan-out写扩散When a message is sent, write one entry into each recipient’s inbox; reading means reading your own inbox. More writes, fast reads; suits conversations with few members. Chapter 6 weighs it; chapter 10 shows it goes with client-built chat lists, where the phone builds its chats from the inbox. Neither v1 nor v2 uses it.See the glossary: it reads only what came, but every message writes one extra row per recipient; writes grow with group size, 500 rows for a message in a 500-member group.
To compare fairly, the inbox keeps the same rule: it downloads all the entries (up to 500 a reply) but only the newest message of each conversation; the rest loads when a chat is opened. Switch the simulator to “A per-user inbox” to compare.
The inbox has one real advantage besides: recalls, edits and reads can queue in the same line. When asking every conversation, they have to be kept per conversation (chapters 14, 18).
4. Estimate
| Ask every conversation | Inbox per person | |
|---|---|---|
| Server reads/s, peak | 13,900 (cache, 69 batches) | 69 |
| Extra writes/s, peak | 0 | 927 |
| Extra storage | 0 (records are kept anyway) | 853 MB a day; 6.0 GB for 7 days |
| Extra phone data a day | 48 KB of seqs | 8.5 KB of entries |
| Away 10 minutes | 2 requests, 2.8 KB | 1 request, 0.5 KB |
| Busy evening (230) | 2 requests, 3.0 KB | 1 request, 8.0 KB |
| Away 1 week | 5 requests, 40 KB | 4 requests, 98 KB |
Where the numbers come from:
- Reads. 100,000 people sync 20 times a day, about 2,000,000 ÷ 86,400 × 3 ≈ 69 syncs a second at peak; each reads 200 latest seqs, 69 × 200 ≈ 13,900. After 10 minutes away, 99.1% of them have not changed.
- Writes. The book assumes a message reaches 10 devices on average, and a person has 1.5 devices, so it reaches 10 ÷ 1.5 ≈ 6.67 people, so the inbox writes 6.67 extra rows per message: 139 × 6.67 ≈ 927 a second at peak, about 853 MB a day.
- Phone. Ben receives 267 messages a day. Asking every conversation at 20 syncs a day is 20 × 2.4 KB = 48 KB; the inbox, 267 × 32 bytes ≈ 8.5 KB.
The rest (how messages spread over conversations, and the requests for 10 minutes, a busy evening and a week) is in demo.py.
At v1’s numbers both sides are small and either choice is defensible. The series takes read fan-out: v1 keeps one copy of each message and does not want another per recipient; the reads sit in a cache and are cheap; a week away runs the same code as ten minutes, while an inbox needs a separate “too long” path for someone away longer than its retention period, whose entries are gone: fetch the whole conversation list instead. People with many conversations make every sync expensive; chapter 11 works that out.
5. How it works
What the server stores
-- sending (as in chapter 5): stored once
UPDATE conversations SET last_seq = last_seq + 1 WHERE id = :conv RETURNING last_seq;
INSERT INTO messages (conversation_id, seq, sender_id, msg_id, text) VALUES (:conv, :seq, ...);
-- before the commit: cached latest seq = max(old, :seq);
-- if that write fails, roll back and return an error
COMMIT; -- then push
-- join, leave, pin (rare): only this person's row, versioned per person
UPDATE users SET record_version = record_version + 1 WHERE id = :ben RETURNING record_version;
INSERT INTO conversation_records (user_id, conversation_id, pinned, muted, deleted, version)
VALUES (:ben, :conv, ...) ON CONFLICT (user_id, conversation_id) DO UPDATE SET ...;
COMMIT;
The latest seqs sit in a cache, one key per conversation (the key is the conversation ID, the value its latest seq); a key that has been evicted is read from the database’s last_seq.
What the phone keeps
Two things: the record version, one number; and each conversation’s last seq, which chapter 5 already keeps. Together they are this phone’s sync cursorsync cursor同步游标What a device keeps as “I have everything up to here”. In this series it is two things: the conversation-record version, and each conversation’s last seq. A device that comes back asks what changed after that version and each conversation’s latest seq, then pulls what it is behind on.See the glossary. Unread counts will come from here too: latest seq minus the read position (chapter 14).
Online nothing changes: a push carries the conversation’s seq; if it is the next one, keep it; if it jumps, pull that conversation (chapter 5).
Step 3 returns at most 50 conversations a reply. For each conversation the phone does three things in one transaction (all of them happen, or none): stores the message; moves that conversation’s last_seq to it; records the part below that it did not fetch as a “hole” (say, the hiking group is missing 4,692 to 4,810). Chapter 7 makes this a rule. When Ben opens the chat, the phone fills the hole backwards from that message.
Why nothing is missed
- Version order is commit order. Changing a record first locks Ben’s row in
usersto take a version number; another change has to wait for it to commit, so “after version v” skips nothing. Being removed from a group marks that rowdeleted(details in chapter 12). - Steps 1 and 2 come from one snapshot (the database as it was at one moment, blind to later commits), so they talk about the same list of conversations. If the phone gets a seq for a conversation it has no record of, it ignores it until the next sync.
- Register for pushes, then sweep. The phone registers on its connection first, then sends the sync request. A message committed during the sync is either already in the seqs read, or pushed.
- The cache is never behind the database. It is written before the commit, upward only; if that write fails, the message rolls back.
Why before the commit: written after it, a server dying between the two would leave the cache on the old seq, and that conversation would never look behind. A rolled-back message gets no ACK, so the sender resends it (chapters 3 and 4). The price is that the cache is sometimes ahead: the phone pulls a seq that has not committed yet, or rolled back, and gets nothing; the next push or message brings it.
6. Cost
- Every sync reads every conversation. Reads grow with the number of conversations, not with the messages that came: 13,900 a second at peak, 139,000 with 2,000 conversations, and 99% of them find nothing new.
- One more round trip for a short absence. For 10 minutes and two or three messages, the inbox takes 1 request and this takes 2: 0.2 s and about 2.3 KB more. After a long absence it flips (a week is 40 KB against 98 KB). The phone could send its 200 seqs up to save the round trip, at 2.4 KB uploaded every time.
- A lost last push still waits. Chapter 5’s hole remains: if the push of a conversation’s last message is lost, there is no jump to see, so it waits for that conversation’s next message or the next sync. The inbox notices sooner: its numbers are contiguous, so the next message from any conversation shows a gap. Ben gets 267 messages a day, so over a day’s 1,440 minutes one comes every 1,440 ÷ 267 ≈ 5.4 minutes on average.
- The history on the phone has holes. Only the newest message came; the rest is pulled when the chat is opened, and a chat opened offline shows only its last line (chapter 7).
7. Other answers
- An inbox per person (write fan-out). Telegram’s private chats and basic groups share one “message box” and one event sequence (
pts, Telegram’s per-account update number), and the same message has different IDs in different accounts. WeChat’s seqsvr (InfoQ, 2016) gives each user a sequence number that only has to increase, not be contiguous, so it can be handed out in batches. Facebook Messenger’s Iris (2014) is a totally ordered queue of updates per user, messages and read states alike. The advantages are real: one ordered stream per person, reading only what came, and how far behind is one subtraction; the price is this chapter’s writes. - Telegram’s split. Supergroups and channels each have their own
ptsand stay out of the message box (basic groups hold at most 200 members, supergroups up to 200,000).updateChannelTooLongin the result ofupdates.getDifferencenames the channels to catch up, each then fetched withupdates.getChannelDifference, 10 to 100 at a time. Small ones fan out on write, big ones on read, while the conversation list itself comes from the server for all of them (chapter 10). - OpenIM (open source, the closest to this chapter): a row per person per conversation with a per-person version, and
GetIncrementalConversationreturns the inserts, updates and deletes after a version;GetMaxSeqreads every conversation’s latest seq from Redis in one pipeline; on connect it pulls 1 message per conversation (connectPullNums = 1). - Matrix’s
/sync: in the spec the client passes the lastnext_batchassince; when too many events are new, a room’s timeline is markedlimited, with aprev_batchto page back from. MSC4186 notes that it slows down with the number of rooms and the time offline, and a first sync for an account with thousands of rooms can take tens of minutes. - One “something new” row per person per conversation (an inbox variant): overwritten with the person’s next number on every message. Its storage is fixed (100,000 × 200 × 32 bytes = 640 MB), and a returning phone downloads one row per changed conversation; it writes as often as the inbox.
- Only each conversation’s seq, no conversation records. It saves a step, but misses a group Ben was added to while away (section 2).
- Notify, then pull: the push only says “this conversation is at seq 42”, an extra round trip per message; this chapter’s pushes still carry the message.
8. This chapter’s decision
Now, however long Ben is away, he comes back to every conversation’s latest line. But where do the messages it fetched live? How is the part not yet pulled recorded? And if the app is killed and reopened, does it pull everything again? Next chapter: the local database on the phone.
Comments
Comments live in GitHub Discussions and need a GitHub account.