KatInterview

Build a Group-Commit Journal Writer with Crash Recovery

System DesignModel answer
HardModel answerSystem Designwrite-ahead-logconcurrencygroup-commit

Last 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:

FieldSizeMeaning
length4 bytes, unsigned big-endianpayload size N
lsn8 bytes, unsigned big-endianlog sequence number, starting at 0 and increasing by 1 per record
crc324 bytes, unsigned big-endianCRC-32 of the payload only
payloadN bytesthe raw record data

Required behavior

  1. 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, append blocks until room is available.
  2. When a batch is flushed.

    • As soon as the buffered bytes reach or exceed max_batch_bytes.
    • Or when max_delay_ms has passed since the first record entered the current batch.
  3. 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.
  4. 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 append concurrently; bytes from different records must never interleave and the file must never be corrupted.
  • A future must never complete before the fsync covering 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.