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 of SUCCESS, FAILED, or SKIPPED.
    • attempts: total number of times func was invoked during this run (0 when SKIPPED).
    • output: return value of func when status == SUCCESS, otherwise None.
    • error: None when status == SUCCESS; "<ExcType>: <message>" from the final raised exception when status == FAILED; and a non-empty reason string when status == 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 in depends_on are treated as a single dependency.
    • retries specifies how many additional attempts func gets if it raises an Exception (so retries=0 runs at most 1 attempt, and retries=2 runs at most 3 attempts).
    • Raise ValueError immediately if name was already registered or if retries < 0.
  • Scheduler.run() -> Dict[str, TaskResult]:
    • Pre-execution graph check: Before invoking any task callable, raise ValueError if 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 to 1 + retries callable attempts), strictly after every direct dependency has finished with SUCCESS.
    • Retries and partial failure isolation: Catch Exception (allowing process-level signals like KeyboardInterrupt and SystemExit to propagate). If all 1 + retries attempts raise Exception, mark the task FAILED. Mark every task that depends directly or transitively on a non-SUCCESS task as SKIPPED (attempts=0) while still executing all unaffected tasks.
    • Return a dictionary mapping every registered task name to its TaskResult ({} for an empty scheduler). Calling run() again on the same Scheduler performs a fresh execution.

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 raises ValueError("corrupt header").
  • "clean_users" (depends_on=["read_users"]): transforms user rows.
  • "read_events" (no dependencies): returns 42.
  • "summarize_events" (depends_on=["read_events"]): returns upstream["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^4 registered tasks and 0 <= E <= 5 * 10^4 dependency edges; scheduler overhead per run() should scale as O(V + E).
  • retries >= 0 for valid registrations (retries < 0 or duplicate name raises ValueError in add_task).
  • Mutating a caller-owned depends_on list after calling add_task must not alter the registered graph.

Step-by-step walkthrough

  1. 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 upstream mapping 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=r gets up to 1 + r attempts. If every attempt raises an exception, the task is marked FAILED, every downstream task that depends on it (directly or indirectly) is marked SKIPPED, and independent branches still run to completion.
    • Up-front graph validation: Unknown dependency names and dependency cycles raise ValueError before 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
    
  2. 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 done set, 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 order
    

    This sketch has two problems:

    1. Quadratic work in reverse order: If V tasks form a chain registered from last to first, each pass unlocks only one task, costing O(V * (V + E)) checks for V tasks and E dependency arrows.
    2. Late failure on broken graphs: If tasks b -> c -> b form a cycle after task a, a has 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.

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

    1. Compute waiting[task] = number of direct dependencies of task, and build a reverse lookup dependents[parent] = list of children that depend on parent.
    2. Put every task with waiting[task] == 0 into a ready FIFO queue.
    3. Pop a task from ready, append it to order, and subtract 1 from waiting[child] for each of its children. Whenever a child's waiting count hits 0, push that child onto ready.

    This procedure is Kahn's algorithm. If order ends up shorter than the total number of tasks, the unvisited tasks still have waiting > 0 because 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]
    
  4. Code task registration and input validation

    add_task checks 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 when run() is called. We also copy and deduplicate depends_on so neither caller list mutations nor repeated entries like ["extract", "extract"] can distort our waiting counts:

    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] = retries
    
  5. Code topological ordering and cycle detection

    _execution_order runs in four clear phases: check that every named parent exists, build waiting and dependents, drain the FIFO ready queue, and verify that all tasks were ordered. Notice that a self-loop (x depending on x) needs no special case: waiting["x"] starts at 1, so x never enters ready and gets caught by len(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 order
    
  6. Code task retries and safe exception handling

    When a task runs, retries specifies how many extra attempts it gets after an exception, so retries=0 means 1 total attempt and retries=2 means up to 3 attempts (while attempts <= max_retries).

    We catch Exception rather than bare except (BaseException): a bug or network error inside one task should become a FAILED result so independent tasks can still finish, whereas KeyboardInterrupt (Ctrl-C) and SystemExit must 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)
    
  7. Code the pipeline execution loop and trace a failure

    Because order is already topologically sorted, every parent of name is guaranteed to have an entry in results before we reach name. If any direct parent has status != SUCCESS (meaning that parent either FAILED or was itself SKIPPED), we mark name as SKIPPED without calling its function. That single != SUCCESS check 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 results
    

    Trace Example 2's five-task graph when read_users raises ValueError("corrupt header") across retries=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_events branch completes cleanly while everything downstream of read_users is safely skipped.

  8. 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), where V is the number of registered tasks and E is the number of distinct dependency edges. We scan all tasks and edges once to validate names and initialize waiting and dependents, 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 the upstream dictionary). A task configured with retries = r invokes its callable up to r + 1 times.
  • Space: O(V + E) for the scheduler's bookkeeping, plus the memory of returned task outputs. Storing _deps and the reverse dependents map uses one entry per edge (O(E)), while _funcs, waiting, ready, and results store one entry per task (O(V)). Because every task's return value stays in results until run() 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 load before extract works cleanly because dependency names are validated inside run(), not add_task().
  • Unknown dependencies, self-loops (x -> x), and multi-step cycles: Detected during _execution_order(), raising ValueError before any task function is called.
  • Duplicate names in depends_on: Deduplicated during add_task(), so depends_on=["a", "a"] counts as one dependency edge.
  • Diamond graph (a -> b, a -> c, b + c -> d): a executes once, b and c both receive a's output, and d executes only after both b and c finish.
  • Partial branch failure: Only tasks downstream of a FAILED task become SKIPPED; unrelated branches still execute normally.
  • Flaky task succeeding on its final retry: Marked SUCCESS with attempts recording how many tries were needed.
  • Repeated run() calls on the same Scheduler: Each call builds fresh counters and a fresh results dictionary 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_on is noticed.
  • Recursive depth-first search without an "in-progress" state: Using only a single visited set either hits RecursionError on cycles or silently produces an invalid order.
  • Marking downstream tasks FAILED instead of SKIPPED: 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 = 0 still requires 1 initial attempt (attempts <= max_retries), not 0 attempts.
  • Catching BaseException (or bare except:): That swallows KeyboardInterrupt and SystemExit, 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 have waiting == 0 right now?" translates directly to parallel worker pools.
  • Python's graphlib.TopologicalSorter: Included in the standard library since Python 3.9, it provides prepare(), get_ready(), and done() with built-in cycle detection. In an interview, implement Kahn's algorithm yourself to show how the mechanics work, then mention graphlib as 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, waiting counts, and dependents map, but instead of executing a flat order list sequentially, submit ready tasks to a ThreadPoolExecutor(max_workers=N) whenever ready is non-empty and fewer than N futures are active. Whenever a future finishes (concurrent.futures.wait(..., return_when=FIRST_COMPLETED)), record its TaskResult on the main thread and decrement waiting for its children, pushing newly unlocked children into ready (if a child has a non-SUCCESS parent, mark it SKIPPED immediately 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 in ProcessPoolExecutor with 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; pass sleep=time.sleep as 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 HTTP 429 / 503 responses. 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 the 10:00 run is still active at 11: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 same run_id, pre-populate results with tasks already marked SUCCESS and 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 same run_id produces 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

Similar questions

More Unity interview questions

All 2 Unity questions →