Concurrent Bounded FIFO Queue with Timeouts and Shutdown
Medium · Software Engineering Fundamentals · Backend Engineer · Onsite
Problem Statement
Build a thread-safe, fixed-capacity FIFO blocking queue supporting concurrent producer and consumer threads, optional wait timeouts, and graceful shutdown.
Implement two exception types—QueueClosedError and QueueTimeoutError—along with BoundedBlockingQueue:
__init__(capacity: int): Creates an empty queue able to buffer at mostcapacityelements at once. RaiseValueErrorwhenevercapacity <= 0.put(item: Any, timeout: Optional[float] = None) -> None: Appendsitemto the back of the queue (Noneand other falsy objects are valid elements). While the queue is open and at full capacity, the caller blocks until a slot opens up,timeoutseconds elapse, orclose()runs (timeout=Nonewaits with no time limit). RaiseQueueClosedErrorif the queue is already closed or closes beforeitemcan be inserted (even if free space exists). RaiseQueueTimeoutErrorif the deadline expires while the queue is still open and full.take(timeout: Optional[float] = None) -> Any: Removes and returns the oldest queued element from the front. While the queue is open and empty, the caller blocks until an item is enqueued,timeoutseconds elapse, orclose()runs (timeout=Nonewaits with no time limit). Afterclose(), any items still buffered in the queue continue to be delivered in FIFO order; once the queue is both closed and empty, waiting and futuretakecalls raiseQueueClosedError. RaiseQueueTimeoutErrorif the deadline expires while the queue remains open and empty.close() -> None: Marks the queue closed and wakes every thread currently waiting inputortake. Invokingclose()additional times is a harmless no-op.
from typing import Any, Optional
class QueueClosedError(Exception):
pass
class QueueTimeoutError(Exception):
pass
class BoundedBlockingQueue:
def __init__(self, capacity: int): ...
def put(self, item: Any, timeout: Optional[float] = None) -> None: ...
def take(self, timeout: Optional[float] = None) -> Any: ...
def close(self) -> None: ...
Examples
Example 1
- Scenario:
capacity = 3with non-blocking timeout and post-close draining
q = BoundedBlockingQueue(capacity=3)
q.put("job-10")
q.put("job-20")
q.put("job-30")
q.put("job-40", timeout=0) # Raises QueueTimeoutError immediately (buffer full)
q.take() # -> "job-10"
q.put("job-50") # Buffer now holds ["job-20", "job-30", "job-50"]
q.close()
q.put("job-60") # Raises QueueClosedError
q.take() # -> "job-20"
q.take() # -> "job-30"
q.take() # -> "job-50"
q.take() # Raises QueueClosedError (closed and drained)
- Walk-through: Once three items fill the queue, a zero-timeout
putfails right away withQueueTimeoutError. Popping"job-10"frees one slot for"job-50". Afterclose(), newputattempts fail immediately, whereastakedrains"job-20","job-30", and"job-50"in FIFO order before raisingQueueClosedError.
Example 2
- Scenario:
capacity = 1withNoneitems, blocking handoff, and closing on a blocked producer
q = BoundedBlockingQueue(capacity=1)
q.put(None) # None is stored as a normal value
# Producer P1 calls q.put(42) -> blocks because capacity 1 is occupied
q.take() # -> None; wakes P1 so 42 enters the buffer
# Producer P2 calls q.put(99) -> blocks because [42] fills the queue
q.close() # Wakes P2, which raises QueueClosedError
q.take() # -> 42
q.take(timeout=0) # Raises QueueClosedError
- Walk-through: Signaling failures with exceptions allows
Noneto pass through the queue safely. Closing whileP2is waiting unblocksP2withQueueClosedErrorwhile preserving buffered42for the next consumer.
Constraints
1 <= capacity <= 10^5(values<= 0raiseValueError).- Arbitrary numbers of producer and consumer threads may call
put,take, andcloseconcurrently. timeout == 0performs one immediate check without sleeping; negativetimeoutvalues must either behave liketimeout = 0or raiseValueError.- Guard against spurious OS wakeups and stolen slots/items so queue bounds (
0 <= len <= capacity), waiter cleanup, and wakeup delivery never break.
Step-by-step walkthrough
Understand the queue contract
Picture a pass-through counter between kitchen cooks (producers) and servers (consumers) that holds at most
capacityplates in strict FIFO (First-In, First-Out) order: new plates go on the back, and the oldest plate comes off the front.Every
putortakecall finishes in one of three ways:Operation Succeeds when... Raises QueueClosedError when... Raises QueueTimeoutError when... --------- -------------------------------------- -------------------------------- -------------------------------- put(item) queue is open AND has a free slot queue is closed (even with space) still full & open at deadline take() queue has >= 1 item (open OR closed) queue is closed AND empty still empty & open at deadlineNotice the deliberate asymmetry when
close()is called: - Producers stop immediately: blocked and futureputcalls fail withQueueClosedError, even if free slots remain. - Consumers drain remaining items first:takekeeps returning buffered items in FIFO order until the queue becomes empty, and only then raisesQueueClosedError. - Zero or negative timeouts never sleep:timeout=0(and clamped negative values) checks the queue once under the lock and either finishes right away or raises an exception.Why one lock plus two condition variables
A mutex lock (
threading.Lock) ensures only one thread reads or modifies the queue at a time. By itself, however, a lock cannot make a thread wait cleanly for space or an item: a thread that sees a full queue would have to release the lock, sleep for an arbitrary guess like 10 ms, and try again, wasting CPU or adding artificial delay.A condition variable (
threading.Condition) solves this by pairing a waiting list with the lock. Callingcond.wait()releases the lock and puts the thread to sleep in one indivisible step so a wakeup signal can never slip into the gap between unlocking and sleeping. Beforewait()returns, it automatically re-acquires the lock.We attach two condition variables to the same lock: -
_not_full: producers sleep here whilelen(_items) == _capacity, and eachtake()wakes one of them. -_not_empty: consumers sleep here whilelen(_items) == 0, and eachput()wakes one of them.Why two instead of one shared condition variable? With a single condition variable on a
capacity = 1queue, atake()callingnotify()might wake a second sleeping consumer instead of a sleeping producer:Single condition bug (capacity = 1, queue = []): Consumer C1 calls take() -> sleeps on cond Consumer C2 calls take() -> sleeps on cond Producer P1 calls put(1) -> queue = [1], wakes C1 Producer P2 calls put(2) -> queue is full, sleeps on cond C1 wakes, pops 1 -> queue = [], calls cond.notify() wakes C2 instead of P2! C2 sees queue = [] -> goes back to sleep; P2 never wakes -> DEADLOCKKeeping separate
_not_fulland_not_emptywait lists guaranteesnotify()always wakes a thread on the opposite side. We also store items incollections.dequeso appending to the right and popping from the left are both O(1), whereaslist.pop(0)shifts every remaining element in O(n).def __init__(self, capacity: int): if capacity <= 0: raise ValueError("capacity must be at least 1") self._capacity = capacity # _items: FIFO deque of queued values, e.g. deque([1, 2]) where 1 is oldest. self._items = deque() # _closed: True once close() is called; blocks all puts and empty takes. self._closed = False # One mutex guards _items and _closed; both condition variables share it # so sleeping on either condition releases the exact same lock. self._lock = threading.Lock() # Producers wait here while len(_items) == _capacity. self._not_full = threading.Condition(self._lock) # Consumers wait here while len(_items) == 0. self._not_empty = threading.Condition(self._lock)Why every wait belongs inside a while loop
When a sleeping thread returns from
wait(), it must re-check the queue state in awhileloop rather than trusting anifstatement, for three independent reasons:- Stolen wakeups:
notify()moves a sleeping thread from the wait list to the runnable state, but that thread still has to re-acquire_lock. A brand-new thread can grab_lockfirst and take the freed slot (or the new item). When the woken thread finally gets_lock, the queue is full (or empty) again. - Spurious wakeups: operating-system condition variables are allowed to wake a waiting thread occasionally even when nobody called
notify(). - Closure wakeups:
close()wakes waiting threads not because space or items appeared, but so they can observeself._closed == Trueand exit.
Inside the loop, we always check the queue state before checking whether the timeout expired:
with self._lock: while cannot proceed yet: 1. Check closed condition -> raise QueueClosedError if disallowed 2. Compute remaining time -> raise QueueTimeoutError if <= 0 3. Sleep on condition.wait(remaining) Perform deque update and notify opposite conditionChecking the queue state before the deadline avoids a subtle lost-wakeup bug: if a thread's
wait(remaining)times out at almost the exact microsecond another thread callsnotify()for it, the woken thread still re-checks the queue first, sees the item (or slot), and completes the call instead of throwing away the notification.- Stolen wakeups:
Track timeouts with a monotonic deadline
Because stolen or spurious wakeups can make a thread loop and call
wait()more than once, we must not pass the originaltimeoutto everywait(). Iftimeout = 1.0second and a thread wakes up after0.4seconds only to find its slot was stolen, its next wait should be at most0.6seconds, not a fresh1.0second.To do this cleanly, convert
timeoutonce at the start of the call into an absolutedeadlineontime.monotonic()— a clock that moves steadily forward and never jumps backward or forward if the machine adjusts its system wall clock.def _compute_deadline(self, timeout: Optional[float]) -> Optional[float]: if timeout is None: return None # Clamp negative timeouts to 0.0 so they perform one non-blocking check, # and use time.monotonic() so wall-clock adjustments cannot skew waits. return time.monotonic() + max(timeout, 0.0) def _seconds_left(self, deadline: Optional[float]) -> Optional[float]: if deadline is None: return None return deadline - time.monotonic()Computing
deadlinebeforewith self._lock:also means any time spent waiting just to acquire the lock is properly counted against the caller's timeout.Implement put and take
putandtakefollow the same loop pattern, with one crucial difference in how they treatself._closed: - Input, we checkif self._closed:first, before checkinglen(self._items) < self._capacity, because a closed queue must reject new items even when slots are empty. - Intake, the loop condition itself iswhile len(self._items) == 0:, so if buffered items remain afterclose(),takeskips the loop body altogether, pops the oldest item, and returns it. Only when the queue is both empty and closed doestakeraiseQueueClosedError.def put(self, item: Any, timeout: Optional[float] = None) -> None: # Start the timeout clock before acquiring _lock so lock contention counts too. deadline = self._compute_deadline(timeout) with self._lock: while True: # Check _closed first: a closed queue rejects new items even with free space. if self._closed: raise QueueClosedError("put on a closed queue") # Check free space before deadline: if a take() called notify() right as our # timer expired, using the slot avoids wasting that wakeup and starving peers. if len(self._items) < self._capacity: break remaining = self._seconds_left(deadline) if remaining is not None and remaining <= 0.0: raise QueueTimeoutError("queue still full after timeout") # Atomically release _lock, sleep up to `remaining` seconds, then re-acquire _lock. self._not_full.wait(remaining) self._items.append(item) # Adding one item can satisfy at most one sleeping consumer. self._not_empty.notify() def take(self, timeout: Optional[float] = None) -> Any: deadline = self._compute_deadline(timeout) with self._lock: # Loop only while empty so buffered items are still drained after close(). while len(self._items) == 0: if self._closed: raise QueueClosedError("take on a closed, empty queue") remaining = self._seconds_left(deadline) if remaining is not None and remaining <= 0.0: raise QueueTimeoutError("queue still empty after timeout") self._not_empty.wait(remaining) item = self._items.popleft() # Freeing one slot can unblock at most one sleeping producer. self._not_full.notify() return itemNotice that
with self._lock:guarantees_lockis always released even whenQueueClosedErrororQueueTimeoutErroris raised, and signaling errors via exceptions allowsNoneitself to be stored as a valid item.Implement close
Closing the queue sets
self._closed = Trueunder the lock and wakes every waiting thread on both condition variables withnotify_all(). Plainnotify()would wake at most one producer and one consumer, leaving any other blocked threads stuck forever.def close(self) -> None: with self._lock: self._closed = True # Wake every sleeping producer and consumer so none stay stuck waiting forever. self._not_full.notify_all() self._not_empty.notify_all()Calling
close()a second time simply sets_closed = Trueagain and sends harmless notifications, making it idempotent (safe to call multiple times with the same effect as calling it once).Trace Example 1 and a stolen wakeup
First, trace Example 1 (
capacity = 3):Call _items after _closed Result ------------------------- ---------------------------------- ------- ----------------------------------------- put("job-10") ["job-10"] False appends "job-10", notifies _not_empty put("job-20") ["job-10", "job-20"] False appends "job-20" put("job-30") ["job-10", "job-20", "job-30"] False appends "job-30" (now at capacity 3) put("job-40", timeout=0) ["job-10", "job-20", "job-30"] False full & remaining <= 0 -> QueueTimeoutError take() ["job-20", "job-30"] False pops "job-10", notifies _not_full put("job-50") ["job-20", "job-30", "job-50"] False appends "job-50" close() ["job-20", "job-30", "job-50"] True wakes all waiters on both conditions put("job-60") ["job-20", "job-30", "job-50"] True sees _closed == True -> QueueClosedError take() x 3 [] True drains "job-20", "job-30", "job-50" take() [] True empty AND _closed -> QueueClosedErrorNext, see how the
whileloop protects capacity during a stolen wakeup oncapacity = 1, starting with_items = ["a"]:Step Thread P (blocked producer) Thread M (other thread) _items ---- -------------------------------------- ---------------------------- ------ 1 put("b"): full -> sleeps on _not_full ["a"] 2 take() -> pops "a", [] notifies _not_full (P wakes) 3 waiting to re-acquire _lock... put("c") grabs _lock first! ["c"] 4 acquires _lock; while-loop re-checks: ["c"] len(_items) == 1 (still full!) -> sleeps again 5 take() -> pops "c", [] notifies _not_full (P wakes) 6 acquires _lock; len(_items) < 1 -> - ["b"] appends "b" and returns cleanlyComplete solution
from typing import Any, Optional from collections import deque import threading import time class QueueClosedError(Exception): """Raised by put on a closed queue, and by take on a closed queue that is empty.""" class QueueTimeoutError(Exception): """Raised when put or take could not finish before its timeout.""" class BoundedBlockingQueue: """FIFO queue with a fixed capacity, safe for many producer and consumer threads. Timeouts are in seconds. None blocks until the call can finish or the queue is closed; 0 or a negative number never blocks (one immediate check). """ def __init__(self, capacity: int): if capacity <= 0: raise ValueError("capacity must be at least 1") self._capacity = capacity # _items: FIFO deque of queued values, e.g. deque([1, 2]) where 1 is oldest. self._items = deque() # _closed: True once close() is called; blocks all puts and empty takes. self._closed = False # One mutex guards _items and _closed; both condition variables share it # so sleeping on either condition releases the exact same lock. self._lock = threading.Lock() # Producers wait here while len(_items) == _capacity. self._not_full = threading.Condition(self._lock) # Consumers wait here while len(_items) == 0. self._not_empty = threading.Condition(self._lock) def _compute_deadline(self, timeout: Optional[float]) -> Optional[float]: if timeout is None: return None # Clamp negative timeouts to 0.0 so they perform one non-blocking check, # and use time.monotonic() so wall-clock adjustments cannot skew waits. return time.monotonic() + max(timeout, 0.0) def _seconds_left(self, deadline: Optional[float]) -> Optional[float]: if deadline is None: return None return deadline - time.monotonic() def put(self, item: Any, timeout: Optional[float] = None) -> None: # Start the timeout clock before acquiring _lock so lock contention counts too. deadline = self._compute_deadline(timeout) with self._lock: while True: # Check _closed first: a closed queue rejects new items even with free space. if self._closed: raise QueueClosedError("put on a closed queue") # Check free space before deadline: if a take() called notify() right as our # timer expired, using the slot avoids wasting that wakeup and starving peers. if len(self._items) < self._capacity: break remaining = self._seconds_left(deadline) if remaining is not None and remaining <= 0.0: raise QueueTimeoutError("queue still full after timeout") # Atomically release _lock, sleep up to `remaining` seconds, then re-acquire _lock. self._not_full.wait(remaining) self._items.append(item) # Adding one item can satisfy at most one sleeping consumer. self._not_empty.notify() def take(self, timeout: Optional[float] = None) -> Any: deadline = self._compute_deadline(timeout) with self._lock: # Loop only while empty so buffered items are still drained after close(). while len(self._items) == 0: if self._closed: raise QueueClosedError("take on a closed, empty queue") remaining = self._seconds_left(deadline) if remaining is not None and remaining <= 0.0: raise QueueTimeoutError("queue still empty after timeout") self._not_empty.wait(remaining) item = self._items.popleft() # Freeing one slot can unblock at most one sleeping producer. self._not_full.notify() return item def close(self) -> None: with self._lock: self._closed = True # Wake every sleeping producer and consumer so none stay stuck waiting forever. self._not_full.notify_all() self._not_empty.notify_all()✅ Submit now — all tests should pass.
Intuition & how it works
Think of the queue as a narrow pass-through shelf between kitchen cooks (producers) and servers (consumers) that holds at most capacity plates in FIFO (First-In, First-Out, meaning oldest item comes out first) order. Instead of having cooks and servers constantly rattle the door to check the shelf, we attach two separate doorbells to one shared mutex lock (a mutual-exclusion lock that lets only one thread inspect or change the shelf at a time): a "space available" condition variable (a synchronization primitive that atomically releases the lock while putting a thread to sleep and re-acquires the lock before waking it) for cooks, and an "item ready" condition variable for servers.
Naive designs fail in subtle ways under concurrency. Polling with time.sleep() inside a loop wastes CPU and adds arbitrary latency; using a single shared condition variable with notify() allows a take() call to wake another sleeping consumer instead of a sleeping producer, causing a permanent deadlock; and checking the queue with if instead of while breaks as soon as a newly arrived thread steals the freed slot before the woken thread re-acquires the lock.
Walk through Example 1 on a queue with capacity = 3:
1. put("job-10"), put("job-20"), and put("job-30") fill _items to deque(["job-10", "job-20", "job-30"]); calling put("job-40", timeout=0) sees len(_items) == 3 with zero remaining budget and immediately raises QueueTimeoutError.
2. take() pops "job-10" from the left and calls _not_full.notify(), freeing space so put("job-50") yields deque(["job-20", "job-30", "job-50"]).
3. close() sets _closed = True and calls notify_all() on both condition variables: put("job-60") immediately raises QueueClosedError, while take() drains "job-20", "job-30", and "job-50" first and raises QueueClosedError on the fourth call once _items is empty.
Complexity
- Time: A
putortakethat does not block performs O(1) work while holding_lock— onedeque.appendordeque.popleft, plus onenotify()that wakes the oldest waiter at the front of the condition variable's wait queue. If a call times out,Condition.waitscans its internal waiter list ofWcurrently sleeping threads to remove its own entry, taking O(W) time, andclose()also takes O(W) time becausenotify_all()wakes every waiting thread. - Space: O(capacity + W), because
_itemsnever stores more thancapacityelements at once, and each of theWcurrently blocked threads holds one lightweight waiter lock insideCondition.waitthat is removed in afinallyblock as soon as the thread wakes or times out.
Edge cases
capacity <= 0: rejected immediately in__init__withValueErrorbefore any lock or thread state is created.capacity == 1: everyputafter the first must hand off to atake; this tightest case immediately exposes lost-wakeup bugs from using a single condition variable.timeout = 0or negative timeout: clamped to a deadline oftime.monotonic() + 0.0using a monotonic clock (a clock that ticks steadily forward and never jumps if the system wall clock is adjusted), so the method checks the queue once under_lockand never sleeps.close()on a non-empty queue:putfails immediately even if capacity remains, whereastakecontinues popping buffered items untillen(_items) == 0and only then raisesQueueClosedError.- Closed and empty queue with
timeout = 0: raisesQueueClosedErrorrather thanQueueTimeoutError, becauseself._closedis checked before the deadline. Noneas a valid element: storingput(None)works cleanly because errors raise exceptions instead of returningNoneas a sentinel.
Common mistakes
- Using
ifinstead ofwhilearoundwait(): after a stolen wakeup (where another thread acquires_lockfirst and consumes the slot or item) or a spurious wakeup (an OS wakeup with no matchingnotify()), anifletsputexceedcapacityortakeraiseIndexErroron an emptydeque. - Trusting the
Falsereturn value ofwait(remaining)blindly: in CPython, a thread's wait timer can expire right before another thread callsnotify()for that waiter while holding_lock.wait()still returnsFalse, so raisingQueueTimeoutErrorwithout re-checking_itemsfirst wastes thatnotify()and leaves another thread asleep forever. - Passing the original
timeouton every loop iteration: each stolen or spurious wakeup restarts the full timeout from scratch instead of waiting only fordeadline - time.monotonic(). - Using
time.time()instead oftime.monotonic(): wall-clock adjustments (such as automatic network clock syncs) can jump backward or forward, making timeouts hang or expire prematurely. - Calling
notify()instead ofnotify_all()insideclose():notify()wakes only a single thread per condition variable, leaving all other blocked producers and consumers hanging forever.
Alternative approaches
- Two counting semaphores plus a mutex: a counting semaphore is a synchronization counter that blocks
acquire()when its count is zero and increments onrelease(). Initializing anempty_slotssemaphore tocapacityand afilled_slotssemaphore to0handles basic blocking cleanly, but supportingclose()and timeouts together without leaking permits becomes messy because blocked semaphore acquisitions cannot easily distinguish a normal slot from shutdown. - Python's
queue.Queue: in production code, standard-libraryqueue.Queueuses the exact same architecture (one mutex shared bynot_emptyandnot_fullcondition variables, plusshutdown()in Python 3.13+).
Follow-up questions
- How could you lower lock contention when dozens of producer and consumer threads hammer the queue simultaneously? A two-lock queue (such as Java's
LinkedBlockingQueue) separates_lockinto aput_lockat the tail and atake_lockat the head of a linked list with a dummy sentinel node (a permanent placeholder node that keeps head and tail pointers from colliding on an empty list), tracking queue size with an atomic integer so one producer and one consumer can work in parallel. For even higher throughput, a bounded ring buffer (a fixed-size circular array) assigns monotonically increasing sequence numbers to each slot and lets threads claim indices via compare-and-swap (an atomic CPU instruction that updates a memory word only if it still equals an expected old value), falling back to OS parking primitives only when the queue is completely full or empty. Note that in standard CPython with the Global Interpreter Lock (GIL) — the interpreter-wide lock allowing only one thread to execute Python bytecodes at a time — splitting Python locks rarely speeds up pure-Python queues; batching (put_many/take_many) helps much more there, while two-lock and lock-free designs shine in C++, Rust, Java, or free-threaded Python. - What techniques let you test concurrent queues reproducibly for deadlocks and missed notifications without brittle sleep delays? Coordinate threads at exact checkpoints using
threading.Barrierandthreading.Event, and run every blocking queue call inside a daemon thread joined with a hard timeout (dumping thread stacks viafaulthandleron failure) so any deadlock fails fast instead of hanging CI. Verify global invariants across thousands of operations oncapacity = 1— every item produced is consumed exactly once, items from any single producer arrive in strict FIFO order, and0 <= len(_items) <= capacityalways holds under_lock. To force rare race windows without sleeps, lower Python's thread switch interval viasys.setswitchinterval(1e-6)and inject deliberatenotify_all()calls in tests to simulate spurious wakeups. - How do you keep internal queue state and waiter wakeups intact if a waiting caller receives an asynchronous interruption? Keep all state mutations strictly after
wait()returns inside a singlewith self._lock:block, never reserving a slot or incrementing counters beforehand. If an asynchronous exception likeKeyboardInterruptunwindsCondition.wait(), itsfinallyblock re-acquires_lock, removes the waiter from the condition's wait list, andwith self._lock:releases the mutex cleanly. The one edge case to guard against is when anotify()was already delivered to the interrupted waiter; catchingBaseExceptionaroundwait()and forwardingcond.notify()before re-raising ensures another waiting thread receives that wakeup, while true end-to-end delivery guarantees across caller crashes require explicit consumer acknowledgments (lease+ack).
Follow-up questions
- How could you lower lock contention when dozens of producer and consumer threads hammer the queue simultaneously?
- What techniques let you test concurrent queues reproducibly for deadlocks and missed notifications without brittle sleep delays?
- How do you keep internal queue state and waiter wakeups intact if a waiting caller receives an asynchronous interruption?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes