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
| Algorithm | Time | Space | Parallel Waves | Cycle Path Diagnostics | Best 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 cycle | Task schedulers, build/ETL planners |
| 3-Color DFS | O(V + E) | O(V + E) | Needs extra longest-path pass | Native from recursion stack | Static config validators |
| Repeated Scan | O(V^2 + E) | O(V + E) | Manual batching | Poor | Never 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)
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:
- Diamond DAG:
A -> B,A -> C,(B, C) -> Dproduces[["A"], ["B", "C"], ["D"]]. - Exact cycle path:
A -> B -> C -> AthrowsCyclicDependencyErrorwith the full cycle chain, running zero task handlers. - Self-loop & unknown dependency:
A -> AthrowsCyclicDependencyError;A -> "ghost"throwsUnknownDependencyError. - Concurrency ceiling: 6 tasks in one wave with
maxConcurrency = 2confirmpeakActive === 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.
| Metric | Before | After |
|---|---|---|
| Nightly pipeline total runtime | 74 minutes (serial) | 19 minutes (8x parallel) |
| Bad-order / stale-read incidents / quarter | 6 | 0 (DAG-enforced) |
| Time to pinpoint circular job config | 45+ mins manual trace | Instant (A -> B -> C -> A in CI) |
| CI worker utilization | 12% average | 78% bounded steady |
Common Failure Modes & Anti-Patterns
- Mutating shared
inDegreestate on the instance: CallingplanWaves()twice returns empty waves ifinDegreeis not rebuilt locally. Fix: Build freshinDegreeanddependentsmaps insideplanWaves()so planning is pure and idempotent. - Throwing a vague
"Cycle detected"message: Leaves engineers hunting across 80 files. Fix: RunextractCycle()over remaining nodes and attachcyclePathtoCyclicDependencyError. - 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 -> AtoCyclicDependencyError. - Cap concurrency explicitly: Enforce
maxConcurrencyso 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.