How does Nx build the project graph, and what counts as a circular dependency?

A project-level circular dependency exists when following edges from project A eventually leads back to A. The cycle can be direct (A imports from B and B imports from A) or longer (A → B → C → A). Nodes in the Nx graph are projects, not files, so a single import anywhere in a project creates an edge for the whole project.

Nx builds these edges from three sources:

  • Source imports. Nx statically analyzes the JavaScript and TypeScript files in each project. It resolves each import specifier through the workspace's TypeScript path aliases and package resolution, and it records an edge when the specifier lands in another project.
  • Package manifests. A package.json dependency on another workspace package also produces an edge.
  • Implicit dependencies. Edges declared in project configuration are added on top of the analyzed edges, whether or not any code references the target.

Because this analysis is mechanical, edges show up that nobody intended. A test helper that imports a fixture from a sibling library creates an edge. So does a barrel file that re-exports another project's API, or an old manifest entry nobody removed. Nx counts these the same way it counts production code.

Expected edges can also go missing. Nx can't resolve an import whose specifier is computed at runtime. It also doesn't see plugins loaded by name from configuration or services that only talk over the network. A cycle between two services that call each other's HTTP APIs never appears in the graph. Neither do file-level cycles inside a single project, because both ends of the cycle belong to the same node.

 +----------------+  +-------------------+  +----------------------+
 | Source imports |  | package.json deps |  | implicitDependencies |
 | parsed JS/TS   |  | on workspace pkgs |  | in project config    |
 | + path aliases |  |                   |  | (no code needed)     |
 +-------+--------+  +---------+---------+  +-----------+----------+
         |                     |                        |
         +---------------------+------------------------+
                               |
                               v
 +------------------------------------------------------------------+
 |               Nx project graph (nodes = projects)                |
 |                                                                  |
 |    +-------+         +-------+         +-------+                 |
 |    |   A   |-------->|   B   |-------->|   C   |                 |
 |    +-------+         +-------+         +-------+                 |
 |        ^                                   |                     |
 |        +-----------------------------------+                     |
 |                  cycle: A -> B -> C -> A                         |
 +------------------------------------------------------------------+

 Never become edges (invisible to the graph):
 +---------------+ +---------------+ +---------------+ +---------------+
 | computed      | | plugins loaded| | HTTP calls    | | file cycles in|
 | import() path | | by name       | | between svcs  | | one project   |
 +---------------+ +---------------+ +---------------+ +---------------+

Nx derives project-level edges from source imports, package.json dependencies and declared implicit dependencies. A cycle such as A -> B -> C -> A forms only from those edges, so computed imports, plugins loaded by name, network calls and file-level cycles never appear in the graph.

How does cycle detection work in Nx?

Every cycle check in Nx works from the same project graph described above. Nx does not run a separate analysis for cycles. Once the graph exists, finding a cycle is a standard graph problem: a cycle exists when a walk along directed edges returns to a project already on the current path.

That one graph is used in three places, and each one reports cycles differently:

  • Task scheduling. When you run a target such as build, Nx expands the project graph into a task graph using each target's dependsOn configuration. With ^build, every project's build waits on the builds of its dependencies. If the projects form a loop, no task can go first. Nx reports the task graph cycle instead of choosing an arbitrary order.
  • Lint. The enforce-module-boundaries rule loads the project graph while it lints a file. For each import that crosses into another project, it checks whether a path already leads from the target project back to the importing project. If one does, the new import would close a loop. The rule reports the import and the chain of projects in the loop.
  • Visualization and export. nx graph renders the same nodes and edges in the browser, and nx graph --file=graph.json writes them to JSON so your own scripts can walk them.

The detection is only as complete as the graph. If an edge is missing, as with computed imports or network calls, no check will see the cycle. If an edge is unintended, as with a stale implicit dependency, every check will report a cycle even though the code is fine. When a reported cycle looks wrong, check the edges before you debug the checker.

