Est.

Circular Dependencies: How to Find, Break and Prevent Them

Two modules that need each other are one module in disguise. Cycles make load order fragile, tests slow and every change bigger than it looks, and they are much easier to keep out than to remove.

The Architecture Graph Editors · Updated

What a circular dependency is

A circular dependency is a loop in a codebase's dependency graph: module A depends on B, and B, directly or through other modules, depends back on A. The loop can be two files importing each other, or a longer chain such as orders → billing → customers → orders. The same thing happens at every level of a codebase: between files, between packages or libraries in a monorepo, between services that call each other, and between objects wired together by a dependency-injection container.

In graph terms, a codebase without cycles is a directed acyclic graph (DAG): its modules can be put in an order where everything only depends on what comes before it. Robert C. Martin named this the Acyclic Dependencies Principle: the dependency graph of packages should have no cycles. Every module inside a cycle can reach every other one, so for building, testing and reasoning about change they behave as a single unit, whatever the folder structure says. The site's piece on dependency graph analysis covers the wider vocabulary.

Why cycles cause problems

  • Load-order bugs. At runtime, a module in a cycle can be used before it has finished loading. Depending on the language this shows up as undefined values, half-initialized objects or import errors that appear only when files load in a particular order (see the next section).
  • No clean layers. If the domain layer imports something that imports the HTTP layer, the layers exist only on paper. Cycles are often the first visible sign that a layering rule has already been broken.
  • Bigger blast radius. A change to any module in a cycle can affect every other module in it. Impact analysis, incremental builds and test selection all have to treat the whole cycle as changed, so they rebuild and retest more than the change touched.
  • Harder to split and reuse. A package caught in a cycle cannot be extracted, published, owned by another team or moved to another repository without dragging the rest of the loop along.
  • Harder to test. Testing one module in a cycle means loading, faking or mocking all the others.
  • Worse for coding agents. An agent that is asked to change one module has to read the whole loop to know what it affects, and an agent that adds the import it needs can close a new cycle without any test failing. That is why cycles belong in the structural invariants a pipeline checks, not in review comments.

How cycles show up in each language

Some toolchains refuse cycles outright; others accept them and fail in confusing ways later. Knowing which one you are in tells you whether a cycle is a build error or a time bomb.

Messages are typical of current versions; exact wording varies by version and tool.
Language or toolCycles allowed?What you see
GoNo, between packagesThe build fails with import cycle not allowed. Cycles between files in the same package are fine.
Rust / CargoNot between cratesCargo rejects a cyclic package dependency. Modules inside one crate may refer to each other freely.
Node.js (CommonJS)Yesrequire returns the other module's unfinished module.exports, so values read during loading are undefined or missing. The Node.js documentation describes this under "Cycles".
JavaScript / TypeScript (ES modules)YesBindings are live, but reading one before its module has run throws ReferenceError: Cannot access 'X' before initialization. Bundlers such as Rollup and Vite print circular-dependency warnings.
PythonYes, with careImportError: cannot import name 'X' from partially initialized module 'Y' (most likely due to a circular import), usually with from Y import X.
JavaYes, between packagesjavac compiles cyclic packages, but Maven rejects cycles between modules ("The projects in the reactor contain a cyclic reference") and the Java module system rejects cycles between modules too.
.NETNot between projectsVisual Studio and MSBuild refuse a project reference that would make a circular dependency. Namespaces inside one assembly can still form cycles.
Spring (Java)Off by default since Boot 2.6Startup fails with "The dependencies of some of the beans in the application context form a cycle". spring.main.allow-circular-references turns the old behaviour back on, which hides the problem rather than fixing it.
C and C++Yes, with include guardsHeaders that include each other compile only with include guards or #pragma once, and usually fail with incomplete-type errors until one side uses a forward declaration.

A toolchain that rejects cycles at one level does not protect the levels below it. Go stops package cycles but not tangled responsibilities inside a package; .NET stops project cycles but not namespace cycles inside an assembly. Decide which level you care about and check that level explicitly.

How to find circular dependencies

