6/12
Technical Architecture & AI Engineering · 7 min read

Dependency and Task Scheduler With Topological Sort and Cycle Detection

Build a DAG task scheduler in TypeScript using Kahn's topological sort, descriptive cycle-path diagnostics, parallel execution waves, and bounded max-concurrency orchestration.

Why This Matters at Engineering Leadership Scale

Dependency scheduling drives CI/CD pipelines, Terraform graphs, database migration runners, and ETL orchestrators. Without proper graph validation, ad-hoc runners either execute serially (wasting 4x wall-clock time) or deadlock silently when a config edit introduces a cycle (A -> B -> A).

In senior engineering and Engineering Manager code design loops, this drill evaluates separating pure graph planning from async concurrency execution. Leading with Kahn's BFS algorithm lets the Minute-30 extension - returning parallel execution waves (TaskId[][]) capped by maxConcurrency - fall out cleanly with minimal changes.

Core Mental Model & Architecture

AlgorithmTimeSpaceParallel WavesCycle Path DiagnosticsBest Fit
Kahn's BFS (In-Degree)O(V + E)O(V + E)Native (each BFS level is a wave)Short DFS over leftover nodes prints exact cycleTask schedulers, build/ETL planners
3-Color DFSO(V + E)O(V + E)Needs extra longest-path passNative from recursion stackStatic config validators
Repeated ScanO(V^2 + E)O(V + E)Manual batchingPoorNever beyond toy scripts

Leading with Kahn's BFS gives three wins: every zero-indegree node is immediately runnable, draining queue levels produces parallel waves automatically, and if processedCount < totalTasks, a targeted DFS over remaining non-zero in-degree nodes extracts the exact cycle chain (build -> test -> lint -> build).

Step-by-Step Implementation Tutorial

1. Implement Kahn's Wave Planner, Cycle Extractor, and Bounded Executor (Minutes 5 to 28)

typescript
export type TaskId = string;
export type TaskFn = () => Promise<void>;

export class CyclicDependencyError extends Error {
  constructor(public readonly cyclePath: TaskId[]) {
    super(`Cyclic dependency detected: ${cyclePath.join(" -> ")}`);
    this.name = "CyclicDependencyError";
  }
}

export class UnknownDependencyError extends Error {
  constructor(taskId: TaskId, missingDep: TaskId) {
    super(`Task "${taskId}" depends on unknown task "${missingDep}"`);
    this.name = "UnknownDependencyError";
  }
}

export class DependencyTaskScheduler {
  private readonly dependencies = new Map<TaskId, Set<TaskId>>();
  private readonly handlers = new Map<TaskId, TaskFn>();

  public addTask(id: TaskId, deps: TaskId[] = [], handler: TaskFn = async () => {}): void {
    if (!id) throw new Error("Task id must be non-empty");
    if (this.handlers.has(id)) throw new Error(`Duplicate task: "${id}"`);
    this.handlers.set(id, handler);
    this.dependencies.set(id, new Set(deps));
  }

  public getExecutionOrder(): TaskId[] {
    return this.planWaves().flat();
  }

  // Minute-30 Extension: Parallel execution waves (TaskId[][])
  public planWaves(): TaskId[][] {
    const dependents = new Map<TaskId, Set<TaskId>>();
    const inDegree = new Map<TaskId, number>();

    for (const id of this.handlers.keys()) {
      dependents.set(id, new Set());
      inDegree.set(id, 0);
    }

    for (const [taskId, deps] of this.dependencies) {
      for (const dep of deps) {
        if (!this.handlers.has(dep)) throw new UnknownDependencyError(taskId, dep);
        if (dep === taskId) throw new CyclicDependencyError([taskId, taskId]);
        dependents.get(dep)!.add(taskId);
        inDegree.set(taskId, (inDegree.get(taskId) ?? 0) + 1);
      }
    }

    let wave = Array.from(inDegree.entries()).filter(([, d]) => d === 0).map(([id]) => id).sort();
    const waves: TaskId[][] = [];
    let processed = 0;

    while (wave.length > 0) {
      waves.push(wave);
      processed += wave.length;
      const nextWave: TaskId[] = [];
      for (const id of wave) {
        for (const depId of dependents.get(id) ?? []) {
          const deg = (inDegree.get(depId) ?? 0) - 1;
          inDegree.set(depId, deg);
          if (deg === 0) nextWave.push(depId);
        }
      }
      wave = nextWave.sort();
    }

    if (processed < this.handlers.size) {
      throw new CyclicDependencyError(this.extractCycle(inDegree, dependents));
    }
    return waves;
  }

  // Minute-30 Extension: Bounded worker pool respecting maxConcurrency
  public async execute(maxConcurrency = 4): Promise<TaskId[]> {
    if (maxConcurrency <= 0) throw new Error("maxConcurrency must be >= 1");
    const waves = this.planWaves(); // Validate full DAG before running side effects
    const completed: TaskId[] = [];

    for (const wave of waves) {
      const queue = [...wave];
      const workers = Array.from({ length: Math.min(maxConcurrency, queue.length) }, async () => {
        while (queue.length > 0) {
          const id = queue.shift()!;
          await this.handlers.get(id)!();
          completed.push(id);
        }
      });
      await Promise.all(workers);
    }
    return completed;
  }

