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:

  1. submit(job_id: str, dependencies: List[str]) -> str
    • Register a unique job_id alongside the list of prerequisite job IDs that must finish with SUCCEEDED before job_id can run, returning job_id's initial status (READY, PENDING, or UPSTREAM_FAILED).
    • Duplicate entries inside dependencies count once.
    • Validate the entire submission before mutating state: raise ValueError (leaving tracker state completely unchanged) if job_id was already submitted, if job_id appears in its own dependencies, or if any prerequisite in dependencies has not been submitted yet. (Requiring prerequisites to exist beforehand guarantees the graph remains acyclic.)
    • If any prerequisite is already FAILED or UPSTREAM_FAILED, job_id immediately enters UPSTREAM_FAILED. Otherwise, if all prerequisites are already SUCCEEDED (including an empty dependencies list), job_id starts in READY and enters the runnable FIFO queue; otherwise it starts in PENDING.
  2. get_status(job_id: str) -> str
    • Return the current status string of job_id, or raise KeyError if job_id is unknown.
  3. claim() -> Optional[str]
    • Atomically remove the job that has been READY the longest (FIFO order of becoming READY), transition its status to RUNNING, and return its job_id. Return None when no READY job is available. Two concurrent claim() calls must never return the same job.
  4. mark_succeeded(job_id: str) -> None
    • Transition a currently RUNNING job to SUCCEEDED (raising ValueError with no state changes if job_id is unknown or not RUNNING). Any PENDING dependent whose last remaining prerequisite just succeeded immediately becomes READY.
  5. mark_failed(job_id: str) -> None
    • Transition a currently RUNNING job to FAILED (raising ValueError with no state changes if job_id is unknown or not RUNNING). Immediately transition every downstream PENDING job that depends on job_id directly or transitively to UPSTREAM_FAILED.

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; dependencies may 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 V jobs and E edges should run in O(V + E) time rather than rescanning all PENDING jobs on every completion.

