The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S8 · V1·08

A Durable Order Log

Volume 1, chapter 08. "Saved" gets a precise meaning: an order change is acknowledged only after its record is fsynced to an append-only log. One writer thread batches appends from every request into a single write and a single fsync (group commit), taking throughput from about 4,000 to 73,000 durable appends per second. An exclusive file lock allows one process per data directory, recovery cuts off a torn tail but refuses to guess about damage in the middle, and the idempotency keys from stage 5 now survive restarts. Then the log is killed with SIGKILL and SIGTERM to check that nothing acknowledged is ever lost, and a demo that wouldn't exit teaches what a non-daemon thread means.

6 parts · ~8 min to read
Updated Suggest a correction

Stage 8: a durable order log

The brief

What you'll build. OrderLog, in core/:

  • open(dir): takes an exclusive lock on dir/LOCK (refusing to start if another process holds it), opens orders.log, fsyncs the directory if the file is new, and recovers: reads every record, rebuilds the latest state of each order and the idempotency keys, truncates a torn tail, and refuses to open if damage is followed by valid records;
  • append(order, key, receivedAt): returns a CompletableFuture that completes only once the record is durable; each record is stage 6's OrderCodec format, with the idempotency key in extension tag 1 and the received time in a new extension tag 2;
  • a single writer thread with group commit: it takes everything queued, writes it with one gathering write, calls force(false) once, and acknowledges the whole batch;
  • close(): stops accepting, writes and fsyncs everything queued, completes anything left over with an error, and releases the lock.

Plus 5 tests (38 in total) and LogDemo, a load generator used for throughput and crash tests.

Why a real company needs this. An order the app confirmed must exist after a power cut, a deploy, or a crash. Without a log, TiffinBox's state (orders, idempotency keys) lives in memory and disappears on every restart; with a naive log (one fsync per order), it can't keep up with lunch hour. Every database has this component at its heart: PostgreSQL's WAL, MySQL's redo log, Kafka's partitions.

Why now. Chapter 08 gives the exact model: write() lands in the page cache, fsync makes it durable, a directory entry is separate from the file, file locks are advisory and per process, and threads coordinate through queues. Stages 5 and 6 left two promises: durable idempotency keys and a place to store the binary records.

What you'll have at the end.

  • OrderLog with recovery and group commit, and 5 tests;
  • measured throughput with 1, 16 and 64 concurrent writers, and crash tests with SIGKILL and SIGTERM;
  • ADR-0010: what "acknowledged" means, and the log's recovery rules.

Theory to own

  1. Layers of "saved". Trace a record from FileChannel.write to the disk. At which points does it survive a process crash (SIGKILL)? A power cut? (Chapter: "Buffering, the page cache and fsync"; Companion, Explain it differently 4.)
  2. fsync arithmetic. If one fsync takes t milliseconds, how many fsyncs per second can one writer do, and how does batching change the number of records per second? (Companion, Interview prep Q6.)
  3. Torn writes. A power cut happens while a 70-byte record is being written. What can the file contain afterwards, and how does a reader tell a torn record from a valid one? (Chapter: "Journaling and crash consistency"; stage 6's length prefix and CRC.)
  4. Advisory locks. Why put the lock on a separate LOCK file instead of on orders.log, and why keep its channel open for the process's whole life? (Companion, Gaps 2 and Code walkthrough.)
  5. One writer. Why one writer thread with a queue, rather than every request thread writing and fsyncing under a lock? (Chapter: "Mutex"; "Condition variables".)

Build it

Step 1: one process per directory

Write the start of OrderLog's constructor: create the directory, open LOCK with CREATE, WRITE, tryLock() it, and if that returns null, close the channel and throw IllegalStateException("another process is using …"). Keep the lock and its channel in fields until close().

Checkpoint. A second open on the same directory fails while the first is open, and succeeds after the first is closed.

Step 2: the record, with the received time

Add TAG_RECEIVED_AT = 2 to OrderCodec: 8 bytes, big-endian epoch milliseconds. append encodes the order with the idempotency key (if any) in tag 1 and the received time in tag 2, puts the bytes and a new CompletableFuture on a queue, and returns the future.

Checkpoint. Stage 6's golden record still decodes (its format didn't change), and a record with tag 2 decodes with the status's own time untouched.

Step 3: one writer, group commit

Start a platform thread named order-log-writer that loops:

  1. take one pending record (blocking), then drainTo up to 4,095 more that are already waiting;
  2. write them all with one gathering write (FileChannel.write(ByteBuffer[])), looping until every buffer is empty;
  3. call log.force(false) once;
  4. complete each future with its record's offset.

If anything throws IOException, fail every future in the batch and mark the log closed: after a failed fsync, nothing is acknowledged and nothing more is written.

Checkpoint. 8 threads appending 250 records each all get acknowledgements, a reopened log holds 2,000 records, and the writer did fewer than 2,000 fsyncs.

Step 4: recovery

On open, read the whole log and walk it record by record, using the header to find each record's length (stage 6's layout). For each valid record, keep the latest snapshot per order id and the idempotency key from tag 1. On the first record that doesn't decode:

  • if no valid record follows it anywhere, it's a torn tail: truncate the file there, fsync, and report how many bytes were cut;
  • if a valid record does follow, the damage is in the middle: refuse to open, and leave the file untouched as evidence.

