Skip to main content

How to Detect Circular Task Dependencies in TypeScript (With Tests)

Updated 10 min readMarkdown
How to Detect Circular Task Dependencies in TypeScript (With Tests)

How to Detect Circular Task Dependencies in TypeScript (With Tests)

Task A can't start until B is done. B is waiting on C. And C is waiting on A.

Nobody did anything wrong on their own. Each link made sense when someone added it. But together they form a loop, and a loop means none of these tasks can ever start.

Any tool that lets tasks block each other has to deal with this: project trackers, build systems, CI pipelines, migration runners. In this post we'll build a small, dependency-free TypeScript module that does three things:

  1. Finds a cycle and tells you exactly which tasks are in it.
  2. Produces a working order where blockers always come first.
  3. Rejects a bad link before it is saved, instead of discovering the loop later.

Everything below is tested, and the code is short enough to read in one sitting.

The data model

Keep the model boring. A plan is a map from each task to the tasks that block it:

export type TaskId = string;

/** Maps a task to the tasks it depends on (its blockers). */
export type DependencyMap = Record<TaskId, TaskId[]>;

So { deploy: ["test"], test: ["build"], build: [] } reads as: deploy waits for test, test waits for build, build waits for nothing.

One decision to make early is the direction of the arrows. Here, an edge from A to B means "A depends on B". Pick a direction and stick with it. Mixing the two is the most common source of confusing bugs in this kind of code.

A cycle error worth reading

"Invalid dependency" is a bad error message. The person who added the link needs to know which tasks form the loop so they can decide which link to remove. So we'll carry the path inside a custom error:

export class CycleError extends Error {
  readonly cycle: TaskId[];

  constructor(cycle: TaskId[]) {
    super(`Circular dependency: ${cycle.join(" -> ")}`);
    this.name = "CycleError";
    this.cycle = cycle;
  }
}

A cycle is represented as a closed path, with the first task repeated at the end: ["A", "B", "C", "A"].

The classic approach is a depth-first search that colours each task with one of three states:

  • unvisited: we haven't looked at it yet
  • in progress: it's on the path we are currently walking
  • done: we've fully explored it and found no loop through it

The key rule: if we walk into a task that is in progress, we have come back to something on our own path. That is a cycle.

const UNVISITED = 0;
const IN_PROGRESS = 1;
const DONE = 2;

export function findCycle(deps: DependencyMap): TaskId[] | null {
  const state = new Map<TaskId, number>();
  const stack: TaskId[] = [];

  const visit = (id: TaskId): TaskId[] | null => {
    state.set(id, IN_PROGRESS);
    stack.push(id);

    for (const next of deps[id] ?? []) {
      const s = state.get(next) ?? UNVISITED;
      if (s === IN_PROGRESS) {
        // `next` is already on the current path: slice out the loop.
        return [...stack.slice(stack.indexOf(next)), next];
      }
      if (s === UNVISITED) {
        const found = visit(next);
        if (found) return found;
      }
    }

    stack.pop();
    state.set(id, DONE);
    return null;
  };

  for (const id of Object.keys(deps)) {
    if ((state.get(id) ?? UNVISITED) === UNVISITED) {
      const found = visit(id);
      if (found) return found;
    }
  }
  return null;
}

Why three states instead of a simple "visited" flag? Consider a diamond: D depends on B and C, and both depend on A. A plain visited flag would see A twice and wrongly call it a cycle. The "done" state says: we have been here, it was fine, move on. Only "in progress" means "this is on my current path".

The stack is what lets us report the loop itself. When we hit a task that is in progress, we find where it sits in the stack and slice from there. If the graph is start -> A -> B -> A, the answer is ["A", "B", "A"]. The start task leads into the loop but isn't part of it, so it is left out.

Complexity is O(V + E), where V is the number of tasks and E the number of links. Each task and each link is looked at once.

Step 2: Produce a working order

Finding a loop is only half the job. Most tools also need an order to work in. This is a topological sort, and Kahn's algorithm is a clean way to do it: repeatedly take tasks that have no unfinished blockers, then "unblock" whatever was waiting on them.

export function workingOrder(deps: DependencyMap): TaskId[] {
  // Collect every task, including ones that only appear as a blocker.
  const ids = new Set<TaskId>(Object.keys(deps));
  for (const blockers of Object.values(deps)) blockers.forEach((b) => ids.add(b));

  const remaining = new Map<TaskId, number>();
  const unblocks = new Map<TaskId, TaskId[]>();
  for (const id of ids) {
    const blockers = [...new Set(deps[id] ?? [])];
    remaining.set(id, blockers.length);
    for (const b of blockers) {
      unblocks.set(b, [...(unblocks.get(b) ?? []), id]);
    }
  }

  const ready = [...ids].filter((id) => remaining.get(id) === 0);
  const order: TaskId[] = [];

  while (ready.length > 0) {
    const id = ready.shift()!;
    order.push(id);
    for (const dependent of unblocks.get(id) ?? []) {
      const left = remaining.get(dependent)! - 1;
      remaining.set(dependent, left);
      if (left === 0) ready.push(dependent);
    }
  }

  if (order.length < ids.size) {
    throw new CycleError(findCycle(deps) ?? []);
  }
  return order;
}

Two details are easy to miss:

  • Tasks that only appear as blockers. In { B: ["A"] }, task A is never a key. If we only iterate over keys, A silently disappears from the order. Collecting ids from both keys and values fixes that.
  • Duplicate links. If someone saves D -> B twice, counting it twice would leave D waiting forever. Wrapping blockers in a Set removes the duplicates.

The cycle detection comes for free. If a loop exists, none of its tasks ever reach zero blockers, so they never enter the order. When order.length comes up short, we know something is stuck, and we call findCycle to say exactly what.

Reporting a loop after the fact is useful. Preventing it is better. When a user adds a link, we can check whether it would close a loop, and reject it on the spot.

The logic is simple. Adding "task depends on blocker" creates a loop only if blocker already depends on task, directly or through other tasks. So we look for a path from blocker back to task:

export function cycleIfAdded(
  deps: DependencyMap,
  task: TaskId,
  blocker: TaskId
): TaskId[] | null {
  if (task === blocker) return [task, task];

  const path = pathBetween(deps, blocker, task);
  return path ? [task, ...path] : null;
}

function pathBetween(deps: DependencyMap, from: TaskId, to: TaskId): TaskId[] | null {
  const seen = new Set<TaskId>();
  const walk = (id: TaskId, path: TaskId[]): TaskId[] | null => {
    if (id === to) return path;
    if (seen.has(id)) return null;
    seen.add(id);
    for (const next of deps[id] ?? []) {
      const found = walk(next, [...path, next]);
      if (found) return found;
    }
    return null;
  };
  return walk(from, [from]);
}

Used at the point where a link is created, it looks like this:

const loop = cycleIfAdded(deps, "A", "C");
if (loop) {
  throw new CycleError(loop); // "Circular dependency: A -> C -> B -> A"
}

The user sees the exact chain that would have formed, which is far more useful than "could not save".

Test the edges, not just the happy path

Cycle code looks right on a three-node example and then breaks on the cases nobody drew. These tests use Node's built-in test runner, so there are no dependencies to install:

import { test } from "node:test";
import assert from "node:assert/strict";
import { findCycle, workingOrder, cycleIfAdded, CycleError, type DependencyMap } from "./dependencies.ts";

test("findCycle reports the exact loop", () => {
  const deps: DependencyMap = { A: ["B"], B: ["C"], C: ["A"] };
  assert.deepEqual(findCycle(deps), ["A", "B", "C", "A"]);
});

test("findCycle ignores the tail leading into a loop", () => {
  const deps: DependencyMap = { start: ["A"], A: ["B"], B: ["A"] };
  assert.deepEqual(findCycle(deps), ["A", "B", "A"]);
});

test("findCycle catches a task that depends on itself", () => {
  assert.deepEqual(findCycle({ A: ["A"] }), ["A", "A"]);
});

test("workingOrder includes tasks that only appear as blockers", () => {
  assert.deepEqual(workingOrder({ B: ["A"] }), ["A", "B"]);
});

test("workingOrder handles duplicate links and diamonds", () => {
  const deps: DependencyMap = { D: ["B", "C", "B"], B: ["A"], C: ["A"], A: [] };
  const order = workingOrder(deps);
  assert.equal(order[0], "A");
  assert.equal(order[3], "D");
});

test("cycleIfAdded blocks a link that closes a loop", () => {
  const deps: DependencyMap = { B: ["A"], C: ["B"] };
  // Making A depend on C would create A -> C -> B -> A.
  assert.deepEqual(cycleIfAdded(deps, "A", "C"), ["A", "C", "B", "A"]);
});

The full suite has 11 tests, including a valid plan, a safe link, and a 2,000-task chain. All 11 pass on Node 22 with node --test dependencies.test.ts. On an older Node version, run the same file through tsx.

The edge cases worth keeping in your own suite are:

Case Why it matters
Task depends on itself The smallest possible loop, and easy to forget
Tail leading into a loop The reported cycle should exclude tasks that merely lead into it
Diamond (two paths to one task) Not a cycle, so a naive "visited" flag gets it wrong
Blocker never listed as a key It must still appear in the working order
Duplicate links They must not leave a task waiting forever
Disconnected groups The search must start from every unvisited task, not just one

A note on recursion

findCycle and pathBetween are recursive, so a very deep chain could overflow the call stack. In a quick check on Node 22, a 50,000-task chain ran without problems. Real plans are far smaller than that, so recursion is fine for most uses. If you expect extreme depth, convert the search to use an explicit stack, which gives the same results.

When to use which function

You need to... Use
Validate a plan that already exists findCycle
Decide what to work on, and in what order workingOrder
Reject a bad link at save time cycleIfAdded

In practice you want all three. Check at save time so loops never get in, and keep the whole-plan check as a safety net for imported or edited data.

Wrapping up

A circular dependency is a small bug with a large effect: one wrong link and part of a plan can never move. The fix is not complicated:

  • Represent the plan as a plain map of task to blockers.
  • Use a three-state depth-first search to find a loop, and report the path.
  • Use Kahn's algorithm for a working order, and let it expose any stuck tasks.
  • Check every new link before saving it.
  • Test the awkward cases: self-links, diamonds, duplicates, and blockers that only appear as values.

Copy the module, adapt the types to your own task shape, and add the tests that match your data.

Disclosure: this post is published by the ProjTL team. The code is a general technique for any task or build system and is not a description of how ProjTL is implemented.

About the author

  • ProjTL is a project management and productivity blog sharing practical insights on project planning, task management, team collaboration, AI-powered workflows and business operations. Explore articles on managing project deadlines, improving team productivity, tracking workloads, reducing project delays and making work more visible. The blog also covers construction project management, WhatsApp-based work updates, time tracking and the evolving role of AI in everyday business workflows. Whether you're a project manager, business owner, team leader or professional, ProjTL offers useful ideas and practical guidance to help teams organise work and manage projects more effectively.

No comments yet. Be the first to comment.