Workbench / The TiffinBox Build
S50 · V3·49
The Ledger Carried Forward
Volume 3, chapter 49. TiffinBox's order log has been its database since stage 8: one file, replayed into memory on every start. Recovery read the whole file into one array, so a log past 2 GiB couldn't open at all, and restarts grew with every order ever placed: 5.2 seconds and 1.9 GB of heap at 500,000 orders. This stage reads files in windows, splits the log into segments, and compacts closed segments into a snapshot that keeps each order's first and last records and the idempotency keys younger than a configured retention, written with a temporary file, fsync, rename and a directory fsync. Forty kill -9s during writes, rolls and compactions lost no acknowledged order. Restarts fell by a quarter and the files by a third, and both still grow with history: compaction bounds the files, not the state, which is the measured case for a database.
Stage 50: the ledger carried forward
The brief
What you'll build.
- Windowed reading:
OrderLog.forEachRecordreads 8 MiB at a time (a record is at most 64 KiB), and damage detection scans the same way. No array the size of the file. - Segments: appends go to
orders.log; atsegmentBytesit's renamed toorders-NNNNNN.logand a new one starts, with the directory fsynced. - Compaction: a background thread folds the newest
snapshot-NNNNNN.logand the closed segments into a new snapshot (two passes; a record is kept if it's an order's first or last, or carries an idempotency key younger thankeyRetention, measured from the newest record), then deletes what it covers. A snapshot is an ordinary log file. - Tidy on open:
.tmpfiles, older snapshots and covered segments are removed before recovery. - Settings:
segment-mb(default 64) andkey-retention(default7d; durations now takehandd). - Tools:
OrderLog.scanDirectory(snapshot, segments,orders.log) forreplayandreport;stats()counts compactions and reports a failure. - Tests:
CompactionTest(a compacted directory recovers the same orders and the live keys; leftovers of an interrupted compaction are tidied; damage in a closed segment names the file; a log past 2 GiB opens). - Measurements in
exp/50:Big.java(big-before.out,big-after.out),Growth.java(growth-before.out,growth-after.out),Crash.java(crash.out).
Why a real company needs this. Data outlives the code that wrote it. A store that works for a year and fails on a size it was never tested at, or takes longer to restart every month, fails on a quiet morning with no change to blame.
Why now. Chapter 49 is persistence: what a database gives the code above it. TiffinBox has been its own database; this stage measures what that costs and gives it a database's first two tools, checkpoints and compaction. Stage 42 deferred snapshots here.
What you'll have at the end.
- a log that opens at any size;
- restarts that read a snapshot and the recent segments;
- compaction that survives
kill -9at any moment; - the numbers for the next storage decision;
- ADR-0052: how TiffinBox stores orders.
Theory to own
- Write-ahead log and checkpoint. What does recovery read, and what bounds it? (Companion, Gaps 2 and Theory 1.)
- Compaction and retention. What may be dropped, and who decides how long keys live? (Companion, Gaps 3, Theory 2 and 5, Code walkthrough.)
- The durability chain. What must be fsynced, in what order, before a file is deleted? (Companion, Gaps 4 and Theory 4.)
- Write amplification. What does each compaction cost as the state grows? (Companion, Theory 3.)
Build it
Step 1: how big, how slow
Write exp/50/Big.java (a sparse log just past 2 GiB) and exp/50/Growth.java (50,000, 200,000 and 500,000 orders through Orders, three restarts each, with time, records and peak heap). Run them on stage 49's code.
Checkpoint. exp/50/big-before.out, growth-before.out.
Step 2: read in windows
Rewrite recovery as forEachRecord over a FileChannel with an 8 MiB window, and laterRecordDecodes to scan in windows. Keep stage 41's rules: a torn tail of orders.log is truncated; damage followed by a good record refuses to open.
Checkpoint. exp/50/big-after.out; aLogLargerThanTwoGibibytesOpens; OrderLogTest unchanged and passing.
Step 3: segments and snapshots
Add Options, the roll in the writer thread, the compactor thread, compact, Layout.of(dir, tidy) and scanDirectory. Move replay and report to scanDirectory. Add segment-mb and key-retention to Config. Write CompactionTest, and run Growth.java again with orders spread at 2,000 a day.
Checkpoint. exp/50/growth-after.out; core 56 tests.
Step 4: kill it
Write exp/50/Crash.java: a child process appends with 32 KiB segments (16 threads, three records per order), printing each acknowledged write; the parent kills it with SIGKILL after 0.8 to 2.3 s, reopens the directory, and checks every acknowledged order is there with at least its acknowledged status. Forty rounds on one directory.
Checkpoint. exp/50/crash.out.
Senior and architect lens
1. Measure the storage you have before choosing the next. Stage 50's numbers say what an in-memory state costs TiffinBox at each volume, which is what the next decision needs.
2. ADR-0052: how TiffinBox stores orders. Write it with these points:
- Format: segmented append-only log, OrderCodec records; snapshots are logs of retained records.
- Durability: group commit with
fdatasync; rolls and compactions fsync the directory; delete only after the replacement is durable; leftovers tidied on open. - Retention: each order's first and last record forever (for now); idempotency keys
key-retention(7 days), a documented limit on client retries. - Limits, measured: restart about 1 s per 100,000 orders and heap about 3 KB per order at peak; the state is every order ever placed.
- Next: when a year's orders no longer restart in under 10 s or fit in half the heap, move orders to a database (rows on disk, indexes, a buffer pool) or archive closed orders out of memory with an index for lookups. Track restart time per release.
3. Compaction is a background job with a cost. It competes with writes for disk; it needs a trigger (size ratio, not every roll), a failure report and a metric.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| every order lives in memory | restart and heap grow with history | stage 56, re-pointed there to Volume 4 (databases: the order history in PostgreSQL) |
| compaction rewrites the whole snapshot | falls behind under heavy writes | stage 52 (jobs: compaction as a scheduled job with a size-ratio trigger and metrics) |
| kitchens are a constant (k1 to k12) | a new kitchen needs a release | stage 56 (projects: kitchens as data), re-pointed there to Volume 4 (databases: kitchens as a table) |
| a damaged closed segment refuses to open | an operator must repair it by hand | stage 56 (projects: tbx log repair) |
Evidence
exp/50/big-before.out,big-after.out,growth-before.out,growth-after.out,crash.out.- Windowed reading, segments, snapshots, tidy on open,
scanDirectory,segment-mb,key-retention. - Core 56, server 66 and tbx 21 tests;
golden master: 47 exchanges, identical; the release check passes. - ADR-0052 is committed.
Carry forward
- No file is read into one array; sizes are
long. - Replace files by temporary name, fsync, rename, directory fsync, then delete.
- Retention periods are settings with owners.