Search

Search papers and lessons

Directed Acyclic Graph

Level 1 · 13 min read

A directed acyclic graph is a set of vertices joined by one-way arrows with no loop of arrows, which makes it a natural model for steps that depend on earlier steps.

On this page

  • Colour = topic mix
  • Discrete math
  • ReadReady to readNot yet

TL;DR

A directed acyclic graph, or DAG, is a graph whose edges are one-way arrows and that has no loop of arrows: you can never leave a vertex and follow arrows back to it. That one rule means the vertices can always be put in a line so that every arrow points forward. DAGs model anything where some steps must come before others and nothing depends on itself.

Builds on: Graph · Leads to: Data Lineage (the record of where a dataset came from), the Spark RDD paper (a cluster engine that runs jobs as a DAG)

Where it's used

Build systems. A compiler build tool such as Make or Bazel is given a list of targets, and each target says which other targets it needs. A program depends on object files, and each object file depends on its source file and headers. Drawing each target as a vertex and each "needed by" relation as an arrow gives a DAG. The tool builds the leaves first and works upward. If the rules ever formed a loop, there would be no first thing to build, so the tool reports an error.

Git history. Each commit points to its parent commit, and a merge commit points to two parents. Git names each commit by a hash that covers its parents, so a commit cannot point to a newer one. Following the pointers from the newest commit back to the first one never returns to a commit you already passed, so the history is a DAG. Git uses that structure to answer questions such as "which commits are in this branch but not in that one".

Distributed data jobs. Apache Spark turns a data program into a graph of transformations: read a file, filter it, join it with another table, count the result. Each transformation takes earlier results as input, so the plan is a DAG. Spark builds this graph before running it, which is a form of lazy evaluation. Spark runs the vertices whose inputs are ready, in parallel where it can, and it can rebuild a lost partition by replaying the path of arrows that produced it.

How it works

Take a small cooking plan with four tasks. Mixing the batter needs the flour and the eggs. Baking needs the batter. The tasks are the vertices, and each arrow means "must finish before".

  1. Draw the vertices and arrows. Vertices: F (flour), E (eggs), M (mix), B (bake). Arrows: F to M, E to M, M to B. Each arrow points from the task that must come first to the task that depends on it.

  2. Check that no loop exists. Try following arrows. From F you reach M, then B, and there is nowhere further to go. From B there are no arrows out. You never return to a vertex you started from, so there is no cycle. The graph is a DAG.

  3. Find the tasks with nothing before them. A vertex with no incoming arrows is a source. F and E have no arrows pointing into them, so both are sources. They can start right now.

  4. Remove them and their outgoing arrows. Remove F and E. The arrows F to M and E to M disappear. Now M has no incoming arrows, so M is the next source. Check: M still needs nothing else, so it is ready.

  5. Repeat. Remove M, which makes B a source. Remove B. Every vertex has been removed.

  6. Read off the order. The order in which you removed the vertices is F, E, M, B (E and F could swap). Every arrow points from an earlier entry in this list to a later one. That list is a topological order, and a graph that has one is a DAG.

Step 6 is the key test. If at some point every remaining vertex still has an incoming arrow, the remaining vertices form a loop and the graph is not a DAG.

flowchart LR
  F[Flour] --> M[Mix]
  E[Eggs] --> M
  M --> B[Bake]

The math

Definition: Directed acyclic graph

A directed graph is a pair G = (V, E), where V is a finite set of vertices and E is a set of ordered pairs (u, v) with u and v in V. The pair (u, v) is an arrow from u to v. A directed cycle is a list of vertices v0,v1,…,vkv_0, v_1, \ldots, v_k with k≥1k \geq 1, vk=v0v_k = v_0, and (vi−1,vi)∈E(v_{i-1}, v_i) \in E for every ii from 1 to kk. A directed acyclic graph is a directed graph with no directed cycle.

A self-loop, an arrow (v, v) from a vertex to itself, is a cycle with k = 1. So a DAG has no self-loops.

Step 2 in symbols: no cycle

A walk that starts at a vertex and follows arrows must either stop or repeat a vertex. If it repeats a vertex, the part between the two visits is a directed cycle. So a DAG is exactly a directed graph in which every walk along arrows stops.

Step 3 in symbols: in-degree and sources

The in-degree of a vertex v is

in⁡(v)=∣{ u∈V:(u,v)∈E }∣\operatorname{in}(v) = |\{\, u \in V : (u, v) \in E \,\}|