Why do dependency cycles cost engineering time in an Nx workspace?

A project cycle undoes the guarantee that ^build gives you: dependencies finish before their dependents start. When lib-a depends on lib-b and lib-b depends on lib-a, no valid order exists. Nx surfaces this as a task graph cycle. Teams then work around it with ad-hoc dependsOn overrides or by building twice, and those workarounds hide real ordering bugs.

The cycle also widens nx affected. Affected status propagates to every dependent, and in a cycle each project is a dependent of the other. A change to either one marks both as affected, plus everything that depends on either. The same coupling hurts caching. If a project's cache inputs include its dependencies, which is common for build and test targets, an edit to either side of the cycle invalidates cached results for both and for their dependents.

Illustrative estimate (assumed numbers, not a benchmark)

Extra CI minutes per day = (affected projects with cycle − affected projects without) × average minutes per project × changes per day

Assume a typical change affects 12 projects without the cycle and 30 with it, each project's targets average 3 minutes, and the team merges 40 changes a day. The cycle costs (30 − 12) × 3 × 40 = 2,160 extra CI minutes per day.

Cycles also block extraction. You cannot publish lib-a without lib-b, so the two must be versioned and released together.

Platform and backend teams that own shared libraries and CI pay most of this cost. Prioritize the work when a cycle touches a widely depended-on library, or before you plan to publish or split out a package.

When should you use Nx's cycle detection and the techniques in this guide?

Use them whenever the Nx project graph drives decisions that matter to you. That covers task ordering, nx affected in CI, and caching. If any of these behave unexpectedly, check for cycles first. Specific situations where the work pays off:

  • A task graph cycle error appears when running a target with ^ dependencies. This is the one case you can't defer, because Nx can't order the tasks.
  • nx affected selects far more projects than a change should touch. A cycle that includes a widely used library pulls every dependent of every project in the loop into the affected set.
  • You plan to publish, version independently, or move a library out of the workspace. Projects in a cycle can only ship together.
  • You are introducing or tightening library layering. Tags and depConstraints are easiest to adopt right after the existing cycles are mapped, because the cycle list shows where the layering is already being broken.
  • A new workspace or a newly migrated codebase. Turning on the lint rule before cycles exist costs far less than removing them later.

Project-level detection is the wrong tool in two cases. The first is file-level cycles inside one project, which the project graph cannot see. The second is runtime coupling between deployed services, which never becomes an edge. Each needs a different check, covered in the alternatives section below.

How do you find a circular dependency with nx graph?

Run nx graph from the workspace root. Nx computes the project graph and opens an interactive view in your browser. Rendering every project at once rarely helps. Hundreds of nodes collapse into an unreadable mesh, and a cycle looks like any other cluster. Start from a project you already suspect instead.

Narrow the view

Focus on a single project, either by selecting it in the sidebar or by launching with nx graph --focus=<project>. This limits the view to that project and the projects it connects to. Look at its dependencies and its dependents separately. A project that shows up on both sides belongs to a loop. Once you have two candidate projects, use the path-tracing option to set one as the start and the other as the end. Nx then highlights the edges between them. Trace in both directions. If paths exist from A to B and from B to A, the edges on those two paths together form the cycle. That shortlist is what you check against source imports in the next step.

Detect cycles in CI

The browser view is for investigation, not enforcement. Run nx graph --file=graph.json to export the graph without opening a browser. The JSON contains a dependency map that is keyed by project name. Each entry lists outgoing edges with a target field. A short script can run a depth-first search over this map and track which projects are on the current recursion stack. If an edge points to a project that is still on the stack, that is a cycle. Print the stack from that point to show the full loop, then exit non-zero.

For very large workspaces, depend on focused views and this kind of scripted check rather than the full graph. They scale, and they produce output that a pipeline can act on.

// detect-cycles.js
// Usage in CI: npx nx graph --file=graph.json && node detect-cycles.js graph.json
const fs = require('fs');

