Blocking Bounded Buffer for Many Producers and Consumers
Data Structure DesignModel answerLast updated
Design and code a fixed-capacity, multi-producer multi-consumer buffer with timed blocking put/get, fair waiter ordering, clean shutdown and backpressure, and explain how you would test it.
Build an in-memory buffer that many threads can share. Any number of producer threads add items and any number of consumer threads remove them. The buffer holds at most capacity items, fixed at construction.
Required behavior
put(item, timeout=None)blocks while the buffer is full.get(timeout=None)blocks while it is empty.- A timeout of
Nonewaits indefinitely,0means "try once without blocking", and a positive value is a deadline in seconds. When the deadline passes, the call raises a timeout error. - Items must come out in the same order they went in.
- Threads must not deadlock, and no thread should wait forever while others keep getting served. Waiting producers should be served in arrival order, and so should waiting consumers.
- Provide a way to shut the buffer down. After shutdown, new
putcalls fail,getstill drains the remaining items and then fails, and every blocked thread wakes up.
What to cover in your answer
- Your locking strategy and why you chose it over the alternatives (a single mutex, separate locks for the two ends, lock-free).
- How threads are signaled, and how you avoid lost wakeups and wake-everyone stampedes.
- What happens when the buffer is full (backpressure), and what choices you give callers.
- A working implementation.
- Time and space complexity.
- How you would test correctness and measure performance.
Hints
Hint 1
Start with one lock guarding a deque and get it correct. Only then ask what changes for fairness, and which parts of a lock-free design would still need a blocking mechanism.
Hint 2
Fairness needs more than a shared condition variable. Keep an explicit FIFO line of waiters for each role, give each waiter its own condition, and let a thread proceed only if it is at the front and the state allows it. Make new arrivals skip the fast path when someone is already waiting.
Hint 3
Every way of leaving a wait (success, timeout, shutdown) must pass the baton: after you leave the line, re-check whether the new front waiter can now proceed and notify it. Compute a single absolute deadline up front so spurious wakeups do not extend the wait.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach in one paragraph
Use one mutex that protects the item buffer and two FIFO lines of waiters (blocked producers and blocked consumers). Each waiter blocks on its own condition variable tied to that mutex. A thread may proceed only when it is at the front of its line and the buffer state permits it. Whenever state changes or a waiter leaves, the code notifies the next front waiter that can make progress. This gives strict FIFO fairness per role, no stampede, and no lost wakeups, at the cost of more bookkeeping than the textbook design.
Clarified contract
capacity >= 1, MPMC, items leave in FIFO order.- Timeouts:
Noneis forever,<= 0is a single non-blocking attempt, positive is a deadline measured on a monotonic clock. close(): furtherputfails,getdrains then fails, all blocked threads are released.- Fairness means no barging. A newly arriving thread must not take a slot ahead of a thread that has been waiting longer.
Locking strategy and trade-offs
| Option | Pros | Cons |
|---|---|---|
| Single mutex + per-waiter conditions (chosen) | Simple to reason about, strict FIFO, targeted wakeups | One lock is a contention point |
Shared not_full / not_empty conditions | Simplest, widely used | Not fair; a late arrival can steal a slot; notify_all causes stampedes |
| Two locks (head and tail) plus atomic count | Producers and consumers do not contend, higher throughput | Cross-signaling between the locks is subtle |
| Lock-free ring (per-slot sequence numbers, CAS on indices) | Best throughput under light blocking | Still needs a parking mechanism for blocking and timeouts, hard to make fair, memory-ordering and ABA risk |
I would build the single-mutex version first and measure. If profiling shows lock contention, move to the two-lock design. I would go lock-free only if the workload is spin-friendly and latency-critical. In CPython the GIL makes lock-free pointless anyway.
Deadlock avoidance: there is one lock, it is never held while running caller code, every wait has a deadline or is released by close(), and every exit path hands off to the next waiter.
Starvation avoidance: FIFO lines, and a fast path that is allowed only when the line is empty.
Backpressure
A full buffer is the signal that consumers cannot keep up. The caller picks the reaction:
- Block with no timeout, which slows the producer to the consumer rate.
- Block with a deadline, then shed load or retry with backoff.
- Fail fast with
timeout=0.
Policies such as drop-oldest or spill-to-disk belong in a wrapper, not hidden inside the buffer. Expose depth and time spent blocked as metrics so upstream systems can rate-limit.
Implementation (Python)
import threading
import time
from collections import deque
class Closed(Exception):
pass
class BoundedBuffer:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("capacity must be >= 1")
self._cap = capacity
self._items = deque()
self._lock = threading.Lock()
self._prod_line = deque() # conditions of blocked producers, FIFO
self._cons_line = deque() # conditions of blocked consumers, FIFO
self._closed = False
def _wake_heads(self):
# Call with the lock held. Wake only waiters that can make progress.
if self._cons_line:
if self._items:
self._cons_line[0].notify()
elif self._closed:
for c in self._cons_line:
c.notify() # they will all see "closed and empty"
if self._prod_line and len(self._items) < self._cap:
self._prod_line[0].notify()
@staticmethod
def _left(deadline):
return None if deadline is None else deadline - time.monotonic()
def put(self, item, timeout=None):
deadline = None if timeout is None else time.monotonic() + timeout
with self._lock:
if self._closed:
raise Closed()
if not self._prod_line and len(self._items) < self._cap:
self._items.append(item)
self._wake_heads()
return
if timeout is not None and timeout <= 0:
raise TimeoutError("put timed out")
me = threading.Condition(self._lock)
self._prod_line.append(me)
try:
while True:
if self._closed:
raise Closed()
if self._prod_line[0] is me and len(self._items) < self._cap:
break
left = self._left(deadline)
if left is not None and left <= 0:
raise TimeoutError("put timed out")
me.wait(left)
self._items.append(item)
finally:
self._prod_line.remove(me)
self._wake_heads() # pass the baton on every exit path
def get(self, timeout=None):
deadline = None if timeout is None else time.monotonic() + timeout
with self._lock:
if not self._cons_line and self._items:
item = self._items.popleft()
self._wake_heads()
return item
if self._closed and not self._items:
raise Closed()
if timeout is not None and timeout <= 0:
raise TimeoutError("get timed out")
me = threading.Condition(self._lock)
self._cons_line.append(me)
try:
while True:
if self._cons_line[0] is me and self._items:
return self._items.popleft()
if self._closed and not self._items:
raise Closed()
left = self._left(deadline)
if left is not None and left <= 0:
raise TimeoutError("get timed out")
me.wait(left)
finally:
self._cons_line.remove(me)
self._wake_heads()
def close(self):
with self._lock:
self._closed = True
for c in self._prod_line:
c.notify()
for c in self._cons_line:
c.notify()
def __len__(self):
with self._lock:
return len(self._items)
Why it is correct
- Safety: all shared state is touched only under the lock, so the size never exceeds
capacityand never goes negative. Items are appended and popped at opposite ends of one deque, so FIFO order holds. - No barging: the fast path requires an empty line, so a newcomer never jumps a waiter. A waiter proceeds only when it is the head.
- No lost wakeups: the condition is re-checked in a loop after each wake, and a thread that leaves the line (success, timeout or close) calls
_wake_heads(). If a head times out just as space appears, the next head is notified instead of the signal being dropped. - Timeouts: one absolute deadline is computed up front, so spurious wakeups do not extend the wait. The state check comes before the deadline check, so a thread that wakes at the deadline with the slot available still succeeds.
- Shutdown:
close()wakes everyone. Producers raise. Consumers drain and then raise, because_wake_heads()wakes all consumers once the buffer is closed and empty.
Complexity
putandgetare O(1) amortized under the lock. Removing a waiter from the middle of a deque on timeout is O(w) in the number of waiters. An ordered map or intrusive linked list makes that O(1).- Space is O(capacity + waiters).
- Wakeups are targeted: one
notifyper state change, not O(waiters).
Testing
Correctness
- Stress test: N producers and M consumers push unique IDs. Assert that nothing is lost or duplicated and that each producer's items arrive in order.
- Invariant checks:
lenstays within[0, capacity]at every sampled point. - Deterministic scenarios using barriers: capacity 1 with several blocked producers should release them in arrival order. Timeouts should fire within a tolerance. A timed-out head must not strand the next waiter.
- Shutdown tests:
close()while threads are blocked, with and without leftover items. - Run repeatedly with randomized sleeps and thread counts, plus a watchdog that fails if the test hangs.
Performance
- Measure throughput and p50/p99/p99.9 latency for put and get while varying thread counts, capacity, and the producer/consumer ratio.
- Compare against the shared-condition baseline to quantify the cost of fairness.
- Watch for lock contention, context-switch rate, and tail latency of the longest waiter.
Common mistakes
- Using
ifinstead ofwhilearound the wait, which breaks on spurious wakeups. - Using a relative timeout in a loop, so the total wait grows with every wakeup.
- Calling
notify_allon every operation, which causes a thundering herd. - Forgetting to re-signal when a waiter times out or is cancelled.
- Claiming fairness while allowing a fast path that skips the waiting line.
- Leaving shutdown undefined, so threads block forever at exit.