What is an nx circular dependency and how does Nx build the project graph?

An Nx circular dependency, in the sense this article uses, is a cycle in the project graph: project A depends on project B, B depends on C, and C (or B directly) depends back on A. Every project in the loop is upstream of every other, so Nx can't place any of them strictly before the others.

Nx builds the project graph by analyzing the workspace instead of trusting a hand-written list. For JavaScript and TypeScript projects it parses source files and records an edge whenever a file in one project imports from another project, typically through a path alias or package name that resolves to that project. It also reads package manifests, so a workspace package listed as a dependency produces an edge too. You can add edges the analysis can't see by declaring implicit dependencies in a project's configuration.

Because inference works at the level of individual imports, a single stray line is enough. If one helper file in orders imports a type from billing, the whole orders project now depends on billing. That holds even if nothing else in either service references the other.

Project-level versus file-level cycles

File-level cycles inside one project are a separate case. Two modules in the same library that import each other may cause initialization-order bugs, but they don't affect how Nx orders tasks, caches, or computes affected projects. Cycles between projects do. This article covers the project-level kind.

The graph UI, CLI flags and lint options described in later sections differ between Nx versions. Check the documentation for the version you have installed.

Why do dependency cycles between services hurt builds and deployments?

A cycle means two projects can no longer be reasoned about separately. Treat it as a design signal: the boundary you drew between orders and billing is not the boundary the code actually follows. Silencing the lint rule leaves that mismatch in place and spreads its costs across CI, runtime and release.

Affected detection and caching weaken. Nx marks a project as affected when it, or anything it depends on, changes. In a cycle, each project depends on the other, so a change to either side marks both as affected, along with every dependent of both. Cache entries are keyed partly on dependency inputs, so the same edit also invalidates cached results on both sides.

Build order becomes undefined. Pipelines that build dependencies first need a topological order, and a cycle has none. Depending on configuration, you get an error or an order that happens to work until it doesn't. At runtime, the same loop can surface as a module that is undefined at import time or a provider that resolves before its dependency is initialized. These bugs are slow to diagnose because they depend on load order rather than on logic.

Deployments couple. Services meant to ship independently now need matching versions, so one team's release waits on the other's.

Illustrative estimate. Assume 15 pull requests a day touch billing, and the cycle pulls orders and four of its dependents into each run at 10 extra CI minutes per run. That comes to 150 minutes a day, or about 3,000 minutes over 20 working days. If initialization-order bugs also cost half a day of engineering time each time one appears, the cycle has a recurring price in both CI minutes and staff hours.

How do you find the import that closes a cycle with nx graph?

Start with nx graph at the workspace root. It opens the interactive UI in a browser, built from the same project graph Nx uses for task scheduling and affected calculations. In a workspace with dozens of services, the initial view is a dense web of edges. Don't try to read it as a whole.

Instead, select orders and choose Focus. The view narrows to orders and the projects directly connected to it. You can get the same view from the command line with nx graph --focus=orders. Use the sidebar to hide unrelated projects, or pass --exclude to drop shared utility libraries that add edges without contributing to the loop.

Next, use path tracing. Set orders as the start and billing as the end. The UI highlights the route between them. Then reverse the start and end. If both directions return a path, you have a cycle. The highlighted edges point to the project pair whose imports you need to inspect, and one specific import closes the loop.

To check for cycles outside the browser, run nx graph --file=graph.json. The exported file contains graph.dependencies, a map from each project name to an array of edges with source, target and type. A short script can load this map and run a depth-first search over it. When the search reaches a project that is already on the current path, the script reports the path from that project back to itself as a cycle. A non-empty result fails the CI job.

These techniques become more important as the workspace grows. The number of edges in the full graph grows faster than the number of projects, so the full view gets harder to read with each service you add. Focusing and filtering keep the view small enough to read, and the JSON export lets CI check for cycles on every change.

// find-cycles.js: report project cycles from an exported Nx graph.
// Usage: nx graph --file=graph.json && node find-cycles.js graph.json
const fs = require('fs');

const file = process.argv[2] || 'graph.json';
const deps = JSON.parse(fs.readFileSync(file, 'utf8')).graph.dependencies;

const state = {}; // undefined = unvisited, 1 = on current path, 2 = finished
const path = [];
const cycles = [];

function visit(project) {
  state[project] = 1;
  path.push(project);
  for (const edge of deps[project] || []) {
    // Skip edges to targets that are not workspace projects (e.g. npm packages).
    if (!(edge.target in deps)) continue;
    if (state[edge.target] === 1) {
      // Target is already on the current path: the slice from it back to
      // here is a loop, and this edge is the import that closes it.
      const start = path.indexOf(edge.target);
      cycles.push([...path.slice(start), edge.target].join(' -> '));
    } else if (state[edge.target] === undefined) {
      visit(edge.target);
    }
  }
  path.pop();
  state[project] = 2;
}

