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:
"add_task"with[task_id]:- If
task_idhas not been seen yet, register it with status"pending". - If
task_idalready exists, keep its current status and existing links unchanged. - Return
None.
- If
"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 thattask_idrequiresdependency_id(duplicate links have no extra effect). - If
dependency_idis already"failed", immediately marktask_idand all of its downstream consumers (direct or multi-hop) as"failed". - Return
None.
- Register either identifier as
"fail_task"with[task_id]:- Register
task_idfirst if unseen, set its status to"failed", and propagate"failed"status to every job that directly or transitively waits ontask_id. - Return
None.
- Register
"get_status"with[task_id]:- Return
"pending"or"failed"iftask_idis registered, orNoneiftask_idhas never been registered (without creating it).
- Return
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_idanddependency_idis a non-empty string. - Dependency graphs may contain diamond paths, cycles, self-links, and chains thousands of hops deep.
Step-by-step walkthrough
Understand the operations and pin down edge-case rules
The judge calls
task_manager_operations(operations, arguments), whereoperations[i]is a method name like"add_dependency"andarguments[i]holds its arguments. Mutating methods (add_task,add_dependency,fail_task) appendNoneto the output list, andget_statusappends the task's current status string (orNoneif 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_dependencyandfail_taskinitialize any unseen task ID as"pending"first (Example 2), whereasget_statuson an unregistered task ID returnsNonewithout creating it. - Duplicate links are harmless: adding the same dependency twice (such as
["api", "db"]in Example 3) stores it once using aset. - Consistent failure rule: a task is
"failed"if and only iffail_taskwas 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 calladd_dependency("report", "worker")(Example 3),"report"(and anything waiting on"report") fails right away.
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"}, thenfail_task("fetch")would have to scan every task in the system just to discover who waits on"fetch". Storing bothdependenciesanddependentsas 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()Why a naive recursive traversal times out or crashes
A tempting first attempt for
fail_taskis a bare recursive loop: mark the task failed, then recursively callfail_taskon every child independents. 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!- Exponential revisiting: Without skipping visited nodes, a 60-layer graph like the one above has
2^58distinct paths fromL0ato each bottom task—hundreds of quadrillions of recursive calls for just 120 tasks! - Infinite loops on cycles: Nothing stops a caller from recording
add_dependency("x", "y")andadd_dependency("y", "x"). Without visited tracking, recursion bounces between"x"and"y"forever. - 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 raisesRecursionError.
- Exponential revisiting: Without skipping visited nodes, a 60-layer graph like the one above has
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 itsdependents(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] == FAILEDacts as our visited mark across the entire lifetime of theTaskManager, without allocating a freshvisitedset on eachfail_task.- Because a task can change from
"pending"to"failed"at most once (and never flips back), each task'sdependentsset is scanned at most once across the whole run!
- When a failure cascade reaches any task whose status is already
Preserve the invariant inside add_dependency
What happens if
dependency_idis already"failed"whenadd_dependency(task_id, dependency_id)is called (likeadd_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_idinsideadd_dependencywheneverself.status[dependency_id] == FAILEDkeeps 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)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):- If
start_idis alreadyFAILED, return immediately. - Otherwise mark
start_idasFAILEDand put it inqueue. - Pop
currentfrom the front ofqueue; for eachchildinself.dependents[current], ifchildis not yetFAILED, markself.status[child] = FAILEDright now (before appendingchildtoqueue).
Marking
childwhen it enters the queue (instead of waiting until it is popped) guarantees that if two failing parents both point tochild, only the first parent enqueueschild.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)- If
Wire up the dispatcher and trace Example 3
task_manager_operationsinstantiatesTaskManager, runs each(operation, args)pair in order, and collects the return values (Nonefor updates, the status string orNoneforget_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 enteredqueueonce.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_taskandget_status; O(V + E) worst-case for a singlefail_task(oradd_dependencyonto a failed task), and O(Q + V + E) = O(Q) total across allQoperations (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 entersqueueonly at that exact transition moment, so itsdependents[current]set is iterated at most once across the entire lifetime ofTaskManager, examining each of theElinks at most once during cascades. - Space: O(V + E).
statusholds one entry per task (O(V)), every dependency link is stored once independenciesand once independents(O(V + E)total across all sets), and the BFSqueuenever holds more thanVtask 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): returnsNonewithout creating"unknown"inself.status. - Implicit task creation on writes:
add_dependency("compile", "lint")andfail_task("z")calladd_taskfirst so unseen task IDs are safely initialized before linking or failing. - Re-adding an existing failed task (
add_task("fetch")afterfail_task("fetch")):if task_id in self.status: returnpreserves"failed"and existing links instead of wiping them back to"pending". - Duplicate dependency calls (Example 3): storing neighbors in Python
sets ignores repeatedadd_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-enteringqueue, so cycles terminate cleanly in one pass. - Adding a dependency onto an already-failed parent (Example 3):
add_dependency("report", "worker")checksif self.status[dependency_id] == FAILEDand 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
dequeloop lives on the heap and never touches Python's call-stack recursion limit.
Common mistakes
- Confusing arrow direction (
dependenciesvsdependents): when"deploy"depends on"compile"(Example 2), failing"compile"must fail"deploy", not upstream"lint"! Cascading alongdependenciesinstead ofdependentsfails upstream prerequisites and leaves broken downstream consumers"pending". - Stopping early at
"failed"nodes without cascading insideadd_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 becauseadd_dependencyimmediately 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 untilpopleft()to markstatusand forget to skip already-failed pops, a task with two parents gets pushed twice at layer 1, four times at layer 2, and2^ktimes at layerk, bringing back exponential blowup! Always markself.status[child] = FAILEDright beforequeue.append(child). - Storing only one direction of the relationship: omitting
dependentsforcesfail_taskto scan allVtasks at every hop (O(V * (V + E))), while omittingdependenciesbreaks the bidirectional storage requirement and prevents upward queries like root-cause inspection or cycle checks.
Alternative approaches
- Lazy upward search on
get_status: store onlydependenciesand adirectly_failedset in O(1) per write, and have eachget_status(task_id)walk upward throughdependencieswith a visited set to check whether any ancestor is indirectly_failed. That makesget_statuscost 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 independencies[task_id], plus a ready queue of"pending"tasks withunmet_deps == 0. Whencomplete_task(u)transitionsuto"completed", loop over eachchildindependents[u], decrementunmet_deps[child], and pushchildinto the ready queue as soon as its count hits0(providedchildis 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_idrequiresdependency_id" creates a cycle if and only iftask_id == dependency_idordependency_idalready depends (directly or transitively) ontask_id. Before inserting the link, run an iterative BFS/DFS starting atdependency_idupward throughself.dependenciesusing a localvisitedset; if the search reachestask_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 booleandirectly_failed[u]alongside an integerfailed_parent_count[u](souis failed wheneverdirectly_failed[u] or failed_parent_count[u] > 0); whenutransitions from failed back to pending (assuming an acyclic graph), propagate a BFS overdependentsdecrementingfailed_parent_count[child]and continuing only through children whose overall failed state flips fromTruetoFalse.
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?
- If cyclic dependencies are disallowed, how would add_dependency(task_id, dependency_id) detect and reject a cycle before inserting the link?
- What additional state would you maintain if a failed task could be retried and restored to pending?
Similar questions
- Expiring Credit Balance Tracker
- Prerequisite-Aware Task Manager
- Proportional Stratified Sampling Without Replacement
- Versioned Key-Value Store with Point-in-Time Rollback
- Multi-Institution Personal Finance Aggregation Platform
- Personalized Content Discovery Feed Architecture
More Perplexity interview questions
- Strict In-Memory Directory Tree and Shell Command Interpreter Hard
- Virtual File System with Working Directory and Relative Paths Medium
- Expiring Credit Balance Tracker Medium Pro
- Multi-Institution Personal Finance Aggregation Platform Hard Pro
- Personalized Content Discovery Feed Architecture Medium Pro
- Design a Real-Time Trending Search System Medium Pro
- Troubleshooting an Overloaded Kubernetes Cluster Hard Pro
- Prerequisite-Aware Task Manager Medium Pro
- Proportional Stratified Sampling Without Replacement Medium Pro
- Design a Resilient Multi-Provider LLM Client Hard Pro