  private extractCycle(inDegree: Map<TaskId, number>, dependents: Map<TaskId, Set<TaskId>>): TaskId[] {
    const remaining = new Set(Array.from(inDegree.entries()).filter(([, d]) => d > 0).map(([id]) => id));
    const visiting = new Set<TaskId>(), visited = new Set<TaskId>(), stack: TaskId[] = [];

    const dfs = (node: TaskId): TaskId[] | null => {
      visiting.add(node);
      stack.push(node);
      for (const next of dependents.get(node) ?? []) {
        if (!remaining.has(next)) continue;
        if (visiting.has(next)) return [...stack.slice(stack.indexOf(next)), next];
        if (!visited.has(next)) {
          const found = dfs(next);
          if (found) return found;
        }
      }
      stack.pop();
      visiting.delete(node);
      visited.add(node);
      return null;
    };

    for (const id of remaining) {
      if (!visited.has(id)) {
        const cycle = dfs(id);
        if (cycle) return cycle;
      }
    }
    return Array.from(remaining);
  }
}

2. Write Unit Tests & Minute-30 Extension Walkthrough (Minutes 30 to 50)

Test four cases:

  1. Diamond DAG: A -> B, A -> C, (B, C) -> D produces [["A"], ["B", "C"], ["D"]].
  2. Exact cycle path: A -> B -> C -> A throws CyclicDependencyError with the full cycle chain, running zero task handlers.
  3. Self-loop & unknown dependency: A -> A throws CyclicDependencyError; A -> "ghost" throws UnknownDependencyError.
  4. Concurrency ceiling: 6 tasks in one wave with maxConcurrency = 2 confirm peakActive === 2.

If the interviewer asks about stragglers inside a wave ("Task B takes 20s, Task C takes 1s, Task E only needs C"), explain upgrading execute() from wave barriers to a dynamic ready queue that enqueues E the moment C finishes rather than waiting on B.

Worked Production Scenario: Before vs. After

Context: A multi-squad data platform ran 64 dependent nightly warehouse and compliance smoke jobs from a hand-ordered YAML list. Bad ordering caused 6 stale-read incidents per quarter, and a cross-squad cycle once deadlocked CI for 90 minutes with zero diagnostics.

After: The Data Platform squad adopted DependencyTaskScheduler, validating planWaves() on every PR in CI and executing independent waves with maxConcurrency = 8.

MetricBeforeAfter
Nightly pipeline total runtime74 minutes (serial)19 minutes (8x parallel)
Bad-order / stale-read incidents / quarter60 (DAG-enforced)
Time to pinpoint circular job config45+ mins manual traceInstant (A -> B -> C -> A in CI)
CI worker utilization12% average78% bounded steady

Common Failure Modes & Anti-Patterns

  1. Mutating shared inDegree state on the instance: Calling planWaves() twice returns empty waves if inDegree is not rebuilt locally. Fix: Build fresh inDegree and dependents maps inside planWaves() so planning is pure and idempotent.
  2. Throwing a vague "Cycle detected" message: Leaves engineers hunting across 80 files. Fix: Run extractCycle() over remaining nodes and attach cyclePath to CyclicDependencyError.
  3. Running Wave 1 before validating the full graph: Mutates production state before discovering a Wave-3 cycle. Fix: Validate planWaves() completely before invoking any handler.

How to Handle Pushback in the Room

Skeptical Principal Engineer: "Wave barriers waste worker slots when one task in a wave is slow - why not build dynamic scheduling upfront?"

Calm Response: "Agreed that dynamic ready-queue scheduling eliminates straggler wait time. Building pure planWaves() first validates the DAG, prints exact cycles, and gives deterministic wave visibility in 20 minutes - and because inDegree and dependents are already modeled, switching execute() to a dynamic ready queue takes ten lines without changing our public API."

Pushing Product Manager: "Can we skip cycle detection for v1 since only internal engineers write configs?"

Calm Response: "Internal teams create cross-domain cycles during refactors regularly. Cycle detection is twenty lines next to topological sort and turns a silent 90-minute production hang into a 10ms PR check."

Key Takeaways & This Week's Action Rep

  • Lead with Kahn's BFS (O(V + E)): Delivers topological order, cycle detection, and parallel waves in one pass.
  • Validate the entire DAG upfront: Never execute side effects on a cyclic or incomplete graph.
  • Report the exact cycle path: Attach A -> B -> C -> A to CyclicDependencyError.
  • Cap concurrency explicitly: Enforce maxConcurrency so large parallel waves never overload downstream pools.

This Week's Action Rep: Run a 45-minute drill without autocomplete. Build DependencyTaskScheduler, then upgrade execute() at minute 35 to a dynamic ready queue that dispatches dependents the instant their own prerequisites finish.