Design an In-Process Record Buffer with Async Disk Writes
System DesignModel answerLast 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:
- Data structures and concurrency primitives — what buffer structure you use, how producers and the background thread share it safely, and why.
- 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. - Backpressure — exactly what happens when the buffer is full, and what alternatives exist to simple blocking.
- Error handling and shutdown — how disk write failures are surfaced, and how
close()guarantees a clean drain. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying the Requirements First
Before reaching for data structures, work out what the numbers demand.
At 50 MB/s with B = 4 MB, the buffer fills and triggers a write roughly every 80 ms. The 200 ms time trigger only matters at low load, when writes are infrequent. Both triggers are necessary.
At a 200 MB/s burst with M = 64 MB, a disk stall lasting just 320 ms fills the cap. Backpressure is not a rare edge case — it is something the design has to handle gracefully on every busy machine.
At 100,000 appends/sec with an average record of 500 bytes, a memcpy under a mutex takes roughly 50–100 ns, so the lock is held for about 1% of elapsed time. A single mutex is sufficient at this scale, provided disk I/O never happens while the lock is held. Lock-free structures add complexity without paying off until you are in the GB/s range.
Questions worth asking before designing:
- Does
flush()needfsync, or is data reaching the OS page cache enough? - When the buffer is full, should
append()block, time out, or drop? - Does cross-producer write ordering matter, or only within a single producer's stream?
API Contract
append(data, timeout=None) -> bool
Copies data into the buffer. Returns False if the component is closed,
has failed, or the caller's backpressure timeout expires.
flush() -> None
Blocks until every record appended before this call has been written
(and fsynced, if configured). Raises if the writer has failed.
close() -> None
Idempotent. Stops new appends, drains remaining data to disk,
joins the background thread, and closes the file handle.
Returning False from append() is the explicit signal for backpressure and shutdown. Callers decide whether to retry, drop, or propagate an error.
Core Data Model
The state the mutex protects:
active— the segment currently accepting appends: a list of byte chunks, a cumulative byte count, andoldest_ts, the arrival time of its first record.sealed— a FIFO queue of segments that are full or have expired and are waiting to be written.in_memory_bytes— the sum across active, sealed, and in-flight segments. Memory is released only after a write completes, so this is the honest bound.appended_seq/durable_seq— monotonically increasing counters thatflush()uses to know when its records have landed on disk.
Three condition variables serve distinct purposes:
work_cv— wakes the background thread when a segment is sealed or the component closes.space_cv— wakes blocked producers after a write frees memory.durable_cv— wakesflush()waiters whendurable_seqadvances.
Architecture: Segment Swap
The key insight is double-buffering generalized to a queue of segments. The background thread claims the active segment — swapping in a fresh empty one — and performs the write outside the lock. Producers are blocked only for the O(1) pointer swap, never for I/O.
producers → [active segment] → (seal: O(1) swap) → [sealed queue] → background thread → disk
↑ |
└─────────────── space_cv (bytes freed) ←────────────────┘
def append(self, rec, timeout=None):
with self.lock:
deadline = None if timeout is None else time.monotonic() + timeout
while not self.closed and self.in_memory + len(rec) > self.M:
remaining = None if deadline is None else deadline - time.monotonic()
if remaining is not None and remaining <= 0:
return False # backpressure timeout
self.space_cv.wait(remaining)
if self.closed or self.failed:
return False
if not self.active.chunks:
self.active.oldest_ts = time.monotonic()
self.active.chunks.append(bytes(rec))
self.active.size += len(rec)
self.in_memory += len(rec)
self.appended_seq += 1
self.active.last_seq = self.appended_seq
if self.active.size >= self.B:
self._seal()
self.work_cv.notify()
return True
def _run(self): # background thread body
while True:
with self.lock:
while not self.sealed:
if self.active.chunks:
wait = self.active.oldest_ts + self.T - time.monotonic()
if wait <= 0 or self.closed or self.flush_requested:
self._seal()
break
elif self.closed:
return
else:
wait = None
self.work_cv.wait(wait)
seg = self.sealed.popleft()
self._write_with_retry(seg) # I/O outside the lock
with self.lock:
self.in_memory -= seg.size
self.durable_seq = seg.last_seq
self.space_cv.notify_all()
self.durable_cv.notify_all()
A few details worth calling out:
- The timed wait for
Tuses a monotonic clock and always re-checks predicates in a loop to handle spurious wakeups. - Producers notify
work_cvonly when a segment crossesB. This avoids up to 100,000 wakeups per second on the background thread. - Any record larger than
Mshould be rejected immediately at the top ofappend(). Otherwise it blocks forever waiting for space that can never appear.
flush() Implementation
Under the lock: record target = appended_seq, set flush_requested, notify work_cv. Then wait on durable_cv until durable_seq >= target or the writer has failed. Multiple concurrent flush() calls coalesce naturally — they all unblock when the relevant segment is written.
Backpressure Policies
The default is to block on space_cv with an optional caller-supplied timeout, then return False. Other valid approaches:
- Drop low-priority records (e.g., debug-level logs) and increment a dropped-records counter that can be exposed as a metric.
- Tiered queues: high-priority records get space; low-priority records are shed first under pressure.
- Never silently grow memory without bound — that path leads to OOM kills.
Disk Error Handling
- Loop on short writes until all bytes are flushed.
- On
EIOorENOSPC, retry with exponential backoff while keeping the segment in hand. No data is lost; backpressure builds naturally. - After N consecutive failures, enter a sticky
failedstate:append()returnsFalse,flush()andclose()raise the stored exception, and all condition variables are notified so no caller hangs indefinitely.
Shutdown
close() sets closed under the lock, notifies all three condition variables (releasing blocked producers, who get False), waits for the background thread to drain and exit, then fsyncs and closes the file. It must be idempotent and safe to call from an error handler.
Durability Trade-offs
| Write mode | Data loss on process crash | Data loss on power loss | Throughput impact |
|---|---|---|---|
write() only | Up to T + in-flight bytes | All page-cache data | Lowest |
Periodic fsync | Up to T + in-flight bytes | Since last fsync | Moderate |
fsync per batch | Up to in-flight bytes | Minimal | Significant |
The right choice depends on the application. A metrics pipeline can usually tolerate losing a few seconds of data on a crash. A write-ahead log for a database almost certainly cannot. Make the mode configurable and document what "persisted" means in your API contract.
Common Mistakes
- I/O inside the lock — the most common error; it serializes all producers behind disk latency.
- Wall clock instead of monotonic clock for the
Tdeadline — DST or NTP jumps can cause missed or doubled flushes. - Releasing memory before the write completes — this understates
in_memory_bytesand lets the buffer exceedM. - Not handling the oversized-record case — a record with
len(rec) > Mwill blockappend()forever. - Non-idempotent
close()— calling it twice from different threads (e.g., a signal handler and normal teardown) must be safe.