Every detector does the same thing: build the dependency graph from imports (or build files), then look for loops. Most report the strongly connected components of the graph (groups of modules that can all reach each other, found with an algorithm such as Tarjan's), and many print one example path per cycle. Common tools:

Options and flags change between versions; check each tool's current documentation.
ToolEcosystemHow to check for cycles
madgeJavaScript / TypeScriptnpx madge --circular --extensions ts,tsx src/ lists each cycle as a chain of files
dependency-cruiserJavaScript / TypeScriptThe no-circular rule (included in the config depcruise --init generates), run with npx depcruise src
ESLint (eslint-plugin-import)JavaScript / TypeScriptThe import/no-cycle rule; its maxDepth option limits how far it follows imports, which matters for speed on large codebases
NxNx monoreposThe @nx/enforce-module-boundaries lint rule reports circular dependencies between projects; nx graph draws the project graph
circular-dependency-pluginWebpack buildsReports cycles found in the bundle at build time
pydeps / import-linterPythonpydeps --show-cycles prints cycles; import-linter's independence and layers contracts forbid imports that would create them
ArchUnitJava / Kotlinslices().matching("com.example.(*)..").should().beFreeOfCycles() as an ordinary unit test
Go toolchainGogo build and go vet fail on package cycles; nothing extra is needed at package level

Two things to settle before trusting a report. First, type-only imports: in TypeScript, import type is erased at compile time and cannot cause a load-order bug, and in Python the same goes for imports under if TYPE_CHECKING:. Most detectors can be told to count or ignore these; decide whether you are hunting runtime failures (ignore them) or design coupling (count them). Second, re-exports and path aliases: a barrel file (index.ts that re-exports a folder) can create cycles that no single import shows, and a detector that does not resolve aliases from tsconfig.json will miss edges. Point the tool at the same configuration the compiler uses.

How to break a circular dependency

Start by looking at what actually crosses the loop: which functions, types or constants does A use from B, and B from A? Often only one or two names close the cycle, and they decide which fix fits.

  1. Move the misplaced code. The most common cause is one function or type living in the wrong module. If billing imports formatCustomerName from customers, and customers imports Invoice from billing, ask whether each name belongs where it is. Moving one of them often removes the cycle with no new abstraction.
  2. Extract what both sides share. When A and B both need the same types or helpers, move those into a new, lower-level module C that both import and that imports neither. Shared types, constants and pure utilities are the usual candidates.
  3. Invert the dependency. When a lower-level module needs to call up into a higher-level one, have the lower module define an interface (or accept a callback) and let the higher module provide the implementation. The dependency now points one way only. In Go, defining the interface in the package that consumes it is the idiomatic version of this.
  4. Use events instead of direct calls. If B only needs to tell A that something happened, B can publish an event or call a registered listener instead of importing A.
  5. Merge the modules. If two modules cannot change without each other and are always used together, they may really be one. Merging them is honest about that, and the merged module can be split again along a better line later.
  6. Defer the import (stopgap only). Importing inside a function in Python, or using a lazy require in Node.js, moves the import to call time and makes the load error go away. The cycle is still there for builds, tests and readers, so treat it as a temporary patch with a ticket, not a fix.

In large tangles, fix the smallest cycles first and re-run the detector after each change: breaking one edge often splits a large strongly connected component into several smaller ones. Choosing the fewest edges to remove from a big cycle in one go is a hard problem in general (the minimum feedback arc set), so working step by step is the practical approach.

Keeping cycles out in CI

Removing cycles is slow; adding one takes a single import. The durable fix is a check that fails the build when a new cycle appears, run on every pull request, whoever or whatever wrote it.

  • Ratchet, don't block on day one. In a codebase that already has cycles, record the existing ones as a baseline and fail only on new ones. dependency-cruiser supports this with depcruise-baseline and --ignore-known; ArchUnit has FreezingArchRule. Shrink the baseline over time and never let it grow.
  • Check at the level you care about. File-level checks catch load-order bugs; package- or project-level checks protect the architecture. In a monorepo, a project-level rule such as Nx's module boundaries or TypeScript project references (which refuse to form a circular graph) is usually the more important of the two. The piece on module boundary design in TypeScript monorepos covers these tools.
  • Make the rule part of the architecture, not the lint noise. A cycle check that runs as a warning gets ignored. Make it a required status check, and pair it with the layer rules that say which direction dependencies may point, so a cycle is reported as "this import points the wrong way".
  • Track the numbers. The count of cycles, the number of modules involved in any cycle, and the size of the largest strongly connected component are cheap to compute on every build and show whether the codebase is getting more or less tangled.
  • Tell coding agents the rule. Put "no circular dependencies" and the command that checks it in the repository's context files for agents, so an agent runs the check before it opens a change instead of finding out in CI.

Frequently asked questions

What is a circular dependency?

A loop in a codebase's dependency graph: module A depends on module B, and B depends, directly or through other modules, back on A. The modules in the loop cannot be built, tested, loaded or understood independently of each other.

Are circular dependencies always bad?

Not always a bug, but almost always a cost. Mutually recursive functions or types inside one module are normal. Between modules, packages or services, a cycle means the parts are not really separate, which makes load order fragile and changes larger. Some toolchains (Go packages, Cargo crates, .NET projects, Maven modules) refuse them outright.

How do I find circular dependencies in a JavaScript or TypeScript project?

Run npx madge --circular src/ for a quick list, or add dependency-cruiser's no-circular rule or ESLint's import/no-cycle rule to check on every change. In an Nx monorepo, the @nx/enforce-module-boundaries lint rule reports cycles between projects.

How do I fix a circular import in Python?

Find the names that cross the loop and move them: put shared code in a third module both can import, or move a function to the module that uses it. Imports needed only for type hints can go under if TYPE_CHECKING:. Moving an import inside a function makes the error go away but leaves the cycle in place.

Should a cycle check run in CI?

Yes. A new cycle takes one import to create and nothing else in a normal test suite will catch it. Run a detector as a required check on every pull request, with a baseline of existing cycles if the codebase already has some, so only new ones fail the build.

Sources

Go deeper