Thread-Safe Dependency Job Scheduler and Status Tracker
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement a thread-safe JobTracker class that coordinates background tasks connected by prerequisite dependencies. External worker threads pull runnable jobs from the tracker and report back whether each job succeeded or failed.
Each registered job occupies one of six status constants:
PENDING = "PENDING"— waiting on at least one unfinished prerequisite.READY = "READY"— every prerequisite has succeeded; waiting in queue to be claimed.RUNNING = "RUNNING"— claimed by a worker; completion has not been reported yet.SUCCEEDED = "SUCCEEDED"— finished without error.FAILED = "FAILED"— ran and reported a failure.UPSTREAM_FAILED = "UPSTREAM_FAILED"— blocked permanently because a direct or transitive prerequisite failed.
Implement the following methods on JobTracker:
submit(job_id: str, dependencies: List[str]) -> str- Register a unique
job_idalongside the list of prerequisite job IDs that must finish withSUCCEEDEDbeforejob_idcan run, returningjob_id's initial status (READY,PENDING, orUPSTREAM_FAILED). - Duplicate entries inside
dependenciescount once. - Validate the entire submission before mutating state: raise
ValueError(leaving tracker state completely unchanged) ifjob_idwas already submitted, ifjob_idappears in its owndependencies, or if any prerequisite independencieshas not been submitted yet. (Requiring prerequisites to exist beforehand guarantees the graph remains acyclic.) - If any prerequisite is already
FAILEDorUPSTREAM_FAILED,job_idimmediately entersUPSTREAM_FAILED. Otherwise, if all prerequisites are alreadySUCCEEDED(including an emptydependencieslist),job_idstarts inREADYand enters the runnable FIFO queue; otherwise it starts inPENDING.
- Register a unique
get_status(job_id: str) -> str- Return the current status string of
job_id, or raiseKeyErrorifjob_idis unknown.
- Return the current status string of
claim() -> Optional[str]- Atomically remove the job that has been
READYthe longest (FIFO order of becomingREADY), transition its status toRUNNING, and return itsjob_id. ReturnNonewhen noREADYjob is available. Two concurrentclaim()calls must never return the same job.
- Atomically remove the job that has been
mark_succeeded(job_id: str) -> None- Transition a currently
RUNNINGjob toSUCCEEDED(raisingValueErrorwith no state changes ifjob_idis unknown or notRUNNING). AnyPENDINGdependent whose last remaining prerequisite just succeeded immediately becomesREADY.
- Transition a currently
mark_failed(job_id: str) -> None- Transition a currently
RUNNINGjob toFAILED(raisingValueErrorwith no state changes ifjob_idis unknown or notRUNNING). Immediately transition every downstreamPENDINGjob that depends onjob_iddirectly or transitively toUPSTREAM_FAILED.
- Transition a currently
Examples
Example 1
Input:
t = JobTracker()
t.submit("fetch", []) -> "READY"
t.submit("clean", ["fetch"]) -> "PENDING"
t.submit("enrich", ["fetch"]) -> "PENDING"
t.submit("publish", ["clean", "enrich"]) -> "PENDING"
t.claim() -> "fetch"
t.get_status("fetch") -> "RUNNING"
t.claim() -> None
t.mark_succeeded("fetch")
t.get_status("clean"), t.get_status("enrich"), t.get_status("publish")
-> ("READY", "READY", "PENDING")
t.claim() -> "clean"
t.mark_succeeded("clean")
t.get_status("publish") -> "PENDING"
t.claim() -> "enrich"
t.mark_succeeded("enrich")
t.get_status("publish") -> "READY"
t.claim() -> "publish"
t.mark_succeeded("publish")
t.get_status("publish") -> "SUCCEEDED"
Explanation: "fetch" has zero prerequisites so it starts READY right away. Completing "fetch" unlocks both "clean" and "enrich" in FIFO order, while "publish" waits in PENDING until both "clean" and "enrich" report SUCCEEDED.
Example 2
Input:
t = JobTracker()
t.submit("schema", []) -> "READY"
t.submit("seed", []) -> "READY"
t.submit("migrate", ["schema"]) -> "PENDING"
t.submit("verify", ["migrate", "seed"]) -> "PENDING"
t.submit("backup", ["seed"]) -> "PENDING"
t.claim() -> "schema"
t.mark_failed("schema")
(t.get_status("schema"), t.get_status("migrate"),
t.get_status("verify"), t.get_status("backup"))
-> ("FAILED", "UPSTREAM_FAILED", "UPSTREAM_FAILED", "PENDING")
t.claim() -> "seed"
t.mark_succeeded("seed")
t.get_status("backup"), t.get_status("verify")
-> ("READY", "UPSTREAM_FAILED")
t.submit("report", ["verify"]) -> "UPSTREAM_FAILED"
t.claim() -> "backup"
t.mark_succeeded("backup")
t.claim() -> None
Explanation: When "schema" fails, the failure cascades through "migrate" to "verify", marking both UPSTREAM_FAILED. Unrelated jobs on "seed" ("backup") continue unaffected, "verify" stays UPSTREAM_FAILED even after "seed" succeeds, and a newly submitted job "report" depending on "verify" starts directly in UPSTREAM_FAILED.
Constraints
- Job IDs are arbitrary unique strings;
dependenciesmay contain repeated IDs. - All public methods (
submit,get_status,claim,mark_succeeded,mark_failed) must be thread-safe when invoked concurrently by multiple worker threads. - Dependency chains can be tens of thousands of jobs deep (avoid unbounded call-stack recursion during cascades) and total graph operations across
Vjobs andEedges should run inO(V + E)time rather than rescanning allPENDINGjobs on every completion.
Step-by-step walkthrough
Clarify the rules and API
Open-ended scheduler design questions leave several policy decisions up for discussion, and each decision shapes the data structures. Let's state our contract clearly up front:
- External workers pull jobs rather than the tracker executing code itself. Workers call
claim()to take the oldest runnable job and later callmark_succeeded(job_id)ormark_failed(job_id). Keeping job execution outside the tracker makes the class fast, easy to test deterministically, and usable whether workers are threads, processes, or remote machines. - Every listed dependency must already be submitted.
submitraisesValueErrorfor a duplicate job ID, a job that depends on itself, or an unknown dependency ID. This rule gives us a huge structural guarantee for free: every dependency edge points strictly backward in time to an older job, so a dependency cycle can never form. The jobs always form a directed acyclic graph (DAG) — a network of one-way dependencies with no loops. - Failures cascade downstream. If job
"fetch"fails, any job that depends on"fetch"(directly or indirectly) can never succeed. Leaving those downstream jobs inPENDINGwould force callers to wait forever, so we immediately transition all of them toUPSTREAM_FAILED. - Thread safety. Every public method must be safe when multiple worker threads call the tracker concurrently.
That gives us a clean, six-method interface:
class JobTracker: def __init__(self) -> None: ... def submit(self, job_id: str, dependencies: list) -> str: ... def get_status(self, job_id: str) -> str: ... def claim(self): ... # returns oldest READY job_id (now RUNNING), or None def mark_succeeded(self, job_id: str) -> None: ... def mark_failed(self, job_id: str) -> None: ...- External workers pull jobs rather than the tracker executing code itself. Workers call
Map out the job lifecycle state machine
Design the lifecycle table first so every allowed transition is explicit before coding any methods. A state machine is simply a fixed set of statuses paired with the exact transitions allowed between them; a terminal state is a final status that can never change again.
Status Meaning Triggering event --------------- --------------------------------------------- --------------------------------------- PENDING Waiting on >= 1 unfinished dependency Last dependency succeeds -> READY Any dependency fails -> UPSTREAM_FAILED READY All dependencies succeeded; waiting in queue Worker calls claim() -> RUNNING RUNNING Claimed by a worker; outcome not reported yet mark_succeeded() -> SUCCEEDED mark_failed() -> FAILED SUCCEEDED Terminal: ran and finished cleanly (none) FAILED Terminal: ran and reported an error (none) UPSTREAM_FAILED Terminal: blocked forever by a failed ancestor (none)Two rules jump right out of this table and simplify every method we write:
- Only
PENDINGjobs ever react to another job finishing. AREADYorRUNNINGjob already had all of its dependencies reachSUCCEEDED, and terminal states never change. - Only
RUNNINGjobs can be marked succeeded or failed. Rejecting reports onPENDING,READY, terminal, or unknown jobs catches buggy workers that report results twice or report a job they never claimed.
- Only
Why rescanning every waiting job is too slow
A beginner-friendly first attempt stores each job's list of dependencies and, whenever any job finishes, scans all
PENDINGjobs from scratch to see which ones now have every dependencySUCCEEDED:def find_newly_ready_by_rescanning(status, deps_by_job): newly_ready = [] for job_id, job_deps in deps_by_job.items(): if status[job_id] != "PENDING": continue all_succeeded = True for dep in job_deps: if status[dep] != "SUCCEEDED": all_succeeded = False break if all_succeeded: newly_ready.append(job_id) return newly_readyThis is easy to verify, so it makes a great test oracle! However, if we have
V = 100,000jobs with3dependencies each (E = 300,000edges), finishing a single job scans up to300,000edges. Across all100,000completions, that adds up to roughly3 × 10^10checks. Almost all of that work is wasted, because finishing"fetch"can only ever affect the handful of downstream jobs that actually list"fetch"as a prerequisite.Key idea: unmet-dependency counters and reverse edges
Instead of asking "Are all of my dependencies done yet?" across every job, flip the arrows around and maintain two small pieces of bookkeeping per job:
_dependents[job]: the reverse edges — a list of downstream jobs that listjobas a dependency._waiting_on[job]: an integer count of how many distinct dependencies ofjobhave not reachedSUCCEEDEDyet.
Forward view (who I wait on): clean -> [fetch] enrich -> [fetch] publish -> [clean, enrich] Stored bookkeeping: _dependents (who waits on me): fetch -> [clean, enrich] clean -> [publish] enrich -> [publish] _waiting_on (unmet count): fetch: 0 (READY) clean: 1 enrich: 1 publish: 2Now look at how cheap each completion becomes:
- When
jobsucceeds: loop only over_dependents[job]and subtract1from eachPENDINGchild's_waiting_oncount. The exact moment a child's count hits0, all of its dependencies have succeeded, so we move it toREADYand push it onto the back of a FIFO queue (collections.deque, first-in, first-out). This is Kahn's algorithm for topological sorting, driven incrementally as workers report back. - When
jobfails: walk_dependents[job]transitively (children, grandchildren, and so on), marking everyPENDINGjobUPSTREAM_FAILED.
Because each job reaches a terminal state at most once, its
_dependentslist is traversed at most once over the entire lifetime of the tracker. Total graph work across all operations drops from quadratic toO(V + E).Code initialization and job submission
Inside
submit(job_id, dependencies), the order of checks matters:- Validate everything before touching state. Check for a duplicate
job_id, a self-dependency, or an unknown dependency across the entire list first. If the 3rd dependency in["failed_job", "ok_job", "unknown_job"]does not exist,submitmust raiseValueErrorand leave every dictionary untouched rather than returningUPSTREAM_FAILEDearly on the 1st item. - Deduplicate
dependencies. If a caller passes["fetch", "fetch"],job_idonly waits on one real job"fetch". Deduplicating ensures_waiting_on[job_id]increments once and_dependents["fetch"]recordsjob_idonce, keeping the counter and reverse edges in lockstep. - Handle dependencies that already finished:
- If any dependency is already
FAILEDorUPSTREAM_FAILED, the new job starts immediately inUPSTREAM_FAILED. - If a dependency is already
SUCCEEDED, do not incrementunfinishedand do not add a reverse edge (because"fetch"has already finished and will never callmark_succeeded("fetch")again). - Otherwise (
PENDING,READY, orRUNNING), addjob_idto_dependents[dep]and incrementunfinished.
- If any dependency is already
from typing import Dict, List, Optional from collections import deque import threading PENDING = "PENDING" # waiting for at least one dependency READY = "READY" # every dependency succeeded; waiting for a worker RUNNING = "RUNNING" # handed to a worker, result not reported yet SUCCEEDED = "SUCCEEDED" FAILED = "FAILED" UPSTREAM_FAILED = "UPSTREAM_FAILED" # a direct or indirect dependency failed; it will never run class JobTracker: def __init__(self) -> None: # Single non-reentrant mutex guarding all tracker dictionaries and the ready queue. self._lock = threading.Lock() # _status: job_id -> status string, e.g. {"fetch": "RUNNING", "clean": "PENDING"} self._status: Dict[str, str] = {} # _waiting_on: PENDING job_id -> count of distinct dependencies not yet SUCCEEDED, e.g. {"publish": 2} self._waiting_on: Dict[str, int] = {} # _dependents: reverse edges mapping job_id -> downstream job_ids waiting on it, e.g. {"fetch": ["clean", "enrich"]} self._dependents: Dict[str, List[str]] = {} # _ready: FIFO queue of READY job_ids ordered from oldest ready to newest ready self._ready = deque() def submit(self, job_id: str, dependencies: List[str]) -> str: with self._lock: # Phase 1: Validate everything before mutating state so invalid calls have zero side effects. if job_id in self._status: raise ValueError(f"job {job_id!r} was already submitted") # Deduplicate dependencies while preserving order so ["fetch", "fetch"] increments the counter once # and registers only one reverse edge in _dependents["fetch"]. unique_deps: List[str] = [] seen = set() for dep in dependencies: if dep == job_id: raise ValueError(f"job {job_id!r} depends on itself") if dep not in self._status: raise ValueError(f"dependency {dep!r} has not been submitted") if dep not in seen: seen.add(dep) unique_deps.append(dep) # Initialize reverse-edge list so later jobs can safely depend on this job. self._dependents[job_id] = [] # Phase 2: If any dependency has already failed, this job can never run. for dep in unique_deps: dep_status = self._status[dep] if dep_status == FAILED or dep_status == UPSTREAM_FAILED: self._status[job_id] = UPSTREAM_FAILED self._waiting_on[job_id] = 0 return UPSTREAM_FAILED # Phase 3: Link only dependencies that have not SUCCEEDED yet; already-SUCCEEDED # dependencies will never fire another completion event. self._status[job_id] = PENDING unfinished = 0 for dep in unique_deps: if self._status[dep] != SUCCEEDED: self._dependents[dep].append(job_id) unfinished += 1 # Phase 4: A job with zero unmet dependencies becomes READY right away. self._waiting_on[job_id] = unfinished if unfinished == 0: self._make_ready(job_id) return self._status[job_id] def get_status(self, job_id: str) -> str: with self._lock: return self._status[job_id] def _make_ready(self, job_id: str) -> None: # Caller must already hold self._lock (threading.Lock is not reentrant). self._status[job_id] = READY self._ready.append(job_id)- Validate everything before touching state. Check for a duplicate
Code worker claiming, success, and failure cascades
Now let's implement the three worker-facing operations:
claim()checks_ready. If empty, it returnsNone. Otherwise it pops from the left (popleft(), the job that becameREADYearliest) and flips its status toRUNNINGin the same locked step.mark_succeeded(job_id)uses_finishto verifyjob_idis currentlyRUNNINGand set it toSUCCEEDED. Then it visits each child in_dependents[job_id]. Notice the guardif self._status[child] == PENDING:: in Example 2,"verify"depended on both"migrate"and"seed"; once"migrate"failed upstream,"verify"becameUPSTREAM_FAILEDand must stayUPSTREAM_FAILEDwhen"seed"later succeeds!mark_failed(job_id)verifiesRUNNING, setsFAILED, and cascadesUPSTREAM_FAILEDthrough all downstream jobs. We use an explicit Pythonlistas a stack rather than recursion because a linear chain of10,000dependent jobs would blow past Python's ~1,000-frame recursion limit. Checkingif self._status[child] == PENDING:before pushingchild's dependents also prevents duplicate work in diamond graphs: the first path to reachchildflips it toUPSTREAM_FAILED, so any second path seesstatus != PENDINGand stops immediately.
def claim(self) -> Optional[str]: with self._lock: if not self._ready: return None # Pop and mark RUNNING atomically under one lock so two threads never claim the same job. job_id = self._ready.popleft() self._status[job_id] = RUNNING return job_id def mark_succeeded(self, job_id: str) -> None: with self._lock: self._finish(job_id, SUCCEEDED) for child in self._dependents[job_id]: # Skip children that are already UPSTREAM_FAILED from another failed dependency. if self._status[child] == PENDING: self._waiting_on[child] -= 1 if self._waiting_on[child] == 0: self._make_ready(child) def mark_failed(self, job_id: str) -> None: with self._lock: self._finish(job_id, FAILED) # Use an explicit stack instead of recursion so deep chains do not hit Python's recursion limit. stack = list(self._dependents[job_id]) while stack: child = stack.pop() # Checking == PENDING both ignores terminal jobs and ensures diamond nodes # (reachable via two paths) are marked and expanded only once. if self._status[child] == PENDING: self._status[child] = UPSTREAM_FAILED stack.extend(self._dependents[child]) def _finish(self, job_id: str, new_status: str) -> None: # Only a currently RUNNING job may report a completion result; caller holds self._lock. if self._status.get(job_id) != RUNNING: raise ValueError(f"job {job_id!r} is not RUNNING") self._status[job_id] = new_statusTrace Example 1's diamond graph and verify thread safety
Let's trace Example 1's 4-job diamond:
"fetch"has no dependencies,"clean"and"enrich"each depend on"fetch", and"publish"depends on["clean", "enrich"].Event _status _waiting_on _ready ------------------------- --------------------------------------------------------- ---------------------------- ----------------- submit all 4 jobs fetch:READY, clean:PENDING, enrich:PENDING, publish:PENDING clean:1, enrich:1, publish:2 [fetch] claim() -> "fetch" fetch:RUNNING, clean:PENDING, enrich:PENDING, publish:... clean:1, enrich:1, publish:2 [] mark_succeeded("fetch") fetch:SUCCEEDED, clean:READY, enrich:READY, publish:... clean:0, enrich:0, publish:2 [clean, enrich] claim() -> "clean" clean:RUNNING, enrich:READY, publish:PENDING publish:2 [enrich] claim() -> "enrich" clean:RUNNING, enrich:RUNNING, publish:PENDING publish:2 [] mark_succeeded("clean") clean:SUCCEEDED, enrich:RUNNING, publish:PENDING publish:2 -> 1 [] mark_succeeded("enrich") enrich:SUCCEEDED, publish:READY publish:1 -> 0 [publish]Now trace what happens if
"clean"fails instead of succeeding:mark_failed("clean")marks"clean"FAILED, pops"publish"fromstack, sees_status["publish"] == PENDING, sets_status["publish"] = UPSTREAM_FAILED, and pushes_dependents["publish"]([]).- When
"enrich"later finishes and callsmark_succeeded("enrich"), it inspects"publish"in_dependents["enrich"], sees_status["publish"] == UPSTREAM_FAILED(notPENDING), and leaves"publish"untouched.
Why is a single
threading.Lockboth safe and fast for concurrent workers?- Prevents lost updates and double claims: Without a lock, two threads finishing
"clean"and"enrich"simultaneously could both read_waiting_on["publish"]as2and both write1, stranding"publish"forever. Likewise, popping from_readyand settingRUNNINGinside onewith self._lock:block makes claiming atomic, so two threads can never receive the same job. - Jobs run outside the lock: The tracker only holds
self._lockfor microseconds of dictionary/queue bookkeeping. Workers execute the actual job payload betweenclaim()andmark_succeeded(), while holding no lock at all. - No deadlock in helpers: Python's
threading.Lockis non-reentrant (if the same thread tries to acquire a lock it already holds, it freezes forever). That is why public methods acquireself._lockand private helpers (_make_ready,_finish) assume it is already held.
Complete solution
from typing import Dict, List, Optional from collections import deque import threading PENDING = "PENDING" # waiting for at least one dependency READY = "READY" # every dependency succeeded; waiting for a worker RUNNING = "RUNNING" # handed to a worker, result not reported yet SUCCEEDED = "SUCCEEDED" FAILED = "FAILED" UPSTREAM_FAILED = "UPSTREAM_FAILED" # a direct or indirect dependency failed; it will never run class JobTracker: """Tracks jobs and their dependencies. External workers claim READY jobs and report results. Rules chosen for this design: - every dependency must already be submitted, so a dependency cycle can never form; - when a job fails, every job that depends on it, directly or indirectly, becomes UPSTREAM_FAILED; - all public methods are safe to call from several threads at once. """ def __init__(self) -> None: # Single non-reentrant mutex guarding all tracker dictionaries and the ready queue. self._lock = threading.Lock() # _status: job_id -> status string, e.g. {"fetch": "RUNNING", "clean": "PENDING"} self._status: Dict[str, str] = {} # _waiting_on: PENDING job_id -> count of distinct dependencies not yet SUCCEEDED, e.g. {"publish": 2} self._waiting_on: Dict[str, int] = {} # _dependents: reverse edges mapping job_id -> downstream job_ids waiting on it, e.g. {"fetch": ["clean", "enrich"]} self._dependents: Dict[str, List[str]] = {} # _ready: FIFO queue of READY job_ids ordered from oldest ready to newest ready self._ready = deque() def submit(self, job_id: str, dependencies: List[str]) -> str: """Register a job and return its initial status. Raise ValueError for a duplicate id, a job that depends on itself, or a dependency that has not been submitted. """ with self._lock: # Phase 1: Validate everything before mutating state so invalid calls have zero side effects. if job_id in self._status: raise ValueError(f"job {job_id!r} was already submitted") # Deduplicate dependencies while preserving order so ["fetch", "fetch"] increments the counter once # and registers only one reverse edge in _dependents["fetch"]. unique_deps: List[str] = [] seen = set() for dep in dependencies: if dep == job_id: raise ValueError(f"job {job_id!r} depends on itself") if dep not in self._status: raise ValueError(f"dependency {dep!r} has not been submitted") if dep not in seen: seen.add(dep) unique_deps.append(dep) # Initialize reverse-edge list so later jobs can safely depend on this job. self._dependents[job_id] = [] # Phase 2: If any dependency has already failed, this job can never run. for dep in unique_deps: dep_status = self._status[dep] if dep_status == FAILED or dep_status == UPSTREAM_FAILED: self._status[job_id] = UPSTREAM_FAILED self._waiting_on[job_id] = 0 return UPSTREAM_FAILED # Phase 3: Link only dependencies that have not SUCCEEDED yet; already-SUCCEEDED # dependencies will never fire another completion event. self._status[job_id] = PENDING unfinished = 0 for dep in unique_deps: if self._status[dep] != SUCCEEDED: self._dependents[dep].append(job_id) unfinished += 1 # Phase 4: A job with zero unmet dependencies becomes READY right away. self._waiting_on[job_id] = unfinished if unfinished == 0: self._make_ready(job_id) return self._status[job_id] def get_status(self, job_id: str) -> str: """Current status of a job. Raise KeyError for an unknown id.""" with self._lock: return self._status[job_id] def claim(self) -> Optional[str]: """Give the caller the oldest READY job and mark it RUNNING. Return None if none is ready.""" with self._lock: if not self._ready: return None # Pop and mark RUNNING atomically under one lock so two threads never claim the same job. job_id = self._ready.popleft() self._status[job_id] = RUNNING return job_id def mark_succeeded(self, job_id: str) -> None: """Record that a RUNNING job succeeded; dependents whose last dependency this was become READY.""" with self._lock: self._finish(job_id, SUCCEEDED) for child in self._dependents[job_id]: # Skip children that are already UPSTREAM_FAILED from another failed dependency. if self._status[child] == PENDING: self._waiting_on[child] -= 1 if self._waiting_on[child] == 0: self._make_ready(child) def mark_failed(self, job_id: str) -> None: """Record that a RUNNING job failed; every job downstream of it becomes UPSTREAM_FAILED.""" with self._lock: self._finish(job_id, FAILED) # Use an explicit stack instead of recursion so deep chains do not hit Python's recursion limit. stack = list(self._dependents[job_id]) while stack: child = stack.pop() # Checking == PENDING both ignores terminal jobs and ensures diamond nodes # (reachable via two paths) are marked and expanded only once. if self._status[child] == PENDING: self._status[child] = UPSTREAM_FAILED stack.extend(self._dependents[child]) def _make_ready(self, job_id: str) -> None: # Caller must already hold self._lock (threading.Lock is not reentrant). self._status[job_id] = READY self._ready.append(job_id) def _finish(self, job_id: str, new_status: str) -> None: # Only a currently RUNNING job may report a completion result; caller holds self._lock. if self._status.get(job_id) != RUNNING: raise ValueError(f"job {job_id!r} is not RUNNING") self._status[job_id] = new_status✅ Submit now — all tests should pass.
Intuition & how it works
Think of each job as a kitchen recipe step with a small countdown tally on it ("still waiting on 2 prep tasks"), while each prep task keeps a short notification list of which recipes are waiting on it. Instead of every chef asking the whole kitchen "Are my ingredients ready yet?" after every dish comes out, a finished prep task simply walks down its own notification list and crosses 1 off each waiting recipe's tally; the moment a tally hits 0, that recipe drops into the "ready to cook" tray.
The naive approach stores only each job's list of dependencies and rescans every PENDING job whenever any job finishes. With 100,000 jobs, each completion inspects thousands of completely unrelated jobs, turning the overall run into slow quadratic work. Even worse, if a job fails and we do not push that failure downstream, every job waiting on it sits in PENDING forever.
We model the tracker as a state machine (a fixed set of job statuses and the exact events allowed to move a job between them) over a directed acyclic graph, or DAG (a network of one-way dependency links with no loops), using Kahn's algorithm (an algorithm that tracks each node's count of unmet prerequisites and unlocks nodes as their counts drop to zero):
- Suppose we submit
"fetch"([]),"clean"(["fetch"]),"enrich"(["fetch"]), and"publish"(["clean", "enrich"]). "fetch"has0unmet dependencies, so it enters a FIFO queue (first-in, first-out queue,collections.deque) asREADY;"clean"and"enrich"wait on1job ("fetch"), and"publish"waits on2jobs ("clean"and"enrich").- A worker calls
claim(), atomically popping"fetch"and marking itRUNNING. Whenmark_succeeded("fetch")is called, we walk"fetch"'s reverse edges (the list of downstream jobs["clean", "enrich"]that depend on"fetch"), decrementing both counters from1to0, so"clean"and"enrich"becomeREADY. - Next, if
"clean"succeeds,"publish"'s counter drops from2to1(stillPENDING); once"enrich"also succeeds,"publish"'s counter drops from1to0and"publish"becomesREADY— whereas if"clean"had failed, a stack traversal along reverse edges would immediately mark"publish"asUPSTREAM_FAILED(a terminal state, meaning a final status that never changes again).
Complexity
submit: O(d) time, wheredis the number of dependencies passed in. We loop over theditems to validate them in O(1) dictionary/set lookups, deduplicate them, check whether any already failed, and append at mostdreverse edges.claimandget_status: O(1) time, becauseclaimperforms a singledeque.popleft()plus a dictionary update, andget_statusperforms one dictionary lookup.mark_succeeded: O(k) time, wherekis the number of direct dependents of the finished job, because we visit each direct dependent once and decrement its integer counter in O(1) time.mark_failed: O(J + E') time, whereJandE'are the downstreamPENDINGjobs and dependency edges reachable from the failed job. Each newly failed job transitions out ofPENDINGonce, so later paths never expand it again.- Whole run across all operations: O(V + E) total time for
Vjobs andEdependency edges, because every job enters a terminal state (SUCCEEDED,FAILED, orUPSTREAM_FAILED) at most once, so its_dependentslist is walked at most once. - Space: O(V + E), because we store one status entry, one integer counter, and at most one queue slot per job (
O(V)), plus one entry in_dependentsfor each unique dependency edge (O(E)).
Edge cases
- Zero dependencies, or all dependencies already
SUCCEEDED:unfinishedevaluates to0, sosubmitimmediately marks the jobREADYand enqueues it. - Submitting a job whose dependency already failed (
FAILEDorUPSTREAM_FAILED):submitreturnsUPSTREAM_FAILEDright away instead of leaving the new job stuck inPENDING. - Duplicate dependencies in one submission (such as
["fetch", "fetch"]): deduplicated before counting and linking. If duplicates incremented_waiting_ontwice while_dependentsstored a set, the counter would freeze at1forever. - Diamond graphs under failure (
"publish"depends on both"clean"and"enrich", and"fetch"fails above both): the failure stack reaches"publish"twice, and theself._status[child] == PENDINGguard marks"publish"and pushes its children only the first time. - Invalid submissions with mixed bad inputs (such as
["failed_job", "unknown_job"]): because validation runs across the entire list before Phase 2 checksFAILED,submitcleanly raisesValueErrorwith zero state changes. - Invalid completion reports: calling
mark_succeededormark_failedon an unknown,PENDING,READY, or already-finished job raisesValueErrorwithout altering any downstream counters. - Deep linear chains (
10,000jobs in a row):mark_faileduses an explicit list as a stack rather than recursion, avoiding Python'sRecursionError.
Common mistakes
- Rescanning all
PENDINGjobs on every completion. Easy to write, but costsO(V + E)per event instead ofO(V + E)across the entire run. - Treating "finished" as "succeeded". Decrementing
_waiting_onwhen a dependency fails would let downstream jobs run on broken or missing inputs instead of cascadingUPSTREAM_FAILED. - Cascading failures only one hop deep. If
"schema" -> "migrate" -> "verify"and"schema"fails, marking only direct children ("migrate") leaves grandchildren ("verify") stuck inPENDINGforever. - Check-then-act races when claiming. A check-then-act race happens when one thread checks a condition (
get_status(x) == READY) and acts on it (start(x)) in two separate locked calls, allowing a second thread to claimxin between. Popping from_readyand settingRUNNINGmust happen inside the same critical section (code block protected by a mutex, or mutual-exclusion lock, so only one thread runs it at a time). - Executing job work while holding
self._lock. That would block every other worker thread from claiming or reporting jobs until the slow job finishes. - Calling locked public methods from inside another locked method. Python's
threading.Lockis non-reentrant, meaning a thread that tries to acquire a lock it already holds will deadlock immediately; keep internal helpers (_make_ready,_finish) lock-free.
Follow-up questions
- When multiple worker threads access the scheduler at once, which state needs synchronization and how do you guarantee each runnable job is claimed at most once? Guard all internal dictionaries (
_status,_waiting_on,_dependents) and_readywith a singlethreading.Lock, held only during fast in-memory method calls while workers execute actual jobs outside the lock. Insideclaim(), popping from_readyand setting_status[job_id] = RUNNINGhappen inside one critical section, so two threads can never receive the same job ID. To let idle workers sleep instead of busy-pollingclaim(), wrap the same lock in a condition variable (threading.Condition, a synchronization primitive that lets threads sleep until notified that state changed):claim()waits while_readyis empty, and_make_ready()callsnotify(). Across multiple machines backed by a database, replace the in-memory pop with an atomic conditional update (UPDATE jobs SET status = 'RUNNING', owner = ? WHERE id = ? AND status = 'READY') paired with a lease (an expiration timestamp renewed by periodic worker heartbeats so a crashed worker's job can be reclaimed).
```python import threading from collections import deque
class BlockingReadyQueue: def init(self): self._lock = threading.Lock() self._has_ready = threading.Condition(self._lock) self._ready = deque()
def claim(self, timeout=None):
with self._lock:
while not self._ready:
if not self._has_ready.wait(timeout=timeout):
return None
return self._ready.popleft()
def push_ready(self, job_id):
with self._lock:
self._ready.append(job_id)
self._has_ready.notify()
```
-
How would you introduce job cancellation, and how should cancellation propagate to downstream dependents? Add
CANCELLEDandUPSTREAM_CANCELLEDterminal statuses. If the target job isPENDINGorREADY, mark itCANCELLEDimmediately under the lock; for aREADYjob, leave its ID in_readyand teachclaim()to skip any popped ID whose status is no longerREADY(lazy deletion keepscancelO(1) instead of scanning the deque). If the job is currentlyRUNNING, set a cancellation-requested flag that the worker polls cooperatively and transition toCANCELLEDwhen the worker stops, then run the exact same stack cascade over_dependentsto mark every downstreamPENDINGjobUPSTREAM_CANCELLED. -
If the scheduler must recover cleanly after a crash or process restart, what data do you write to durable storage and how do you handle in-flight jobs? Persist every
submitcall (job_idanddependencies) and every status transition synchronously to a database table or an append-only log (a file where new events are only ever added at the end) before returning to the caller. On restart, replay those persisted records to reconstruct_status,_waiting_on,_dependents, and_readyin memory — none of the derived counters or reverse edges need to be stored separately. Any job recorded asRUNNINGwhen the crash happened has an unknown real-world outcome: if jobs are idempotent (safe to run more than once with the same final effect), reset them toREADYso a worker re-runs them; otherwise transition them toFAILED(or aLOSTstatus) for operator or retry-policy review. -
How would you support bounded automatic retries on failure while keeping downstream jobs waiting transparently until attempts are exhausted? Track
attempts[job_id](incremented insideclaim()) alongsidemax_attempts[job_id]. Whenmark_failed(job_id)is called andattempts[job_id] < max_attempts[job_id], do not mark the jobFAILEDand do not run the failure cascade; instead put the job back intoREADY(or into a min-heap keyed bynext_retry_timefor exponential backoff). Because downstream jobs only react toSUCCEEDEDor a finalFAILED, every dependent stays calmly inPENDINGacross transient retry attempts and only cascades toUPSTREAM_FAILEDif the final allowed attempt fails.
text
fetch (max_attempts=3): RUNNING -> fail #1 -> READY -> RUNNING -> fail #2 -> READY -> RUNNING -> succeed -> SUCCEEDED
dependents of fetch: PENDING -------------------------------------------------------------------------> READY
Alternative approaches
- Allowing forward references (submitting a child before its parent) with cycle detection. Count not-yet-submitted dependency IDs as unmet in
_waiting_onand pre-create their_dependentslists. Because forward references make cycles possible (xdepends ony, thenydepends onx), eachsubmit(job_id, deps)must traverse the graph fromdepsto verifyjob_idcannot be reached (O(V + E)worst case per submission), and the tracker should expose amissing_dependencies()helper so callers can spot jobs waiting on IDs that were never submitted. - Batch DAG submission. When the entire workflow is known ahead of time (as in many build systems and ETL pipelines), accept all jobs in one
submit_all(graph)call, run Kahn's algorithm once inO(V + E)time to verify that every node can be reached (any unvisited nodes belong to or sit downstream of a cycle), and reject the whole batch atomically if a cycle exists.
Follow-up questions
- When multiple worker threads access the scheduler at once, which state needs synchronization and how do you guarantee each runnable job is claimed at most once?
- How would you introduce job cancellation, and how should cancellation propagate to downstream dependents?
- If the scheduler must recover cleanly after a crash or process restart, what data do you write to durable storage and how do you handle in-flight jobs?
- How would you support bounded automatic retries on failure while keeping downstream jobs waiting transparently until attempts are exhausted?
Similar questions
- Event-Driven Strategy Execution Framework for Quantitative Teams
- Linear-Time BST Preorder From Postorder Sequence
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging