Storage: an engine made for seeks
Tern keeps mail in an engine written for it, not in files of messages and not in a database someone else made. The aim it was designed to: as few disk reads for each mailbox operation as can be, on spinning disks, with nothing cached.
The constraint
On a spinning disk a seek costs about 10 ms, and reading on from there is about 150 MB a second. Seeks are the scarce thing. A 256 KiB block of mail compresses about five-fold and takes under 2 ms to transfer, so it is cheap to read more than was asked for and dear to go anywhere else for it.
Everything below follows from that: what a screen shows together is laid out together, and a design whose speed depends on fast solid-state storage counts as a failure.
A message, taken apart
A message that arrives is split into a skeleton and its parts.
- The skeleton is every byte that is not part content: the headers and the boundaries between parts. Its outline is the message's structure, so the tree of parts costs no read of any attachment.
- Small parts, 16 KiB or less, stay with the skeleton in the message's row. A message without attachments opens with one block read.
- Large parts go to the blob store, named by the hash of their content and stored decoded. An attachment sent as base64 is kept as the bytes it stands for, three quarters of what was sent, before compression. The same attachment in a hundred messages is kept once.
- The recipe in the row says how the pieces go together again, with each part's transfer encoding as it was written.
Before a delivery is acknowledged the message is put together from its pieces and compared with what arrived. A part whose encoding cannot be made again exactly is kept as it was sent.
| What | On disk |
|---|---|
| Large parts: 31,267 blobs, decoded, once each, compressed | 3.2 GiB |
| Message rows: skeletons and small parts, compressed in blocks | 0.9 GiB |
| The index, with the words of every body | 0.14 GiB |
| Total | 4.2 GiB |
Two keyspaces, one log
The engine knows keys, values, batches and merge rules. It does not know what mail is. On top of it the mail schema defines rows and operations.
- The index keyspace is small and read by range: labels, counters, listings, postings. It is merged eagerly, to keep it in few runs.
- The messages keyspace is large and read only by exact key. Filters find the right run, so it can be merged lazily, and the largest rewrites stay bounded.
- One log serves both, so a delivery that writes a message row and twenty index rows is one record and one sync.
Readers never block writers and writers never block readers. A view of the store holds references to immutable runs and to the tables in memory as they were.
A run
Each keyspace is a set of immutable sorted runs on disk and a table of recent writes in memory. A run file is:
- Blocks: rows in key order, compressed with zstd, each with a checksum, keys prefix-compressed. 256 KiB in the messages keyspace, 64 KiB in the index keyspace.
- A block index: the first key and position of every block, held in memory, so finding the block for a key reads nothing from disk.
- A filter, held in memory: over whole keys in the messages keyspace, about 10 bits each, and over the users present in the index keyspace.
- A footer with counts, the smallest and largest key, the format's version and a checksum.
The memory this takes is about 4.6 bytes a message: 1.86 MiB for the example mailbox.
The rows
Keys are built from fixed-width big-endian fields, so the order of bytes is the order that matters. In the index keyspace all of one user's rows lie together.
| Row | Key, after the user | Holds |
|---|---|---|
| Label | label id | Name and role: inbox, sent, trash |
| Counters | label id | Messages, unseen messages |
| State | message id | The message's labels, flags and thread |
| Listing | label id, inverted message id | What a list shows: sender, recipients, subject, dates, size |
| Postings | tag, first id | Message ids, up to 1,024 a row |
| Message | message id | The record, the skeleton, the small parts |
- A page of a folder is one range read. A listing row lies under each label a message has, with the message id inverted so that reading forward gives the newest first.
- A flag change never rewrites a listing row. Flags live in the state row and in postings. A listing row is written once.
- Label 0 is All mail. Every message has a listing row under it, which makes All mail a range read too, and is where a search result's fields are found.
- Unseen is the tag, not seen, because unseen is what is counted and searched for.
Three merge rules
The schema tells the engine which rule a key has. Rules are applied when reading and when merging, with the same result, so a counter is changed by writing one small operand and reading nothing.
| Rule | Meaning | Used for |
|---|---|---|
| Replace | The newest put or delete wins | Most rows |
| Sum | Operands are added together | Counters, quota, references to parts |
| Set | Operands add or remove message ids from a set | Postings |
One batch, one sync
Each write is one batch, applied entirely or not at all, and it returns when it is on disk.
- Group commit. Writers hand their batches to one log thread. It writes everything that is waiting, syncs once, and wakes them all. A sync is about a seek, so this is where deliveries and flag changes that happen together share their cost.
- A delivery is one batch: the message row, its state, a listing row under each label, postings for labels, thread, header terms and words, counters and quota, a reference for each large part.
- Large parts are written first, and the blob store answers only when a blob is durable. A crash leaves at worst a blob nothing refers to, never a message whose part is missing.
Delivering the example mailbox into a new store, every word indexed on the way: 149 to 158 seconds on NVMe, 524 seconds on three spinning disks. That is 770 messages a second on the disks, with the large parts in the blob store already: it is the engine's own cost, rows, lists and their syncs.
After a crash
- The manifest lists the live runs and how far the log is already in them. It is replaced atomically: written beside, synced, renamed, the directory synced.
- Recovery reads the manifest, opens its runs, deletes files it does not name, and replays the log after that point.
- A record with a bad checksum at the end of the log is an unfinished write and is dropped. A bad record anywhere else is corruption, and stops the engine.
- If a write to the log or a sync fails, the engine stops taking writes. It does not retry and carry on, because the state of the disk is then unknown.
Nothing is rebuilt by scanning. An acknowledged write that a crash loses is one of the three outcomes the design names as failure, with a message whose part is missing and a store that must be scanned to come back.
Merging, and giving space back
- Runs are grouped into tiers by size, and a tier that holds enough runs is merged: two of similar size in the index keyspace, eight in the messages keyspace. The number of tiers grows with the logarithm of the data.
- Merges run in the background and are rate-limited, so they do not starve reads.
- Message ids are never reused, which is what makes it safe to drop a deleted row as soon as a merge meets its tombstone.
- A run whose share of deleted rows passes a threshold is merged by itself, to give the space back.
- Large parts no message uses any more are removed by a sweep with a pace: so many a call and so many a second, with no lock held while pausing. A report says beforehand what a store could give back and what holds it. Both are tools for now: the server does not run the sweep by itself yet.
On spinning disks
The example mailbox on a ZFS raidz1 of three spinning disks, in a virtual machine with 8 cores, the host keeping none of its data in memory. From cold means the guest's caches were dropped and the server started anew before the flow, which then ran once. The flows are IMAP's, as a mail API backend sends them. Milliseconds.
| Flow | Cold | Warm |
|---|---|---|
| Folder list in one command | 0.8 | 0.8 |
| Open the inbox (36,898 messages) | 91 | 35 |
A page of the inbox: open, STATUS, sort by arrival, fetch 50 | 205 | 61 |
| The same sorted by date sent | 230 | 105 |
| A word of a subject, sorted | 210 | 82 |
| Resynchronise the inbox, nothing changed | 92 | 33 |
| A thread in the inbox | 284 | 132 |
| One message, whole | 115 | 1.4 |
| Its text part | 2.0 | 0.8 |
| A word in the text, inbox | 590 | 125 |
| Open the largest folder (166,143) | 227 | 80 |
| A page of it | 306 | 136 |
| A word in the text, the largest folder | 650 | 181 |
| Flags of every message of the inbox | 316 | 313 |
Measured 2026-11-27, in two runs: the three rows that look for a word are from the second, after IMAP's searches were made to fold accents. The disks are shared with other machines, which moves the figures from one run to the next. Not measured: many users at once, and a mailbox being written while it is read.
What is slow, and why
Two things read headers, and headers are where this layout pays.
| Flow | Cold | Warm |
|---|---|---|
| Sizes, flags and 14 header fields of every message of the inbox | 12,300 to 25,000 | 4,400 to 5,500 |
A word in text or header (IMAP's TEXT), inbox | 14,300 | 3,800 |
A folder's messages lie among all of the user's messages, in the order they arrived. The inbox is a tenth of this mailbox, so each 256 KiB block has two or three of its messages among twenty or so. Reading the headers of the whole inbox decompresses nearly every block of the message rows, some 2.6 GB, to use a tenth of it.
A cache does not mend that, and one was tried: the remedy is in the layout. The 16 header fields mail clients ask for come to 34 MB compressed for the whole mailbox, a twenty-eighth of the message rows, and could be kept by folder. That is measured and not yet built.
A desktop IMAP client asks for those fields when it first meets a folder. The tmail apps never do: a list's row has what a list shows.
How it is checked
- Byte for byte, on real mail. All 12.08 GB of the example mailbox read back through IMAP in 227 seconds and compared with what was received: each whole message, and 2,172,296 sections of them. Nothing differs. (1,282 sections were passed over, in messages of more than 200 sections.)
- Every part. All 36,130 parts that are not text, read back through
GetPart, are byte for byte what a general-purpose parser decoded from the original. - Generated mail. Three million generated messages through the splitter and back.
- Crashes. Change tracking under four writers, a reader, merges and a crash, by a reviewer who had not seen the design's reasoning.