Design a Thread-Safe Batch Writer
Records arrive continuously from a stream and must be written to a database. Many threads receive records and hand them to your component at the same time. Writing one record at a time is too slow, but the database client offers batchInsert(records), which inserts a list in one call and may throw on failure.
Design and implement BatchWriter(db, maxBatchSize, maxWaitSeconds) with submit(record), called concurrently from many threads, and close(), which writes everything still buffered and stops. maxBatchSize caps one batchInsert; maxWaitSeconds bounds how long a record may sit in the buffer when traffic is low.
Sending each record to a thread pool whose workers each write one record is parallel but not batching; the point is to accumulate records and use the batch API. Decide and state: what happens when batchInsert fails, whether order is preserved, what submit does when the database falls behind, and whether several batches may be in flight at once.
Hints
Hint 1
Two reasons to flush: the buffer reached maxBatchSize, or the oldest record has waited maxWaitSeconds. The first is checked in submit, the second needs a timer or a flusher thread that wakes up on a deadline.
Hint 2
Keep the lock short: under the lock, swap the full buffer for an empty one; call batchInsert outside the lock on the swapped buffer, so submitters never wait on the database.
Hint 3
Backpressure is a bounded buffer: when it is full, submit blocks (or fails fast, or drops) by an explicit policy, and close sets a stopped flag, flushes the remainder and waits for in-flight batches.
Asked at
Sign in to talk to the interviewer — ask what's in scope, what scale to design for, or for a nudge when you're stuck. Conversations save to your account.
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.