KatInterview

Concurrent Micro-Batching Writer with Backpressure and Timed Flush

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencycondition-variablesbackpressure

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

  1. The number of buffered records reaches batch_size.
  2. More than flush_interval_ms milliseconds 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 reaches max_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 calling write().
  • 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.