KatInterview

Build a Keyed Task Dispatcher with Global Concurrency Cap

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythread-safetyexecutor

Last 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 submit at 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 maxConcurrent tasks may be running across all keys at any instant.
  • submit returns 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

  1. For concurrent submits that share a key, what exactly defines "submission order"? State the point at which order is fixed.
  2. Which data structures do you keep, and what invariants do they maintain?
  3. How do you pick the next key to run without scanning every queue, and without running user code under your internal lock?
  4. How do you guarantee a concurrency slot is freed and progress continues when a task throws?
  5. 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.