Crash-Safe Job Dispatcher with Lease Timeouts and Dependency Graphs
Data Structure DesignModel answerLast updated
Build an in-memory job dispatcher where workers hold timed leases, stale workers are fenced off, jobs form a dependency DAG, and you justify the delivery guarantees.
Design and implement a job dispatcher for a compute platform. Clients enqueue jobs. A fleet of workers repeatedly asks for a job, executes it, and reports back. Workers may crash or stall at any time without telling anyone, yet every job must eventually either finish or be recorded as permanently failed.
Jobs may also declare prerequisites. A job may start only after every prerequisite has finished successfully, and the prerequisite relationships must form a directed acyclic graph.
Before coding, state any assumptions you make about the following:
- Whether a job can depend on jobs from earlier submissions, the same submission, or jobs not yet submitted.
- How long a job may run, and whether a worker can extend its hold on a job.
- How many attempts a job gets, and what happens to its downstream jobs when it fails for good.
- Whether side effects must occur exactly once, or whether at-least-once is fine for idempotent jobs.
- Whether the service is purely in-memory for now, with durability discussed afterward.
Part 1: Claim, lease, and report
Implement claim(now) so a worker obtains a runnable job, plus the calls a worker uses to renew its hold and to report success or failure. Requirements:
- A job held by a worker that dies must eventually be given to another worker.
- A slow worker that has already lost its hold must not be able to change the job's state when it finally reports.
- Jobs have a maximum number of attempts, after which they enter a terminal failed state.
- Expired holds should be found efficiently rather than by scanning every job.
Part 2: Dependency graph
Extend the dispatcher so a job becomes runnable only when all prerequisites have succeeded.
- Reject any submission that would introduce a cycle, with an error that is useful to the caller.
- Release downstream jobs as their prerequisites finish.
- Decide and document what happens to downstream jobs when a prerequisite fails permanently.
- Validate unknown and duplicate job IDs.
Part 3: Delivery guarantees
Say whether your dispatcher gives at-most-once, at-least-once, or exactly-once execution. Explain what it would take to get effectively exactly-once outcomes and what that costs.
Expected deliverable: the state machine, the data structures, the core code, the crash and race scenarios you would test, and a discussion of how this would become durable and multi-server.
Hints
Hint 1
Give each job an explicit state (blocked, ready, leased, succeeded, failed) and a monotonically increasing token that changes every time the job is leased. Every report must present the token, and a mismatch means the report is stale.
Hint 2
Keep a min-heap of (lease_expiry, job_id, token) entries and lazily discard entries whose token no longer matches. At the start of each claim, pop all expired entries and requeue or fail those jobs. Track an unmet-prerequisite counter per job and decrement it as prerequisites succeed.
Hint 3
For cycle detection with prerequisites that may already exist, run a DFS or a reachability check from the new job's prerequisites back to the new job before committing, and return the cycle path. For delivery semantics, reason about the window between a worker finishing its side effect and the dispatcher recording the result.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Single in-memory service, with time passed in as
nowso tests are deterministic. - A job may depend only on jobs that already exist. This makes cycles impossible for new jobs, but I still validate on submission and also support batch submission, where a cycle check is needed.
- Fixed lease duration with renewal allowed. Each job has
max_attempts. - When a job fails permanently, all transitive dependents are marked
failedwith reasonupstream_failed. The alternative, leaving them blocked forever, hides the problem. - Jobs are expected to be idempotent.
State machine
blocked --(all prereqs succeeded)--> ready
ready --(claim)------------------> leased
leased --(success, valid token)---> succeeded
leased --(failure/expiry, attempts left)--> ready
leased --(failure/expiry, no attempts)----> failed
blocked/ready --(upstream failed)--> failed
succeeded and failed are terminal. Any report that does not match the current leased state and token is rejected.
Data structures
jobs: dict[id -> Job]withstate,attempts,max_attempts,token,lease_expiry,pending_deps(count),dependents(list).ready: dequeof job IDs (or a priority heap if priorities exist).expiries: min-heapof(expiry, job_id, token).- A global or per-job counter for tokens.
Core code
import heapq
from collections import deque
class Dispatcher:
def __init__(self, lease=30):
self.jobs, self.ready, self.expiries = {}, deque(), []
self.lease, self.next_token = lease, 0
def submit(self, jid, deps=(), max_attempts=3):
if jid in self.jobs: raise ValueError("duplicate id")
for d in deps:
if d not in self.jobs: raise ValueError(f"unknown dep {d}")
if jid in deps: raise ValueError("self-dependency")
pend = 0
for d in deps:
st = self.jobs[d]["state"]
if st == "failed": return self._add_failed(jid, deps, max_attempts)
if st != "succeeded": pend += 1
self.jobs[jid] = dict(state="blocked", attempts=0, max=max_attempts,
token=0, exp=None, pend=pend, dependents=[])
for d in set(deps): self.jobs[d]["dependents"].append(jid)
if pend == 0: self._make_ready(jid)
def _make_ready(self, jid):
self.jobs[jid]["state"] = "ready"; self.ready.append(jid)
def _reap(self, now):
while self.expiries and self.expiries[0][0] <= now:
exp, jid, tok = heapq.heappop(self.expiries)
j = self.jobs[jid]
if j["state"] == "leased" and j["token"] == tok and j["exp"] == exp:
self._retry_or_fail(jid)
def _retry_or_fail(self, jid):
j = self.jobs[jid]
if j["attempts"] >= j["max"]: self._fail(jid)
else: self._make_ready(jid)
def claim(self, now):
self._reap(now)
while self.ready:
jid = self.ready.popleft()
j = self.jobs[jid]
if j["state"] != "ready": continue
self.next_token += 1
j.update(state="leased", token=self.next_token,
exp=now + self.lease, attempts=j["attempts"] + 1)
heapq.heappush(self.expiries, (j["exp"], jid, j["token"]))
return jid, j["token"]
return None
def renew(self, jid, token, now):
j = self.jobs[jid]
if j["state"] != "leased" or j["token"] != token or j["exp"] <= now:
return False
j["exp"] = now + self.lease
heapq.heappush(self.expiries, (j["exp"], jid, token))
return True
def succeed(self, jid, token, now):
self._reap(now)
j = self.jobs[jid]
if j["state"] != "leased" or j["token"] != token: return False
j["state"] = "succeeded"
for c in j["dependents"]:
d = self.jobs[c]
if d["state"] == "blocked":
d["pend"] -= 1
if d["pend"] == 0: self._make_ready(c)
return True
def fail(self, jid, token, now):
self._reap(now)
j = self.jobs[jid]
if j["state"] != "leased" or j["token"] != token: return False
self._retry_or_fail(jid); return True
def _fail(self, jid):
stack = [jid]
while stack:
x = self.jobs[stack.pop()]
if x["state"] in ("failed", "succeeded"): continue
x["state"] = "failed"
stack.extend(x["dependents"])
(_add_failed simply inserts the job directly in the failed state.)
Notes: renewal pushes a new heap entry rather than updating in place, and stale entries are discarded when popped because the expiry or token no longer matches. Each entry is pushed and popped once, so reaping is amortized O(log n).
Cycle detection
If dependencies must already exist, a new job cannot close a cycle. If batch submission or forward references are allowed, add all jobs in the batch to a staging graph and run Kahn's algorithm. If the processed count is less than the node count, the leftover nodes contain a cycle. Run a DFS with a recursion stack on those nodes to extract and report one concrete path such as a -> b -> c -> a. Reject the entire batch atomically. Cost is O(V + E).
Complexity
submit: O(deps).claim: amortized O(log n).succeed: O(dependents). Permanent failure propagation: O(reachable subgraph), each node visited once.
Delivery semantics
The dispatcher gives at-least-once execution. A worker may finish the side effect and then crash or be partitioned before its report arrives; the lease expires and another worker re-runs the job. Choosing at-most-once would mean never reassigning, which violates the liveness requirement.
The fencing token protects the dispatcher's own state: a stale success cannot overwrite a newer attempt. It does not undo side effects the stale worker already performed.
To get effectively exactly-once outcomes:
- Idempotency keys: pass
job_idas a key to downstream systems so repeats are deduplicated. - Fencing at the resource: the downstream store rejects writes carrying a token lower than the highest it has seen.
- Transactional outcome: write the result and the job's completion in the same transaction when both live in one database.
Costs: extra storage for dedup keys, a round trip or coordination at the sink, and the fact that external systems without idempotent or conditional writes (emails, payments via a third party) cannot be made exactly-once by the queue alone.
Persistence and scale
Store jobs in a database with a row per job and an index on (state, lease_expiry). Claiming becomes a conditional update (UPDATE ... WHERE state='ready' ... SKIP LOCKED) that increments the token. Multiple servers then coordinate through the database; clock skew is handled by using database time for leases.
Tests to include
- Worker crashes; job is reclaimed after expiry.
- Stale worker reports success after reassignment; rejected.
- Renewal just before and just after expiry.
- Attempts exhausted leads to failure and downstream propagation.
- Diamond dependency releases the join node only once.
- Cycle, duplicate ID and unknown dependency rejected.
Common mistakes
- Using the job ID alone to validate reports, so stale workers are accepted.
- Scanning all jobs for expired leases.
- Releasing a dependent twice in a diamond graph.
- Leaving dependents of a failed job blocked forever.
- Claiming exactly-once without addressing the report-loss window.