Design a Crash-Safe High-Throughput Append Log
System DesignModel answerLast updated
Design an embedded append-only log writer that handles thousands of concurrent producers, batches writes efficiently, and recovers cleanly from crashes.
Context
You are designing a low-level, in-process log writer for an embedded storage engine. Thousands of worker threads simultaneously produce variable-length byte payloads that must be durably recorded to a single append-only file on local NVMe storage.
This is not a distributed log service. Everything runs in one process, on one machine, writing to one file. The challenge is squeezing maximum throughput and minimum latency out of that setup while making strong correctness guarantees.
Functional Requirements
- Write API: Expose an
append(data: bytes) -> WriteReceiptcall — synchronous or asynchronous — that returns a stable identifier for the record's position in the log (an offset or sequence number). - Ordering & Atomicity: Writes must appear in a strict total order. A reader must never see a partial record or two records interleaved. Each write is all-or-nothing.
- Crash Recovery: After an unclean shutdown, a recovery pass must scan the file, find the last valid record, discard any incomplete write at the tail, and leave the log in a state ready for new appends.
- Graceful Shutdown: Draining all queued records, issuing a final sync to disk, and closing file descriptors cleanly.
Non-Functional Requirements
- Concurrency: Up to 5,000 threads calling
appendat the same time. - Throughput: Sustain at least 50,000 writes/sec and 200 MB/sec on a modern local SSD.
- Durability Latency: In group-commit mode, every write must be persisted within 5 ms or when a batch reaches 1 MB in size, whichever comes first.
- Memory Cap: No more than 64 MB of data may be buffered in flight at any time. When that limit is reached, producers must be slowed down in a predictable way.
What Your Answer Should Cover
- Thread coordination: How do 5,000 producers hand off data to the writer without creating contention hot spots?
- On-disk record format: What does each record's binary layout look like, and what fields make recovery reliable?
- Batching and I/O mechanics: How does group commit work? What OS primitives help?
- Backpressure and error handling: What happens when the buffer fills up, the disk is slow, or a write fails?
- Recovery algorithm: Step by step, how does the process find and discard torn writes at startup?
- Observability: Which metrics matter for detecting problems early?
Hints
Hint 1
Start with the math: average record size, batch composition, and sync budget. Those numbers justify almost every design decision that follows.
Hint 2
Think carefully about who owns the file descriptor. Limiting I/O to a single writer thread eliminates an entire class of ordering bugs and removes the need for locks around syscalls.
Hint 3
Recovery needs to distinguish a torn write at the tail (safe to truncate) from corruption in the middle of already-acknowledged data (not safe to silently discard). How does your record format support that distinction?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Nail the Numbers First
Before drawing any boxes, verify the operating point — it drives every decision.
Record size: 50k writes/sec at 200 MB/s means average payload ≈ 4 KB. Ask for the maximum. Capping it at 16 MB keeps any single record well under the 64 MB buffer budget.
Batch composition: A 5 ms commit window at 50k/s holds about 250 records. At 200 MB/s, 5 ms of data is about 1 MB. The two triggers are calibrated for the same operating point — they will usually fire together.
Sync cost: fdatasync on NVMe takes roughly 50 µs–2 ms. Syncing per record caps throughput at single-digit thousands of writes/sec. Batching amortizes one sync over hundreds of records and is the only way to hit the 50k target.
Buffer headroom: 64 MB at 200 MB/s is about 320 ms. That covers reasonable jitter, but not a sustained disk stall. Backpressure must be real, not advisory.
2. API Surface
append(data: bytes, durability="GROUP") -> Future[LSN]
# durability: NONE (no sync), GROUP (batched sync), SYNC (immediate sync)
flush() -> Future[LSN] # ensures everything up to now is durable
close(timeout_ms) # drain, sync, close fds
Use the byte offset of the frame as the LSN. It is monotonically increasing, makes random reads O(1), and lets recovery verify frame continuity without extra bookkeeping.
3. Thread Coordination: Many Producers, One Writer
Use a multi-producer single-consumer (MPSC) pattern. Only one thread ever touches the file descriptor. This eliminates lock convoys around syscalls and makes ordering trivial to reason about.
Producer path (three steps, no I/O):
- Backpressure gate. Acquire
frame_bytesfrom a semaphore capped at 64 MB. Block here if the buffer is full. - Claim a slot. Atomic
fetch_addon a shared tail counter assigns the LSN and fixes total order. This is nanoseconds. - Fill and publish. Serialize the framed record into the ring slot, then set a per-slot "ready" flag with release ordering.
The writer advances only over the contiguous published prefix. A stalled producer holds back persistence of higher LSNs but cannot reorder or corrupt them.
A simpler alternative: a lightweight mutex protecting only the LSN assignment and a pointer push. The critical section never contains I/O, so contention is sub-microsecond. The trade-off is that the lock-free ring handles more producers without touching shared cache lines, but adds meaningful complexity around ring wraparound and record fragmentation.
4. On-Disk Record Format
Segment header (first 4 KB, sector-aligned): magic bytes, format version, base LSN, creation timestamp, header CRC.
Per-record frame (8-byte aligned):
| Field | Size | Purpose |
|---|---|---|
| Magic | 4 B | Fast scan anchor and sanity check |
| Type/flags | 2 B | FULL, FIRST, MIDDLE, LAST for large-record fragmentation |
| Reserved | 2 B | |
| Payload length | 4 B | Bounded; prevents corrupt length from causing huge reads |
| LSN | 8 B | Must equal the frame's own offset |
| CRC32C | 4 B | Covers all header fields (except CRC itself) plus payload |
| Payload | N B | Followed by padding to 8-byte boundary |
Why each field matters for recovery:
- CRC32C is hardware-accelerated via SSE4.2 — checksumming 200 MB/s is nearly free. It is the primary tool for detecting torn writes.
- Embedded LSN catches false positives: pre-allocated file regions or recycled sectors can have bytes that pass a CRC check by chance. The LSN must equal the frame's offset, which is an independent constraint.
- Length bound prevents a single corrupt length field from sending the recovery scanner off reading gigabytes.
5. I/O Pipeline and Group Commit
The writer thread runs a tight loop:
loop:
wait until: pending_bytes >= 1 MB
OR time since oldest unsynced frame >= 5 ms
OR a SYNC-durability record is queued
OR shutdown signal
collect all published frames into an iovec (up to IOV_MAX = 1024 entries)
writev(fd, iov, count) # loop on EINTR / short writes
fdatasync(fd)
durable_lsn = end of this batch
complete all futures with LSN <= durable_lsn
release semaphore bytes and ring slots
Useful optimizations:
fallocatepre-allocation. Pre-extending the file means appends don't change file size, sofdatasyncskips the metadata journal write on most Linux filesystems. This can cut sync latency by 30–50%.- Writer/syncer pipeline. Split into two threads: one issues
writev, the other issuesfdatasync. While batch N is syncing, batch N+1 is being written. A singlefdatasynccovers everything written before it, so the syncer just needs to track the highest written offset. - Adaptive batching. Under light load, don't wait the full 5 ms. Sync as soon as the queue drains. The 5 ms figure is a latency ceiling, not a fixed timer.
6. Backpressure and Failure Handling
Buffer full. The semaphore blocks producers in FIFO order — deterministic, no starvation. Expose try_append (returns Busy immediately) and append(timeout_ms) for callers that want to shed load rather than block.
Slow disk. Batches grow to the 1 MB cap, improving I/O efficiency at the cost of latency. The semaphore throttles producers automatically. Alert when average buffer occupancy stays above 80%.
ENOSPC. Pre-allocate the next segment before the current one fills. This surfaces disk-full before records are in flight. If allocation fails mid-write: stop accepting new appends, fail all unsynced futures, truncate back to durable_lsn, and enter a read-only degraded state.
EIO or a failed fdatasync. This is the most dangerous case. After a failed fsync, Linux may discard the dirty pages and clear the error flag, meaning a retry can return success with the data never reaching disk. The correct response is to treat this as fatal:
- Fail every pending future immediately.
- Mark the log poisoned — no further writes are accepted.
- Close the file descriptor and restart from the last durable LSN, or crash the process to force operator intervention.
Records with receipts already delivered remain safe; they were synced before the error.
7. Recovery Algorithm
- List segments by base LSN. Validate the header of the final segment. If invalid, the segment was created but never written — delete it and move to the previous one.
- Begin scanning at the segment's base LSN (or a checkpointed safe offset).
- At each position, read the 24-byte frame header. Stop if any of the following are true:
- Fewer bytes remain than a complete header or frame.
- Magic bytes are wrong.
length > MAX_RECORD_SIZE.- Embedded LSN does not equal the current scan position.
- CRC does not match header + payload.
- Otherwise advance by
aligned_frame_sizeand continue. - Distinguish tail corruption from mid-log corruption. After stopping, scan forward for any frame with a valid magic and a plausible LSN.
- Nothing found until EOF, or only zeros: this is a torn write at the tail. Safe to truncate.
- A valid frame appears after the gap: this is corruption inside already-acknowledged data. Do not auto-truncate. Alert and require explicit operator intervention or a point-in-time restore.
- Truncate the file to the last valid LSN. Set the writer's starting position there. The log is now ready for new appends.
8. Key Metrics to Expose
| Metric | Why it matters |
|---|---|
| Semaphore wait time (p99) | Leading indicator of backpressure |
| Batch fill ratio (bytes / 1 MB cap) | Tells you how efficiently I/O is being amortized |
fdatasync latency (p50, p99) | Directly sets durability latency; spikes mean disk trouble |
| Queue depth (records and bytes) | Tracks lag between producers and the writer |
| Bytes written vs. bytes synced | A widening gap means the syncer is falling behind |
| Recovery truncation events | Should be zero in normal operation |
Common Mistakes to Avoid
- Syncing per record. Kills throughput entirely. Always batch.
- Retrying a failed
fsyncin hopes it succeeds. It may succeed and lie. Treat it as fatal. - Relying on CRC alone for recovery. Pre-allocated regions can have bytes that pass a CRC check. The embedded LSN is the second independent check that eliminates false positives.
- Auto-truncating mid-log corruption. Truncating a torn tail is safe. Silently discarding acknowledged data in the middle of the log is data loss masquerading as recovery.
- Holding a lock during I/O. Even a fast mutex held across
writevorfdatasyncserializes all 5,000 producers through a multi-millisecond call. The writer thread must own I/O exclusively and never hold a shared lock while doing it.