Build a Keyed Task Dispatcher with Global Concurrency Cap
Data Structure DesignModel answerLast updated
Design a component that runs tasks in strict order per key, lets different keys run in parallel up to a global limit, and stays correct under concurrent submits and task failures.
Keyed Task Dispatcher
You are given an existing thread pool. Build a small in-process class that sits on top of it and schedules work by key.
The class is constructed with a maxConcurrent limit and a reference to the thread pool. It exposes one main operation:
submit(key, task)
Required behavior
- Several threads may call
submitat the same time. - Tasks that share a key must run in the order they were submitted, and no two tasks of the same key may ever run at the same moment.
- Tasks with different keys may run in parallel, but no more than
maxConcurrenttasks may be running across all keys at any instant. submitreturns once the task has been queued or scheduled. It never waits for the task to finish.- You do not need to write the thread pool. Assume it accepts work while your component is open, and that every task eventually returns or throws.
- While one key is executing a slow task, no lock may be held, and no pool workers may sit blocked waiting on that key, if other keys could use the free capacity.
What to discuss
- For concurrent submits that share a key, what exactly defines "submission order"? State the point at which order is fixed.
- Which data structures do you keep, and what invariants do they maintain?
- How do you pick the next key to run without scanning every queue, and without running user code under your internal lock?
- How do you guarantee a concurrency slot is freed and progress continues when a task throws?
- How do you clean up idle keys, and what fairness concerns remain?
Also state your assumptions on questions the spec leaves open: whether queues are bounded and how overload would be reported, what a task failure means for later tasks of the same key, and whether shutdown or pool rejection is part of the interface.
Write the implementation in a language of your choice, explain it, and give its complexity.
Hints
Hint 1
Think of each key as a small state machine: idle, queued as ready, or running. Only a key with pending work and no running task should be eligible to start.
Hint 2
Keep a FIFO queue of ready keys, separate from the per-key task queues, so dispatch is O(1) and never scans keys that are blocked or empty.
Hint 3
Do all bookkeeping (queue pushes, counters, state changes) under one short lock, pick the work to start while holding it, and only call the pool or run user code after releasing it. Release the slot in a finally block.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each key as a tiny state machine and keep one scheduler lock that guards only bookkeeping. User code and pool submission happen outside that lock.
State
Map<Key, Deque<Task>> pending: tasks waiting for each key, in FIFO order.Set<Key> active: keys that currently have a task running or a task handed to the pool but not yet finished.Deque<Key> ready: keys that have pending tasks, are not active, and are waiting for a global slot.int running: number of tasks currently holding a global slot.- One
lockprotecting all of the above.
Invariants
- A key is in at most one of:
ready,active, or absent (idle). - A key in
readyhas a non-empty queue. running <= maxConcurrent, andrunning == |active|.- A key's queue is only popped by the dispatcher when the key moves from
readytoactive, so same-key tasks can never overlap.
Ordering definition
The linearization point for a submission is the moment the submitting thread appends the task to the key's queue while holding the lock. Two concurrent submits for the same key are ordered by who acquires the lock first. Submits from a single thread are ordered by program order. This is the strongest guarantee one can sensibly offer, and it should be said explicitly.
Algorithm
submit(key, task)
- Lock.
- Append
tasktopending[key](create the deque if absent). - If the key is neither active nor already in
ready, push it ontoready. - Collect work to launch with
drain()(below). - Unlock, then hand each collected item to the pool.
drain() (called under the lock)
batch = []
while running < maxConcurrent and ready not empty:
k = ready.pollFirst()
t = pending[k].pollFirst()
active.add(k)
running++
batch.add((k, t))
return batch
run(k, t) (executed on a pool worker)
try:
t.run()
catch Throwable e:
log / report e # policy decision, see below
finally:
lock
running--
active.remove(k)
if pending[k] is non-empty: ready.addLast(k) # back of the line: fairness
else: pending.remove(k) # cleanup of idle key
batch = drain()
unlock
launch(batch)
Because completion calls drain(), the freed slot is immediately given to the next ready key, and the same key's next task is chained only after the previous one finished. No worker ever blocks waiting on another key, and no lock is held during t.run().
Sketch in Java
final class KeyedDispatcher {
private final int max;
private final Executor pool;
private final Object lock = new Object();
private final Map<Object, ArrayDeque<Runnable>> pending = new HashMap<>();
private final Set<Object> active = new HashSet<>();
private final ArrayDeque<Object> ready = new ArrayDeque<>();
private int running;
KeyedDispatcher(int max, Executor pool) { this.max = max; this.pool = pool; }
void submit(Object key, Runnable task) {
List<Map.Entry<Object, Runnable>> batch;
synchronized (lock) {
pending.computeIfAbsent(key, k -> new ArrayDeque<>()).addLast(task);
if (!active.contains(key) && !ready.contains(key)) ready.addLast(key);
batch = drain();
}
launch(batch);
}
...
}
In real code, avoid ready.contains (O(n)) by tracking a queued flag per key, for example a small KeyState object holding the deque and a state enum IDLE / READY / ACTIVE. That keeps submit at O(1).
Complexity
submit: O(1) amortized under the lock, plus pool handoff outside it.- Completion: O(1) amortized plus up to the number of freed slots (usually 1).
- Memory: O(pending tasks + keys with pending work).
Design decisions to state
- Task exceptions: the default is to log and continue, so one bad task does not stall the key forever. An alternative is to cancel the key's remaining tasks, but that must be an explicit policy. In either case the slot release must be in
finally. - Bounded queues: add a per-key or global cap and have
submitthrow or return a rejection result when exceeded. Blocking submitters is possible but risks deadlock if a task submits to the same dispatcher. - Pool rejection / shutdown: if the pool throws on handoff, you must undo the bookkeeping (decrement
running, remove fromactive, re-queue or fail the task), otherwise the slot leaks. Aclose()flag checked insubmitmakes shutdown semantics explicit. - Fairness: requeueing a finished key at the back of
readyprevents a busy key from monopolizing slots. Without it, a hot key would chain and starve others. - Idle key cleanup: remove the map entry when the queue empties, otherwise memory grows with the number of distinct keys ever seen.
Common mistakes
- Running the task while holding the lock, which serializes everything.
- One single-thread executor per key, or a worker that blocks waiting for its key's previous task. This wastes threads and can deadlock the pool.
- Releasing the slot only on success, so a throwing task permanently reduces capacity.
- Checking "is key active" and then enqueueing in separate critical sections, which creates a race that either duplicates a key in
readyor loses a wakeup. - Scanning all keys on every completion rather than keeping a ready queue.
- Forgetting that the pool handoff itself can fail.
Possible follow-ups
- Replace the single lock with striped locks per key plus an atomic global semaphore. This reduces contention but makes the ready-queue handoff more delicate.
- Add priorities across keys, or weighted fairness.
- Support futures returned from
submitso callers can observe results or failures.