This is the number of arrows that end at v. A source is a vertex with in(v) = 0. In the cooking example, in(F) = in(E) = 0, in(M) = 2 and in(B) = 1.

Every finite DAG with at least one vertex has a source. The reason: start at any vertex and walk backward along incoming arrows. Each step goes to a vertex that has an arrow into the current one. If the walk never stopped, some vertex would repeat, and the arrows between the two visits would form a directed cycle, which a DAG does not contain. Since there are finitely many vertices, the walk must stop at a vertex with no incoming arrows, which is a source.

Step 4 and 5 in symbols: topological order

A topological order of a directed graph is a bijection σ from V to the numbers 1 up to n, where n = |V|, such that

(u,v)∈E  ⟹  σ(u)<σ(v)(u, v) \in E \implies \sigma(u) \lt \sigma(v)

Every arrow points from a smaller number to a larger one. A finite directed graph has a topological order exactly when it is a DAG. The forward direction follows by repeatedly removing a source, as in the cooking example. The backward direction is short: if there were an order and a directed cycle, the numbers would have to increase all the way around the cycle and return to the starting number, which is impossible.

A counting fact

A DAG on nn vertices can have at most n(n−1)/2n(n-1)/2 arrows. Put the vertices in a topological order. Every arrow goes from an earlier vertex to a later one, so each arrow is a choice of two different vertices, and there are n(n−1)/2n(n-1)/2 such pairs. For n=4n = 4 the limit is 4⋅3/2=64 \cdot 3 / 2 = 6 arrows.

Worked examples

Example
Tiny: a path of three vertices

Vertices 1, 2, 3. Arrows: 1 to 2, and 2 to 3.

  1. Compute the in-degrees. in(1) = 0, because no arrow ends at 1. in(2) = 1, from the arrow 1 to 2. in(3) = 1, from the arrow 2 to 3.
  2. Find the sources. Only vertex 1 has in-degree 0. Remove it. The arrow 1 to 2 goes, so in(2) becomes 0.
  3. Remove vertex 2, which is now a source. The arrow 2 to 3 goes, so in(3) becomes 0.
  4. Remove vertex 3.
  5. Read off the order: 1, 2, 3. Each arrow points forward in this list.
  6. Interpretation: there is no way to return from 3 to 1, so the graph is a DAG. Its only topological order is 1, 2, 3.
Example
Standard: the diamond

Vertices A, B, C, D. Arrows: A to B, A to C, B to D, C to D.

  1. Compute the in-degrees. in(A) = 0. in(B) = 1 (from A). in(C) = 1 (from A). in(D) = 2 (from B and from C).
  2. Remove the source A. The arrows A to B and A to C go, so in(B) = 0 and in(C) = 0. Now in(D) is still 2.
  3. Remove B and its arrow to D. Now in(D) = 1. C is still a source.
  4. Remove C and its arrow to D. Now in(D) = 0.
  5. Remove D. The order is A, B, C, D.
  6. Check each arrow: A to B goes from position 1 to 2, A to C from 1 to 3, B to D from 2 to 4, and C to D from 3 to 4. All point forward. Swapping B and C gives another valid order, A, C, B, D, so a DAG can have more than one topological order.
  7. Interpretation: this is a DAG with two paths from A to D. It is not a tree, because it has 4 vertices and 4 arrows, while a tree on 4 vertices has 3 edges.
Example
Realistic: a data pipeline with a broken rule

A nightly job has five stages. Arrows: ingest to clean; clean to count; clean to join; count to join; join to report.

  1. Compute the in-degrees. ingest: 0. clean: 1. count: 1. join: 2 (from clean and count). report: 1.
  2. Remove ingest, the only source. Now in(clean) = 0.
  3. Remove clean. Now in(count) = 0 and in(join) = 1.
  4. Remove count. Now in(join) = 0.
  5. Remove join. Now in(report) = 0.
  6. Remove report. The order is ingest, clean, count, join, report. The job can run in that order. It is the only order here, because join needs count and cannot run before it.
  7. Interpretation: the job is a DAG, so the scheduler can run it from start to finish.

Try it: someone adds the arrow report to clean, so that clean waits for the report. Does the graph stay a DAG? Answer: No. The arrows clean to join, join to report and report to clean form a directed cycle, and after ingest is removed, every remaining vertex (clean, count, join, report) still has an incoming arrow, so there is no source to start with.

