# Chapter 9: v1: a reliable channel

> On the way from Ana’s phone to Ben’s, what guarantees did v1 add, and what does each one cost?

IM Systems in Depth · https://im.liko.page/en/v1-reliable-channel/

At the start of chapter 3, the complaint was “I know I sent it, and they say it never arrived.” Each of the six chapters since then fixed one thing: messages get lost (chapter 3), repeated (chapter 4) and out of order (chapter 5); a phone coming back must catch up (chapter 6); a killed app must not lose messages (chapter 7); a photo must not block the text behind it (chapter 8).

This chapter makes no new decision. It does four things: it follows one message through v1 from end to end; it puts the six decisions and their costs in one table; it redoes the bill for the whole server and for one phone, from v0 to v1; and it says plainly what v1 cannot do yet.

The scale has not changed: 100,000 daily users, 10,000 online at peak, 139 messages a second, one server, one database. v1 did not add a single user. Everything it added is a guarantee.

## 1. One message, end to end

7 pm. Ana is in a lift and sends Ben “I’m downstairs.” Ben is on the underground, with no signal.

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

**Ana’s phone**

1. **Written to the local database first.** The app makes a message ID for the message (a 128-bit random number, say) and, in one **transaction**, writes a row to the local `messages` table in state “sending”. A transaction is a group of writes that either all take effect or none do. The screen reads that row from the database and shows it at the bottom of the chat (chapters 4, 5, 7). The row is the outbox: if the app is killed now, it is still there next time.
2. **Sent, then wait for the ACK.** The message goes out on the long-lived connection with the conversation, the message ID and the text. In the lift the connection drops and the ACK never comes. The phone reconnects and resends with backoff (at 0, 1, 3, 7 and 15 s in the simulator; a real app counts time, keeps waiting while there is no network, and adds some random jitter), always with the same message ID (chapter 3).

**The server: message layer**

3. **Repeats recognised.** First it checks the message IDs seen in the last few minutes (32 s in the simulator), kept in memory. If it has seen this one, it writes nothing and sends the first ACK again, unchanged (chapter 4).
4. **One transaction.** If not, it does two things in one transaction: it takes the conversation’s next seq (chapter 5), and it stores the message. The message is stored only this once, not copied for Ana and Ben; before the commit, the conversation’s latest seq is written into the cache, upward only, and if that write fails the whole transaction rolls back. So the cache is never older than the database: the latest seq Ben reads when he comes back never misses a stored message (chapter 6). The message table has two **unique keys**: the database will not accept a second row with the same sender + message ID, or the same conversation + seq. Hitting the first one means a repeat the window missed, such as a message resent from the outbox an hour later after the app was killed; the server looks up the original and sends the same ACK (chapter 4).
5. **The ACK only after the commit**, carrying the message’s seq. Ana’s phone runs one `UPDATE` that marks the row “sent” and fills in the seq; the message moves to its place by seq (chapters 5, 7).

**Dispatch layer**

6. **Push.** The server finds Ben’s connection and pushes the message with its seq. Ben is on the underground, his connection died long ago, and the push is lost. That is fine: a push is only a hint, and the message is already in the conversation (chapters 2, 6).

**Ben’s phone**

7. **Out of the underground: sync.** The phone’s sync cursor is two things: the record version, and each conversation’s last seq. Once reconnected, the first request asks with the record version: the server answers with the conversation records changed since (a group he was just added to, say), plus the latest seq of all Ben’s conversations, read from the cache in one go. Comparing, the phone sees its chat with Ana is behind; the second request pulls the newest message of each conversation behind, committed in one transaction with each conversation’s `last_seq` (chapters 6, 7). The older messages are recorded locally as a **gap**, a marker that says “this stretch is still on the server, not pulled yet”, filled in when Ben opens that chat and scrolls up to it.
8. **Later pushes.** While connected, a push whose seq is exactly the conversation’s `last_seq` + 1 is committed together with the new `last_seq`. If the number jumps, the phone stores the message, leaves `last_seq` where it is, waits 0.5 s, and if something is still missing pulls that conversation’s missing stretch (chapters 5, 7).
9. **The screen reads only the local database.** Ben opens the chat with Ana: no request, and “I’m downstairs” is already there (chapter 7).