Step-by-step walkthrough

  1. 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 call mark_succeeded(job_id) or mark_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. submit raises ValueError for 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 in PENDING would force callers to wait forever, so we immediately transition all of them to UPSTREAM_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: ...
    
  2. 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 PENDING jobs ever react to another job finishing. A READY or RUNNING job already had all of its dependencies reach SUCCEEDED, and terminal states never change.
    • Only RUNNING jobs can be marked succeeded or failed. Rejecting reports on PENDING, READY, terminal, or unknown jobs catches buggy workers that report results twice or report a job they never claimed.
  3. 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 PENDING jobs from scratch to see which ones now have every dependency SUCCEEDED:

    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_ready
    

    This is easy to verify, so it makes a great test oracle! However, if we have V = 100,000 jobs with 3 dependencies each (E = 300,000 edges), finishing a single job scans up to 300,000 edges. Across all 100,000 completions, that adds up to roughly 3 × 10^10 checks. 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.

  4. 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:

    1. _dependents[job]: the reverse edges — a list of downstream jobs that list job as a dependency.
    2. _waiting_on[job]: an integer count of how many distinct dependencies of job have not reached SUCCEEDED yet.
    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: 2
    

    Now look at how cheap each completion becomes:

    • When job succeeds: loop only over _dependents[job] and subtract 1 from each PENDING child's _waiting_on count. The exact moment a child's count hits 0, all of its dependencies have succeeded, so we move it to READY and 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 job fails: walk _dependents[job] transitively (children, grandchildren, and so on), marking every PENDING job UPSTREAM_FAILED.

    Because each job reaches a terminal state at most once, its _dependents list is traversed at most once over the entire lifetime of the tracker. Total graph work across all operations drops from quadratic to O(V + E).

  5. Code initialization and job submission

    Inside submit(job_id, dependencies), the order of checks matters:

    1. 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, submit must raise ValueError and leave every dictionary untouched rather than returning UPSTREAM_FAILED early on the 1st item.
    2. Deduplicate dependencies. If a caller passes ["fetch", "fetch"], job_id only waits on one real job "fetch". Deduplicating ensures _waiting_on[job_id] increments once and _dependents["fetch"] records job_id once, keeping the counter and reverse edges in lockstep.
    3. Handle dependencies that already finished:
      • If any dependency is already FAILED or UPSTREAM_FAILED, the new job starts immediately in UPSTREAM_FAILED.
      • If a dependency is already SUCCEEDED, do not increment unfinished and do not add a reverse edge (because "fetch" has already finished and will never call mark_succeeded("fetch") again).
      • Otherwise (PENDING, READY, or RUNNING), add job_id to _dependents[dep] and increment unfinished.
    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)
    
  6. Code worker claiming, success, and failure cascades

    Now let's implement the three worker-facing operations:

    • claim() checks _ready. If empty, it returns None. Otherwise it pops from the left (popleft(), the job that became READY earliest) and flips its status to RUNNING in the same locked step.
    • mark_succeeded(job_id) uses _finish to verify job_id is currently RUNNING and set it to SUCCEEDED. Then it visits each child in _dependents[job_id]. Notice the guard if self._status[child] == PENDING:: in Example 2, "verify" depended on both "migrate" and "seed"; once "migrate" failed upstream, "verify" became UPSTREAM_FAILED and must stay UPSTREAM_FAILED when "seed" later succeeds!
    • mark_failed(job_id) verifies RUNNING, sets FAILED, and cascades UPSTREAM_FAILED through all downstream jobs. We use an explicit Python list as a stack rather than recursion because a linear chain of 10,000 dependent jobs would blow past Python's ~1,000-frame recursion limit. Checking if self._status[child] == PENDING: before pushing child's dependents also prevents duplicate work in diamond graphs: the first path to reach child flips it to UPSTREAM_FAILED, so any second path sees status != PENDING and 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_status
    
  7. Trace 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:

    1. mark_failed("clean") marks "clean" FAILED, pops "publish" from stack, sees _status["publish"] == PENDING, sets _status["publish"] = UPSTREAM_FAILED, and pushes _dependents["publish"] ([]).
    2. When "enrich" later finishes and calls mark_succeeded("enrich"), it inspects "publish" in _dependents["enrich"], sees _status["publish"] == UPSTREAM_FAILED (not PENDING), and leaves "publish" untouched.

    Why is a single threading.Lock both 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"] as 2 and both write 1, stranding "publish" forever. Likewise, popping from _ready and setting RUNNING inside one with 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._lock for microseconds of dictionary/queue bookkeeping. Workers execute the actual job payload between claim() and mark_succeeded(), while holding no lock at all.
    • No deadlock in helpers: Python's threading.Lock is non-reentrant (if the same thread tries to acquire a lock it already holds, it freezes forever). That is why public methods acquire self._lock and private helpers (_make_ready, _finish) assume it is already held.
  8. 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" has 0 unmet dependencies, so it enters a FIFO queue (first-in, first-out queue, collections.deque) as READY; "clean" and "enrich" wait on 1 job ("fetch"), and "publish" waits on 2 jobs ("clean" and "enrich").
  • A worker calls claim(), atomically popping "fetch" and marking it RUNNING. When mark_succeeded("fetch") is called, we walk "fetch"'s reverse edges (the list of downstream jobs ["clean", "enrich"] that depend on "fetch"), decrementing both counters from 1 to 0, so "clean" and "enrich" become READY.
  • Next, if "clean" succeeds, "publish"'s counter drops from 2 to 1 (still PENDING); once "enrich" also succeeds, "publish"'s counter drops from 1 to 0 and "publish" becomes READY — whereas if "clean" had failed, a stack traversal along reverse edges would immediately mark "publish" as UPSTREAM_FAILED (a terminal state, meaning a final status that never changes again).

