Build a Multi-Key Task Queue with Ordering and Concurrency Control
Data Structure DesignModel answerLast updated
Create a thread-safe task scheduler that runs tasks sequentially per key while respecting a global worker limit and capacity bound.
Problem
Build a thread-safe task scheduler called OrderedKeyExecutor that manages asynchronous task execution with the following requirements:
-
Sequential per-key execution: Tasks submitted with the same key must run one at a time, in submission order. No two tasks for the same key can execute simultaneously.
-
Limited parallel execution: The scheduler can run at most
max_workerstasks concurrently across all keys combined. -
Capacity enforcement: The total number of waiting tasks (not yet started) cannot exceed
max_capacity. New submissions beyond this limit must fail immediately. -
Cancellation support: Tasks that haven't started yet can be cancelled through their handle.
-
Clean shutdown: The scheduler must support a
shutdown(wait=True, timeout=None)operation that stops accepting new work and optionally waits for running tasks to finish.
API
from typing import Callable, Any, Optional
class TaskRejectedException(Exception):
"""Raised when a task cannot be accepted."""
pass
class TaskHandle:
def result(self, timeout: Optional[float] = None) -> Any:
"""Block until task completes and return its result or raise its exception."""
pass
def cancel(self) -> bool:
"""Try to cancel the task. Returns True only if cancelled before execution."""
pass
class OrderedKeyExecutor:
def __init__(self, max_workers: int = 4, max_capacity: int = 100):
"""Create a scheduler with the given worker and capacity limits."""
pass
def submit(self, key: str, fn: Callable[[], Any]) -> TaskHandle:
"""
Submit a task for the given key.
Raises TaskRejectedException if at capacity or shut down.
"""
pass
def shutdown(self, wait: bool = True, timeout: Optional[float] = None) -> bool:
"""
Stop accepting tasks. If wait=True, block until all work completes or timeout expires.
Returns True if all tasks finished.
"""
pass
Example Usage
scheduler = OrderedKeyExecutor(max_workers=2, max_capacity=10)
# Submit tasks
h1 = scheduler.submit("alice", job_a) # Starts immediately (worker 1)
h2 = scheduler.submit("bob", job_b) # Starts immediately (worker 2)
h3 = scheduler.submit("alice", job_c) # Queued: alice is busy
h4 = scheduler.submit("carol", job_d) # Queued: both workers occupied
# When job_a finishes, job_c runs next (maintaining alice's task order)
Requirements & Edge Cases
- Worker and capacity parameters:
1 <= max_workers <= 64,1 <= max_capacity <= 100,000 - Tasks may throw exceptions; one task's failure must not block others for that key or crash worker threads
- Keys with no pending work should release their internal resources to avoid memory leaks
- All operations must be thread-safe (concurrent submissions, cancellations, result queries)
- Attempting to cancel an already-running or completed task returns
False
Hints
Hint 1
Maintain separate structures for queued work per key, keys currently executing, and keys ready to run
Hint 2
Use a single lock to coordinate state changes and worker threads
Hint 3
When a task finishes, check if that key has more work before releasing it
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is coordinating three constraints: per-key ordering, a global worker limit, and bounded capacity. The solution maintains three synchronized data structures under one lock:
queues: dict[key -> deque[TaskHandle]]stores pending tasks for each key in submission orderrunning_keys: set[key]tracks which keys currently have a task executingready: deque[key]holds keys with pending work that aren't currently running
The critical invariant: a key is in ready if and only if it has queued tasks and isn't running.
Worker threads follow this loop:
- Wait for a key to appear in
ready - Pop the key and its first task, mark the key as running
- Release the lock, execute the task
- Re-acquire the lock, mark the key as no longer running
- If the key still has queued work, append it back to
ready
This design ensures per-key mutual exclusion (a key can't be running and ready simultaneously) while maintaining submission order (each key's deque is FIFO, and only the head is removed).
Data Structures
class OrderedKeyExecutor:
def __init__(self, max_workers: int = 4, max_capacity: int = 100):
self._lock = threading.Lock()
self._work_available = threading.Condition(self._lock)
self._all_done = threading.Condition(self._lock)
self._queues = {} # key -> deque of TaskHandle
self._ready = deque() # keys eligible to run
self._running_keys = set() # keys currently executing
self._pending_count = 0
self._capacity = max_capacity
self._shutdown_flag = False
# Start worker threads
self._workers = [
threading.Thread(target=self._worker_loop, daemon=True)
for _ in range(max_workers)
]
for thread in self._workers:
thread.start()
Submit Logic
def submit(self, key: str, fn: Callable[[], Any]) -> TaskHandle:
with self._lock:
if self._shutdown_flag:
raise TaskRejectedException("scheduler shut down")
if self._pending_count >= self._capacity:
raise TaskRejectedException("capacity limit reached")
handle = TaskHandle(self, key, fn)
# Add to key's queue
if key not in self._queues:
self._queues[key] = deque()
# Key becomes ready only if not already running
if key not in self._running_keys:
self._ready.append(key)
self._work_available.notify()
self._queues[key].append(handle)
self._pending_count += 1
return handle
Capacity is checked atomically with queue insertion. If a key is newly created and isn't running, it's added to ready and a worker is notified.
Worker Loop
def _worker_loop(self):
while True:
with self._lock:
# Wait for work or shutdown
while not self._ready and not self._shutdown_flag:
self._work_available.wait()
if not self._ready:
break # Shutdown with no work remaining
# Claim a key and its next task
key = self._ready.popleft()
task_queue = self._queues[key]
handle = task_queue.popleft()
# Mark key as running
self._running_keys.add(key)
handle._state = RUNNING
self._pending_count -= 1
# Execute task outside the lock
try:
handle._result = handle._fn()
except Exception as e:
handle._exception = e
finally:
handle._state = DONE
handle._done_event.set()
# Release key and potentially re-queue
with self._lock:
self._running_keys.remove(key)
if self._queues[key]:
# More work for this key
self._ready.append(key)
self._work_available.notify()
else:
# Key is idle, clean up
del self._queues[key]
if self._pending_count == 0 and not self._running_keys:
self._all_done.notify_all()
The worker releases the lock during task execution, allowing other workers to dispatch different keys. The finish logic re-queues the key if it has more work, preserving order.
Cancellation
def _cancel_task(self, handle: TaskHandle) -> bool:
with self._lock:
if handle._state != PENDING:
return False
key = handle._key
queue = self._queues[key]
queue.remove(handle) # O(n) search in the deque
if not queue:
del self._queues[key]
if key not in self._running_keys:
self._ready.remove(key)
handle._state = CANCELLED
handle._done_event.set()
self._pending_count -= 1
return True
Cancel removes the task from its key's queue. If the queue becomes empty and the key isn't running, the key is removed from ready.
Shutdown
def shutdown(self, wait: bool = True, timeout: Optional[float] = None) -> bool:
with self._lock:
self._shutdown_flag = True
self._work_available.notify_all()
if not wait:
return True
# Wait for all work to complete
return self._all_done.wait_for(
lambda: self._pending_count == 0 and not self._running_keys,
timeout=timeout
)
Setting the shutdown flag causes workers to exit once ready is empty. If waiting, the method blocks until both pending and running counts reach zero.
Complexity
- Submit: O(1) amortized
- Worker dispatch/finish: O(1) amortized
- Cancel: O(queue length for that key) due to deque.remove
Space usage is O(pending tasks + distinct active keys + max_workers).
Common Mistakes
- Using one lock per key: Creates deadlock risks when managing the global worker pool
- Checking capacity after queueing: Race condition allows exceeding the limit
- Not cleaning up empty key queues: Memory leak as keys accumulate
- Forgetting to re-queue keys with remaining work: Tasks get stuck in queue forever
- Holding the lock during task execution: Serializes all work, defeating the purpose
- Not handling task exceptions: Crashes worker threads and stalls the key
Trade-offs
This design prioritizes correctness and simplicity over maximum throughput. Cancel is O(n) because it eagerly removes tasks; a lazy deletion approach (mark cancelled, skip during dispatch) would be O(1) but complicates capacity accounting and requires careful cleanup logic. For an interview, the eager approach is clearer and easier to verify.