Dependency-Aware ETL Task Runner in Python
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build an in-memory workflow runner in pure Python that registers named data-pipeline tasks alongside their upstream dependencies and executes the workflow once per run() call.
Each task is represented by a Python callable func(upstream) accepting one dictionary argument upstream: Dict[str, Any] that maps the name of each direct parent task to that parent's return value (or {} when the task has no dependencies).
Implement TaskResult and Scheduler matching the starter interface:
- Status constants:
SUCCESS = "success",FAILED = "failed",SKIPPED = "skipped". TaskResult(status: str, attempts: int = 0, output: Any = None, error: Optional[str] = None):status: one ofSUCCESS,FAILED, orSKIPPED.attempts: total number of timesfuncwas invoked during this run (0whenSKIPPED).output: return value offuncwhenstatus == SUCCESS, otherwiseNone.error:Nonewhenstatus == SUCCESS;"<ExcType>: <message>"from the final raised exception whenstatus == FAILED; and a non-empty reason string whenstatus == SKIPPED.
Scheduler.add_task(name, func, depends_on=None, retries=0):- Registers task
name. Callers may register tasks in any order—a parent task may be added after a task that depends on it, and duplicate parent names independs_onare treated as a single dependency. retriesspecifies how many additional attemptsfuncgets if it raises anException(soretries=0runs at most1attempt, andretries=2runs at most3attempts).- Raise
ValueErrorimmediately ifnamewas already registered or ifretries < 0.
- Registers task
Scheduler.run() -> Dict[str, TaskResult]:- Pre-execution graph check: Before invoking any task callable, raise
ValueErrorif any dependency names an unregistered task or if the dependency graph contains a cycle (including self-dependencies). - Dependency-ordered execution: Run each task at most once per
run()call (up to1 + retriescallable attempts), strictly after every direct dependency has finished withSUCCESS. - Retries and partial failure isolation: Catch
Exception(allowing process-level signals likeKeyboardInterruptandSystemExitto propagate). If all1 + retriesattempts raiseException, mark the taskFAILED. Mark every task that depends directly or transitively on a non-SUCCESStask asSKIPPED(attempts=0) while still executing all unaffected tasks. - Return a dictionary mapping every registered task name to its
TaskResult({}for an empty scheduler). Callingrun()again on the sameSchedulerperforms a fresh execution.
- Pre-execution graph check: Before invoking any task callable, raise
Examples
Example 1
Input:
sched = Scheduler()
sched.add_task("fetch_orders", lambda up: [120, 80, 50])
# Suppose fetch_rates raises ConnectionError("timeout") on call 1, then returns 0.1 on call 2:
sched.add_task("fetch_rates", flaky_rates, retries=1)
sched.add_task(
"compute_tax",
lambda up: sum(round(x * up["fetch_rates"], 2) for x in up["fetch_orders"]),
depends_on=["fetch_orders", "fetch_rates"],
)
results = sched.run()
Output:
{
"fetch_orders": TaskResult(status="success", attempts=1, output=[120, 80, 50], error=None),
"fetch_rates": TaskResult(status="success", attempts=2, output=0.1, error=None),
"compute_tax": TaskResult(status="success", attempts=1, output=25.0, error=None),
}
Walk-through: "fetch_orders" and "fetch_rates" have zero dependencies, so both run first. "fetch_rates" fails once and recovers on its single retry (attempts=2). Once both parents succeed, "compute_tax" receives {"fetch_orders": [120, 80, 50], "fetch_rates": 0.1} and returns 12.0 + 8.0 + 5.0 = 25.0.
Example 2
Input:
"read_users"(no dependencies,retries=1): always raisesValueError("corrupt header")."clean_users"(depends_on=["read_users"]): transforms user rows."read_events"(no dependencies): returns42."summarize_events"(depends_on=["read_events"]): returnsupstream["read_events"] * 2."publish_report"(depends_on=["clean_users", "summarize_events"]): combines both branches.
Output:
"read_users":TaskResult(status="failed", attempts=2, output=None, error="ValueError: corrupt header")"clean_users":TaskResult(status="skipped", attempts=0, output=None, error=...)"read_events":TaskResult(status="success", attempts=1, output=42, error=None)"summarize_events":TaskResult(status="success", attempts=1, output=84, error=None)"publish_report":TaskResult(status="skipped", attempts=0, output=None, error=...)
Walk-through: "read_users" exhausts both attempts (1 + 1 = 2) and becomes FAILED. That skips "clean_users" directly and cascades to skip "publish_report", while the independent "read_events" -> "summarize_events" branch still runs to completion.
Example 3
Input:
"init_db"(no dependencies)"stage_a"(depends_on=["stage_b"])"stage_b"(depends_on=["stage_a"])
Output: sched.run() raises ValueError, and "init_db" is invoked 0 times.
Walk-through: "stage_a" and "stage_b" form a two-node cycle, which run() detects up front before executing any task.
Constraints
- Use only the Python standard library (no third-party packages).
0 <= V <= 10^4registered tasks and0 <= E <= 5 * 10^4dependency edges; scheduler overhead perrun()should scale asO(V + E).retries >= 0for valid registrations (retries < 0or duplicatenameraisesValueErrorinadd_task).- Mutating a caller-owned
depends_onlist after callingadd_taskmust not alter the registered graph.
Step-by-step walkthrough
Agree on scope, contracts, and failure rules
An ETL (Extract, Transform, Load) pipeline is a set of data-processing steps—reading raw data, cleaning it, and writing the result—connected by dependencies so each step runs only after the steps it relies on finish. Together, valid tasks and dependencies form a DAG (directed acyclic graph): a network of one-way arrows with no circular loops.
Because the prompt is intentionally open-ended, confirm your concrete design choices before writing code:
- Triggering:
run()executes the pipeline once on demand. Hourly scheduling belongs in an outer caller. - Data passing: Each task callable accepts a dictionary
upstreammapping each direct parent's name to that parent's return value ({}when a task has no dependencies). - Retries and partial failure: A task with
retries=rgets up to1 + rattempts. If every attempt raises an exception, the task is markedFAILED, every downstream task that depends on it (directly or indirectly) is markedSKIPPED, and independent branches still run to completion. - Up-front graph validation: Unknown dependency names and dependency cycles raise
ValueErrorbefore any task executes, so a broken pipeline never half-runs side effects.
from typing import Any, Callable, Dict, List, Optional from dataclasses import dataclass SUCCESS = "success" FAILED = "failed" SKIPPED = "skipped" @dataclass class TaskResult: """What happened to one task during a run.""" status: str # SUCCESS, FAILED or SKIPPED attempts: int = 0 # how many times the task's callable was called output: Any = None # the callable's return value, when status is SUCCESS error: Optional[str] = None # why the task failed or was skipped- Triggering:
Why naive repeated scanning falls short
A tempting first attempt is to loop over all tasks repeatedly, execute whichever task has all of its dependencies in a
doneset, and stop when a full pass makes no progress:def run_by_scanning(deps, funcs): done = set() order = [] progress = True while progress: progress = False for name in deps: if name in done: continue ready = True for dep in deps[name]: if dep not in done: ready = False if ready: funcs[name]({}) done.add(name) order.append(name) progress = True return orderThis sketch has two problems:
- Quadratic work in reverse order: If
Vtasks form a chain registered from last to first, each pass unlocks only one task, costingO(V * (V + E))checks forVtasks andEdependency arrows. - Late failure on broken graphs: If tasks
b -> c -> bform a cycle after taska,ahas already executed (and perhaps written to a database!) before the loop stalls and notices the cycle.
We want to validate and order the entire graph before running a single task, in
O(V + E)time.- Quadratic work in reverse order: If
Key idea: count unfinished dependencies (Kahn's algorithm)
A topological sort orders the tasks in a line so every parent appears before all of its children. To build one without rescanning, track each task's in-degree—the number of direct dependencies it is still waiting on:
- Compute
waiting[task]= number of direct dependencies oftask, and build a reverse lookupdependents[parent]= list of children that depend onparent. - Put every task with
waiting[task] == 0into areadyFIFO queue. - Pop a task from
ready, append it toorder, and subtract1fromwaiting[child]for each of its children. Whenever a child'swaitingcount hits0, push that child ontoready.
This procedure is Kahn's algorithm. If
orderends up shorter than the total number of tasks, the unvisited tasks still havewaiting > 0because they lie on a cycle (or downstream of one) and can never unlock:Pipeline graph: Initial waiting counts: read_users read_events read_users: 0 <- ready immediately | | read_events: 0 <- ready immediately clean_users summarize_events clean_users: 1 \ / summarize_events: 1 publish_report publish_report: 2 Queue trace: start ready=[read_users, read_events] pop read_users clean_users: 1 -> 0 (push) ready=[read_events, clean_users] pop read_events summarize_events: 1 -> 0 (push) ready=[clean_users, summarize_events] pop clean_users publish_report: 2 -> 1 ready=[summarize_events] pop summarize_events publish_report: 1 -> 0 (push) ready=[publish_report] pop publish_report done! order = [read_users, read_events, clean_users, summarize_events, publish_report]- Compute
Code task registration and input validation
add_taskchecks local invariants right away (duplicate task names and negative retry counts). Because callers are allowed to register a downstream task before registering its parents, unknown parent names are checked later whenrun()is called. We also copy and deduplicatedepends_onso neither caller list mutations nor repeated entries like["extract", "extract"]can distort ourwaitingcounts:from typing import Any, Callable, Dict, List, Optional from collections import deque from dataclasses import dataclass class Scheduler: def __init__(self) -> None: # _funcs: {"transform": <callable>, ...} mapping each task name to its function self._funcs: Dict[str, Callable[[Dict[str, Any]], Any]] = {} # _deps: {"transform": ["extract"], ...} mapping each task to unique parent names self._deps: Dict[str, List[str]] = {} # _retries: {"transform": 2, ...} mapping each task to extra attempts after failure self._retries: Dict[str, int] = {} def add_task(self, name: str, func: Callable[[Dict[str, Any]], Any], depends_on: Optional[List[str]] = None, retries: int = 0) -> None: if name in self._funcs: raise ValueError(f"task {name!r} is already registered") if retries < 0: raise ValueError("retries must be >= 0") # Copy and deduplicate dependencies in order so caller mutations or repeated # names (e.g. ["extract", "extract"]) cannot distort our edge counts later. unique_deps: List[str] = [] if depends_on is not None: seen_deps = set() for dep in depends_on: if dep not in seen_deps: seen_deps.add(dep) unique_deps.append(dep) self._funcs[name] = func self._deps[name] = unique_deps self._retries[name] = retriesCode topological ordering and cycle detection
_execution_orderruns in four clear phases: check that every named parent exists, buildwaitinganddependents, drain the FIFOreadyqueue, and verify that all tasks were ordered. Notice that a self-loop (xdepending onx) needs no special case:waiting["x"]starts at1, soxnever entersreadyand gets caught bylen(order) < len(self._funcs).class Scheduler: # ... __init__ and add_task above ... def _execution_order(self) -> List[str]: """Kahn's algorithm: return a valid topological order, or raise ValueError.""" # Phase 1: Ensure every referenced dependency was actually registered. # We check this in run() rather than add_task() so tasks can be added in any order. for name, deps in self._deps.items(): for dep in deps: if dep not in self._funcs: raise ValueError(f"task {name!r} depends on unknown task {dep!r}") # Phase 2: Build in-degree counts and reverse adjacency lists. # waiting: {"load": 2, ...} -> how many direct dependencies are not yet ordered waiting: Dict[str, int] = {} # dependents: {"extract": ["transform"], ...} -> downstream tasks unlocked by each task dependents: Dict[str, List[str]] = {} for name in self._funcs: waiting[name] = len(self._deps[name]) dependents[name] = [] for name, deps in self._deps.items(): for dep in deps: dependents[dep].append(name) # Phase 3: Seed a FIFO queue with tasks that have zero dependencies right now, # then repeatedly pop a ready task and decrement its children's waiting counts. ready = deque() for name in self._funcs: if waiting[name] == 0: ready.append(name) order: List[str] = [] while ready: name = ready.popleft() order.append(name) for child in dependents[name]: waiting[child] -= 1 # A child becomes ready only after its very last dependency is ordered. if waiting[child] == 0: ready.append(child) # Phase 4: If fewer than all tasks were ordered, every remaining task is either # part of a cycle or stuck downstream of a cycle. if len(order) < len(self._funcs): stuck: List[str] = [] for name in self._funcs: if waiting[name] > 0: stuck.append(name) raise ValueError(f"dependency cycle: these tasks can never become ready: {stuck}") return orderCode task retries and safe exception handling
When a task runs,
retriesspecifies how many extra attempts it gets after an exception, soretries=0means1total attempt andretries=2means up to3attempts (while attempts <= max_retries).We catch
Exceptionrather than bareexcept(BaseException): a bug or network error inside one task should become aFAILEDresult so independent tasks can still finish, whereasKeyboardInterrupt(Ctrl-C) andSystemExitmust still stop the Python process immediately.class Scheduler: # ... previous methods ... def _run_with_retries(self, name: str, upstream: Dict[str, Any]) -> TaskResult: attempts = 0 last_error: Optional[str] = None max_retries = self._retries[name] # Use <= because retries=0 still runs 1 initial attempt (total max = 1 + retries). while attempts <= max_retries: attempts += 1 try: output = self._funcs[name](upstream) except Exception as exc: # Catch Exception (not BaseException) so task bugs become FAILED results # while KeyboardInterrupt / SystemExit still stop the Python process. last_error = f"{type(exc).__name__}: {exc}" continue return TaskResult(SUCCESS, attempts, output) return TaskResult(FAILED, attempts, error=last_error)Code the pipeline execution loop and trace a failure
Because
orderis already topologically sorted, every parent ofnameis guaranteed to have an entry inresultsbefore we reachname. If any direct parent hasstatus != SUCCESS(meaning that parent eitherFAILEDor was itselfSKIPPED), we marknameasSKIPPEDwithout calling its function. That single!= SUCCESScheck automatically cascades skips down any number of levels!class Scheduler: # ... previous methods ... def run(self) -> Dict[str, TaskResult]: # Validate the entire dependency graph before running any task so a broken # pipeline never half-executes side effects. order = self._execution_order() results: Dict[str, TaskResult] = {} for name in order: # Because `order` is topological, every dep in self._deps[name] is already in `results`. blocked_by: Optional[str] = None for dep in self._deps[name]: # Checking != SUCCESS handles both FAILED parents and SKIPPED grandparents. if results[dep].status != SUCCESS: blocked_by = dep break if blocked_by is not None: results[name] = TaskResult( SKIPPED, error=f"upstream task {blocked_by!r} did not succeed", ) continue # Collect direct parent return values: {"extract": [1, 2, 3], ...} upstream: Dict[str, Any] = {} for dep in self._deps[name]: upstream[dep] = results[dep].output results[name] = self._run_with_retries(name, upstream) return resultsTrace Example 2's five-task graph when
read_usersraisesValueError("corrupt header")acrossretries=1:Step Task Parent statuses Result recorded ---- ---------------- -------------------------------------- ------------------------------- 1 read_users (none) FAILED (attempts=2, ValueError) 2 read_events (none) SUCCESS (attempts=1, output=42) 3 clean_users read_users is FAILED (!= SUCCESS) SKIPPED (attempts=0) 4 summarize_events read_events is SUCCESS SUCCESS (attempts=1, output=84) 5 publish_report clean_users is SKIPPED (!= SUCCESS) SKIPPED (attempts=0)The
read_events -> summarize_eventsbranch completes cleanly while everything downstream ofread_usersis safely skipped.Complete solution
from typing import Any, Callable, Dict, List, Optional from collections import deque from dataclasses import dataclass SUCCESS = "success" FAILED = "failed" SKIPPED = "skipped" @dataclass class TaskResult: """What happened to one task during a run.""" status: str # SUCCESS, FAILED or SKIPPED attempts: int = 0 # how many times the task's callable was called output: Any = None # the callable's return value, when status is SUCCESS error: Optional[str] = None # why the task failed or was skipped class Scheduler: """Registers ETL tasks with dependencies and runs the pipeline once per run() call. A task is a callable taking one argument: a dict that maps each of its direct dependencies' names to that dependency's return value (an empty dict for a task with no dependencies). """ def __init__(self) -> None: # _funcs: {"transform": <callable>, ...} mapping each task name to its function self._funcs: Dict[str, Callable[[Dict[str, Any]], Any]] = {} # _deps: {"transform": ["extract"], ...} mapping each task to unique parent names self._deps: Dict[str, List[str]] = {} # _retries: {"transform": 2, ...} mapping each task to extra attempts after failure self._retries: Dict[str, int] = {} def add_task(self, name: str, func: Callable[[Dict[str, Any]], Any], depends_on: Optional[List[str]] = None, retries: int = 0) -> None: if name in self._funcs: raise ValueError(f"task {name!r} is already registered") if retries < 0: raise ValueError("retries must be >= 0") # Copy and deduplicate dependencies in order so caller mutations or repeated # names (e.g. ["extract", "extract"]) cannot distort our edge counts later. unique_deps: List[str] = [] if depends_on is not None: seen_deps = set() for dep in depends_on: if dep not in seen_deps: seen_deps.add(dep) unique_deps.append(dep) self._funcs[name] = func self._deps[name] = unique_deps self._retries[name] = retries def _execution_order(self) -> List[str]: """Kahn's algorithm: return a valid topological order, or raise ValueError.""" # Phase 1: Ensure every referenced dependency was actually registered. # We check this in run() rather than add_task() so tasks can be added in any order. for name, deps in self._deps.items(): for dep in deps: if dep not in self._funcs: raise ValueError(f"task {name!r} depends on unknown task {dep!r}") # Phase 2: Build in-degree counts and reverse adjacency lists. # waiting: {"load": 2, ...} -> how many direct dependencies are not yet ordered waiting: Dict[str, int] = {} # dependents: {"extract": ["transform"], ...} -> downstream tasks unlocked by each task dependents: Dict[str, List[str]] = {} for name in self._funcs: waiting[name] = len(self._deps[name]) dependents[name] = [] for name, deps in self._deps.items(): for dep in deps: dependents[dep].append(name) # Phase 3: Seed a FIFO queue with tasks that have zero dependencies right now, # then repeatedly pop a ready task and decrement its children's waiting counts. ready = deque() for name in self._funcs: if waiting[name] == 0: ready.append(name) order: List[str] = [] while ready: name = ready.popleft() order.append(name) for child in dependents[name]: waiting[child] -= 1 # A child becomes ready only after its very last dependency is ordered. if waiting[child] == 0: ready.append(child) # Phase 4: If fewer than all tasks were ordered, every remaining task is either # part of a cycle or stuck downstream of a cycle. if len(order) < len(self._funcs): stuck: List[str] = [] for name in self._funcs: if waiting[name] > 0: stuck.append(name) raise ValueError(f"dependency cycle: these tasks can never become ready: {stuck}") return order def _run_with_retries(self, name: str, upstream: Dict[str, Any]) -> TaskResult: attempts = 0 last_error: Optional[str] = None max_retries = self._retries[name] # Use <= because retries=0 still runs 1 initial attempt (total max = 1 + retries). while attempts <= max_retries: attempts += 1 try: output = self._funcs[name](upstream) except Exception as exc: # Catch Exception (not BaseException) so task bugs become FAILED results # while KeyboardInterrupt / SystemExit still stop the Python process. last_error = f"{type(exc).__name__}: {exc}" continue return TaskResult(SUCCESS, attempts, output) return TaskResult(FAILED, attempts, error=last_error) def run(self) -> Dict[str, TaskResult]: # Validate the entire dependency graph before running any task so a broken # pipeline never half-executes side effects. order = self._execution_order() results: Dict[str, TaskResult] = {} for name in order: # Because `order` is topological, every dep in self._deps[name] is already in `results`. blocked_by: Optional[str] = None for dep in self._deps[name]: # Checking != SUCCESS handles both FAILED parents and SKIPPED grandparents. if results[dep].status != SUCCESS: blocked_by = dep break if blocked_by is not None: results[name] = TaskResult( SKIPPED, error=f"upstream task {blocked_by!r} did not succeed", ) continue # Collect direct parent return values: {"extract": [1, 2, 3], ...} upstream: Dict[str, Any] = {} for dep in self._deps[name]: upstream[dep] = results[dep].output results[name] = self._run_with_retries(name, upstream) return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of an ETL (Extract, Transform, Load) pipeline—a workflow that pulls raw data, cleans it, and saves the result—like cooking dinner from a checklist where each step notes how many prerequisite steps it is still waiting on. "Boil water" and "chop vegetables" wait on 0 steps so they can start right away; "cook pasta" waits on 1 step (boiled water); "combine pasta and sauce" waits on 2 steps. Whenever a step finishes, you cross it off and subtract 1 from the waiting counter of every step that depends on it; as soon as a step's counter hits 0, it moves onto the ready list.
A naive scheduler might loop over all tasks again and again, running whichever task has all parents finished until a pass makes no progress. That approach rescans unready tasks up to O(V * (V + E)) times when tasks are registered in reverse order, and—much worse—it executes early tasks (potentially writing to external databases) before discovering that later tasks contain a circular loop or a misspelled dependency name.
Instead, we treat the pipeline as a DAG (directed acyclic graph)—a network of one-way dependency arrows with no cycles—and run Kahn's algorithm, which computes a topological sort (an execution order where every parent comes before all of its children) by tracking each task's in-degree (its count of unfinished dependencies) before running a single task. Take Example 2's five tasks: read_users and read_events (no parents), clean_users (depends on read_users), summarize_events (depends on read_events), and publish_report (depends on both clean_users and summarize_events). Initially waiting is {read_users: 0, read_events: 0, clean_users: 1, summarize_events: 1, publish_report: 2} and ready = [read_users, read_events]. Draining the queue unlocks clean_users and summarize_events first and publish_report only after both drop its counter from 2 to 0, giving order = [read_users, read_events, clean_users, summarize_events, publish_report]. During execution, if read_users fails after exhausting retries=1 (attempts=2), clean_users sees a non-success parent and becomes skipped, read_events (42) and summarize_events (84) still run and succeed, and publish_report sees clean_users.status != "success" and is marked skipped with 0 attempts.
Complexity
- Time:
O(V + E)scheduler work per run (plus the runtime of the task callables themselves), whereVis the number of registered tasks andEis the number of distinct dependency edges. We scan all tasks and edges once to validate names and initializewaitinganddependents, enqueue and pop each task once in Kahn's queue while decrementing across each edge once, and inspect each edge at most twice during execution (checking parent statuses and building theupstreamdictionary). A task configured withretries = rinvokes its callable up tor + 1times. - Space:
O(V + E)for the scheduler's bookkeeping, plus the memory of returned task outputs. Storing_depsand the reversedependentsmap uses one entry per edge (O(E)), while_funcs,waiting,ready, andresultsstore one entry per task (O(V)). Because every task's return value stays inresultsuntilrun()finishes, real pipelines pass file paths or table names rather than gigabyte-sized dataframes in memory.
Edge cases
- Empty pipeline: Calling
run()with zero registered tasks immediately returns{}. - Out-of-order registration: Registering
loadbeforeextractworks cleanly because dependency names are validated insiderun(), notadd_task(). - Unknown dependencies, self-loops (
x -> x), and multi-step cycles: Detected during_execution_order(), raisingValueErrorbefore any task function is called. - Duplicate names in
depends_on: Deduplicated duringadd_task(), sodepends_on=["a", "a"]counts as one dependency edge. - Diamond graph (
a -> b, a -> c, b + c -> d):aexecutes once,bandcboth receivea's output, anddexecutes only after bothbandcfinish. - Partial branch failure: Only tasks downstream of a
FAILEDtask becomeSKIPPED; unrelated branches still execute normally. - Flaky task succeeding on its final retry: Marked
SUCCESSwithattemptsrecording how many tries were needed. - Repeated
run()calls on the sameScheduler: Each call builds fresh counters and a freshresultsdictionary without leftover state.
Common mistakes
- Running tasks while discovering the order: Executing tasks on the fly means side effects happen before a downstream cycle or typo in
depends_onis noticed. - Recursive depth-first search without an "in-progress" state: Using only a single
visitedset either hitsRecursionErroron cycles or silently produces an invalid order. - Marking downstream tasks
FAILEDinstead ofSKIPPED: Operators debugging an incident need to distinguish the root-cause task that raised an exception from healthy downstream tasks that never ran. - Using
<instead of<=in the retry loop:retries = 0still requires1initial attempt (attempts <= max_retries), not0attempts. - Catching
BaseException(or bareexcept:): That swallowsKeyboardInterruptandSystemExit, preventing users from stopping a stuck job with Ctrl-C. - Using a mutable default
depends_on=[]or keeping the caller's list reference: Mutating that list outside the scheduler can silently corrupt the graph.
Alternative approaches
- Depth-first search (DFS) with three-color marking: Marking nodes unvisited, visiting (currently on the recursion stack), or visited produces a valid reverse post-order in
O(V + E)time and detects cycles whenever an edge points to a "visiting" node. Kahn's in-degree counting is usually preferred for schedulers because "which tasks havewaiting == 0right now?" translates directly to parallel worker pools. - Python's
graphlib.TopologicalSorter: Included in the standard library since Python 3.9, it providesprepare(),get_ready(), anddone()with built-in cycle detection. In an interview, implement Kahn's algorithm yourself to show how the mechanics work, then mentiongraphlibas the production standard-library tool.
Follow-up questions
- How would you modify the runner to execute ready tasks concurrently with a maximum worker cap of N? Keep the exact same up-front validation,
waitingcounts, anddependentsmap, but instead of executing a flatorderlist sequentially, submit ready tasks to aThreadPoolExecutor(max_workers=N)wheneverreadyis non-empty and fewer thanNfutures are active. Whenever a future finishes (concurrent.futures.wait(..., return_when=FIRST_COMPLETED)), record itsTaskResulton the main thread and decrementwaitingfor its children, pushing newly unlocked children intoready(if a child has a non-SUCCESSparent, mark itSKIPPEDimmediately and decrement its children too). Keeping all counter updates on the main thread avoids locks, and for CPU-heavy Python work—where the GIL (Global Interpreter Lock), a mutex allowing only one thread to execute Python bytecode at a time, prevents true multi-core parallelism—swap inProcessPoolExecutorwith picklable functions and inputs. - Suppose you introduce exponential-backoff delays between attempts. Which error classes are safe to retry, and which should fail immediately? Exponential backoff doubles the wait between retries (
min(cap, base * 2^(attempt - 1))seconds) and adds jitter—a random delay such as choosing uniformly from[0, wait]—so dozens of tasks failing during a brief outage do not all slam the server again at the exact same second; passsleep=time.sleepas an argument so unit tests can inject a no-op fake timer. Retry only transient infrastructure glitches like network timeouts, dropped connections, database deadlocks, and HTTP429/503responses. Never retry deterministic errors that will fail identically every time, such as code bugs (TypeError,KeyError), invalid credentials (401,403), schema validation failures, or non-idempotent writes that could duplicate records. - If this workflow is triggered on a recurring hourly cadence, how do you handle a run that exceeds sixty minutes? Trigger runs on fixed wall-clock boundaries (
10:00,11:00,12:00) rather than sleeping 3600 seconds after completion (which drifts forward every hour), and pass the target data window (such as[10:00, 11:00)) as an explicit parameter so delayed runs still query the intended hour. If the10:00run is still active at11:00, acquire an exclusive lease lock with an expiration timestamp so overlapping runs do not clobber shared tables, and apply an explicit overrun policy: either queue missed windows to catch up sequentially or skip intermediate ticks if only the latest snapshot matters. Alert whenever run duration approaches 70–80% of the schedule interval, because a job that consistently takes 65 minutes on an hourly schedule will fall further behind forever. - If the worker process dies mid-pipeline, how can you recover from a checkpoint without duplicating downstream writes? Record each task's
(run_id, task_name, status, output_location)in durable storage such as SQLite or Postgres immediately after each task finishes, and store intermediate task outputs in external files or tables rather than Python memory. On restart with the samerun_id, pre-populateresultswith tasks already markedSUCCESSand execute only the remaining tasks. Because the process could crash in the tiny gap after a load writes data to the target database before its checkpoint status is saved, every load step must also be idempotent—meaning running it twice for the samerun_idproduces the exact same stored state as running it once—by overwriting that window's partition, upserting on a unique primary key, or committing the data write and checkpoint row inside a single database transaction.
Follow-up questions
- How would you modify the runner to execute ready tasks concurrently with a maximum worker cap of N?
- Suppose you introduce exponential-backoff delays between attempts. Which error classes are safe to retry, and which should fail immediately?
- If this workflow is triggered on a recurring hourly cadence, how do you handle a run that exceeds sixty minutes?
- If the worker process dies mid-pipeline, how can you recover from a checkpoint without duplicating downstream writes?
Similar questions
- Dual-Path ML Feature Store for Historical Training and Live Inference
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager