Design a Durable Multi-Threaded Append-Only Log Writer
System DesignModel answerLast updated
Design a thread-safe writer that lets thousands of threads durably append sub-1KB opaque records to one local file, with crash-safe framing and safe error handling.
You must design a small class, shared by a single-process application on one machine, that many worker threads use to append records to a file on the local disk.
class DataWriter:
def __init__(self, file_path_on_disk: str): ...
def push(self, data: bytes) -> None: ...
Each data argument is a bytes blob of at most 1 KB, and its contents are opaque — you never need to parse or transform them. Thousands of application threads call push concurrently and continuously.
A closely related variant of this problem states the core tension outright: every write to the single file must be synchronous (the caller only proceeds once the write has happened), and at the same time many threads are writing at once.
The interviewer will say: "Go ahead and start designing. Ask me anything you need before you begin."
What you are expected to deliver:
- Defend a precise durability contract for
push— when it returns, what is guaranteed to have survived a power loss? - Show a concurrency design that never loses, duplicates, or interleaves records, and that does not require one disk sync per call.
- Specify an on-disk record layout that lets a later reader split the file back into the original records and detect a torn or corrupt tail after a crash.
- Analyze the latency/throughput trade-off of batching and describe backpressure when the disk can't keep up.
- Explain error handling when a write or sync fails, plus clean shutdown.
- Provide working code or precise pseudocode for
pushand the flush path.
Assume (unless you argue otherwise in your clarifying questions): records are appended in some order across threads but each thread's own records stay in order; the file must be readable and split into records later; the class does not need rotation or truncation but does need a close.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Step 1 — Nail down the contract. The first clarifying question that matters most is: when push returns, must the bytes survive power loss, or is handing them to the OS cache enough? I'd propose push returns only after the record is durable (fsynced), because "durable event writer" implies that, but I state it explicitly: a faster variant returns after write(2) and only a periodic fsync/close guarantees durability. Ordering: cross-thread order can be arbitrary, but each thread's records must stay in insertion order — that falls out of serializing appends. The file format must be self-delimiting so a reader can recover records and detect a torn tail.
Step 2 — The naive design and why it fails. Simplest correct version: a threading.Lock around fp.write(record); fp.flush(); os.fsync(fp.fileno()). Correct, but every caller waits for a full round-trip to stable storage. A consumer SSD fsyncs in roughly 0.1–1 ms; spinning disks are 5–10 ms. At 0.5 ms that caps you near 2,000 pushes/sec total regardless of thread count, so 1,000 threads each get ~2 calls/sec. That's the latency/throughput trap the interviewer wants you to identify.
Step 3 — Group commit. Decouple "my bytes were written" from "my bytes are durable" and let many callers share one fsync:
pushserializes under a lock, appends the framed record to an in-memory staging buffer, records the buffer's current end offset as its "target", registers anEvent(or condition variable), and releases the lock.- A single writer thread (or whichever caller wins the flush race) drains the whole buffer to the file with one
write, then onefsync, then sets the target offsets for every buffered record. - Each caller blocks on its
Eventuntil the flush covering its offset completes, then returns.
One fsync now serves every record that arrived during the previous fsync. Under load, throughput becomes disk-bandwidth-limited (megabytes/sec), not fsync-latency-limited; with 10 KB of records per flush cycle and a 0.5 ms fsync you get ~20 MB/s and thousands of pushes/sec. Individual latency for a caller is bounded by up to two fsync periods, which is the trade you must name.
Step 4 — Alternative: bounded queue + dedicated writer. A queue.Queue(maxsize=N) of small tuples; N writer threads each do write then flush+fsync per N records. Simpler to reason about, but if the queue is unbounded it becomes an unbounded memory leak when the disk is slow; bound it so push blocks (backpressure) or raises. Group commit is tighter; the queue is easier to get right. I'd say so explicitly.
Step 5 — Framing on disk. Each record: 4-byte little-endian length L, 4-byte CRC32 of the payload, then the L payload bytes. Total ≤ 1 KB + 8. On recovery, loop: read 8 bytes; short read → stop (truncate here). Read L bytes; short → stop. Verify CRC; mismatch → stop and truncate. This makes the last record atomic-ish: a tear leaves a frame that fails the length check or the CRC, and everything before it is valid. Common mistake: writing raw bytes with no delimiter, then being unable to recover after a crash.
Step 6 — Serialization and the critical section. The lock is only held for buffer append + bookkeeping (microseconds); the actual write/fsync happens outside it, on whichever thread is flushing. That keeps push cheap under contention. Use a per-caller Event rather than a single condition variable if you want to avoid thundering-herd wakeups; with a single condition variable, notify_all after each flush is simpler but wakeups scale with waiters.
Step 7 — Errors. If write or fsync fails (ENOSPC, EIO), you must not silently drop. Options: (a) fail the current batch — every waiter in that batch gets an OSError from push; (b) latch a "poisoned" flag so all later push calls fail fast rather than retrying into a broken disk; (c) attempt a bounded number of retries first. A sensible default: retry transient EINTR/EAGAIN with small backoff, and on a hard error latch poisoned state and fail this and all future pushes; the caller can rebuild the writer. Choose one and state the consequences — don't hand-wave.
Step 8 — Shutdown. close() must: refuse new pushes, drain the staging buffer, fsync, close the fd, and then unblock any waiters with an error. Idempotent so a double close is harmless.
Sketch:
class DataWriter:
def __init__(self, path):
self._fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
self._lock = threading.Lock()
self._cond = threading.Condition(self._lock)
self._buf = bytearray()
self._durable = 0 # bytes of buffer known fsynced
self._closed = False
self._error = None
def push(self, data):
frame = len(data).to_bytes(4, "little") + zlib.crc32(data).to_bytes(4, "little") + data
with self._cond:
if self._error: raise self._error
if self._closed: raise ValueError("closed")
self._buf += frame
target = len(self._buf)
self._cond.notify()
while self._durable < target:
if self._error: raise self._error
self._cond.wait()
def _flusher(self): # dedicated thread
while True:
with self._cond:
while not self._buf and not self._closed and not self._error:
self._cond.wait()
if self._error or (self._closed and not self._buf):
self._cond.notify_all(); return
chunk = bytes(self._buf); self._buf.clear()
base = self._durable
try:
os.write(self._fd, chunk); os.fsync(self._fd)
with self._cond:
self._durable = base + len(chunk)
self._cond.notify_all()
except OSError as e:
with self._cond:
self._error = e; self._cond.notify_all(); return
Step 9 — Test the right things. Concurrency correctness (N threads × M pushes, count records, verify no duplicates/corruption); ordering within a thread; crash recovery by killing the process mid-write and validating truncation; the error path by simulating a failing fsync; and throughput measurement with many threads to prove the batching actually helps.
Common pitfalls to avoid: holding the lock during fsync; one fsync per push and pretending it scales; forgetting the reader side of the format; ignoring backpressure (unbounded buffer); treating a partial write as success; and forgetting close/drain semantics. The interviewer is mostly watching whether you state one durable contract clearly, defend a concurrency scheme that amortizes the fsync cost, and prove the file format is recoverable.