**If it is a photo.** Before step 1 there is one more stage: the phone compresses the photo, asks the server for an upload address, and uploads the file in parts to an upload service in front of object storage, in state “uploading”; after a drop it asks the upload service “how much do you have?” and goes on from there. Only then does it send a small message of about 300 bytes with the file id, size, hash, width and height and a placeholder. From step 2 on, that small message takes the same path as text. Ben sees the placeholder and a thumbnail first, and downloads the full photo from a CDN when he taps it (chapter 8).

Any of the nine steps can go wrong: the connection in the lift, the lost ACK, the push into the underground, the app killed halfway. Each of these is caught by a later step, and what catches it is not “be more careful” but a rule.

## 2. Switch one off, and what comes back

Each chapter’s simulator is still in its chapter, and you can go back and switch things off yourself. Below are the numbers each of them gives, all at the series’ 10% loss; as chapter 3 said, that is far more than real networks lose, chosen so the problems are visible.

| Switch off | What comes back (in that chapter’s simulator) |
|---|---|
| ACKs and resends | [Chapter 3](/en/acks-and-retries/): the phone shows “sent” but the server never stored it, **10.1%** of 10,000 messages |
| Message ID | [Chapter 4](/en/duplicates/): Ben sees repeats, **1,113** in 10,000 (11.1%). With only the window of recent IDs and no unique key, a resend an hour later still shows twice |
| Conversation seq | [Chapter 5](/en/ordering/): the two screens disagree on order, **19.6 pairs** per 100 messages; a lost push goes unnoticed, **10.0** per 100 (0.01 with seq) |
| Records and latest seqs | [Chapter 6](/en/offline-sync/): with an inbox per person instead, nothing is lost and the phone still catches up; the price moves elsewhere: 6.67 more rows per message, **927 more writes/s** at peak. Drop only the conversation records and ask with each conversation’s seq, and a group Ben was added to while away goes unseen |
| One transaction | [Chapter 7](/en/local-database/): the app is killed after the phone has shrunk a gap, noting “this stretch is pulled”, but before the messages are written, so it never asks for them again. Gap first, messages committed one by one: filling the busy evening’s holes, killed at 1.2 s, **31 messages** are missing and will not be pulled again; a kill at a random moment loses some **85.2%** of the time (a commit per page: 4.3%; one transaction: 0) |
| Separate upload | [Chapter 8](/en/media-messages/): text waits behind the photo, the three lines wait **27.7, 23.7 and 20.7 s**; on a link that drops every 8 s, not one line gets out in 60 s |

Chapter 6’s row deserves a fair word: it does not fix a bug, it is a trade. v1 pays on the read side: each sync reads the latest seq of all of Ben’s conversations, about **13,900 cache reads/s** at peak, growing with how many conversations he has, however few messages came; and a return takes one more round trip than with an inbox. The inbox pays on the write side: each message writes one row for each person it reaches, 6.67 on average (a message reaches 10 devices on average and each person has 1.5, so 10 ÷ 1.5 ≈ 6.67 people), growing with the size of the conversation, so that each sync reads only what actually arrived. At v1’s scale, either way is defensible.

## 3. Two halves, built facing each other

Split the nine steps by where they happen, and v1 is two halves, each with the phone and the server built to match:

- **The sending half**: the phone’s outbox, message ID and resends, facing the message layer’s dedup, seq and ACK. Together, each message Ana sends is stored exactly once on the server, with one definite place in its conversation.
- **The receiving half**: the dispatch layer’s pushes with the seq, facing the phone’s sync: the record version and each conversation’s seq, pulls on a jump, and pages written into the local database one transaction each. Together, Ben’s phone ends up with every message.

Both halves use the same three rules, and each rule appears once at each end:

- **A unique key recognises repeats.** On the server it is sender + message ID (chapter 4); the phone’s local database has the same unique key, so however many times a message arrives, by push, by sync or as an ACK, it lands on the same row (chapter 7).
- **A number is committed with what it stands for.** The server takes the seq inside the transaction that writes the message, and the record version inside the one that changes a conversation record, so the order of the numbers is the order of the commits (chapters 5, 6); the phone moves its cursor inside the transaction that writes the messages, so the cursor never gets ahead of them (chapter 7).
- **A push is a hint; the pull is the truth.** A push that is lost, late or out of order is made good by a pull by number (chapters 2, 5, 6).

What people call “exactly once” is, here, two things put together: **at least once** (resends, sync) plus **recognising repeats** (the unique key). A network cannot deliver exactly once; what you can do is make a repeat harmless.

## 4. The whole v1 map

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

Compared with chapter 2’s v0, it is still one program on one server, with a media path beside it. Almost nothing in v1 changed the boxes; what changed are the rules between them, and the nine steps above are those rules.

## 5. v1’s six decisions

| Chapter | Decision | Cost | Revisit when |
|---|---|---|---|
| [3 Acks and retries](/en/acks-and-retries/) | The message goes into an outbox; the server ACKs once it is stored; without an ACK, reconnect and resend with backoff (and jitter); mark it failed only when it keeps failing | A lost ACK stores a repeat (about 10% of messages at 10% loss); a resent message arrives later; the outbox must be on disk | What “stored” means (chapter 29); reconnect storms when the network comes back (chapter 24) |
| [4 Duplicates](/en/duplicates/) | The phone makes a message ID before the first try; the server remembers recent IDs; a unique key on sender + message ID is the backstop | One more unique index, one more lookup on a repeat; the phone must keep IDs from colliding | Several message servers (chapter 28); ACK after writing a log (chapter 29) |
| [5 Ordering](/en/ordering/) | One counter per conversation, seq taken in the write’s transaction; phones order by seq, sending ones at the bottom, and fetch on a jump | One conversation’s writes take turns (at most 200/s at 5 ms a write); your own messages may move; a lost push of the last message waits for the next one | One server cannot hand out seqs for every conversation (chapter 28) |
| [6 Offline sync](/en/offline-sync/) | Messages are not copied per person; one conversation record per person per conversation, with a per-person record version. On return, record changes and every conversation’s latest seq in one go, the newest message of each conversation behind, the rest when opened | Every sync reads every conversation’s latest seq (about 13,900/s at peak, growing with conversations); one more round trip than an inbox; a lost last push waits for that conversation’s next message or the next sync | Who builds the conversation list (chapter 10); users with very many conversations (chapter 11); joining and leaving (chapter 12); read positions (chapter 14); several devices per person (chapter 16) |
| [7 The local database](/en/local-database/) | SQLite on the phone; the screen reads only it; each page, push and ACK is committed in one transaction with the cursor or state it moves | Two copies of the truth, and the client must repair itself; about 34 MB of text a year; migrations on every upgrade; transaction discipline | How deep a new device syncs (chapter 16); the conversation list (chapters 10, 11); the web client (chapter 27); one SDK for every platform (chapter 30) |
| [8 Images and files](/en/media-messages/) | Files are uploaded in parts to an upload service and stored in object storage, then a small message of about 300 bytes is sent; the receiver sees a thumbnail first and downloads from a CDN on tap | Two paths that must stay consistent (orphan files, images that will not open); a photo’s seq comes after text sent during the upload; whoever has a file’s address can open it; an upload service, object storage and a CDN to run, 43.8 TB of storage a year | A photo in a group of 500 is seen by 750 devices (chapter 19); new devices (chapter 16); a placeholder message updated later (chapter 18); end-to-end encryption (chapter 42) |

Of the six costs, the one that will hurt first is chapter 6’s: every sync sweeps every conversation. Ben has 200 conversations, so each sync downloads 200 latest seqs; Ana has joined many groups and is in 2,000 conversations, so each of her syncs is 2,000 × 12 bytes = 24 KB, 480 KB a day at 20 syncs; she receives as many messages as anyone, 267 × 200 bytes ≈ 53 KB, so the seqs are about 9 times that, and 99% of it unchanged. The server’s cache reads, on the other hand, hold up.

