Build a Group-Commit Journal Writer with Crash Recovery
System DesignModel answerLast updated
Design a thread-safe append-only journal that batches fsyncs, assigns ordered sequence numbers, acknowledges only after durability, and recovers by truncating a corrupted tail.
Build a Group-Commit Journal Writer
A storage engine cannot afford one fsync per transaction, yet it must not acknowledge a write until that write is truly on disk. A common answer is an append-only journal (a write-ahead log) that lets many threads submit records while one background worker persists them together, in batches.
Design and implement a WALWriter class that accepts byte records from any number of producer threads and makes them durable in bounded batches.
On-disk frame layout
Each record is stored as a frame with these fields, in order:
| Field | Size | Meaning |
|---|---|---|
length | 4 bytes, unsigned big-endian | payload size N |
lsn | 8 bytes, unsigned big-endian | log sequence number, starting at 0 and increasing by 1 per record |
crc32 | 4 bytes, unsigned big-endian | CRC-32 of the payload only |
payload | N bytes | the raw record data |
Required behavior
-
Appending.
append(payload) -> Future[int]- Assigns the next LSN right away when the record is accepted.
- Places the record in an in-memory batch without making other writers wait on disk I/O.
- The returned future resolves to the LSN only after the batch holding the record has been written and
fsync(or an equivalent) has completed. - Backpressure: if the number of accepted-but-not-yet-durable records reaches
max_uncommitted_records,appendblocks until room is available.
-
When a batch is flushed.
- As soon as the buffered bytes reach or exceed
max_batch_bytes. - Or when
max_delay_mshas passed since the first record entered the current batch.
- As soon as the buffered bytes reach or exceed
-
Recovery.
recover(file_path) -> list[(lsn, payload)]- Reads the file from the start, checking the frame layout, the length, and the CRC.
- Stops at the first bad or incomplete frame (for example a torn write at the end). Everything before it is returned, and the damaged tail is truncated from the file.
-
Shutdown.
close()flushes and syncs everything still buffered, resolves all outstanding futures, and releases file handles.
Interface
from concurrent.futures import Future
from typing import List, Tuple
class WALWriter:
def __init__(self, file_path: str, max_batch_bytes: int = 64 * 1024,
max_delay_ms: float = 10.0, max_uncommitted_records: int = 10000):
...
def append(self, payload: bytes) -> Future: # resolves to int (the LSN)
...
def close(self) -> None:
...
@classmethod
def recover(cls, file_path: str) -> List[Tuple[int, bytes]]:
...
Constraints
0 <= len(payload) <= 16 * 1024 * 1024.- Any number of threads may call
appendconcurrently; bytes from different records must never interleave and the file must never be corrupted. - A future must never complete before the
fsynccovering its record has returned.
What to cover in your answer
Explain the threading model, how you keep LSN order identical to file order, how backpressure and shutdown work, what recovery checks, and the edge cases (empty payloads, oversized payloads, reopening an existing file, I/O errors). Give code and complexity.
Hints
Hint 1
Keep the producer path tiny and put all disk writes in one background flusher thread. Think about which operations must happen together under a single lock so that the order of LSNs equals the order of bytes in the file.
Hint 2
Use double buffering: under the lock, swap the pending list for an empty one, then do `write` and `fsync` outside the lock so producers can keep appending. Resolve futures only after `fsync` returns, and propagate exceptions to them if it fails.
Hint 3
For recovery, treat the file as an append-only sequence where damage can only be at the tail. Validate header size, length bound, truncated payload, CRC, and LSN contiguity; truncate to the last good offset and fsync. On reopen, run recovery first and continue from the last LSN + 1.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the work into a cheap foreground path (many producers) and one background flusher that owns the file. Group commit comes from the fact that while one fsync is running, other records pile up and share the next one.
Foreground: append
- Copy the input with
bytes(payload)so later mutation by the caller cannot change what is logged. - Reject payloads over 16 MiB with
ValueErrorbefore taking an LSN, so no LSN gap is created. - Compute the CRC outside the lock (it is O(N) and needs no shared state).
- Take the mutex briefly and, in a single critical section:
- wait while
uncommitted >= max_uncommitted_records(backpressure, via a condition variable), bailing out if the log is closing or failed; - assign
lsn = next_lsn++; - pack the 16-byte header, append header and payload to the current batch, register the
Future; - if this is the first record in the batch, record the batch start time; if the byte threshold is reached, notify the flusher.
- wait while
Assigning the LSN and enqueuing the bytes inside the same critical section is essential. With a separate atomic counter, two threads could obtain LSNs 5 and 6 and enqueue them as 6, 5, breaking the "file order equals LSN order" property recovery relies on.
Background: the flusher
Loop:
- Under the lock, wait until one of: batch bytes >=
max_batch_bytes,max_delay_mselapsed since the batch's first record (use a monotonic clock and a timed wait), orclosingis set with data remaining. - Swap out the buffer and future list (double buffering), reset counters, release the lock.
- Join the pieces into one buffer, loop on
os.writeuntil fully written (partial writes are legal), thenos.fsync. - Only now call
set_result(lsn)on each future. - Re-take the lock, decrease
uncommittedby the batch size, andnotify_allon the space condition so blocked producers wake.
If write or fsync raises, call set_exception on every future in that batch, mark the log as failed, and wake blocked appenders so they raise rather than hang. After a failed fsync the state of the file is unknown, so the safe policy is to refuse further writes.
Shutdown
close() sets closing, notifies the flusher, which drains remaining records without waiting for the timer. It then exits, close() joins it, and closes the file descriptor. Appenders blocked on backpressure wake and raise RuntimeError. Make close() idempotent.
Recovery
Read frames sequentially from offset 0 and stop at the first frame that fails any check:
- fewer than 16 header bytes remain;
lengthexceeds 16 MiB;offset + 16 + lengthgoes past end of file (torn payload);- CRC of the payload does not match;
- LSN is not exactly the previous LSN + 1 (starting from 0).
Return the valid prefix, then truncate to the last good offset and fsync. Because the CRC covers only the payload, a corrupted length field is caught by the bound check, the end-of-file check, or the LSN continuity check, not by the CRC. Since the log is append-only, damage can only occur at the tail, so the first invalid frame marks the end of the longest valid prefix.
The constructor calls recover first, so reopening an existing file removes any torn tail and continues from last_lsn + 1. Also fsync the containing directory when creating a new file so the directory entry is durable.
Code sketch
import os, struct, threading, time, zlib
from concurrent.futures import Future
HDR = struct.Struct(">IQI")
MAXREC = 16 * 1024 * 1024
class WALWriter:
def __init__(self, path, max_batch_bytes=64*1024, max_delay_ms=10.0,
max_uncommitted_records=10000):
if max_uncommitted_records < 1:
raise ValueError("max_uncommitted_records must be >= 1")
rec = self.recover(path)
self._next = rec[-1][0] + 1 if rec else 0
self._fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
self._maxb, self._delay = max_batch_bytes, max_delay_ms / 1000
self._maxu = max_uncommitted_records
self._lock = threading.Lock()
self._work = threading.Condition(self._lock)
self._space = threading.Condition(self._lock)
self._buf, self._futs = [], []
self._bytes = self._uncommitted = 0
self._start = 0.0
self._closing, self._err = False, None
self._t = threading.Thread(target=self._run, daemon=True)
self._t.start()
def append(self, payload):
data = bytes(payload)
if len(data) > MAXREC:
raise ValueError("payload too large")
crc = zlib.crc32(data) & 0xFFFFFFFF
fut = Future()
with self._lock:
while self._uncommitted >= self._maxu and not self._closing and not self._err:
self._space.wait()
if self._err: raise IOError("WAL failed") from self._err
if self._closing: raise RuntimeError("WAL closed")
lsn = self._next; self._next += 1
if not self._futs: self._start = time.monotonic()
self._buf += [HDR.pack(len(data), lsn, crc), data]
self._futs.append((fut, lsn))
self._bytes += HDR.size + len(data)
self._uncommitted += 1
if len(self._futs) == 1 or self._bytes >= self._maxb:
self._work.notify()
return fut
def _run(self):
while True:
with self._lock:
while True:
if self._futs:
if self._closing or self._bytes >= self._maxb:
break
rem = self._start + self._delay - time.monotonic()
if rem <= 0: break
self._work.wait(rem)
elif self._closing:
return
else:
self._work.wait()
buf, futs = self._buf, self._futs
self._buf, self._futs, self._bytes = [], [], 0
blob = b"".join(buf)
try:
mv = memoryview(blob)
while mv:
mv = mv[os.write(self._fd, mv):]
os.fsync(self._fd)
except BaseException as e:
with self._lock:
self._err = e
self._space.notify_all()
for f, _ in futs: f.set_exception(e)
continue
for f, lsn in futs: f.set_result(lsn)
with self._lock:
self._uncommitted -= len(futs)
self._space.notify_all()
def close(self):
with self._lock:
self._closing = True
self._work.notify_all(); self._space.notify_all()
self._t.join()
os.close(self._fd)
recover is a straightforward loop implementing the checks above, followed by os.truncate and fsync. (After a failure the flusher should keep draining and failing remaining batches so no future is left pending.)
Complexity
append: O(N) for copy and CRC outside the lock, O(1) inside.- Flush: O(B) per batch of B bytes plus one
fsync, which is amortized over all records in the batch. recover: O(file size) time; streaming with a fixed buffer keeps memory O(max record).- Writer memory: O(
max_uncommitted_recordsx average record size); also cap bytes if records can be large.
Trade-offs and common mistakes
- Larger batches and longer delays raise throughput but add latency;
max_delay_msbounds the added latency for a lone writer. - Resolving futures before
fsyncbreaks the durability promise. - Using a separate atomic LSN counter instead of assigning inside the enqueue critical section reorders records.
- Holding the lock during
write/fsyncserializes producers and defeats batching. - Forgetting partial writes, or continuing to write after a failed
fsync. - Returning records after a corrupted frame, or not truncating the tail, so new appends land after garbage.
- Letting blocked appenders hang forever on close or failure.