KatInterview

Design an In-Process Record Buffer with Async Disk Writes

System DesignModel answer
MediumModel answerSystem Designconcurrencybufferingbackpressure

Last updated

Design a thread-safe, memory-bounded write buffer that batches records in memory and drains them to disk via a background thread under high producer concurrency.

Context

High-throughput services — analytics pipelines, metrics collectors, event loggers — generate enormous volumes of small records. Writing each record directly to disk is impractical: the latency of every write() syscall accumulates, and the overhead crushes throughput before the storage device is even close to saturated.

A common solution is an in-process write buffer: producers deposit records into memory as fast as they like, while a dedicated background thread handles the slower work of batching those records and writing them to persistent storage.

Your Task

Design a RecordBuffer component in the language of your choice. It must expose the following interface:

append(data: bytes) -> bool
flush() -> None
close() -> None

The component operates under these rules:

Batching and write triggers. A background worker thread monitors the buffer and writes accumulated records to disk whenever at least one of these conditions is true:

  • The total size of buffered data reaches a byte threshold B (e.g., 4 MB).
  • The time elapsed since the earliest unwritten record arrived exceeds a latency deadline T (e.g., 200 ms).

Backpressure. The total in-memory footprint of buffered data — including records awaiting a write and records currently being written — must never exceed a configured cap M (e.g., 64 MB). If the disk falls behind, producers must be slowed down rather than allowed to exhaust heap memory.

Graceful shutdown. Calling close() must ensure all buffered data reaches disk before the background thread is stopped. After close() is called, any subsequent append() must return False.

Scale and Constraints

  • Up to 50 concurrent producer threads, each calling append() at high frequency.
  • Steady-state aggregate throughput of ~50 MB/s; burst up to ~200 MB/s.
  • Average record size is roughly 500 bytes, implying roughly 100,000 appends per second at steady state.
  • At 200 MB/s burst, a disk stall of even 300 ms can fill the buffer — treat backpressure as a normal operating condition, not an edge case.

What to Cover

Your answer should address the following areas:

  1. Data structures and concurrency primitives — what buffer structure you use, how producers and the background thread share it safely, and why.
  2. The flush lifecycle — how the background thread decides when to write, how it extracts a batch without blocking producers for the duration of the I/O, and how flush() lets a caller wait for a specific write to complete.
  3. Backpressure — exactly what happens when the buffer is full, and what alternatives exist to simple blocking.
  4. Error handling and shutdown — how disk write failures are surfaced, and how close() guarantees a clean drain.
  5. Durability trade-offs — what data-loss scenarios exist under different write modes (write() vs. fsync), and how you would communicate those to callers.

Hints

Hint 1

Start by working out what the numbers actually imply: at 50 MB/s and B = 4 MB, how often does the size trigger fire? How long does a disk stall have to last before you hit the M cap? Those answers will tell you how much complexity you actually need in the locking model.

Hint 2

The central design challenge is keeping I/O outside the lock. Think about a double-buffer or segment-swap scheme: producers write into an 'active' buffer, and the background thread atomically claims it and writes to disk without holding the lock during the actual I/O.

Hint 3

For flush() to work correctly, you need a way to tie a specific append to a specific write completion. A monotonic sequence number on each sealed batch — compared against a 'durable up to' counter after each successful write — gives you that without extra synchronization.