Complexity

  • submit: O(d) time, where d is the number of dependencies passed in. We loop over the d items to validate them in O(1) dictionary/set lookups, deduplicate them, check whether any already failed, and append at most d reverse edges.
  • claim and get_status: O(1) time, because claim performs a single deque.popleft() plus a dictionary update, and get_status performs one dictionary lookup.
  • mark_succeeded: O(k) time, where k is 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, where J and E' are the downstream PENDING jobs and dependency edges reachable from the failed job. Each newly failed job transitions out of PENDING once, so later paths never expand it again.
  • Whole run across all operations: O(V + E) total time for V jobs and E dependency edges, because every job enters a terminal state (SUCCEEDED, FAILED, or UPSTREAM_FAILED) at most once, so its _dependents list 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 _dependents for each unique dependency edge (O(E)).

Edge cases

  • Zero dependencies, or all dependencies already SUCCEEDED: unfinished evaluates to 0, so submit immediately marks the job READY and enqueues it.
  • Submitting a job whose dependency already failed (FAILED or UPSTREAM_FAILED): submit returns UPSTREAM_FAILED right away instead of leaving the new job stuck in PENDING.
  • Duplicate dependencies in one submission (such as ["fetch", "fetch"]): deduplicated before counting and linking. If duplicates incremented _waiting_on twice while _dependents stored a set, the counter would freeze at 1 forever.
  • Diamond graphs under failure ("publish" depends on both "clean" and "enrich", and "fetch" fails above both): the failure stack reaches "publish" twice, and the self._status[child] == PENDING guard 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 checks FAILED, submit cleanly raises ValueError with zero state changes.
  • Invalid completion reports: calling mark_succeeded or mark_failed on an unknown, PENDING, READY, or already-finished job raises ValueError without altering any downstream counters.
  • Deep linear chains (10,000 jobs in a row): mark_failed uses an explicit list as a stack rather than recursion, avoiding Python's RecursionError.

Common mistakes

  • Rescanning all PENDING jobs on every completion. Easy to write, but costs O(V + E) per event instead of O(V + E) across the entire run.
  • Treating "finished" as "succeeded". Decrementing _waiting_on when a dependency fails would let downstream jobs run on broken or missing inputs instead of cascading UPSTREAM_FAILED.
  • Cascading failures only one hop deep. If "schema" -> "migrate" -> "verify" and "schema" fails, marking only direct children ("migrate") leaves grandchildren ("verify") stuck in PENDING forever.
  • 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 claim x in between. Popping from _ready and setting RUNNING must 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.Lock is 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 _ready with a single threading.Lock, held only during fast in-memory method calls while workers execute actual jobs outside the lock. Inside claim(), popping from _ready and setting _status[job_id] = RUNNING happen inside one critical section, so two threads can never receive the same job ID. To let idle workers sleep instead of busy-polling claim(), 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 _ready is empty, and _make_ready() calls notify(). 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 CANCELLED and UPSTREAM_CANCELLED terminal statuses. If the target job is PENDING or READY, mark it CANCELLED immediately under the lock; for a READY job, leave its ID in _ready and teach claim() to skip any popped ID whose status is no longer READY (lazy deletion keeps cancel O(1) instead of scanning the deque). If the job is currently RUNNING, set a cancellation-requested flag that the worker polls cooperatively and transition to CANCELLED when the worker stops, then run the exact same stack cascade over _dependents to mark every downstream PENDING job UPSTREAM_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 submit call (job_id and dependencies) 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 _ready in memory — none of the derived counters or reverse edges need to be stored separately. Any job recorded as RUNNING when 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 to READY so a worker re-runs them; otherwise transition them to FAILED (or a LOST status) 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 inside claim()) alongside max_attempts[job_id]. When mark_failed(job_id) is called and attempts[job_id] < max_attempts[job_id], do not mark the job FAILED and do not run the failure cascade; instead put the job back into READY (or into a min-heap keyed by next_retry_time for exponential backoff). Because downstream jobs only react to SUCCEEDED or a final FAILED, every dependent stays calmly in PENDING across transient retry attempts and only cascades to UPSTREAM_FAILED if 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_on and pre-create their _dependents lists. Because forward references make cycles possible (x depends on y, then y depends on x), each submit(job_id, deps) must traverse the graph from deps to verify job_id cannot be reached (O(V + E) worst case per submission), and the tracker should expose a missing_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 in O(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

Similar questions

More Cubist interview questions

All 3 Cubist questions →