## 6. v1’s bill

As in chapter 2, here is the bill for the whole server and for one phone. Both columns use the same assumptions: v0 is the push design at the end of chapter 2, with phones that store no messages and ask the server for the latest 50 every time a chat is opened (the approach at the start of chapter 7); every number in the v1 column comes from the chapter in brackets.

**The server (10,000 online, at peak)**

One item is in both columns: a pull each time the app is opened, 100,000 people 20 times a day, at peak 2,000,000 ÷ 86,400 × 3 ≈ **69 a second**. v0 has one more: 100,000 × 60 = 6 million chat opens a day, about **208 a second** at peak, each answered with 50 × 200 bytes = 10 KB.

| Resource | v0 (end of chapter 2) | v1 |
|---|---|---|
| CPU | About 1,389 pushed frames/s; 69 pulls/s; 208 chat-open queries/s; a burst of handshakes on restart (about 5 s for 10,000 phones) | Pushes unchanged; 69 syncs/s, each reading 200 conversations’ latest seqs from the cache, then pulling the conversations behind (chapter 6); the 208 chat-open queries are gone; sends received and ACKs sent, 139/s with no loss; at the series’ 10% loss, a message is sent 1.23 times on average and each try arrives 90% of the time, so the server receives 139 × 1.23 × 0.9 ≈ 154/s, about 15 of them repeats (chapters 3, 4), each ACKed; about 7 upload addresses/s (chapter 8); each message’s transaction writes two rows, the message and the conversation’s counter, instead of 1 (chapter 5) |
| Memory | About 30 KB per connection, about 300 MB for 10,000; user → connections | The same, plus the window of recent IDs: about 4,400 IDs, 142 KB for 32 s, and only 1.3 MB for 5 minutes (chapter 4); a cache of each conversation’s latest seq, one key per conversation (chapter 6) |
| Bandwidth | Pushes 1,389 × 200 bytes ≈ 2.2 Mbit/s; chat opens 208 × 10 KB ≈ 16.7 Mbit/s; about 19 Mbit/s in all | About 2.2 Mbit/s, since a photo message is only about 300 bytes; the photos themselves skip the message server: 11.1 Mbit/s uploaded to the upload service, about 39 Mbit/s downloaded, mostly from the CDN (chapter 8) |
| NIC packets | A push frame plus its ACK, about 2 packets: about 2,800/s; chat opens: 208 requests/s, each 10 KB reply about 7 packets (up to about 1,460 bytes each, not counting TCP ACKs), about 1,700 more: about 4,400 in all | 139 ACK frames/s more, about 280 packets, and no chat-open packets: about 3,100 in all with no loss |
| Disk capacity | About 0.8 GB of messages a day, about 292 GB a year | Messages unchanged, plus two unique indexes; conversation records, one row per person per conversation, 100,000 × 200 = 20 million rows, written only on join, leave or pin, and membership is stored anyway (chapter 6); photos in object storage, 40 GB a day, 14.6 TB a year, 43.8 TB with 3 copies (chapter 8) |
| Disk IO | Writes: about 139 inserts/s at peak, each one commit that waits for fsync (until the data is really on disk); reads: 69 pulls/s and 208 chat-open queries/s | Still about 139 commits/s (chapter 5), each also writing the conversation’s row; no per-person copies (chapter 6); reads: about 13,900 latest-seq reads/s at peak, mostly from the cache (chapter 6), plus pulls of the conversations behind |

File descriptors are as in v0: 10,000 connections are 10,000 descriptors; photo uploads connect to the upload service, not to the message server.

In one sentence: what v1 adds to the message server is a cheap kind of **read**: every sync sweeps every conversation’s latest seq, about 13,900 a second, mostly from the cache; the messages themselves are not written again. What it removes is the expensive reads: with a copy on each phone, the 208 chat-open queries a second and about 17 Mbit/s are gone. The big numbers are on the other path: photos are 40 GB a day, 50 times all the text, which is why they need a path of their own (chapter 8).

**Ben’s phone (one day)**

Most of v1’s changes only show over a day (a sync per app open, how many chats are opened a day), so this table counts a day rather than chapter 2’s hour. The v0 phone, as above, stores no messages; v0 had no photos either.

| Resource | v0 | v1 |
|---|---|---|
| Requests | A pull per app open (20); for each chat opened, a request for the latest 50 (60); 40 messages sent | A sync per app open, usually two requests (20; 13.3 messages arrive between opens on average, in about 10.7 conversations: first the record changes and 200 latest seqs, then the newest message of each conversation behind, chapter 6); opening a chat pulls only if messages are still missing there; 40 messages sent, each waiting for an ACK; photos: 2 uploads, about 13 thumbnails and 4 full photos downloaded (chapter 8) |
| Data | Down: 53 KB of pushes plus 600 KB for opened chats, about 650 KB | Down: 53 KB of text, 935 KB of photos (thumbnails plus the 30% opened); up: 400 KB more for photos; each sync downloads 200 latest seqs, 200 × 12 bytes = 2.4 KB, about 48 KB a day (chapter 6) |
| Battery | The radio wakes for each push; each chat opened waits for a round trip | Pushes unchanged; opening a chat uses no network; a few resends on a bad signal (1.23 tries per message at 10% loss); back after a week offline (1,869 messages in 190 conversations), the newest message of each conversation behind comes first: 5 requests, about 40 KB, and the other 1,679 when their chats are opened (chapter 6) |
| Background | The system closes the connection; no outbox, so a message written to the connection counts as sent | The connection is still closed, but the outbox and upload progress are in the local database, and sending and uploading continue at the next open; nothing can wake the phone yet (chapters 17, 26) |
| Storage | Almost none | About 92 KB of text a day, about 34 MB a year (chapter 7); a photo cache of about 487 MB a year that can be cleared (chapter 8) |

The phone spends more on storage and on photo data; what it saves is downloading the same messages again: v0’s 600 KB a day for opening chats is gone.

## 7. What v1 cannot do yet

v1 does one thing well: **between two people, a message is not lost, repeated or reordered, and a killed app loses nothing.** Here is what it cannot do yet:

- **A group of 500.** A message is stored once, so storage does not mind the group’s size; but each of the 500 sweeps all of their own conversations when they come back, and people with many conversations make every sync expensive. Whether each phone builds its conversation list from the messages, or the server builds it and every device syncs it, goes hand in hand with storing once or copying into per-person inboxes: chapter 10. How someone with many conversations syncs only what changed is chapter 11. Who is in the group, and who gets the messages at the moment someone joins or leaves, is chapter 12.
- **Who may message whom.** v1’s business layer is still one check: “is Ana in this conversation?” Strangers, blocks, buyers and sellers differ from product to product, and are in the branch chapters (workplace, customer service, IM as a platform).
- **Unread counts and read receipts.** v1 knows how far Ben’s phone has received, not how far Ben has read (chapter 14), nor whether anyone has read Ana’s message (chapter 15).
- **Several devices.** The series assumes 1.5 per person; Ana has a phone and a laptop. Each device keeps its own record version and conversation seqs, so catching up is easy; but “read up to here” has to be combined across devices (chapter 14), and how deep a new device should sync has no answer yet (chapter 16).
- **Waking a closed phone.** Once the app goes to the background the connection is gone; the message waits in the conversation, and Ben does not know (chapter 17).
- **Recall and edit** (chapter 18).

All of this is v2 (chapters 10–19). Further on, v1 is still one server: with more connections it cannot hold them, and every deploy disconnects everyone. That is v3.

Next, chapter 10: Ana logs in to the desktop app on a new laptop. Where does its conversation list come from? Does each device build it from the messages, or does the server build it and devices sync it? After v2’s nine chapters, chapter 19 walks through all of v2 the way this chapter did for v1.