const file = process.argv[2] || 'graph.json';
const { graph } = JSON.parse(fs.readFileSync(file, 'utf8'));
const deps = graph.dependencies; // { [project]: [{ source, target, type }] }

const state = new Map(); // missing = unvisited, 1 = on stack, 2 = finished
const stack = [];
const cycles = [];

function visit(project) {
  state.set(project, 1);
  stack.push(project);
  for (const { target } of deps[project] || []) {
    if (!(target in deps)) continue; // skip external nodes such as npm:react
    if (state.get(target) === 1) {
      // Back edge: target is still on the stack, so the slice from it is the loop
      cycles.push([...stack.slice(stack.indexOf(target)), target]);
    } else if (!state.has(target)) {
      visit(target);
    }
  }
  stack.pop();
  state.set(project, 2);
}

for (const project of Object.keys(deps)) {
  if (!state.has(project)) visit(project);
}

if (cycles.length > 0) {
  for (const c of cycles) console.error('Cycle: ' + c.join(' -> '));
  process.exit(1); // fail the pipeline
}
console.log('No project cycles found.');

A Node script that runs a depth-first search over the dependency map exported by nx graph --file=graph.json, prints each loop it finds, and exits non-zero so CI fails.

How do you tell which edge in a cycle is the wrong one?

Start by writing the cycle out as a list of edges, then compare each edge against your intended layering. In most workspaces the layers run feature → data-access/ui → util. The edge that points up a layer is almost always the one to cut, because every other edge in the loop is doing what the architecture expects. Before you change anything, find the exact file and import behind that edge. An edge can exist only because of a single line, and its fix depends on what that line is.

Culprit How to recognise it Runtime effect Usual fix
Shared util imports from a feature lib A low-level lib reaches for a helper or constant owned by a feature Real coupling, and it may cause load-order bugs Move the helper down into the util lib
Broad barrel (index) file The import uses the lib's root entry point but only needs one symbol Often none, because bundlers tree-shake Narrow the import, or split the barrel into secondary entry points
Type-only import The import pulls in an interface or type only None, because types are erased at compile time Move shared types into a types lib both sides can depend on
Hand-added implicit dependency The edge appears in project configuration, not in source Affects task ordering and caching Delete it if the code no longer needs it

The last two rows cause the most trouble. A type-only or barrel cycle breaks nothing at runtime, but it is still an edge in the project graph. It blocks the lint rule and muddies "affected" calculations. Because nothing visibly breaks, teams are tempted to add a lint suppression and move on. Fix the edge instead, since a suppressed cycle stops being visible and won't be noticed again.

Implicit dependencies have a different problem: they drift. Nothing checks them against the code, so an entry added for a reason that disappeared long ago will keep creating edges, and possibly cycles, until someone deletes it.

// BEFORE: libs/shared/util/src/lib/format-price.ts
// This edge points UP a layer (util -> feature) and closes the cycle:
//   feature-orders -> data-access-orders -> shared-util -> feature-orders

// Type-only: erased at compile time, but still an edge in the project graph.
import type { OrderLine } from '@acme/feature-orders';
// Barrel import: pulls the feature's root index.ts to reach one constant.
import { DEFAULT_CURRENCY } from '@acme/feature-orders';

export function formatLineTotal(line: OrderLine): string {
  return `${(line.qty * line.unitPrice).toFixed(2)} ${DEFAULT_CURRENCY}`;
}

// AFTER: move what util needs DOWN, so every edge points the expected way.

// libs/shared/types/src/lib/order-line.ts (new types lib, no dependencies)
export interface OrderLine {
  qty: number;
  unitPrice: number;
}

// libs/shared/util/src/lib/currency.ts (the constant now lives in util)
export const DEFAULT_CURRENCY = 'EUR';

// libs/shared/util/src/lib/format-price.ts
import type { OrderLine } from '@acme/shared-types';
import { DEFAULT_CURRENCY } from './currency';

