Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to Build a Browser DAG Runner with Kahn’s Algorithm

Kahn’s algorithm finds ready tasks, but an asynchronous DAG runtime must also schedule bounded concurrency and define how it handles failure, cycles, and cancellation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To run dependent tasks in order while allowing independent tasks to overlap, use Kahn’s algorithm to maintain a set of ready nodes, then add a separate asynchronous scheduler to dispatch them. The algorithm supplies dependency order; the runtime must also define concurrency, results, errors, and cancellation.

Model the dependency graph

Represent each task as a node and each dependency as a directed edge. Use the convention A -> B to mean that A must finish in the required prerequisite state before B can run. The graph-run project describes the same dependency-before-dependent contract: graph-run documentation.

As an Amazon Associate I earn from qualifying purchases.

Keep a registry of node identifiers, an adjacency list mapping each node to its successors, and a remaining-indegree count for each node. Indegree is the number of prerequisite edges that have not yet been satisfied. Before running anything, decide how the API treats duplicate identifiers, unknown dependencies, repeated edges, and self-edges; these are input-validation choices, not rules imposed by Kahn’s algorithm.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Kahn’s algorithm to find ready work

  1. Initialize the remaining-indegree count for every node.
  2. Add every zero-indegree node to a ready queue.
  3. Take a ready node. For a pure sort, emit it immediately; for a runtime, dispatch it and wait for the prerequisite state your API requires.
  4. Once a node qualifies as processed, decrement the remaining-indegree count of each successor. Add a successor to the ready queue when its count reaches zero.
  5. Continue until no ready node remains.

Several nodes may be ready at once, so a graph can have more than one valid topological ordering. A FIFO queue is a straightforward policy; use a priority structure if callers need a particular order among equally ready tasks, and document that choice.

Turn the ready queue into an asynchronous scheduler

A topological sort returns an ordering; it does not itself execute tasks in parallel. A scheduler should dispatch ready operations asynchronously, subject to a concurrency limit, and collect their outcomes. The graph-run documentation makes this distinction, describing a runner that awaits asynchronous work while allowing independent operations to run concurrently: graph-run.

Track scheduled and completed tasks separately

Do not release a successor merely because its prerequisite was started. Track work that is ready, running, and completed as separate states. When an operation finishes in the state required by your contract, update its successors’ remaining-indegree counts and enqueue any newly eligible work. A worker limit caps the number of active operations; if no slot is free, ready nodes wait in the queue.

In JavaScript, async/await has the same concurrency semantics as promise chains, as MDN explains: Using promises. Awaiting one operation suspends that async function; it does not make a different task dependent on it unless the scheduler imposes that dependency. This is asynchronous coordination, not parallel CPU execution on the browser’s main thread.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keep CPU-heavy work from monopolizing the browser

Browser JavaScript jobs run to completion. A long synchronous task can therefore delay input handling and other work on the same thread. A DAG scheduler can coordinate asynchronous operations, but it does not make CPU-intensive functions yield automatically. MDN describes the browser’s execution model and run-to-completion behavior here: JavaScript execution model.

Choose and document failure behavior

Failure semantics determine whether downstream nodes are allowed to run. For a strict dependency contract, release a successor only after its prerequisites succeed; if a prerequisite fails, mark the successor blocked and report the failure. An alternative API might treat failure as a completed prerequisite or continue independent branches, but it must state that explicitly. Decide whether the runner stops at the first error, returns branch-level outcomes, or aggregates errors; there is no universal policy established by the cited runtime example.

Whichever policy you choose, distinguish a task’s failure from a cycle. A failed task can block descendants even when the graph is acyclic. A cycle is a structural condition in which no topological ordering can satisfy all edges.

Detect cycles instead of accepting a partial run

For a pure ordering function, compare the number of emitted nodes with the graph’s total node count. If fewer nodes were emitted, the remaining graph contains a cycle or is blocked by one; the output is not a complete valid order. Report the condition rather than treating the partial list as success. In an executor, use the same structural check while accounting separately for nodes intentionally blocked by failed prerequisites. The graph-run documentation discusses cyclic graphs and their dependency-order consequences: graph-run documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Make cancellation reach the work

A Promise does not provide a universal cancellation protocol. MDN notes that cancellation generally has to reach the underlying asynchronous operation, often through AbortController and AbortSignal: Using promises.

If your runner accepts an AbortSignal, pass it to operations that support it and define what abort means: it can stop future dispatch, signal active operations, or do both. A signal cannot guarantee that an operation which ignores it will stop. The graph-run documentation also describes skipping pending work when its supplied signal fires: graph-run.

Specify the runtime contract

Before exposing the runner, make its behavior predictable for callers. Document these choices:

  • Input validation: how duplicate node IDs, unknown dependencies, duplicate edges, and self-edges are handled.
  • Ready-node order: whether equally ready nodes use FIFO insertion order or a documented priority rule.
  • Concurrency: the limit on active work and whether a caller can configure it.
  • Prerequisite success: whether a dependent waits for successful completion, any completion, or another defined state.
  • Errors: whether failure is fail-fast, branch-local, or aggregated, and how blocked descendants appear in results.
  • Cancellation: whether abort prevents new work, signals running tasks, or both, and what happens to results already collected.
  • Cycles: whether diagnostics identify only that a cycle exists or also identify affected nodes.

The Promises/A+ specification describes promise behavior, not a DAG scheduler’s policies: Promises/A+. Treat ordering, dispatch, and failure handling as separate parts of your API contract.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.