for (const project of Object.keys(deps)) {
  if (state[project] === undefined) visit(project);
}

if (cycles.length > 0) {
  console.error('Circular dependencies found:\n' + cycles.join('\n'));
  process.exit(1); // A non-zero exit code fails the CI job.
}
console.log('No circular dependencies.');

This Node.js script loads the file written by nx graph --file=graph.json, runs a depth-first search over graph.dependencies, prints each cycle it finds and exits non-zero so CI fails when a cycle exists.

How does the enforce-module-boundaries rule report circular dependencies?

The rule ships with the Nx ESLint plugin as @nx/enforce-module-boundaries; older workspaces may still reference it under the @nrwl scope. It reads the same project graph that nx graph renders. When it lints an import, it checks whether the target project can already reach the importing project. If it can, that import closes a loop. The report names the projects in the cycle, shows the project path (for example orders -> billing -> orders), and lists a circular file chain: the specific source files whose imports form each edge. That file chain is the useful part. It shows the exact line to change, not just two projects that are somehow tangled.

Option names and their defaults have changed across releases. This includes settings such as allowCircularSelfDependency, the allow list, and depConstraints. Confirm them against the docs for your Nx version before copying configuration between repos.

Avoid suppressing the error with a file-level eslint-disable. The comment silences the linter, but the import still exists, so the project graph keeps the edge. Nx still treats both projects as affected by each other's changes and still has to order their builds around the loop. The cycle is still there; it has only dropped out of the lint output.

In an existing monorepo, turning the rule on often produces dozens of violations at once. A gradual rollout works better:

  • Enable the rule at warn severity across the workspace.
  • Set it to error for projects that already pass.
  • Lint only affected projects in CI, so new imports are checked immediately while old cycles go into a tracked backlog.
  • Raise the severity to error project by project as each cycle is broken.
// eslint.config.mjs (workspace root, ESLint flat config)
// Confirm option names and defaults against the Nx docs for your version.
import nx from '@nx/eslint-plugin';

// One shared options object so 'warn' and 'error' entries never drift apart.
const boundaryOptions = {
  enforceBuildableLibDependency: true,
  allow: [],
  depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }],
};

export default [
  ...nx.configs['flat/base'],
  ...nx.configs['flat/typescript'],

  // Step 1: report cycles everywhere without failing the build yet.
  {
    files: ['**/*.ts', '**/*.tsx'],
    rules: {
      '@nx/enforce-module-boundaries': ['warn', boundaryOptions],
    },
  },

  // Steps 2 and 4: projects that are already clean, or whose cycles
  // have been broken, are promoted to 'error' so they cannot regress.
  // Add each project here as its backlog entry is closed.
  {
    files: ['libs/billing/**/*.ts', 'libs/catalog/**/*.ts'],
    rules: {
      '@nx/enforce-module-boundaries': ['error', boundaryOptions],
    },
  },
];

// Step 3: in CI, lint only projects affected by the change, so new
// imports are checked immediately:
//   npx nx affected -t lint

A root ESLint flat config that runs @nx/enforce-module-boundaries at warn severity across the workspace and at error severity for projects already free of cycles, with CI linting only affected projects.

Worked example: breaking an orders–billing cycle step by step

Assume three projects: an orders service, a billing service and a shared-contracts library that both already depend on. orders calls billing to create invoices, which is a legitimate edge. Later, someone working in billing needs the OrderStatus type and imports it directly from orders because it is already there. That one convenience import closes the loop.

Before: orders → billing → orders, with both also pointing down to shared-contracts.

Step 1: Identify the edge

Run nx graph, focus on billing, and inspect the edge pointing back to orders. The edge tells you which file in billing imports from orders. Here it is a single type import. That matters because a type is a contract, not behavior, so it can move without dragging logic along.

Step 2: Move the contract down

Move OrderStatus into shared-contracts, the lowest layer both services already depend on. Don't create a new library just for this. Adding a project for one type adds graph noise without adding clarity.

Step 3: Update the imports

Point both orders and billing at shared-contracts. Remove the old export from orders so nobody re-creates the edge by habit.

Step 4: Confirm

Re-run nx graph and check that billing no longer has an edge to orders. Then lint both projects so the enforce-module-boundaries rule confirms the cycle is gone.

After: orders → billing → shared-contracts, and orders → shared-contracts. Every edge now points one way.

// BEFORE: libs/billing/src/lib/invoice.ts
// A convenience import back into orders creates billing -> orders,
// which closes the loop with the existing orders -> billing edge.
// import { OrderStatus } from '@acme/orders';

// STEP 2: libs/shared-contracts/src/lib/order-status.ts
// The contract moves to the lowest layer both services already use.
export type OrderStatus = 'pending' | 'paid' | 'cancelled';

