# Chapter 7: The local database

> Where on the phone do the fetched messages go? If the app is killed halfway through writing them, are some missing when it opens again?

IM Systems in Depth · https://im.liko.page/en/local-database/

At the end of chapter 6, Ben came out of the underground; his phone asked for every conversation’s latest seq and pulled the newest message of each conversation that was behind. What that chapter did not say: **where do the fetched messages go, and how is the part not yet pulled recorded?**

Earlier chapters left two debts: chapter 3’s outbox must survive the app being killed, and chapter 6’s cursor, the record version and each conversation’s seq, must survive a restart. This chapter puts them, and the messages themselves, into a local database on the phone, and answers its real question: how to write it so that no message goes missing, no matter when the app is killed.

## 1. Why the phone keeps a copy

Keeping nothing is possible: each time a chat is opened, ask the server for the last 50 messages. Web clients often do (chapter 27). On a phone it costs this:

- Ben opens the app 20 times a day; say he looks at 3 chats each time: **60 chats opened** a day.
- Each is 50 × 200 bytes = **10 KB**, **600 KB** a day; what he actually receives is 267 × 200 bytes ≈ **53 KB** a day (chapter 6). The same messages are downloaded again and again, **11 times** what arrives.
- Each open waits at least one round trip, 60 × 0.2 = **12 s** a day. On the underground, nothing shows.

The outbox and the cursor must be on disk anyway, so the messages go there too. The work splits like this:

- **The screen reads only the local database**; opening a chat does not touch the network.
- **Everything from the network is written to the database first**: each sync page, each push, each ACK.
- **Sent messages are written first too**, as “sending”, shown at once, and marked “sent” when the ACK comes.

Most phones use SQLite: not a server to connect to but a library inside the app, the whole database one file in the app’s folder. iOS and Android both ship it.

## 2. What to store

```sql
CREATE TABLE messages (
  id              INTEGER PRIMARY KEY,
  conversation_id INTEGER NOT NULL,
  seq             INTEGER,               -- the server's seq in the conversation (chapter 5); none yet while sending
  sender_id       INTEGER NOT NULL,
  msg_id          BLOB NOT NULL,         -- the message ID the phone made (chapter 4)
  text            TEXT,
  state           TEXT NOT NULL,         -- 'sending' / 'sent' / 'failed' / 'received'
  UNIQUE (conversation_id, seq),
  UNIQUE (sender_id, msg_id)
);
CREATE TABLE conversations (id INTEGER PRIMARY KEY, last_seq INTEGER, pinned INTEGER, muted INTEGER);  -- how far each conversation has got
CREATE TABLE gaps (conversation_id INTEGER, from_seq INTEGER, to_seq INTEGER);  -- a stretch not downloaded yet
CREATE TABLE sync_state (key TEXT PRIMARY KEY, value INTEGER);                  -- the record version
```

- **The outbox is not another table**: it is the rows with `state = 'sending'`. On restart the app finds them and resends them with their original message IDs (chapter 4).
- **`(conversation_id, seq)`** is the index the chat screen uses: opening a chat asks for “the 50 with the highest seq”, and the database goes straight to the end of that conversation and reads 50 rows, as fast with a million messages stored.
- **`gaps` records holes.** On return, chapter 6 takes only each conversation’s newest message, so a stretch below it is missing locally, for example a row `(hiking, 4,692, 4,810)`. When Ben opens the chat and scrolls up to it, the phone fetches it.
- **Gaps, cursors and messages live in the same database.** The next section shows why.

`conversations.last_seq` is how far each conversation has got: chapter 5 uses it to spot a jump, chapter 6 to tell which conversations are behind. With the record version in `sync_state`, it is this phone’s cursor.

**How big it gets.** Ben receives 267 messages a day and sends 40. At 300 bytes each (the message plus indexes; an assumption), that is about **92 KB** a day, **33.6 MB** a year. Text is not what fills a phone; photos and videos are (chapter 8).

## 3. Watch it fail: the gap shrinks before the messages reach the disk

A row in `gaps` means “I do not have this stretch yet”. Filling it backwards, each page that comes back shortens the row a little, which says “I have this part now”. After a restart the phone fills only the stretches still in `gaps`, and the server can only take its word for it.

As soon as “how far I have got” and the messages are written in two separate steps, there is a window between them: say the `gaps` row is shortened as each reply arrives (a tiny, fast transaction) while a write queue on a background thread writes the messages; or the sync progress lives in another store (iOS’s UserDefaults and Android’s SharedPreferences are small files separate from the database). If the app is killed between the two writes, the gap has shrunk and the messages are not yet on disk. Here is how big that window is.

Chapter 6’s busy evening again: three groups got 120, 80 and 30 messages; on return each group’s newest message came back, leaving a hole below each, 119, 79 and 29 messages, 227 in all. Here the phone fills the three holes in the background: conversation by conversation, at most 50 a page, a page every 0.2 s, 6 pages in all. Say writing one message takes 0.1 ms and each **commit**, which waits until the data is really on flash, 5 ms. Drag “the app is killed at”.

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