export function formatLineTotal(line: OrderLine): string {
  return `${(line.qty * line.unitPrice).toFixed(2)} ${DEFAULT_CURRENCY}`;
}

// feature-orders now imports OrderLine from @acme/shared-types and
// DEFAULT_CURRENCY from @acme/shared-util, so util no longer imports a feature.

A util lib that closes a cycle by importing a type and a constant from a feature lib's barrel, fixed by moving the type into a shared types lib and the constant into util so no edge points up a layer.

What refactoring patterns break existing cycles, and what are the trade-offs?

Once you know which edge is wrong, there are four ways to remove it. They differ in how much they change the graph, and in how much they cost to keep working afterwards.

Extract a shared lower-level library. If orders and billing import each other only to reach formatMoney and Currency, move those into a new shared-money library that both depend on. The cycle becomes a fork. Avoid this for a single helper, because every new project adds its own configuration, tags and lint scope.

Invert the dependency. billing declares interface OrderLookup { findById(id: string): Order }, and the app wires in the implementation from orders. Inversion adds indirection: readers can no longer jump to the implementation, and wiring bugs show up at runtime.

Move code to its owner. A validator in billing that only checks order state belongs in orders. This usually takes the least effort and leaves the cleanest result.

Merge the projects. If two projects always change together, the boundary was never real. The cost is caching: any edit invalidates one larger target, and more dependents show up as affected.

Pattern Effort Ongoing cost Caching / affected Readability
Extract library Medium New project to maintain Finer-grained, smaller affected set Good if cohesive
Invert dependency Medium Wiring and contracts Unchanged or better Worse, indirect
Move to owner Low None Better Better
Merge projects Low Larger project Coarser, more affected Simpler imports
// BEFORE: libs/billing imports orders, and libs/orders imports billing -> cycle.

// libs/billing/src/lib/order-lookup.ts
// Inversion: billing owns the contract it needs and imports nothing from orders.
export interface Order {
  id: string;
  totalCents: number;
  currency: string;
}

export interface OrderLookup {
  findById(id: string): Promise<Order | undefined>;
}

// libs/billing/src/lib/create-invoice.ts
// The lookup is injected, so billing depends only on its own interface.
export async function createInvoice(orderId: string, orders: OrderLookup) {
  const order = await orders.findById(orderId);
  if (!order) throw new Error(`Order ${orderId} not found`);
  return { orderId: order.id, amountCents: order.totalCents, currency: order.currency };
}

// libs/orders/src/lib/order-repository.ts
// orders satisfies billing's interface structurally, with no import of billing,
// so the only remaining edge is orders -> billing (if any).
export class OrderRepository {
  async findById(id: string) {
    return { id, totalCents: 4200, currency: 'EUR' };
  }
}

// apps/api/src/main.ts
// The app is the composition root: it depends on both libs and wires them together.
// A wiring mistake here surfaces at runtime, not as a graph error.
import { createInvoice } from '@acme/billing';
import { OrderRepository } from '@acme/orders';

const invoice = await createInvoice('ord_123', new OrderRepository());

Breaking an orders/billing cycle by inversion: billing declares the OrderLookup interface it needs, orders implements it structurally, and the app wires the two together, which removes the billing-to-orders edge.

How do you stop new cycles with enforce-module-boundaries and tags?

Once the cycles are broken, use lint to keep them from coming back. The enforce-module-boundaries rule in Nx's ESLint plugin checks every import against the project graph. If an import would close a loop, the rule fails and reports the chain of projects in the cycle along with the file and import that close it. Run it in editors and pre-commit hooks for fast feedback. Also run it as a required CI check, because hooks can be skipped and CI cannot.

Cycle detection only catches a loop once both directions exist. Tags and depConstraints prevent most cycles earlier, at the first import that goes against the layering. Give each project a type: tag in its project configuration. Then declare constraints such as:

  • type:feature may depend on type:data-access and type:util.
  • type:util may depend only on type:util.

