What is the Nx project graph and how does Nx build it?
The Nx project graph is a directed graph of every project in your workspace (apps, libraries, and the external packages they consume), with an edge wherever one project depends on another. Nx caches it and reuses it for task ordering, affected calculations, and boundary lint rules.
Nx builds the graph from three sources:
- Source imports. Nx statically analyzes TypeScript and JavaScript files and resolves each import specifier, including
requirecalls and dynamic imports with literal paths, to the project that owns the target file. Path aliases from the root tsconfig are what make@acme/billing-coremap to a project. - Package manifests. Dependencies listed in
package.jsonfiles create edges to other workspace projects and to external npm nodes. - Declared
implicitDependencies. In a project's configuration you can assert an edge that no import expresses, such as a service that needs a shared schema regenerated first.
The graph records what code references. It does not record what your architecture diagram intends. If orders-api imports a helper from payments-service internals, the edge exists whether or not anyone approved it.
The reverse matters more for backend systems. Several couplings never appear in import statements: one service calling another over HTTP or gRPC, producers and consumers sharing a queue topic, a config-driven plugin loader, or an import path assembled from a string at runtime. Nx cannot see any of these. They stay invisible until you declare them as implicit dependencies.
Backend and platform engineers running many services in one repo get the most from the graph, because they are the ones who pay for hidden coupling during builds, deploys, and incidents.
+--------------------------+
| Source imports |---+
| import, require, | |
| import('literal/path') | |
+--------------------------+ | +-----------------------------------+
+--------------------------+ | | NX PROJECT GRAPH (cached) |
| package.json manifests |---+---->| |
+--------------------------+ | | orders-api ------> billing-core |
+--------------------------+ | | | |
| implicitDependencies |---+ | +----------> payments-service |
| (declared in config) | | (internal import: edge exists |
+--------------------------+ | even if never approved) |
^ | |
| only way in | used by: task order, affected, |
| | module boundary lint rules |
+--------------------------+ +-----------------------------------+
| RUNTIME COUPLINGS |
| (invisible to Nx) |
| - HTTP / gRPC calls |
| - shared queue topics |
| - config-driven plugins |
| - import paths built |
| from strings |
+--------------------------+
Nx builds its cached project graph from static imports, package manifests and declared implicitDependencies; runtime couplings stay invisible unless you declare them.
How do you run a first-pass dependency audit with nx graph?
Running nx graph opens the interactive view in a browser. In a workspace with dozens of services, showing every project at once yields an unreadable mass of edges, so start narrow. Focus on one deployable service, either from the sidebar or with nx graph --focus=<project>. The view then shows that service and the projects connected to it, which is the set Nx has to consider when the service changes.
Turn on grouping by folder next (the sidebar option or --groupByFolder). Most backend repos encode intent in their directory layout, such as apps/, libs/<domain>/, and libs/shared/. Edges that cross those groups unexpectedly are usually your first findings.
While reading the focused view, look for three smells:
| Smell | What it looks like in the graph | Why it hurts |
|---|---|---|
| Service imports service | An edge from one app to another app | Deploy units become coupled, and a change to one rebuilds and retests the other |
| Hub shared library | One shared or common lib with edges from nearly every project |
Any edit marks most of the repo as affected |
| Domain pulls in infrastructure | A domain lib depending on a database client, HTTP framework, or queue adapter lib | Business logic can't be tested or reused without dragging the runtime along |
Note each finding with the project names on both ends of the edge, then move on to the next service. The interactive view works well for exploring one area at a time. It does not scale to a whole-repo audit. Once a workspace has hundreds of projects, the full graph is too dense to read, and you need the exported graph data to go further.
# First-pass audit: one service at a time, never the whole repo at once.
# 1. Focus on a single deployable service and group projects by folder
# (apps/, libs/<domain>/, libs/shared/) so cross-boundary edges stand out.
npx nx graph --focus=orders-api --groupByFolder
# 2. Hide noise that is not part of the runtime dependency picture,
# such as the service's e2e project, so real findings are easier to read.
npx nx graph --focus=orders-api --groupByFolder --exclude=orders-api-e2e
# 3. Repeat for the next service. Record each smell as "source -> target":
# orders-api -> billing-api (service imports service)
# orders-api -> shared-utils (check how many projects hit this hub)
# orders-domain -> db-postgres (domain pulls in infrastructure)
npx nx graph --focus=billing-api --groupByFolder
# 4. When the workspace is too large to read visually, write the graph
# to a file instead of opening the browser, for scripted analysis later.
npx nx graph --file=graph.json
# Example follow-up: list app -> app edges (the service-imports-service smell).
jq -r '
.graph.nodes as $n
| .graph.dependencies[][]
| select($n[.source].type == "app" and $n[.target].type == "app")
| "\(.source) -> \(.target)"
' graph.json
Shows a focused, folder-grouped nx graph pass over one service at a time, then exports the graph to JSON so you can find service-to-service edges once the interactive view gets too dense to read.
How do you export and query the project graph to find circular dependencies?
Nx can write the graph to a JSON file instead of opening the browser view. Run nx graph --help to confirm the exact output flag for your version, then commit a small audit script that reads the file. The export maps each project to its outgoing dependencies. That structure is enough to compute the numbers that matter:
- Fan-out per project shows how many projects it depends on. A high count means it is exposed to churn from many places.
- Fan-in per project shows how many projects depend on it. A shared
db-clientwith high fan-in is expected. A feature library with high fan-in is a design problem. - Transitive reach is the full set of projects a change can affect. Compute it with a breadth-first walk over reverse edges.
- Longest chain is the deepest dependency path. It bounds how sequential your build can get.
- Cycles can be found with a depth-first search that tracks the current stack, or with a strongly-connected-components pass that groups every project caught in the same loop.
Cycles cost backend teams in three ways. Every project in a cycle lands in the affected set when any one of them changes. No member of the cycle can be versioned or released on its own. Build and test ordering also starts to depend on task scheduling details rather than a clear topological order. The module-boundaries lint rule reports project-level cycles too, but the script gives you the whole picture in one pass.
Parse the export defensively. Check for the keys you expect and fail loudly if they are missing, because the format can change between Nx versions. Emit sorted plain text or JSON instead of screenshots, so each audit can be diffed against the last one in code review.
#!/usr/bin/env python3
# Export first: nx graph --file=graph.json (confirm the flag via `nx graph --help`)
# Then: python3 audit_graph.py graph.json > graph-audit.txt
import json, sys
from collections import deque
from functools import lru_cache
data = json.load(open(sys.argv[1]))
deps = data.get("graph", {}).get("dependencies")
if not isinstance(deps, dict): # format can change between Nx versions: fail loudly
sys.exit("unexpected export format: missing graph.dependencies")
# Keep project->project edges only; external (e.g. npm) nodes are noise here.
out = {p: sorted({d["target"] for d in ds if d.get("target") in deps}) for p, ds in deps.items()}
inc = {p: [] for p in out}
for p, targets in out.items():
for t in targets: inc[t].append(p)
def reach(start, edges): # breadth-first walk; excludes start unless it loops back
seen, queue = set(), deque([start])
while queue:
for n in edges[queue.popleft()]:
if n not in seen: seen.add(n); queue.append(n)
return seen
fwd = {p: reach(p, out) for p in out}
# p and q share a cycle if each reaches the other; group them like an SCC pass would.
cycles = sorted({tuple(sorted(q for q in fwd[p] if p in fwd[q])) for p in out if p in fwd[p]})
for p in sorted(out): # sorted, tab-separated text so audits diff cleanly in review
print(f"{p}\tfan_out={len(out[p])}\tfan_in={len(inc[p])}\treach={len(reach(p, inc))}")
for c in cycles: print("CYCLE\t" + ", ".join(c))
if cycles:
print("LONGEST_CHAIN\tskipped: break cycles first")
else:
@lru_cache(None)
def depth(p): return 1 + max((depth(t) for t in out[p]), default=0)
print(f"LONGEST_CHAIN\t{max((depth(p) for p in out), default=0)}")
sys.exit(1 if cycles else 0) # non-zero exit lets CI flag new cycles
A defensive audit script that reads an exported Nx project graph and prints sorted, diffable fan-out, fan-in, transitive reach, cycle groups and longest chain per project, exiting non-zero when cycles exist.
How should backend teams tag projects and enforce module boundaries?
Audits find tangles. Tags stop new ones from forming. Give every project two tags. The type: tag describes the project's architectural role. The scope: tag names the bounded context the project belongs to, such as scope:billing, scope:identity or scope:shared. The two dimensions are checked independently, so a single import has to satisfy both.
| Type tag | May depend on | Reason |
|---|---|---|
type:app |
feature, data-access, domain, util | Apps are deployment shells. An app importing another app couples their release cycles. |
type:feature |
data-access, domain, util | Orchestrates use cases and is the only layer that wires persistence to logic. |
type:data-access |
domain, util | Implements repositories and clients against interfaces defined in the domain. |
type:domain |
domain, util | Pure business rules. If it imported data-access, tests would need a database. |
type:util |
util | Leaf code with no business meaning. |
In the @nx/enforce-module-boundaries ESLint rule, each row maps to a depConstraints entry. The sourceTag matches the row's type tag, and onlyDependOnLibsWithTags lists the types it may import. The domain rule is worth stating twice: add notDependOnLibsWithTags: ["type:data-access"]. That way a later broadening of the allow-list cannot silently reopen the dependency. For scope, scope:billing gets onlyDependOnLibsWithTags: ["scope:billing", "scope:shared"].
Tags are organizational decisions. If a scope cuts across two teams, or one team owns code under three scopes, engineers will hit violations they cannot fix on their own. They will respond with re-exports through shared, inline lint disables, or exemption requests. Draw scopes along ownership lines. When ownership changes, move the tags rather than adding exceptions. A growing scope:shared usually means a missing bounded context.
// eslint.config.js (workspace root, ESLint flat config)
const nx = require('@nx/eslint-plugin');
module.exports = [
{
files: ['**/*.ts'],
plugins: { '@nx': nx },
rules: {
'@nx/enforce-module-boundaries': ['error', {
allow: [],
depConstraints: [
// Type dimension: architectural layers.
// type:app is absent from every allow-list, so apps never import apps.
{ sourceTag: 'type:app', onlyDependOnLibsWithTags: ['type:feature', 'type:data-access', 'type:domain', 'type:util'] },
{ sourceTag: 'type:feature', onlyDependOnLibsWithTags: ['type:data-access', 'type:domain', 'type:util'] },
{ sourceTag: 'type:data-access', onlyDependOnLibsWithTags: ['type:domain', 'type:util'] },
{
sourceTag: 'type:domain',
onlyDependOnLibsWithTags: ['type:domain', 'type:util'],
// Stated twice so a later broadening of the allow-list cannot reopen this edge.
notDependOnLibsWithTags: ['type:data-access'],
},
{ sourceTag: 'type:util', onlyDependOnLibsWithTags: ['type:util'] },
// Scope dimension: bounded contexts. Checked independently of type,
// so every import must pass one type rule and one scope rule.
{ sourceTag: 'scope:billing', onlyDependOnLibsWithTags: ['scope:billing', 'scope:shared'] },
{ sourceTag: 'scope:identity', onlyDependOnLibsWithTags: ['scope:identity', 'scope:shared'] },
// shared must not reach back into any context.
{ sourceTag: 'scope:shared', onlyDependOnLibsWithTags: ['scope:shared'] },
],
}],
},
},
];
// Each project declares both tags, e.g. in libs/billing/invoicing/project.json:
// "tags": ["type:feature", "scope:billing"]
A flat-config ESLint setup for @nx/enforce-module-boundaries that checks the type and scope tag dimensions separately. It keeps apps from importing apps, blocks domain from depending on data-access twice over, and limits scope:billing to billing and shared projects.
Which refactoring patterns untangle backend dependency graphs?
Each pattern below removes a specific kind of edge. Pick the one that matches the shape of the tangle, not the one that produces the tidiest picture.
| Pattern | Before | After | Main cost |
|---|---|---|---|
| Extract to lower-level lib | orders and billing import each other for a shared Money type |
Both depend on a new domain-money lib |
One more project to configure |
| Invert via contract lib | orders imports notifications to send emails |
orders depends on a notifier interface. notifications implements it and is wired in at the app layer |
Indirection when reading code |
| Split god library by consumer | shared-utils is imported by every project, so any edit affects everything |
utils-http, utils-date, utils-auth, each used only by its real consumers |
Migration churn across imports |
| Publish a client library | payments-api imports ledger-service internals directly |
ledger-client exposes request/response types and calls |
Keeping the client in sync with the service |
| Move test helpers out | orders ships factories and fakes used only in specs |
orders-testing is consumed only by test targets |
Another tag rule to enforce |
The common goal is to make arrows point one way. Volatile code should depend on stable code, and the reverse should not happen.
Each new project adds configuration, lint rules, and nodes to the graph. Past a certain point the graph becomes harder to read than the original tangle. Split only when it removes a cycle or narrows a wide affected set.
Contract and client libraries attract high fan-in by design. Keep them small, keep them limited to types, and change them rarely. If one changes every sprint, it has turned into the next god library.
How do you roll out boundary enforcement on an already tangled repo?
Start by tagging every project with a scope (for example scope:billing) and a type (type:api, type:data-access, type:contracts), but keep the constraints permissive, such as allowing *, so @nx/enforce-module-boundaries passes on day one. Tags are useful even before they enforce anything. They make the graph filterable and force a decision about who owns each project.
Next, write the constraints you actually want, run lint, and commit every reported violation to a baseline file. CI compares each run against that baseline and fails only on violations that are not already in it. Then pick one bounded context, ideally one with a clear owning team and planned work nearby, fix its baselined violations, and remove those entries. The baseline should only shrink. Review any pull request that adds to it the way you would review a schema migration.
| Approach | Upfront cost | Ongoing cost | Main risk |
|---|---|---|---|
Broad suppression (disable comments, * constraints left in place) |
Very low | High: new tangles accumulate unseen | The graph looks governed but isn't |
| Fix everything at once | Very high: a long-lived branch touching many teams | Low once merged | Merge conflicts and stalled feature work; often abandoned |
| Baseline and ratchet | Low | Moderate: per-context cleanup plus baseline review | Baseline treated as permanent |
The ratchet is worth its slower pace when the repo has many owners and steady feature traffic. That combination makes a big-bang branch impractical to merge. If the repo is small, has a single owner, and has only a few violations, fixing them in one pull request is cheaper than running the baseline process.
When does a clean nx project graph mislead you, and what are the alternatives?
The project graph only sees what Nx can infer from source imports and explicit configuration. Two services can share no import edge and still break together. This happens when one calls the other's HTTP endpoint, when both write to the same database tables, or when both consume a message whose schema lives in neither. A tidy graph in that situation means Nx cannot see the coupling. It does not mean the coupling is absent.
Keeping the graph honest
Use implicitDependencies for edges that imports cannot reveal. Typical cases are a migrations project that several services depend on, a generated API client built from another service's spec, and shared config files that change runtime behavior. Declare too little and Nx skips rebuilds, so a service ships against a stale client and fails after deploy. Declare too much and every change pulls half the repo into the affected set, which erodes trust in the graph until people bypass it. Treat edits to implicitDependencies, tags, and boundary rules as architecture changes. Require an owner's review on the pull request so a convenient exemption does not quietly become permanent.
Where other checks fit
| Approach | Catches | Misses |
|---|---|---|
| Nx graph + boundary rules | Import-level violations, tag policy | Runtime calls, shared tables, message formats |
| Code review conventions | Intent, design drift | Anything reviewers don't notice; inconsistent at scale |
| Generic import-analysis tools | Cycles inside a single project | Cross-service runtime coupling |
| Contract or schema checks | Breaking API, event, and DB schema changes | Internal code structure |
Pair the graph with contract checks for runtime coupling. Neither covers the other's blind spot.
How can the affected set measure whether untangling saved engineering time?
The affected computation is the most honest measure of whether untangling paid off, because CI selects work from that same graph. Do not rely on someone else's speedup claims. The answer depends entirely on the shape of your graph.
Replay real changes. Pick five to ten representative commits from recent history. A good set includes a shared DTO tweak, a core utility fix, and a single-service bug fix. Before the refactor, run nx affected with each commit's base and head and record the affected project count. After the refactor, replay equivalent changes and record the count again.
Illustrative estimate (assumed numbers, not a benchmark)
Assumed inputs:
- 120 merged PRs per month touch shared code.
- Each touches 18 affected projects before the refactor and 6 after.
- Each affected project costs 5 CI minutes.
- 5 deployable services are affected per PR before, and 2 after.
Formulas:
- CI minutes saved = PRs × (affected_before − affected_after) × minutes_per_project = 120 × 12 × 5 = 7,200 machine-minutes per month
- Redeploys avoided = PRs × (deployables_before − deployables_after) = 120 × 3 = 360 per month
Machine-minutes are not wall-clock minutes. Parallel agents shrink the wait time a developer actually feels, so report both numbers.
Track it continuously. Log the affected count and the deployable count on every PR. Store them next to the metrics from your exported graph: edge count, cycle count, and the fan-in of your top shared libraries. Read the two sets of numbers together. If affected counts rise while edge count stays flat, a hub library is quietly absorbing more consumers, and that library is your next split candidate.
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 project graph, 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.