# 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?

IM Systems in Depth · https://im.liko.page/en/offline-sync/

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 sweep), 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.

*[Interactive figure: open the page to use it, https://im.liko.page/en/offline-sync/]*

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 record**: 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 version**: 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:

1. Ask “what changed in my conversation records after version v”. Usually nothing; a group he was added to shows up here.
2. In the same request, get the latest seq of all its conversations and compare with the phone’s to find those behind.
3. 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 inbox 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-out: 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-out: 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

```sql
-- 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 cursor. 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

1. **Version order is commit order.** Changing a record first locks Ben’s row in `users` to 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 row `deleted` (details in chapter 12).
2. **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.
3. **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.
4. **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](https://core.telegram.org/api/updates)’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](https://www.infoq.cn/article/wechat-serial-number-generator-architecture) (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](https://engineering.fb.com/2014/10/09/production-engineering/building-mobile-first-infrastructure-for-messenger/) (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](https://core.telegram.org/api/channel) each have their own `pts` and stay out of the message box (basic groups hold at most 200 members, supergroups up to 200,000). `updateChannelTooLong` in the result of `updates.getDifference` names the channels to catch up, each then fetched with [`updates.getChannelDifference`](https://core.telegram.org/method/updates.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 [`GetIncrementalConversation`](https://github.com/openimsdk/open-im-server/blob/175a7bb0673eca18e9d1b10bff4f728da6b1b513/internal/rpc/conversation/sync.go) returns the inserts, updates and deletes after a version; `GetMaxSeq` [reads every conversation’s latest seq from Redis in one pipeline](https://github.com/openimsdk/open-im-server/blob/175a7bb0673eca18e9d1b10bff4f728da6b1b513/pkg/common/storage/cache/redis/seq_conversation.go); on connect it pulls [1 message per conversation](https://github.com/openimsdk/openim-sdk-core/blob/061ac673ffa31f4d863651fdffee7882609a5f62/internal/interaction/msg_sync.go#L38) (`connectPullNums = 1`).
- **Matrix’s `/sync`**: in the [spec](https://spec.matrix.org/latest/client-server-api/#syncing) the client passes the last `next_batch` as `since`; when too many events are new, a room’s timeline is marked `limited`, with a `prev_batch` to page back from. [MSC4186](https://github.com/matrix-org/matrix-spec-proposals/pull/4186) 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

*[Interactive figure: open the page to use it, https://im.liko.page/en/offline-sync/]*

**Decision card**

- Problem: Ben was offline for 10 minutes and is in 200 conversations. Chapter 1’s after=<id> skips messages that commit late and cannot say which conversation is missing what; and a group he was added to while away is unknown to the phone.
- Choice: A message is still stored once, in its conversation. Each person has a conversation record per conversation, with a per-person record version. On return, one request asks “what changed after version v” and the latest seq of every conversation (read from a cache in one batch); another pulls the newest message of each conversation behind. Online, pushes carry the message and its seq; a jump pulls.
- Cost: Every sync reads every conversation’s latest seq, growing with conversations (about 13,900 a second at peak, 139,000 with 2,000 conversations); one more round trip than an inbox for a short absence, about 2.3 KB more; a lost last push waits for the next message or sync; the cache is sometimes ahead, so the phone pulls once for nothing; the history on the phone has holes.
- Revisit when: Holes recorded locally and filled on opening (chapter 7); who builds the conversation list (chapter 10); people with many conversations make every sync expensive (chapter 11); who is in a group, joining and leaving (chapter 12); read positions, unread counts (chapter 14); each device keeps its own (chapter 16); recall and edit (chapter 18).
- Other answers: An inbox per person (Telegram private chats and basic groups, WeChat seqsvr, Facebook Iris); Telegram’s big groups with their own pts, caught up on demand; OpenIM (versioned conversation records, every conversation’s latest seq in one read, 1 message per conversation on connect); Matrix /sync (since cursor, limited timeline plus prev_batch); seqs without conversation records (misses new groups); notify, then pull.

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.
