Hardening a Multithreaded Task Dispatcher with Rate Limiting
System DesignModel answerLast 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 + 1attempts. A transient failure puts it back in the queue; once retries are exhausted it moves tofailed. - 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
- 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.
- 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.
- 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.
- 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.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method: invariants first
Write these down before hunting for bugs:
- Single membership. A task is in exactly one of
pending,running,completed,failedat any instant (apart from a brief, lock-protected transition). - Exclusive dispatch. At most one worker runs a given task attempt.
- Terminal finality.
completedandfailedare absorbing: no transitions out. - Bounded attempts. Attempts per task ≤
max_retries + 1; the retry count only increases. - Conservation.
pending + running + completed + failed = Nat every consistent snapshot. - Bounded concurrency and rate. Running tasks ≤ W; starts in any 1-second window ≤ R.
Part 1: defects and fixes
| Defect | Triggering interleaving | Observable result | Fix |
|---|---|---|---|
Check-then-act on pending (peek or in check, then pop) | Two workers both see task T, both start it | Double execution, violates (1) and (2); remove may raise KeyError | Make claim atomic: with lock: task = pending.popleft() plus move to running in the same critical section |
Unsynchronized counters and metrics (retries += 1, completed_count += 1) | Two threads read the same value, both write value+1 | Lost updates; totals do not add up to N, violating (5) | Update under the state lock, or give each task its own object mutated only by its owning worker and aggregate at the end |
Multi-step transition not atomic (running.remove(t) then completed.add(t)) | Observer or canceller runs between the two steps | Task is in no set (or two); breaks (1) and (5) | One method _transition(task, src, dst) under the lock that asserts the source state |
| Callable run under the scheduler lock | A slow or blocking job holds the lock | Whole scheduler stalls; contention hot spot, possible deadlock if the job calls back in | Release the lock before calling user code; reacquire to record the result |
| Two locks taken in different orders (e.g. state lock and metrics lock) | Thread A holds state, wants metrics; thread B holds metrics, wants state | Deadlock | Use a single lock, or a documented global order; never call out while holding either |
| Retry re-enqueue races with completion | A retry is pushed while another path marks the task failed | Task is both queued and terminal; violates (3) | Decide the outcome and perform the transition in one critical section, checking the current state |
| Busy-wait or polling on a shared condition | Workers spin on while not pending | CPU burn, lock contention | Use queue.Queue or threading.Condition with wait/notify |
Contention: a single global lock is fine at hundreds to thousands of tasks as long as the critical sections are a few dictionary or deque operations. At very high scale, shard queues or use a lock-free-ish queue.Queue for dispatch and keep the lock only for state transitions. Measure lock-wait time before sharding.
Retries and idempotency: a retry re-runs user code, so duplicate side effects are possible if the callable is not idempotent. Pass an attempt number or idempotency key to the callable, and document at-least-once semantics.
Part 2: rate limiter
A typical bug is now = time.time(); if now - last_start >= 1/R: last_start = now; return with the read and write in separate steps, or a list of timestamps pruned and appended without a lock. Two workers can both observe a free slot and both start, so the limit is exceeded. Other problems: time.time() can jump with NTP or manual adjustment, < vs <= at the window edge, and sleeping while holding the lock, which serializes every caller.
Fix (strict sliding window): keep a deque of the last R start times, using time.monotonic().
class SlidingWindowLimiter:
def __init__(self, rate, window=1.0):
self.rate, self.window = rate, window
self.starts = collections.deque()
self.lock = threading.Lock()
def acquire(self):
while True:
with self.lock:
now = time.monotonic()
while self.starts and now - self.starts[0] >= self.window:
self.starts.popleft()
if len(self.starts) < self.rate:
self.starts.append(now)
return
wait = self.window - (now - self.starts[0])
time.sleep(wait) # sleep outside the lock
Decide-and-record happens in one critical section, so no more than R starts fall in any window of length 1s. This is strict. A token bucket (capacity C, refill R/s) is cheaper and allows bursts up to C with a long-run rate ≤ R. Pick strict if downstream systems truly cannot take bursts, and state the choice.
Part 3: tests
- Success: N trivial tasks; assert all in
completed,failedempty, each ran once. - Permanent failure: callable always raises with
max_retries=k; assert it ran exactly k+1 times, ends infailed, retry count is k. - Retry: callable fails j < k times then succeeds; assert final state
completedand retry count j. - Cancellation: cancel a pending task, assert it never starts; cancel mid-run per the agreed semantics (cooperative flag) and assert a single terminal state.
- No double execution: 1000 tasks, W=32, each callable increments a per-task counter under its own lock; use a
threading.Barrierso workers hit the claim step together; repeat 50-100 times. Assert every counter equals 1 and the conservation invariant holds. This fails against the check-then-act code. - Rate limit: record start timestamps with the monotonic clock; for the strict design assert that for every start
s_i, the number of starts in[s_i, s_i + 1)is ≤ R. For a bucket, assert burst ≤ C and total starts / elapsed ≲ R. - Deadlock: run under
faulthandler.dump_traceback_lateror a join timeout so a hang fails the test instead of freezing CI. - Stress: inject random sleeps and
sys.setswitchinterval(1e-6)to widen race windows.
Part 4: time and success rate
- Makespan =
max(finish_time) - min(start_time)over tasks that actually started. - Success rate =
succeeded / N. Tasks that failed then succeeded on retry count as successes (report mean retries separately). Cancelled tasks: state the convention; I would keep them in the denominator and report them separately.
Lower bound:
makespan >= max( sum(d_i) / W , max(d_i) , (N - 1) / R )
The first term is the parallelism floor, the second the longest single task, the third the start-rate floor (the first start is free; under strict per-second discretization it is about ⌈N/R⌉ − 1 seconds). With retries, d_i should include every attempt. The actual time is usually above this bound because of limiter granularity and uneven task durations.
Part 5: instrumentation
Two layers:
- Per-task structured events with task_id, attempt, state transition, timestamps, worker id, error type and message. This lets you replay one task's life and spot an impossible sequence (two
startedevents for the same attempt). - Aggregates: queue depth, running gauge, counts per state, starts per second (live), lock-wait and lock-hold histograms, limiter wait time, retry rate, latency percentiles, and an invariant-check gauge (
N - sum of states).
Separating causes: starts/s above R or a non-zero invariant gauge points to the scheduler; rising lock-wait with falling throughput points to contention or a blocked critical section; stuck running count with idle workers suggests a deadlock or lost wakeup. A spike in one callable's error_type with healthy scheduler gauges points to business logic. Add a watchdog that dumps all thread stacks if no transition happens for a set time.
Common mistakes
- Fixing symptoms with more locks rather than defining the invariants.
- Calling user code under a lock, or sleeping inside the limiter lock.
- Using
time.time()for rate limiting. - Tests that only cover the happy path, or race tests that pass by luck without barriers or repetition.
- Ignoring that retries imply at-least-once execution.