Common mistakes and tradeoffs

It is tempting to think a DAG is just a tree with arrows. In fact a tree is connected and has exactly one path between any two vertices, while a DAG may be disconnected and may have many paths between two vertices, as the diamond does. A DAG does not need to be connected, and it does not need n−1n-1 arrows.

It is tempting to think that removing the arrows' direction keeps the same property. In fact an undirected graph with no cycles is a forest, and direction matters: the diamond with its arrows removed has a cycle A–B–D–C–A, so the undirected version is not a forest even though the directed graph is acyclic.

It is tempting to think a DAG has only one correct order. In fact a DAG usually has many topological orders, and any of them is a valid schedule. The order only has to respect the arrows.

When to use one. Use a DAG when dependencies flow one way and a step should never wait on itself: builds, schedules, version histories, data lineage, and spreadsheets without circular references.

When not to use one. Do not use a DAG when the real system has feedback. Two people who each wait for the other, a recurrent neural network, or a metabolic cycle in biology all contain loops. Forcing them into a DAG hides the loop. Use a general directed graph and an algorithm that handles cycles, or break the loop explicitly by naming one step as the starting point.

Alternatives. If you only care whether one vertex can reach another, the reachability relation of a DAG is a partial order. If you need to store the graph in a program, an adjacency matrix or an adjacency list is the usual format. To visit every vertex reachable from a start, a breadth-first search works on any directed graph. To compute a value for every vertex with each vertex using the values of its inputs, dynamic programming visits the vertices in a topological order.

StructureArrowsCycles allowedTypical example
TreeNone (or one direction from root)NoFolder hierarchy
Undirected graphNoneYesRoad network
DAGOne-wayNoBuild dependencies
Directed graphOne-wayYesWeb links

History

Project planners in the late 1950s needed to schedule tasks that depended on each other, and they needed an order that never started a task before its inputs were done. Historians often connect the idea of a topological order to that practical problem. In 1962 Arthur B. Kahn published an algorithm that does what the cooking example does by hand: repeatedly remove a vertex with no incoming arrows, keeping the current sources in a queue, and report an error if none exists. That procedure is still taught as a standard way to check for cycles and to sort.

The idea caught on because so many systems share the same shape. Once programmers saw that builds, schedules and data jobs were all DAGs, they built tools around the one fact that makes them work: a DAG always has a place to start.

Recap

  • A graph with one-way arrows is directed. A directed cycle is a path of arrows that returns to its start.
  • A DAG is a directed graph with no directed cycle.
  • Every DAG has a source, a vertex with no incoming arrows, and removing sources one at a time gives a topological order.
  • A directed graph has a topological order exactly when it is a DAG.
  • DAGs model builds, git history, data pipelines and any system where steps depend only on earlier steps.

Next, read partial order to see the same structure as a ranking, and Data Lineage to see how a DAG records where data came from.

Check yourself

QuestionRecall: what is a directed cycle, and why does a DAG have none?Show answer

A directed cycle is a list of vertices v0,v1,…,vkv_0, v_1, \ldots, v_k with vk=v0v_k = v_0 and an arrow from each vertex to the next, with k≥1k \geq 1. A DAG has none by definition. If it had one, following that cycle would return to where it started, so no vertex on the cycle could ever be scheduled first.

QuestionComputation: a DAG has vertices P, Q, R, S and arrows P to R, Q to R, R to S. How many sources does it have, and how many arrows point into S?Show answer

The sources are the vertices with no incoming arrows. P has none, and Q has none, so there are 2 sources. R has two incoming arrows (from P and Q), and S has one incoming arrow (from R). The answer is 2 sources, and 1 arrow points into S.

QuestionWhy: why does every finite DAG with at least one vertex have a source?Show answer

Walk backward from any vertex along incoming arrows. If the walk never stopped, it would revisit a vertex, and the arrows between the two visits would form a directed cycle. A DAG has no directed cycle, so the walk must stop, and it can only stop at a vertex with no incoming arrows, which is a source.

QuestionApplied: a team's build has targets app, lib and test. The app depends on lib, test depends on app, and lib depends on test. Can the build tool order them, and why?Show answer

No. The arrows lib to app, app to test and test to lib form a directed cycle, so after removing any vertex the remaining ones still have incoming arrows. No source exists to start with, so there is no topological order and the tool must report an error. The team has to break one of the dependencies, for example by moving the shared code out of test.

Sources