Thread-Safe Kitchen: Cook-Once, Pickup-Once Order Pipeline
Data Structure DesignModel answerLast updated
Build a thread-safe kitchen where producers place orders, chefs cook them, and customers block until their dish is ready, with no races, deadlocks, or busy-waiting.
Multi-threaded kitchen with blocking pickup
Implement a thread-safe in-memory kitchen. Many threads submit orders, a pool of chef threads cooks them, and many customer threads wait for their own dish and collect it.
Order data
Every order carries:
order_id: a unique integeritem_name: a stringcook_time_ms: a positive integer, the time a chef spends cooking it
Operations
Names and signatures are up to you:
placeOrder(order_id, item_name, cook_time_ms)submits an order.startKitchen(num_chefs)launches the background chef threads.pickupOrder(order_id)blocks until that order has been cooked, then returns it to the caller.shutdown()stops all background threads cleanly.
Guarantees your design must provide
- An order is never handed over before it has finished cooking.
- Each order is cooked exactly once and collected at most once.
- No deadlocks, and no busy-waiting or polling loops.
- The system stays correct when
Norders are placed and picked up concurrently from many threads.
What to cover in your answer
- Which synchronization primitives you use (locks, condition variables, semaphores, blocking queues) and why.
- The data structures and state model used to track each order.
- How you avoid race conditions and keep the service reasonably fair.
- How shutdown behaves and which edge cases you handle.
Assume a single process with shared memory. No networking is needed.
Hints
Hint 1
Separate two concerns: distributing cooking work to chefs, and letting customers wait for a specific order. Different primitives suit each.
Hint 2
A FIFO blocking queue of order IDs hands each item to exactly one consumer, which gives cook-once for free. Model each order's lifecycle as a small state machine, and do the check-and-transition for pickup inside one critical section.
Hint 3
Never sleep or block on the queue while holding the shared lock. Wait on a condition in a `while` loop, think about pickup arriving before placement, and use a sentinel per chef that is enqueued after all accepted orders so shutdown drains cleanly.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the problem as two separate concerns and give each one the right primitive.
1. Work distribution: cook exactly once
Use an unbounded FIFO blocking queue (queue.Queue in Python, LinkedBlockingQueue in Java) holding order IDs.
placeOrderenqueues the ID once.- Each chef loops on
queue.get(), which blocks without polling. - A blocking queue delivers each element to exactly one consumer, so an order that is enqueued once is cooked once.
- FIFO ordering gives fairness: orders start cooking in the order they were accepted, so none starves.
2. State tracking and handoff: pick up at most once, never early
Keep a map order_id -> record guarded by a single lock. Each record holds:
- the order data,
- a state:
PENDING -> QUEUED -> COOKING -> READY -> PICKED_UP, - a per-order condition variable bound to the shared lock.
Flow:
- A customer calls
pickupOrder, takes the lock, and doeswhile state != READY: cond.wait(). - When a chef finishes, it takes the lock, sets
READY, and callsnotify_allon that order's condition only. - The customer that wakes sees
READY, flips the state toPICKED_UPin the same critical section, and returns the order.
Per-order conditions avoid a thundering herd. A single global condition would wake every waiting customer on every completion, which is O(waiters) wasted wakeups per dish.
Key design details
- Pickup before placement. Create the record lazily in
PENDING. A customer can then start waiting for an order that has not been placed yet, and the later placement fills in the same record. - Do not hold the lock while cooking. The chef takes the lock only to mark
COOKING, releases it, sleeps forcook_time_ms, and retakes it to markREADY. Placements and pickups are never blocked by a slow dish. - Wait in a
whileloop, not anif, to handle spurious wakeups and the case where another thread has already taken the order. - Enqueue under the lock in
placeOrder. Because the queue is unbounded,putnever blocks, so this cannot deadlock. It also guarantees that all accepted orders are ordered before any shutdown sentinel.
Why the guarantees hold
- No early pickup:
READYis set only by a chef, only after the cook time has elapsed, andpickupOrderreturns only after observingREADYunder the lock. - Cooked once:
placeOrderrejects an ID whose record is notPENDING, so each ID is enqueued at most once. The queue gives it to one chef. - Picked up at most once: the
READYcheck and the move toPICKED_UPhappen atomically. If several customers wait on the same order, exactly one wins. The rest wake, seePICKED_UP, and fail with an "already picked up" error. - No deadlock: there is one lock, and no thread blocks on the queue or sleeps while holding it.
Condition.waitreleases the lock atomically while waiting. - No busy-waiting: chefs block in
get, customers block inwait.
Shutdown
- Under the lock, set
accepting = Falseso no new orders come in. - Still under the lock, enqueue one sentinel per chef. Since every accepted order was enqueued earlier under the same lock, all real work sits ahead of the sentinels, so chefs drain everything before exiting.
- Join the chef threads.
- Set
stopped = Trueandnotify_allon every record so customers waiting on an order that will never be cooked get an error rather than hanging forever.
Orders already READY can still be picked up after shutdown. Calling shutdown twice is a no-op.
Complexity
placeOrder: O(1).pickupOrder: O(1) work apart from blocking time.- Makespan with
Cchefs: roughlysum(cook_time) / C, bounded below by the longest single dish. - Space: O(N) for records, plus O(C) threads. Records are kept after pickup to detect duplicate placement or pickup. A long-running system would evict them after a TTL.
Sketch (Python)
class Kitchen:
_SENTINEL = object()
def __init__(self):
self._lock = threading.Lock()
self._records = {}
self._q = queue.Queue()
self._chefs = []
self._accepting = True
self._stopped = False
def _rec(self, oid): # caller holds the lock
r = self._records.get(oid)
if r is None:
r = Record(self._lock) # state=PENDING, cond=Condition(lock)
self._records[oid] = r
return r
def place_order(self, oid, name, ms):
if ms <= 0: raise ValueError
with self._lock:
if not self._accepting: raise RuntimeError
r = self._rec(oid)
if r.state is not State.PENDING: raise ValueError("duplicate")
r.order, r.state = Order(oid, name, ms), State.QUEUED
self._q.put(oid)
def _chef(self):
while True:
oid = self._q.get()
if oid is self._SENTINEL: return
with self._lock:
r = self._records[oid]; r.state = State.COOKING
time.sleep(r.order.cook_time_ms / 1000)
with self._lock:
r.state = State.READY
r.cond.notify_all()
def pickup_order(self, oid, timeout=None):
with self._lock:
r = self._rec(oid)
ok = r.cond.wait_for(
lambda: r.state in (State.READY, State.PICKED_UP) or self._stopped,
timeout)
if not ok: raise TimeoutError
if r.state is State.PICKED_UP: raise RuntimeError("already picked up")
if r.state is not State.READY: raise RuntimeError("kitchen stopped")
r.state = State.PICKED_UP
r.cond.notify_all() # wake losers so they fail fast
return r.order
start_kitchen spawns the chef threads (once only), and shutdown follows the steps above.
Edge cases to mention
- Duplicate
order_idon placement: raise, never cook twice. - Pickup of an order never placed: blocks, with an optional timeout, and errors after shutdown.
- Two customers collecting the same order: one succeeds, the other gets an error.
cook_time_ms <= 0ornum_chefs <= 0: reject.- Orders placed before
startKitchen: they wait in the queue until chefs start. startKitchencalled twice or after shutdown: reject.- Shutdown with no chefs started: queued orders never cook, and their waiters are released with an error.
Common mistakes
- Sleeping while holding the lock, which serializes all chefs and blocks pickups.
- Using
ifinstead ofwhilearoundwait. - Checking
READYand settingPICKED_UPin separate critical sections, which allows a double pickup. - Using one global condition and
notify_all, causing a thundering herd. - Enqueuing sentinels without ordering them after accepted orders, which drops work on shutdown.
- Using a
sleep-and-recheck loop to wait for readiness instead of a condition variable.
Trade-offs
- A bounded queue adds backpressure but means
putcan block, so it must not be called under the lock, which then needs extra care to keep the sentinel ordering. - A priority queue (shortest cook time first) lowers average wait but can starve long dishes. FIFO is the simple, fair default.
- Per-order conditions cost memory per record, but they give targeted wakeups, which matters with many concurrent waiters.