Detecting Dependency Cycles Before They Ship

Nobody plans a dependency cycle. It appears the day a developer on one team needs a helper that lives in another team's module, and the other module already imports theirs. Everything still compiles, so nothing complains. The damage shows up months later, in builds and tests, long after anyone remembers why.

What a cycle costs

Chapter 3 lays out four separate costs, and they are worth keeping apart because each one hurts a different person.

  • No valid build order. If invoicing depends on customers, customers on notifications, and notifications back on invoicing, then each must be built before the next and also after it. The book notes that the usual workaround is to build the whole loop as a unit, which gives up modularity.
  • Tangled tests. To test any member in isolation you must fake the next one round the loop, so every test depends on a neighbour's interface and the fakes slowly start to hold real logic.
  • Endless change propagation. A change to one member may force changes to the next, and so on, round and back to the start.
  • Cognitive load. To understand one member you have to understand its neighbour and, through it, everything else in the loop, so in the end you cannot understand any part without understanding all of it.

Finding a cycle: follow the path

The simplest detector is a depth-first search. Walk the graph from some starting point, always going to a dependency you have not yet seen, and keep track of the path you are currently on. If you ever meet a component that is already on your current path, you have walked in a circle. If you run out of new dependencies, you back up and carry on from somewhere else. The book calls the path-tracking set a recursion stack.

The point that makes it work is the difference between "seen before" and "on my current path". Meeting a component you finished with earlier is harmless, because that is just two routes to the same place. Only meeting one you are still inside is a cycle. Here is a small version in Python that also returns the offending loop:

def find_cycle(graph):
    colour, trail = {}, []
    def visit(node):
        colour[node] = "grey"          # on the current path
        trail.append(node)
        for nxt in graph.get(node, []):
            if colour.get(nxt) == "grey":
                return trail[trail.index(nxt):] + [nxt]
            if nxt not in colour and (loop := visit(nxt)):
                return loop
        trail.pop()
        colour[node] = "black"         # finished, safe
    for start in list(graph):
        if start not in colour and (loop := visit(start)):
            return loop

Feed it a graph in which invoices leads to customers, then notifications, then back to invoices, and it hands you that three-step loop rather than a bare "true". A report that names the loop is what turns a failing build into a fixable one.

Finding all the tangles at once

A depth-first search is good at saying that a cycle exists. When a codebase has accumulated several, you want to know the shape of the problem, and for that the book uses Tarjan's algorithm. It makes one pass over the graph and groups components into strongly connected components, meaning sets whose members can all reach each other. Any group with more than one member is a cycle that needs resolving. A group of one is simply a healthy component.

That is a useful way to prioritise. Instead of a list of individual loops that overlap, you get a short list of tangled clusters, each of which is one refactoring task.

It is cheap, so there is no excuse

The chapter proves that both approaches run in time proportional to components plus dependencies, using memory proportional to the number of components, and observes that this is optimal: any method has to look at every dependency at least once. The practical meaning is that checking for cycles on every commit costs next to nothing, even in a large repository. The book also shows that the same linear cost applies to computing a build order for a graph with no cycles.

What to do when you do find one is a separate question, with three standard answers: move the shared code down, invert the dependency through an interface, or merge the components. Those appear in architecture verification with graphs.

The takeaway

Cycles are expensive in four different ways and cheap to detect in one. Track the current path, report the loop by name, and run the check automatically so it fails before the cycle ships. LVD goes a step further by making cycles impossible by construction, which a separate article explains, and you can see the background ideas in graph theory for architects.

What the book covers

  • The pseudocode for depth-first cycle detection and for Tarjan's strongly connected components
  • A TypeScript implementation of cycle detection
  • The complexity proofs for cycle detection and topological sorting
  • How cycle checks slot into a full architecture-verification routine