With these rules, a util that imports a feature is rejected before any cycle forms. The only cycles still possible are within a single layer, and those are rare enough to review case by case. Add a second dimension such as scope:billing or scope:identity to stop cross-domain coupling the same way.

Approach When it catches problems What it sees Cost
Lint rule in CI Every change, before merge Individual imports and project cycles Low after initial tagging
Script over nx graph --file=graph.json output Scheduled or per pipeline Whole-graph structure, trends, cycle counts Script maintenance
Manual audit in the graph UI Occasionally Architectural drift that rules don't encode Engineer time, misses in-between regressions

Use lint as the gate. Use exported-graph scripts to track metrics over time. Keep manual audits for revisiting the tag model itself.

What are the alternatives to Nx's built-in cycle detection?

Nx's checks work at project granularity and only see edges that appear in the static project graph. Other approaches cover different granularities, and some teams use them alongside Nx or in its place.

  • TypeScript project references. When each library has its own tsconfig with references to the projects it depends on, tsc --build refuses to build a circular set of references. This enforces acyclicity at compile time without Nx. The trade-off is that the references are maintained by hand, or by tooling, and they can drift from the real imports in the same way implicit dependencies do.
  • File-level cycle linting. ESLint rules from the wider ecosystem can detect import cycles between individual modules. They find loops inside a single project, which the Nx project graph cannot see. They resolve far more modules than a project-level check, so they are slower on large codebases and are often limited to selected directories.
  • Standalone module-graph analysis tools. Dedicated dependency analyzers for JavaScript and TypeScript build a file-level graph, report cycles, and can enforce custom path-based rules. They are useful in repositories that don't use Nx, or where layering is defined by folders rather than by projects and tags.
  • Package-manager workspace boundaries. Splitting code into workspace packages with explicit package.json dependencies turns each dependency into a declared, reviewable edge. Reviewers can spot a cycle when a manifest change adds the reverse dependency. Nothing enforces this automatically unless a tool checks it.
  • Custom scripts over an exported graph. The depth-first search shown earlier can be extended to whatever policy you need, for example ignoring test-only edges or reporting strongly connected components. You maintain the script yourself.
  • Runtime and architecture checks for services. Cycles between deployed services travel over the network. Static import analysis of any kind won't find them. Use service dependency documentation, tracing data, or contract reviews instead.

In an Nx workspace, enforce-module-boundaries with tags is usually the primary gate, because it uses the same graph that drives affected and caching. Add a file-level check when intra-project cycles cause load-order bugs. Add project references when you also want the TypeScript compiler to enforce the structure.

How should you triage a workspace that already has many cycles?

Start with an inventory. Run lint across the workspace and collect every circular-dependency violation, or export the project graph to JSON and run a cycle-finding script over it. Store the list where the team can see it so progress is measurable.

Rank edges by participation

Cycles in a large workspace usually overlap. Count how many detected cycles each edge appears in, then fix the edges at the top of that list first. One misplaced import from a shared library can sit inside a dozen cycles, and removing it clears all of them in one change.

Illustrative estimate. Assume 15 projects form one strongly connected component, so a change to any of them marks all 15 as affected. Assume lint reports 12 cycles, and two edges appear in 7 and 5 of them. If removing those two edges splits the component into groups of at most 4 projects, a typical change now affects about 4 projects instead of 15.

Ratchet enforcement

Record the current violation count. Fail CI when the count rises, and lower the threshold each time an edge is fixed. This blocks new cycles while existing ones are paid down at a sustainable pace.

A strict rollout on day one fails dozens of unrelated pull requests. Engineers under deadline respond by adding disable comments, which hide the problem and make the inventory inaccurate.

Even when the graph reaches zero cycles, runtime cycles can still exist. Lazy imports, dependency injection, and string-based lookups create dependencies that the static graph does not record.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx circular dependency, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.