Checkpoint. A log with half a record appended opens with the good records and its tail cut off; a log with a flipped byte in its first record refuses to open and keeps its size.

Step 5: tests

Write OrderLogTest with five tests, each in its own temporary directory: replay of latest state and keys, one process per directory, a torn tail (append half a record by hand, reopen, check the count, the truncated bytes and the file size, reopen again and check nothing more is truncated), damage in the middle (flip bits in the first record, expect the exact refusal and an unchanged file size), and concurrent appends sharing fsyncs.

Checkpoint. The build prints tests: 38 passed.

Step 6: measure throughput, and find a process that won't exit

Write LogDemo DIR WRITERS SECONDS: open the log, register a shutdown hook that closes it, start W threads that each append and wait for their acknowledgement in a loop for S seconds, print the acknowledged count every 250 ms, then print the throughput and log.stats(). Run it with 1, 16 and 64 writers.

Checkpoint. You have appends per second and batches for each writer count, and every run exits by itself.

Step 7: crash it

Run LogDemo with 64 writers for 10 seconds, and:

  • after 2.6 seconds, kill -9 it; then reopen the directory and compare the recovered record count with the last acknowledged count printed;
  • separately, after 2.6 seconds, kill -TERM it, and compare the same way.

Checkpoint. In both cases, records recovered ≥ records acknowledged, and there's no torn tail after SIGKILL.

Senior and architect lens

1. Define "acknowledged" in one sentence, and make the code match it. "An order change is acknowledged only after its record has been fsynced to the log." Every other decision follows: group commit to make it affordable, no retries after a failed fsync, a torn tail treated as never acknowledged, and recovery that refuses to guess about damage in the middle.

2. ADR-0010: the order log. Write it with these points:

  • Decision: a single append-only log per data directory, of OrderCodec records with event time (in the status) and received time (tag 2); one writer thread with group commit; force(false) per batch; one process per directory via an exclusive lock on LOCK.
  • Recovery rules: a torn tail is truncated; damage followed by valid records stops startup and keeps the file; idempotency keys are rebuilt from tag 1.
  • Measured: about 4,000 durable appends per second with one writer and 73,000 with 64 concurrent writers on this storage, with fsyncs of 0.2–0.4 ms.
  • Revisit when: the log outgrows a full read at startup (segments plus periodic snapshots); more than one node must write (Volume 5's replicated logs); or a database takes over durability (Volume 3), at which point the log's ideas live on as the database's WAL and an outbox table.

3. Single-writer designs remove whole classes of bugs. No two threads ever touch the file, so there's no lock on the write path, no interleaving (the Companion's drill D2), and no reordering. Request threads only enqueue and wait. LMAX Disruptor, Redis and Kafka's partition leaders all use the same principle: concentrate writes in one place, and scale by partitioning, not by sharing.

4. Crash testing is a skill. kill -9 tests process crashes; it doesn't test power loss, because the page cache survives. Real durability testing needs either a simulated torn tail (as in step 5), a filesystem that can drop unsynced writes on demand (dm-flakey, or fault-injecting filesystems used by database teams), or real power cuts. Know which failure each test actually covers.

5. Lifecycle is part of the API. A component that owns a thread must be closed, or the process won't exit; one that owns a lock must be closed, or the next instance can't start. OrderLog implements Closeable, close() is idempotent, and LogDemo both closes at the end and in a shutdown hook. Volume 3's Spring service gets this from the container's lifecycle, which is why @PreDestroy exists.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
the log grows for months startup reads the whole file into memory Volume 3 (database), or segments plus snapshots
more than one server one writer per directory, on one machine Volume 5 (replicated logs, consensus)
clients outside the process nothing serves the log over a network stage 9 (HTTP server in front of the core)
a disk that lies about fsync acknowledged data lost on power cut operations: storage with power-loss protection; Volume 6
reporting from the log DayColumns is built from objects in memory stage 11 rebuilds the day's columns from the log

Evidence

  • OrderLog and OrderLogTest are in core/, and the build prints tests: 38 passed.
  • Your LogDemo throughput for 1, 16 and 64 writers, with average fsync time, is in the README, with the disk you measured on.
  • Both crash runs (SIGKILL and SIGTERM) are in the README, with recovered ≥ acknowledged and an explanation of the difference.
  • The README explains why the first LogDemo didn't exit, and how it was fixed.
  • Starting a second instance on the same directory fails with "another process is using …" (paste it).
  • ADR-0010 is committed.

Carry forward

  • OrderLog is TiffinBox's source of truth until Volume 3's database. Stage 9's server appends to it before answering, and stage 11 rebuilds everything (orders, keys, the day's columns) from it.
  • "Acknowledge after fsync" becomes Volume 3's "commit before responding", and Volume 5's "acknowledge after replication".
  • Event time and received time are stored from now on; later stages can accept late events honestly.
  • Durable-but-unacknowledged plus idempotent retries is the pattern every later network boundary relies on.