Deadline-Aware Task Dispatcher with Dependencies and Leases
System DesignModel answerLast updated
Build a task dispatcher that serves the earliest-deadline runnable task, handles prerequisites, and grows into a fault-tolerant multi-worker service.
You are asked to design a dispatcher for a stream of tasks. It accepts work continuously and hands it out to workers, honoring both deadlines and dependencies. The design is built up in three stages, and a strong answer keeps one coherent design across all of them.
Each task has:
id: a unique identifierdeadline: an orderable value, such as an epoch timestampprerequisites: a list of task ids that must finish first (empty in the first two stages)
Rules
- Among tasks that are runnable (every prerequisite finished), the earliest deadline goes first. Ties are broken deterministically, for example by
id. - Running a task at-least-once is acceptable, so workers must be idempotent. However, one task must never be leased to two workers at the same time.
- Stages 1 and 2 may assume a single-process, single-threaded implementation. Concurrency, persistence and distribution only appear in stage 3.
- Pseudocode or Python/Go is fine, but data structures and complexities must be explicit.
Questions you may want to raise first: Can a task reference a prerequisite that has not been submitted yet? Is there one global dependency graph or many independent workflows? What happens to dependents if a prerequisite fails permanently? Is a deadline a hard SLA or just a priority hint? What are the expected ingest rates and live-task counts?
Stage 1: Deadline ordering
Implement a Scheduler with:
add_tasks(tasks): accepts a single task or a batch.consume_task(): removes and returns the task with the earliest deadline, or a sentinel (Noneor"no task") when nothing is available.
State the time complexity of each operation and the memory cost.
Stage 2: Prerequisites
Tasks now carry prerequisites. Add complete_task(id) so the scheduler learns when a task finishes. consume_task() must return the earliest-deadline task among runnable ones only. Explain how this stays efficient as tasks complete and how it relates to a topological ordering.
Stage 3: Turn it into a service
Extend the design so that it:
- Accepts batches or a continuous stream of tasks.
- Validates input: malformed tasks, duplicate ids, self-dependencies, and prerequisites that can never resolve.
- Rejects submissions that would create a dependency cycle.
- Dispatches only runnable tasks, earliest deadline first.
- Supports many concurrent workers without double assignment.
- Recovers from worker crashes and retries (a task held by a dead worker must become runnable again).
- Scales to large volumes with bursty ingest and offers useful monitoring.
Cover the API, storage model, scheduling logic, DAG validation (batch versus streaming), concurrency control, fault tolerance and scaling.
Hints
Hint 1
For stage 1, you only ever need the minimum element repeatedly. Put a tuple like (deadline, id) into the ordering key so ties are deterministic, and keep a side dictionary for lookup and cancel.
Hint 2
For stage 2, store for each task a count of unfinished prerequisites plus a reverse map from a task to the tasks that depend on it. A task enters the heap exactly when its count reaches zero. This is Kahn's algorithm with a heap as the frontier.
Hint 3
For stage 3, model a task state machine (WAITING, RUNNABLE, LEASED, COMPLETED, FAILED) and make the RUNNABLE to LEASED transition atomic in the store, for example with a row-locking query that skips locked rows or a single atomic script. Give every lease an expiry so a sweeper can return abandoned tasks to RUNNABLE.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
One idea runs through all three stages: a priority queue over the "frontier" of tasks that are ready to run, fed by a dependency counter that releases tasks as their prerequisites finish. Stage 3 externalizes each in-memory piece into durable, concurrent infrastructure.
Stage 1: Deadline ordering
Use a binary min-heap keyed by (deadline, id). Including id in the key gives a total, deterministic order instead of relying on undefined heap tie behavior.
add_tasks:O(log n)per task. A batch ofktasks costsO(k log n), orO(n + k)if you heapify a large batch into an empty heap.consume_task:O(log n). ReturnNonewhen the heap is empty.- Memory:
O(n).
A heap cannot find an arbitrary element, so keep a dict id -> task. It supports duplicate detection now and cancel (via lazy deletion) later.
Stage 2: Dependencies
State per task:
remaining[id]: number of prerequisites not yet completed.dependents[p]: list of tasks that listpas a prerequisite (reverse adjacency).done: set of completed ids.
import heapq
class Scheduler:
def __init__(self):
self.tasks = {}
self.remaining = {}
self.dependents = {}
self.done = set()
self.heap = []
def add_tasks(self, batch):
if not isinstance(batch, list):
batch = [batch]
for t in batch:
if t.id in self.tasks:
raise ValueError("duplicate id")
prereqs = set(t.prerequisites) # collapse duplicate edges
if t.id in prereqs:
raise ValueError("self dependency")
self.tasks[t.id] = t
pending = [p for p in prereqs if p not in self.done]
self.remaining[t.id] = len(pending)
for p in pending:
self.dependents.setdefault(p, []).append(t.id)
if not pending:
heapq.heappush(self.heap, (t.deadline, t.id))
def consume_task(self):
if not self.heap:
return None
_, tid = heapq.heappop(self.heap)
return self.tasks[tid]
def complete_task(self, tid):
self.done.add(tid)
for d in self.dependents.pop(tid, []):
self.remaining[d] -= 1
if self.remaining[d] == 0:
t = self.tasks[d]
heapq.heappush(self.heap, (t.deadline, d))
Here, forward references simply wait: the dependent is registered under a prerequisite that has not arrived yet, and unblocks when that id completes. If you prefer to reject unknown prerequisites, check p in self.tasks or p in self.done at insert time. Whichever contract you choose must be applied consistently.
Complexity: a completion costs O(d log n) where d is the number of dependents. Across the whole run, each edge is handled once, giving O((V + E) log V) total. This is Kahn's algorithm: the runnable frontier is the set of zero-indegree nodes, and the heap orders it by deadline instead of FIFO. Tasks that never reach zero are either waiting on missing prerequisites or sit on a cycle.
Edge cases: a task whose prerequisites are all already done goes straight into the heap; duplicate edges are collapsed with a set so the counter is accurate.
Stage 3: The service
State machine
WAITING -> RUNNABLE -> LEASED -> COMPLETED, with LEASED -> RUNNABLE on lease expiry or retry, and LEASED -> FAILED after the attempt cap. Mapping to the earlier code: WAITING is "remaining > 0", RUNNABLE is "in the heap", and COMPLETED triggers the dependents decrement.
API
POST /tasks:batch(idempotent by task id or a client batch key)POST /lease?worker=w&n=kreturns tasks with alease_id(fence token) and expiryPOST /tasks/{id}/heartbeatextends the leasePOST /tasks/{id}/completeand/fail, both carrying the fence token
Storage
tasks(id, workflow_id, deadline, state, attempts, lease_owner, lease_expiry, fence, remaining)edges(prereq_id, dependent_id)indexed onprereq_id- Runnable index: either a partial SQL index on
(deadline, id) WHERE state='RUNNABLE', or a Redis sorted set scored by deadline - An ingest log (Kafka or similar) to absorb bursts and permit replay
Atomic leasing
Double assignment is prevented by a single atomic claim. In SQL:
UPDATE tasks SET state='LEASED', lease_owner=:w,
lease_expiry=now()+interval '30 s', fence=fence+1
WHERE id IN (
SELECT id FROM tasks WHERE state='RUNNABLE'
ORDER BY deadline, id
LIMIT :k FOR UPDATE SKIP LOCKED)
RETURNING *;
SKIP LOCKED lets concurrent workers take disjoint rows without blocking. In Redis, use a Lua script that pops from the sorted set and writes the lease in one step. Completion decrements dependents in the same transaction as marking the task complete, so a crash cannot leave the graph half updated.
Fault tolerance
- A sweeper returns tasks with
lease_expiry < now()to RUNNABLE and incrementsattempts. - Retries use exponential backoff with jitter and an attempt cap, after which the task goes to FAILED or a dead-letter queue. Policy for dependents (cancel the subtree versus hold) should be decided up front.
- Completion and failure calls must present the current fence token, so a zombie worker whose lease expired cannot overwrite newer state. Combined with idempotent workers, this gives safe at-least-once execution.
- On restart, all state is rebuilt from the durable store; the in-memory heap is only a cache.
DAG validation
- Batch per workflow: require the whole DAG at submit time and run Kahn's algorithm or DFS in
O(V + E). Reject on a cycle or an unresolvable reference. - Streaming edge-at-a-time: each new edge needs a reachability check (is the new task reachable from its prerequisites?), which can be expensive on large graphs. Pragmatic restrictions help: require prerequisites to already exist (new nodes can then only point backwards, so no cycle is possible), or require a complete DAG per workflow before it is activated.
- Always reject self-dependencies and duplicate ids at the door.
Scaling and observability
- Partition by
workflow_idso every dependency edge lives on one shard, with a runnable queue per shard. Workers lease from multiple shards. A single enormous workflow is the hard case and may need a restriction on size. - Separate ingest, scheduling/lease, and completion paths so bursts on one do not starve the others.
- Metrics: runnable backlog and age of oldest runnable task, deadline-miss rate, lease expirations and retry counts, per-state task counts, lease latency, sweeper lag, dead-letter volume. An invariant check for "tasks with more than one active lease" should always read zero.
Common mistakes
- Leaving tie-breaking to the heap implementation.
- Scanning the graph on every completion instead of using counters and reverse edges.
- Forgetting duplicate edges, which corrupt the counter.
- Check-then-update leasing without an atomic claim.
- No lease expiry, so a crashed worker strands tasks forever.
- Accepting stale completions without a fence token.
- Running a full cycle check on every streaming insert without acknowledging its cost.