Cascading Failures in a Task Graph

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build an in-memory dependency and failure tracker for a multi-stage job pipeline, exposed through task_manager_operations(operations: List[str], arguments: List[List[object]]) -> List[object].

Each registered job has a string identifier task_id and a status of either "pending" or "failed". Jobs can wait on prerequisite jobs: when X waits on Y, Y is an upstream prerequisite of X and X is a downstream consumer of Y. Your underlying tracker class must maintain both directions of every link (each job's upstream prerequisites and its downstream consumers), allowing any job to have multiple prerequisites and multiple consumers.

Starting from an empty tracker, execute (operations[i], arguments[i]) in sequence and collect one return value per call:

  1. "add_task" with [task_id]:
    • If task_id has not been seen yet, register it with status "pending".
    • If task_id already exists, keep its current status and existing links unchanged.
    • Return None.
  2. "add_dependency" with [task_id, dependency_id]:
    • Register either identifier as "pending" first if it has not been seen yet, then record the bidirectional link indicating that task_id requires dependency_id (duplicate links have no extra effect).
    • If dependency_id is already "failed", immediately mark task_id and all of its downstream consumers (direct or multi-hop) as "failed".
    • Return None.
  3. "fail_task" with [task_id]:
    • Register task_id first if unseen, set its status to "failed", and propagate "failed" status to every job that directly or transitively waits on task_id.
    • Return None.
  4. "get_status" with [task_id]:
    • Return "pending" or "failed" if task_id is registered, or None if task_id has never been registered (without creating it).

Your propagation logic must scale to large, densely connected graphs (including diamonds, long chains, and cycles) without redundantly re-exploring failed subgraphs or overflowing the call stack.

Examples

Example 1

Input:
  operations = ["add_task", "add_task", "add_task", "add_dependency", "get_status", "fail_task", "get_status", "get_status", "get_status"]
  arguments  = [["fetch"], ["parse"], ["metrics"], ["parse", "fetch"], ["parse"], ["fetch"], ["fetch"], ["parse"], ["metrics"]]
Output:
  [None, None, None, None, "pending", None, "failed", "failed", "pending"]

"parse" requires "fetch", whereas "metrics" is independent. Prior to any failure, "parse" is "pending". Failing "fetch" marks "fetch" and downstream "parse" as "failed", leaving "metrics" "pending".

Example 2

Input:
  operations = ["add_dependency", "add_dependency", "fail_task", "get_status", "get_status", "get_status", "get_status"]
  arguments  = [["compile", "lint"], ["deploy", "compile"], ["compile"], ["lint"], ["compile"], ["deploy"], ["unknown"]]
Output:
  [None, None, None, "pending", "failed", "failed", None]

"compile" waits on "lint", and "deploy" waits on "compile". Failing "compile" cascades forward to "deploy", leaves upstream "lint" "pending", and querying unregistered "unknown" yields None.

Example 3

Input:
  operations = ["add_dependency", "add_dependency", "add_dependency", "fail_task", "add_dependency", "get_status", "get_status", "get_status"]
  arguments  = [["api", "db"], ["api", "db"], ["worker", "db"], ["db"], ["report", "worker"], ["db"], ["api"], ["report"]]
Output:
  [None, None, None, None, None, "failed", "failed", "failed"]

Duplicate "api" -> "db" registrations are deduplicated. Failing "db" propagates to both "api" and "worker". Attaching "report" to already-failed "worker" immediately transitions "report" to "failed" as well.

Constraints

  • 1 <= len(operations) == len(arguments) <= 10^5
  • Every operations[i] is one of "add_task", "add_dependency", "fail_task", or "get_status".
  • Every task_id and dependency_id is a non-empty string.
  • Dependency graphs may contain diamond paths, cycles, self-links, and chains thousands of hops deep.

Step-by-step walkthrough

  1. Understand the operations and pin down edge-case rules

    The judge calls task_manager_operations(operations, arguments), where operations[i] is a method name like "add_dependency" and arguments[i] holds its arguments. Mutating methods (add_task, add_dependency, fail_task) append None to the output list, and get_status appends the task's current status string (or None if unseen).

    Newly registered tasks start as "pending" and failed tasks become "failed". Four clean rules make every case predictable:

    • add_task(task_id) is idempotent (calling it again on an existing task changes nothing): in particular, re-adding an already-failed task must not reset it back to "pending".
    • Implicit creation on writes, not on reads: add_dependency and fail_task initialize any unseen task ID as "pending" first (Example 2), whereas get_status on an unregistered task ID returns None without creating it.
    • Duplicate links are harmless: adding the same dependency twice (such as ["api", "db"] in Example 3) stores it once using a set.
    • Consistent failure rule: a task is "failed" if and only if fail_task was called on it or on any task it requires directly or transitively (through a chain of intermediate prerequisites, like "deploy" -> "compile" -> "lint"). Therefore, if "worker" has already failed and we later call add_dependency("report", "worker") (Example 3), "report" (and anything waiting on "report") fails right away.
  2. Store both directions of every dependency link

    Our jobs form a directed graph (a network of nodes connected by one-way arrows). Getting the arrow direction straight is half the battle. When add_dependency("parse", "fetch") says "parse" requires "fetch", "fetch" is the upstream prerequisite that must succeed first, and "parse" is the downstream consumer waiting on "fetch"—so failure flows from "fetch" to "parse":

    add_dependency("parse", "fetch")   ->   "parse requires fetch"
    
      Upstream prerequisite (parent)       Downstream consumer (child)
               [ fetch ]   =========================>   [ parse ]
                             failure cascades ->
    
      dependencies["parse"] = {"fetch"}   (tasks that "parse" waits on)
      dependents["fetch"]   = {"parse"}   (tasks that must fail if "fetch" fails)
    

    If we only stored dependencies["parse"] = {"fetch"}, then fail_task("fetch") would have to scan every task in the system just to discover who waits on "fetch". Storing both dependencies and dependents as dictionaries of sets lets us walk in either direction in O(1) lookup time per link and deduplicates repeated links automatically.

    from typing import Dict, Set
    
    PENDING = "pending"
    FAILED = "failed"
    
    
    class TaskManager:
        def __init__(self) -> None:
            # status: {"fetch": "pending", "parse": "failed"} maps each known task_id to its current state
            self.status: Dict[str, str] = {}
            # dependencies: {"parse": {"fetch"}} maps a task to the upstream parent tasks it waits on
            self.dependencies: Dict[str, Set[str]] = {}
            # dependents: {"fetch": {"parse"}} maps a task to the downstream child tasks waiting on it
            self.dependents: Dict[str, Set[str]] = {}
    
        def add_task(self, task_id: str) -> None:
            if task_id in self.status:
                # Existing tasks keep their current status (a failed task stays failed) and links.
                return
            self.status[task_id] = PENDING
            self.dependencies[task_id] = set()
            self.dependents[task_id] = set()
    
  3. Why a naive recursive traversal times out or crashes

    A tempting first attempt for fail_task is a bare recursive loop: mark the task failed, then recursively call fail_task on every child in dependents. That breaks in three ways on interconnected graphs:

    Layered diamonds (each layer depends on BOTH tasks above it):
    
       L0a     L0b
       |  \   /  |
       |   \ /   |        Paths from L0a:
       L1a  X  L1b        -> 1 path to each L1 task
       |  \   /  |        -> 2 paths to each L2 task
       L2a  X  L2b        -> 2^(k-1) paths to each Lk task!
    
    1. Exponential revisiting: Without skipping visited nodes, a 60-layer graph like the one above has 2^58 distinct paths from L0a to each bottom task—hundreds of quadrillions of recursive calls for just 120 tasks!
    2. Infinite loops on cycles: Nothing stops a caller from recording add_dependency("x", "y") and add_dependency("y", "x"). Without visited tracking, recursion bounces between "x" and "y" forever.
    3. Call-stack overflow: Even with a visited set, recursion pushes one call frame per hop. On a 5,000-task chain t0 -> t1 -> ... -> t4999, Python hits its ~1,000-frame recursion limit and raises RecursionError.
  4. Key invariant: every dependent of a failed task is already failed

    An invariant is a property we keep true before and after every single method call. Here is ours:

    Whenever a task's status is "failed", every downstream task in its dependents (directly or transitively) is already "failed" too.

    Why is this invariant so helpful?

    • When a failure cascade reaches any task whose status is already "failed", it can stop immediately—there is no need to re-scan that task's subtree because everything below it has already failed.
    • self.status[task] == FAILED acts as our visited mark across the entire lifetime of the TaskManager, without allocating a fresh visited set on each fail_task.
    • Because a task can change from "pending" to "failed" at most once (and never flips back), each task's dependents set is scanned at most once across the whole run!
  5. Preserve the invariant inside add_dependency

    What happens if dependency_id is already "failed" when add_dependency(task_id, dependency_id) is called (like add_dependency("report", "worker") in Example 3)? Look at what would go wrong if we simply added the link without cascading:

    1. add_dependency("worker", "db")      # "worker" waits on "db"
    2. fail_task("worker")                 # "worker" is now FAILED; "db" is still PENDING
    3. add_dependency("report", "worker")  # "report" now waits on already-FAILED "worker"!
                                           # (If "report" stayed PENDING, our invariant would break.)
    4. fail_task("db")                     # Cascade from "db" sees "worker" is already FAILED,
                                           # stops early, and would miss "report" completely!
    

    Propagating failure from task_id inside add_dependency whenever self.status[dependency_id] == FAILED keeps the invariant intact at every step:

    def add_dependency(self, task_id: str, dependency_id: str) -> None:
        # Ensure both tasks exist before wiring the two-way link (task_id depends on dependency_id).
        self.add_task(task_id)
        self.add_task(dependency_id)
        self.dependencies[task_id].add(dependency_id)
        self.dependents[dependency_id].add(task_id)
    
        # Keep our invariant intact: if the upstream dependency already failed, cascade to task_id immediately.
        if self.status[dependency_id] == FAILED:
            self._fail_from(task_id)
    
  6. Propagate failures with an iterative BFS queue

    We implement _fail_from(start_id) with breadth-first search (BFS) using a queue (collections.deque, a first-in, first-out list with O(1) pops from the front):

    1. If start_id is already FAILED, return immediately.
    2. Otherwise mark start_id as FAILED and put it in queue.
    3. Pop current from the front of queue; for each child in self.dependents[current], if child is not yet FAILED, mark self.status[child] = FAILED right now (before appending child to queue).

    Marking child when it enters the queue (instead of waiting until it is popped) guarantees that if two failing parents both point to child, only the first parent enqueues child.

    from collections import deque
    from typing import Optional
    
    
    def fail_task(self, task_id: str) -> None:
        self.add_task(task_id)
        self._fail_from(task_id)
    
    
    def get_status(self, task_id: str) -> Optional[str]:
        return self.status.get(task_id)
    
    
    def _fail_from(self, start_id: str) -> None:
        """Mark start_id and all transitive dependents as failed, visiting each newly failed task once."""
        if self.status[start_id] == FAILED:
            # By our invariant, all downstream dependents of an already-failed task are already failed.
            return
    
        self.status[start_id] = FAILED
        # queue: FIFO deque of task_ids that just turned FAILED and need their dependents notified
        queue: deque[str] = deque([start_id])
    
        while queue:
            current = queue.popleft()
            for child in self.dependents[current]:
                # Mark child FAILED before enqueueing so diamonds never push the same child twice.
                if self.status[child] != FAILED:
                    self.status[child] = FAILED
                    queue.append(child)
    
  7. Wire up the dispatcher and trace Example 3

    task_manager_operations instantiates TaskManager, runs each (operation, args) pair in order, and collects the return values (None for updates, the status string or None for get_status).

    Let's trace Example 3 (["api", "db"] twice, ["worker", "db"], fail_task("db"), then ["report", "worker"]):

              [ db ]                dependents after first 3 calls:
              /    \                  db     -> {api, worker}
             v      v                 api    -> {}
          [ api ] [ worker ]          worker -> {}
    
    1. fail_task("db"):
       - mark "db" FAILED, queue = ["db"]
       - pop "db" -> mark "api" and "worker" FAILED, queue = ["api", "worker"]
       - pop "api", pop "worker" -> no children -> queue = []
    
    2. add_dependency("report", "worker"):
       - register "report" as "pending", link dependents["worker"].add("report")
       - see status["worker"] == "failed" -> call _fail_from("report")
       - mark "report" FAILED, queue = ["report"] -> pop "report" -> queue = []
       Final queried statuses: db="failed", api="failed", report="failed"
    

    Every task transitioned from "pending" to "failed" once and entered queue once.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import deque
    
    PENDING = "pending"
    FAILED = "failed"
    
    
    class TaskManager:
        """In-memory task graph with bidirectional dependency links and cascading failures."""
    
        def __init__(self) -> None:
            # status: {"fetch": "pending", "parse": "failed"} maps each known task_id to its current state
            self.status: Dict[str, str] = {}
            # dependencies: {"parse": {"fetch"}} maps a task to the upstream parent tasks it waits on
            self.dependencies: Dict[str, Set[str]] = {}
            # dependents: {"fetch": {"parse"}} maps a task to the downstream child tasks waiting on it
            self.dependents: Dict[str, Set[str]] = {}
    
        def add_task(self, task_id: str) -> None:
            if task_id in self.status:
                # Existing tasks keep their current status (a failed task stays failed) and links.
                return
            self.status[task_id] = PENDING
            self.dependencies[task_id] = set()
            self.dependents[task_id] = set()
    
        def add_dependency(self, task_id: str, dependency_id: str) -> None:
            # Ensure both tasks exist before wiring the two-way link (task_id depends on dependency_id).
            self.add_task(task_id)
            self.add_task(dependency_id)
            self.dependencies[task_id].add(dependency_id)
            self.dependents[dependency_id].add(task_id)
    
            # Keep our invariant intact: if the upstream dependency already failed, cascade to task_id immediately.
            if self.status[dependency_id] == FAILED:
                self._fail_from(task_id)
    
        def fail_task(self, task_id: str) -> None:
            self.add_task(task_id)
            self._fail_from(task_id)
    
        def get_status(self, task_id: str) -> Optional[str]:
            return self.status.get(task_id)
    
        def _fail_from(self, start_id: str) -> None:
            """Mark start_id and all transitive dependents as failed, visiting each newly failed task once."""
            if self.status[start_id] == FAILED:
                # By our invariant, all downstream dependents of an already-failed task are already failed.
                return
    
            self.status[start_id] = FAILED
            # queue: FIFO deque of task_ids that just turned FAILED and need their dependents notified
            queue: deque[str] = deque([start_id])
    
            while queue:
                current = queue.popleft()
                for child in self.dependents[current]:
                    # Mark child FAILED before enqueueing so diamonds never push the same child twice.
                    if self.status[child] != FAILED:
                        self.status[child] = FAILED
                        queue.append(child)
    
    
    def task_manager_operations(operations: List[str], arguments: List[List[object]]) -> List[object]:
        manager = TaskManager()
        results: List[object] = []
    
        # Dispatch each operation name with its argument list and record None for mutating methods.
        for operation, args in zip(operations, arguments):
            if operation == "add_task":
                manager.add_task(str(args[0]))
                results.append(None)
            elif operation == "add_dependency":
                manager.add_dependency(str(args[0]), str(args[1]))
                results.append(None)
            elif operation == "fail_task":
                manager.fail_task(str(args[0]))
                results.append(None)
            elif operation == "get_status":
                results.append(manager.get_status(str(args[0])))
            else:
                raise ValueError(f"Unknown operation: {operation}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a multi-stage job pipeline—say, starting a database (db), launching an API server (api) and background worker (worker), and generating a report (report)—arranged like upright dominoes in a directed graph (a network of items connected by one-way prerequisite arrows). If db fails, every downstream step waiting on db directly (api, worker) or through a transitive dependency (a multi-hop chain like report waiting on worker which waits on db) cannot proceed and must topple too, whereas independent or upstream jobs stay standing (like "lint" in Example 2 when "compile" fails). Better yet, once a domino has fallen ("failed"), it stays fallen forever: if we maintain the invariant (a rule guaranteed to stay true after every operation) that every downstream consumer of a failed task is already failed, then any future cascade that touches an already-failed task can stop on the spot.

A naive recursive traversal fails in three ways on interconnected graphs. First, without tracking visited tasks, it explores every distinct path rather than every task, turning 60 two-node diamond layers into 2^58 redundant visits. Second, if two tasks form a cycle (a closed loop such as "x" waiting on "y" and "y" waiting on "x"), naive recursion loops forever. Third, even with a visited set, recursion uses one call-stack frame per hop and crashes with RecursionError on chains deeper than ~1,000 tasks. Storing two-way hash sets (dependencies and dependents) and cascading failures with an iterative breadth-first search (BFS) (exploring layer by layer) over a queue (a first-in, first-out deque) eliminates all three problems.

Walk through Example 3 ("api" and "worker" require "db", then "db" fails, then "report" is linked to "worker"): 1. Wire links: dependents becomes {"db": {"api", "worker"}, "api": set(), "worker": set()} (and dependencies stores the reverse prerequisite sets). All three tasks start "pending", and the duplicate ("api", "db") call is ignored by the set. 2. Run fail_task("db"): mark "db" as "failed" and initialize queue = deque(["db"]); pop "db", mark "api" and "worker" "failed", push both, and pop them cleanly. 3. Link onto an already-failed parent: add_dependency("report", "worker") registers "report", notices "worker" is already "failed", and immediately runs _fail_from("report") so "report" becomes "failed" too.

Complexity

Let V be the total number of distinct tasks, E be the total number of distinct dependency links, and Q be the total number of operations (V <= 2Q and E <= Q). Hash-map and hash-set lookups run in O(1) average time.

  • Time: O(1) per add_task and get_status; O(V + E) worst-case for a single fail_task (or add_dependency onto a failed task), and O(Q + V + E) = O(Q) total across all Q operations (O(1) amortized time per operation), where amortized time means the average cost per operation across the entire sequence even if one step does a burst of work. Why does the whole run cost only O(Q + V + E)? Each task transitions from "pending" to "failed" at most once and never reverts to "pending". A task enters queue only at that exact transition moment, so its dependents[current] set is iterated at most once across the entire lifetime of TaskManager, examining each of the E links at most once during cascades.
  • Space: O(V + E). status holds one entry per task (O(V)), every dependency link is stored once in dependencies and once in dependents (O(V + E) total across all sets), and the BFS queue never holds more than V task IDs at one time because a task is marked "failed" before being enqueued.

Edge cases

  • Querying an unregistered task (get_status("unknown") in Example 2): returns None without creating "unknown" in self.status.
  • Implicit task creation on writes: add_dependency("compile", "lint") and fail_task("z") call add_task first so unseen task IDs are safely initialized before linking or failing.
  • Re-adding an existing failed task (add_task("fetch") after fail_task("fetch")): if task_id in self.status: return preserves "failed" and existing links instead of wiping them back to "pending".
  • Duplicate dependency calls (Example 3): storing neighbors in Python sets ignores repeated add_dependency("api", "db") calls in O(1) time.
  • Cycles (A <-> B) and self-dependencies (S -> S): marking a task "failed" before enqueueing prevents it from ever re-entering queue, so cycles terminate cleanly in one pass.
  • Adding a dependency onto an already-failed parent (Example 3): add_dependency("report", "worker") checks if self.status[dependency_id] == FAILED and cascades to "report" immediately, preserving the invariant so later upstream failures cannot stop early at "worker" and miss "worker"'s children.
  • Deep chains (5,000+ tasks): the iterative deque loop lives on the heap and never touches Python's call-stack recursion limit.

Common mistakes

  • Confusing arrow direction (dependencies vs dependents): when "deploy" depends on "compile" (Example 2), failing "compile" must fail "deploy", not upstream "lint"! Cascading along dependencies instead of dependents fails upstream prerequisites and leaves broken downstream consumers "pending".
  • Stopping early at "failed" nodes without cascading inside add_dependency: if "worker" fails first, "report" is later linked to "worker" while staying "pending", and then "db" (upstream of "worker") fails, an early stop at already-failed "worker" leaves "report" wrongly "pending". Early stopping is valid only because add_dependency immediately cascades from any already-failed prerequisite.
  • Marking nodes "failed" when popping from the queue instead of when pushing: in a layered diamond graph, if you wait until popleft() to mark status and forget to skip already-failed pops, a task with two parents gets pushed twice at layer 1, four times at layer 2, and 2^k times at layer k, bringing back exponential blowup! Always mark self.status[child] = FAILED right before queue.append(child).
  • Storing only one direction of the relationship: omitting dependents forces fail_task to scan all V tasks at every hop (O(V * (V + E))), while omitting dependencies breaks the bidirectional storage requirement and prevents upward queries like root-cause inspection or cycle checks.

Alternative approaches

  • Lazy upward search on get_status: store only dependencies and a directly_failed set in O(1) per write, and have each get_status(task_id) walk upward through dependencies with a visited set to check whether any ancestor is in directly_failed. That makes get_status cost O(V + E) per query instead of O(1), which is much slower on read-heavy workloads than our eager O(Q) total approach—though it makes edge removal or task retries simple when graphs mutate in reverse, and it serves as an independent oracle in randomized unit tests.

Follow-up questions

  • How would you extend the manager with a complete_task(task_id) method that tracks which pending tasks have all prerequisites satisfied? Maintain an unmet_deps[task_id] counter initialized to the number of incomplete prerequisites in dependencies[task_id], plus a ready queue of "pending" tasks with unmet_deps == 0. When complete_task(u) transitions u to "completed", loop over each child in dependents[u], decrement unmet_deps[child], and push child into the ready queue as soon as its count hits 0 (provided child is not "failed"). This incremental topological order (an execution sequence where every prerequisite finishes before its consumers, known as Kahn's algorithm) runs in O(1) amortized time per link.
  • If cyclic dependencies are disallowed, how would add_dependency(task_id, dependency_id) detect and reject a cycle before inserting the link? Adding "task_id requires dependency_id" creates a cycle if and only if task_id == dependency_id or dependency_id already depends (directly or transitively) on task_id. Before inserting the link, run an iterative BFS/DFS starting at dependency_id upward through self.dependencies using a local visited set; if the search reaches task_id, reject the link and raise an error, taking O(V + E) time in the worst case.
  • What additional state would you maintain if a failed task could be retried and restored to pending? Once tasks can recover, a downstream consumer should revert to "pending" only when it is not directly failed and zero of its prerequisites remain failed. Store a boolean directly_failed[u] alongside an integer failed_parent_count[u] (so u is failed whenever directly_failed[u] or failed_parent_count[u] > 0); when u transitions from failed back to pending (assuming an acyclic graph), propagate a BFS over dependents decrementing failed_parent_count[child] and continuing only through children whose overall failed state flips from True to False.

Follow-up questions

Similar questions

More Perplexity interview questions

All 13 Perplexity questions →