Concurrent Micro-Batching Writer with Backpressure and Timed Flush
Data Structure DesignModel answerLast updated
Build a thread-safe buffer that accepts records from many producers and writes them to a database in batches, triggered by size, age of the oldest record, or shutdown, without holding locks during I/O.
Micro-Batching Writer
Inserting event records into a database one row at a time wastes network round trips and strains the connection pool. A common remedy is to hold records briefly in memory and send them in groups.
Design and implement a thread-safe BatchWriter class. Many producer threads call it concurrently, and it forwards the records to a database client in batches.
A batch must be sent when either condition holds:
- The number of buffered records reaches
batch_size. - More than
flush_interval_msmilliseconds have passed since the oldest record still waiting in the buffer was added.
Database calls are slow. Your implementation must not hold the lock that guards the incoming buffer while db_client.insert_batch(...) runs, so that producers can keep adding records during the network call.
Interface
class DatabaseClient:
def insert_batch(self, records: list[dict]) -> None:
"""Persists a batch of records. May be slow."""
pass
class BatchWriter:
def __init__(self, db_client: DatabaseClient, batch_size: int,
flush_interval_ms: int, max_capacity: int):
"""Configures size and time thresholds and the backpressure limit."""
pass
def write(self, record: dict) -> None:
"""Adds a record. Blocks while the writer is at max_capacity."""
pass
def flush(self) -> None:
"""Immediately pushes out everything currently buffered."""
pass
def close(self) -> None:
"""Rejects new writes, persists everything outstanding, and stops background threads."""
pass
Constraints
batch_size >= 1,flush_interval_ms >= 10,max_capacity >= batch_size.write()must be safe to call from many threads. When the number of pending records reachesmax_capacity, callers block until space frees up.- Take the batch out of the shared buffer (swap or copy) while holding the lock, release the lock, and only then call
insert_batch. close()must stop further writes, flush every remaining record, and wait for in-progress inserts to complete.
Example
# batch_size=3, flush_interval_ms=500, max_capacity=10
writer = BatchWriter(db_client, batch_size=3, flush_interval_ms=500, max_capacity=10)
# t=0ms thread A writes record 1
# t=10ms thread B writes record 2
# t=500ms the age limit is hit -> insert_batch([rec1, rec2])
# t=600ms thread A writes records 3, 4, 5 in quick succession
# size limit reached -> insert_batch([rec3, rec4, rec5]) right away
writer.close() # nothing may be lost
Edge cases to address
close()running while producers are still callingwrite().- The timer firing when nothing has been buffered (no empty inserts).
- The age timer being recalculated correctly after a size-triggered flush.
What to deliver
Explain your design (threads, locks, condition variables), justify why it is correct, give complexity, discuss failure handling, and provide working code.
Hints
Hint 1
Split the work into two roles: producers only append to an in-memory queue under a short lock, while a single background thread owns all database calls.
Hint 2
Store a timestamp with each buffered record. The deadline is then always 'oldest buffered timestamp + interval', and it recomputes itself after a size-based flush removes the head. Let the flusher wait on a condition variable with a timeout equal to the remaining time, and re-check the predicate on every wakeup.
Hint 3
Decide what counts toward max_capacity. If you decrement the pending counter when a batch leaves the buffer rather than when its insert finishes, memory is no longer bounded. Also think about what flush() should wait for; monotonic counters (accepted vs persisted) give it a precise meaning.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Separate ingestion from persistence.
- Producers hold the lock only briefly: they check capacity, append
(timestamp, record)to a deque, update counters, and wake the flusher if needed. - One flusher thread owns every database call. Under the lock it decides whether a batch is due and removes up to
batch_sizerecords. It then releases the lock and callsinsert_batch.
Three condition variables share one lock:
| Condition | Waiters | Notified when |
|---|---|---|
work | flusher | buffer goes 0 to 1, size threshold reached, flush requested, close |
not_full | blocked producers | a batch finishes persisting, close |
done | flush() callers | a batch finishes persisting |
Flusher loop
- Lock. While there is nothing to do:
- Buffer empty and not closed:
work.wait()with no timeout. This is why timer wakeups on an empty buffer never produce an empty insert. - Buffer non-empty: compute
due = oldest_ts + interval. Iflen(buffer) >= batch_size, ornow >= due, or a forced flush is pending, or the writer is closed, take a batch. Otherwisework.wait(due - now).
- Buffer empty and not closed:
- Pop up to
batch_sizeentries into a local list. - Release the lock and call
insert_batch(batch). Catch exceptions. - Re-lock, subtract
len(batch)frompending, add topersisted, thennotify_allonnot_fullanddone. - Exit when closed and the buffer is empty.
Why it works
- No I/O under the lock. The batch is a private local list by the time
insert_batchis called, so producers append freely during network calls. - Timer from the oldest record. Because each entry carries its own timestamp, the deadline is derived from the current head. After a size flush removes the head, the next iteration automatically uses the new head's age. No timer needs cancelling or resetting.
- Spurious wakeups. The flusher always re-evaluates the predicate after waking.
- Backpressure bounds memory.
pendingcounts buffered plus in-flight records and drops only afterinsert_batchreturns. If it dropped at dequeue time, a slow database would allow up tomax_capacitybuffered records plus an unbounded number in flight. - Ordering. One FIFO deque and one flusher means batches reach the database in arrival order.
flush()semantics. Keep monotonic countersenqueuedandpersisted.flush()recordstarget = enqueued, sets a force target so the flusher ignores the age and size rules untildispatched >= target, and waits ondoneuntilpersisted >= target. Large backlogs are still sent in chunks of at mostbatch_size.- Clean
close(). Setclosedunder the lock andnotify_allonworkandnot_full. Blocked producers wake and raise. The flusher drains the remainder and exits.close()joins the flusher, so it returns only after all in-flight inserts finish. Awritethat entered the buffer beforeclosedwas set is guaranteed to be persisted; one that arrives later raises.
Sketch of the code
import threading, time
from collections import deque
class BatchWriter:
def __init__(self, db_client, batch_size, flush_interval_ms, max_capacity):
if batch_size < 1 or flush_interval_ms < 10 or max_capacity < batch_size:
raise ValueError("invalid configuration")
self._db = db_client
self._bs = batch_size
self._interval = flush_interval_ms / 1000.0
self._cap = max_capacity
self._lock = threading.Lock()
self._work = threading.Condition(self._lock)
self._not_full = threading.Condition(self._lock)
self._done = threading.Condition(self._lock)
self._buf = deque()
self._pending = self._enqueued = self._dispatched = self._persisted = 0
self._force_target = 0
self._closed = False
self._error = None
self._t = threading.Thread(target=self._run, daemon=True)
self._t.start()
def write(self, record):
with self._lock:
while not self._closed and self._pending >= self._cap:
self._not_full.wait()
if self._closed:
raise RuntimeError("closed")
self._buf.append((time.monotonic(), record))
self._pending += 1
self._enqueued += 1
n = len(self._buf)
if n == 1 or n >= self._bs:
self._work.notify()
def flush(self):
with self._lock:
target = self._enqueued
if target > self._force_target:
self._force_target = target
self._work.notify()
while self._persisted < target:
self._done.wait()
self._raise_error()
def close(self):
with self._lock:
self._closed = True
self._work.notify_all()
self._not_full.notify_all()
self._t.join()
with self._lock:
self._raise_error()
def _raise_error(self):
err, self._error = self._error, None
if err:
raise err
def _run(self):
while True:
with self._lock:
while True:
if not self._buf:
if self._closed:
return
self._work.wait()
continue
due = self._buf[0][0] + self._interval
now = time.monotonic()
if (len(self._buf) >= self._bs or now >= due
or self._dispatched < self._force_target
or self._closed):
break
self._work.wait(due - now)
k = min(self._bs, len(self._buf))
batch = [self._buf.popleft()[1] for _ in range(k)]
self._dispatched += k
try:
self._db.insert_batch(batch)
except Exception as e:
self._error = e
with self._lock:
self._pending -= k
self._persisted += k
self._not_full.notify_all()
self._done.notify_all()
Complexity
write: O(1) amortized, plus any time blocked on backpressure.- Flusher: O(b) under the lock per batch of b records, with the database call outside it.
flush/close: O(N / batch_size) database calls for N buffered records.- Space: O(max_capacity).
Edge cases and trade-offs
close()racing withwrite(): whoever takes the lock first wins. The record is either accepted and guaranteed persisted, orwriteraises.- Idempotent
close(): a second call joins a finished thread and is harmless. flush()on an empty buffer or after close:persisted == enqueued, so it returns immediately.insert_batchraises: the flusher must not die or leave producers blocked. Record the error, still release capacity, and surface it from the nextflush()/close(). In production add bounded retries with backoff, a dead-letter path, and metrics. Dropping silently is a bug.- Reentrancy: calling
flush()orclose()from insideinsert_batchwould deadlock because it runs on the flusher thread. Document it as unsupported. - Throughput trade-off: a single flusher keeps ordering simple but caps throughput at one in-flight insert. A pool of flushers raises throughput but loses ordering unless records are partitioned by key.
Common mistakes
- Holding the lock across
insert_batch. - Using a fixed periodic timer, which flushes too early after a size flush and sends empty batches.
- Decrementing the capacity counter at dequeue time, so memory is unbounded under a slow database.
- Using
ifrather thanwhilearound condition waits. - Forgetting to wake blocked producers on
close(), causing hangs. - Letting the flusher thread die on an exception.