- **Gap first, then messages one by one**: a transaction per message, 255 ms for a page of 50, slower than the next page arrives, so the queue grows. Killed at 1.2 s, just as the last page arrives: 196 messages on disk, but `gaps` says all 227 are there. The phone will never ask for the **31** in between again.
- **Gap first, then a page at a time**: a page written in 10 ms; the window is smaller but still there: if the app dies at a random moment while the holes are being filled, **4.3%** of the time it loses a page.
- **One transaction**: a page of messages and the shortened `gaps` row commit together, both or neither. **No moment loses a message.**

The first two ways’ figures (31 messages, 4.3%) rest on the 5 ms commit assumption; only the final 0 rests on none.

The missing messages do not come back on their own. The stretch is gone from `gaps`, so the phone will not fill it; the server does not know what the phone lacks, and chapter 6’s sync sees no difference, since the latest seqs matched long ago. Only when Ben scrolls up to that spot and the screen sees the seqs break off does the phone get a chance to fetch them. If the missing one were Ben’s mother’s “arriving tomorrow morning”, he might never know.

Being killed is common: iOS gives a background app little time, and [Apple’s documentation](https://developer.apple.com/documentation/uikit/extending-your-app-s-background-execution-time) says that if you don’t end your tasks in time, the system terminates your app; Android kills background processes when memory is short; users swipe apps away, and apps crash. At v1’s 2,000,000 syncs a day, if only 1 in 10,000 is cut between the two writes, that is **200 phones** a day missing messages, **20** at 1 in 100,000, with no error and hard to reproduce.

## 4. The fix: a page of messages and the gap or cursor it moves, one transaction

One rule: **a gap may not shrink before the messages it stood for are written; nor may a cursor move.** The simplest way is one transaction:

```sql
BEGIN;
INSERT INTO messages (...) VALUES (...), (...), ...    -- this page's 50
  ON CONFLICT (sender_id, msg_id) DO UPDATE SET seq = excluded.seq, state = excluded.state;  -- a repeat lands on its original row
UPDATE gaps SET to_seq = :page_first_seq - 1 WHERE conversation_id = :conv AND to_seq = :old_to;  -- filling backwards, the gap shrinks from the top; delete the row when empty
COMMIT;
```

SQLite’s [documentation](https://www.sqlite.org/transactional.html) guarantees that a transaction’s changes happen completely or not at all, even if the program crashes or the power fails halfway. That is why gaps and cursors must be in the same database and change with the messages: the settings file and the database are two stores, and no transaction spans both.

If the app is killed before the commit, the same page comes again after the restart; a push and a sync may bring the same message. The repeat lands on its original row by the unique key `(sender_id, msg_id)`, the same idea as chapter 4’s server dedup, done on the phone; it is also how Ben’s own “sending” row becomes “sent” when the message comes back from the conversation.

The same rule everywhere the phone writes:

- **The newest message from a sync** (chapter 6’s step 3): store the message, move `last_seq` to it, and record the stretch below as a `gaps` row, all three in one transaction.
- **A push**: if its seq is exactly the conversation’s `last_seq` + 1, the message and the new `last_seq` commit together; if it jumps, store only the message and fetch that conversation’s missing stretch. Say the hiking group’s `last_seq` is 4,811 and the push carries 4,813: 4,813 is stored, `last_seq` stays at 4,811, and the phone fetches 4,812; when 4,812 comes back, it commits together with `last_seq` moved to 4,813.
- **Sending**: write the “sending” row first, then send; when the ACK comes, the same row gets its seq and becomes “sent”.
- **Filling a gap**: the older messages and the shortened `gaps` row commit together.

Telegram’s public API has a “how far I’ve caught up” the client must store too: when there is too much to catch up, [`updates.getDifference`](https://core.telegram.org/api/updates) returns only one slice (`updates.differenceSlice`), and the docs say the client must save the intermediate state in it and ask for the next slice from there. The docs don’t say how to write it together with the messages; by this section’s rule, it should commit in the same transaction as that slice’s messages.

## 5. Estimate: how much the phone writes in a big sync

A transaction per page also fixes writing too slowly. Back from a week offline (chapter 6), Ben got only the newest message of each conversation, leaving **1,679 messages** in the holes of 156 conversations. If the phone fills them all, that is **170 pages** by conversation: a transaction per message is 1,679 commits, about **8.6 s** of writing; one per page is 170 commits, about **1.0 s**. A month offline (7,810 messages, 292 pages): **39.8 s** against **2.2 s**. The 5 ms is an assumption; the number of commits, about 10 times fewer (27 for a month), is not. SQLite’s [FAQ](https://www.sqlite.org/faq.html#q19) says exactly this: it does tens of thousands of `INSERT`s a second but only “a few dozen transactions per second” (a figure for spinning disks; flash is much faster), and wrapping many `INSERT`s in one transaction spreads the commit’s cost over all of them.

## 6. Reinstalling and new phones

The local database lives in the app’s folder; delete the app or change phones and it is gone. How much comes back depends on how much the server keeps. In this series the server keeps the messages, so a new phone does chapter 6’s three steps: the record version starts at 0, so all 200 conversation records come; then 200 latest seqs; then the newest message of each conversation. At 24 bytes a record (conversation ID 8 bytes, version 8 bytes, flags such as pinned and muted 8 bytes), plus 12 bytes for each conversation’s latest seq (chapter 6) and 200 bytes for each newest message: 200 × 24 + 200 × 12 + 200 × 200 bytes ≈ **47 KB**. One request brings the records and the latest seqs, and the newest messages come 50 conversations a page, 4 pages: 1 + ⌈200 ÷ 50⌉ = **5 requests**; older messages as Ben scrolls. How deep a new device’s first sync should go is chapter 16’s question. Some products’ servers delete a message once delivered, such as WhatsApp ([privacy policy](https://www.whatsapp.com/legal/privacy-policy)) and Signal ([terms](https://signal.org/legal/)); history is only on the phone, and losing it means a backup or the old phone: chapter 42.

## 7. The cost

- **Two copies of the truth.** The phone’s copy can be wrong: a message the server rejects must be marked failed, a hole from syncing must be recorded and filled when reached, and the conversation list drifts from the server’s (chapter 10). The client must be able to repair itself.
- **Storage.** About 34 MB of text a year; in v2 the 500-member hiking group sends 1,000 messages a day, 110 MB a year for that one group. Users need a way to clean up.
- **Upgrades need migrations.** The tables change between versions, and each upgrade must change the old database on every phone in place (chapter 30).
- **Discipline in the code.** Every place that shrinks a gap or moves a cursor or a state must do it in one transaction with the data it stands for. The rule is easy; keeping everyone to it as the code grows is not.

| Resource | Nothing stored, ask the server each time | Local database, a transaction per page |
|---|---|---|
| Phone requests | one per chat opened, 60 a day | none to open a chat; only syncs and gap fills |
| Phone data | about 600 KB a day for opening chats | only new messages, about 53 KB a day |
| Phone storage | almost none | about 92 KB a day, 34 MB a year |
| Phone disk writes | almost none | 170 commits to fill a week’s holes (1,679 one by one) |

## 8. Other answers

- **Store nothing, or only the latest few**: no migrations and no second copy. Fine where the network is good and conversations are few (say, a customer-service window in a browser); chapter 27 covers the web.
- **Messages first, then the cursor, in separate stores**: when the cursor cannot join the transaction, this order loses nothing either: killed between the two writes, the cursor is still at the old place, so after a restart the same page is fetched again and the repeats land on their existing rows by the unique key. The cost is downloading a page again after a kill.
- **TDLib**: Telegram’s open-source client library; its [README](https://github.com/tdlib/td) says it takes care of the network, encryption and local data storage, and its source includes SQLite; the `use_message_database` [parameter](https://core.telegram.org/tdlib/docs/classtd_1_1td__api_1_1set_tdlib_parameters.html) keeps chats and messages between restarts.
- **Signal**: the local database is an encrypted SQLite (SQLCipher, in the [Android](https://github.com/signalapp/Signal-Android/blob/main/gradle/libs.versions.toml) and [desktop](https://github.com/signalapp/Signal-Desktop/blob/main/package.json) dependencies). The server keeps no history, so the phone holds all of it, and encryption is worth it.

## 9. This chapter’s decision

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

**Decision card**

- Problem: Fetched messages, unsent messages and the sync cursor must all survive the app being killed and restarted; asking the server each time a chat opens costs about 600 KB a day and shows nothing offline. With a gap (or cursor) and the messages written in two steps, an app killed between them shrinks the gap before the messages reach the disk, and those messages are never fetched again.
- Choice: A local database (SQLite) on the phone: messages, gaps and the cursor all in it, the outbox being the rows marked “sending”. The screen reads only the database; everything from the network is written into it first. Each sync page, push and ACK commits in one transaction with the gap, cursor or state it moves; a repeated write lands on its original row by the unique key (sender, message ID).
- Cost: Two copies of the truth, and a client that must repair itself; about 34 MB of text a year, more with media; a migration on every upgrade; the transaction discipline wherever a gap or cursor moves.
- Revisit when: Where images and files go (chapter 8); how deep a new device’s first sync goes (chapter 16); the conversation list in the local database (chapter 11); how much the web stores (chapter 27); one local database for every platform, and migrations (chapter 30); servers that keep no history (chapter 42).
- Other answers: Store nothing or only the latest (web, customer-service windows); messages first, then the cursor (one page downloaded again); TDLib’s message database; Signal’s encrypted SQLite (SQLCipher).

The messages have a home. Next chapter: a 4 MB original photo should not squeeze through the same connection as the text messages.
