KatInterview

Hardening a Multithreaded Task Dispatcher with Rate Limiting

System DesignModel answer
MediumModel answerSystem Designconcurrencydebuggingrate-limiting

Last updated

Review a flawed Python task dispatcher for races, deadlocks and limiter bugs, then write tests, derive makespan and success-rate formulas, and design telemetry.

Scenario

You inherit a Python dispatcher that executes many independent tasks in parallel. You are given the source (not reproduced here) and asked to review it, repair it, and reason about its behavior. Assume the following about its design.

  • Every task has an ID, a callable, a retry budget max_retries, and ends in exactly one terminal state: succeeded or failed.
  • The dispatcher tracks tasks in four collections: pending, running, completed, failed.
  • Work is run by a pool of at most W worker threads (or in-flight async tasks). This limit is independent of the start-rate limit.
  • A limiter permits at most R task starts per second. Tasks already running do not count against it.
  • A task gets up to max_retries + 1 attempts. A transient failure puts it back in the queue; once retries are exhausted it moves to failed.
  • Per-task metrics are recorded: start time, finish time, latency, retry count, final status.
  • Task callables are untrusted user code. They may block, sleep, raise, or run for an unpredictable time.
  • Assume CPython. The GIL makes single bytecodes atomic but not multi-step read-modify-write or check-then-act sequences.
  • "Run a batch" means submitting N tasks and waiting until every one is terminal.

Before answering, state which clarifying questions you would ask (threads vs. asyncio, strict vs. burst limiter, cancellation semantics, definition of failure, idempotency of retries, scale).

Tasks

  1. Concurrency defects. List the state invariants the dispatcher must preserve. Then identify the data races, deadlocks and lock-contention hot spots you would look for. For each, describe the interleaving that triggers it, the corruption you would observe, and the fix.
  2. Rate limiter. Decide whether a typical limiter implementation really enforces "at most R starts per second" when many workers call it at once. Fix it if needed, and state exactly which semantics you provide (strict sliding window vs. token bucket) and which clock you use.
  3. Tests. Describe tests for success, permanent failure, retry, cancellation and high concurrency. Show how you force bad interleavings and which tests would fail on the original code.
  4. Time and success rate. Define the total batch time and the final success rate from the recorded metrics, and give a theoretical lower bound on batch time in terms of N, R, W and the task durations.
  5. Instrumentation. Say which logs, metrics and traces you would add so the next concurrency bug can be diagnosed from telemetry, and how you would tell a genuine task failure from a dispatcher bug.

Hints

Hint 1

Write the invariants first (for example: a task is in exactly one set at any time; it starts at most once per attempt; terminal states are final). Then frame every bug as a violation of one of them.

Hint 2

Look for check-then-act sequences (`if task in pending: pending.remove(task); run`) and unlocked `counter += 1` updates. Also look for user callables invoked while a lock is held, and two code paths that take two locks in opposite orders.

Hint 3

For the lower bound, take the maximum of three independent floors: total work divided by parallelism, the longest single task, and the start-rate floor. For the limiter, use a monotonic clock, one critical section for decide-and-record, and sleep outside the lock.