// libs/shared-contracts/src/index.ts
// Expose it through the library's public entry point.
export * from './lib/order-status';

// STEP 3: libs/billing/src/lib/invoice.ts
// billing now depends only downward, on shared-contracts.
import type { OrderStatus } from '@acme/shared-contracts';

export function canInvoice(status: OrderStatus): boolean {
  return status === 'pending';
}

// STEP 3: libs/orders/src/lib/order.ts
// orders uses the same contract from the same place.
import type { OrderStatus } from '@acme/shared-contracts';

export interface Order {
  id: string;
  status: OrderStatus;
}

// libs/orders/src/index.ts
// Remove the old re-export so nobody recreates billing -> orders by habit.
// export * from './lib/order-status';   <- deleted
export * from './lib/order';

The OrderStatus type moves from orders into shared-contracts, and both services import it from there, so billing no longer depends on orders.

What are the alternatives for breaking a cycle, and when should you avoid each?

Extraction is only one of three options, and each one fits a different situation.

Approach Fits when Avoid when
Extract shared types and contracts into a lower-level library Both projects need the same DTOs, enums or schemas, and nothing else The library starts collecting helpers and business logic "because both sides use it"
Invert the dependency through an interface owned by the consumer One side needs a capability (for example "charge this order"), not the other side's internals Only one implementation exists and is likely to stay, so the abstraction adds indirection without decoupling anything
Replace code imports with events or API calls The services deploy independently and must not share a release cycle They ship together, or the caller needs a synchronous, consistent answer

The shared library becomes a problem when it grows into a catch-all common package. Every project depends on it, so any change to it marks nearly the whole workspace as affected. The coupling has also only moved: two services that once imported each other now change together through a third project.

Events and API calls remove the build-time edge, but they add runtime costs. You have to version contracts. You have to accept eventual consistency. When something fails, you follow a request across process boundaries instead of a stack trace.

Two shortcuts look like fixes but are not:

  • Ignore comments on the enforce-module-boundaries rule silence the report while the cycle stays in place.
  • Hand-declared implicit dependencies make the graph describe the structure you wish you had instead of the imports that actually exist, so affected calculations and the graph view both become less reliable.

How can tags and dependency constraints prevent cycles by construction?

Fixing cycles one at a time is reactive. A layering policy encoded as tags makes most cycles impossible to merge.

Give every project a type:* tag in its project configuration. Then add one depConstraints entry per layer to the @nx/enforce-module-boundaries rule, using sourceTag and onlyDependOnLibsWithTags. If each layer may only depend on layers strictly below it, an import that points upward fails lint. Same-layer edges are still permitted, so a cycle can only form between peers. That narrows the search space when one does appear.

Tag May depend on Rationale
type:app type:service, type:domain, type:util Entry points wire things together. Nothing imports them.
type:service type:domain, type:util Services share models, not each other's internals.
type:domain type:util Business rules stay free of transport and I/O.
type:util type:util Leaf helpers with no upward knowledge.

To close the remaining gap, forbid type:service → type:service and route shared contracts through a domain library.

Platform teams that own monorepo standards should introduce this policy. The best time is before the workspace grows past a handful of services, because retrofitting means tagging and fixing every existing violation at once. In an existing repo, tag first, run lint to measure the violations, and then enforce the constraints.

These constraints have a hard limit. The project graph comes from static analysis. Dynamic imports with computed paths, runtime service discovery and calls made only over HTTP or a message queue never become edges. A clean graph therefore says nothing about runtime coupling. Where you declare implicitDependencies, review them alongside code changes so they keep matching what the code actually does.

// eslint.config.mjs (workspace root)
// Each project declares its layer in project.json, e.g. "tags": ["type:service"]
import nx from '@nx/eslint-plugin';

export default [
  ...nx.configs['flat/base'],
  {
    files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
    rules: {
      '@nx/enforce-module-boundaries': [
        'error',
        {
          allow: [],
          depConstraints: [
            // Apps wire everything together; nothing may import an app.
            {
              sourceTag: 'type:app',
              onlyDependOnLibsWithTags: ['type:service', 'type:domain', 'type:util'],
            },
            // Services do not list type:service, so service -> service imports fail lint.
            // Shared contracts go through a domain library instead.
            {
              sourceTag: 'type:service',
              onlyDependOnLibsWithTags: ['type:domain', 'type:util'],
            },
            // Business rules stay free of transport and I/O layers.
            { sourceTag: 'type:domain', onlyDependOnLibsWithTags: ['type:util'] },
            // Utils may only use other utils, so a cycle can only form among peers here.
            { sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },
          ],
        },
      ],
    },
  },
];

A flat ESLint config that uses @nx/enforce-module-boundaries depConstraints so each type: layer can import only the layers below it, and service-to-service imports are rejected.*

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.