What does it mean to split an Nx monorepo, and why do teams want to?
To split an Nx monorepo is to turn one workspace, with its single project graph, lockfile and CI pipeline, into two repositories that are built, versioned and released independently. After the split, code that used to be imported by path is consumed as a published package or called over a network API. Changes no longer land atomically across that line.
Teams usually start talking about a split because of friction. CI takes too long, pull requests touch many unrelated projects, clones are slow, and reviewers from different teams get pulled into each other's changes. These complaints are real, but most of them come from how the workspace is configured, not from how big it is. Affected-only builds, caching, CODEOWNERS and sparse checkouts often address them. A split also brings its own costs: version skew and cross-repo coordination.
| Complaint that starts the conversation | Structural signal that justifies a split |
|---|---|
| Slow CI on every PR | Parts of the code ship on genuinely independent release cadences |
| Noisy, sprawling pull requests | Distinct ownership, with little shared code between teams |
| Long clones and large checkouts | Divergent toolchains or runtimes that fight over one lockfile |
| Review contention across teams | Compliance or access-control rules that require separate repos |
The signals in the right-hand column describe how the system is organised. The complaints in the left-hand column describe symptoms of workspace configuration. The thesis of this article is that workspace size alone is rarely the reason to split. A split pays off when the code already behaves like two products, and the repository should reflect that.
What should you try inside the monorepo before splitting it?
Most of the pain that prompts a split comes from how the workspace is run, not from how big it is. Nx has a fix for each common symptom, and none of them require moving code.
| Pain | In-repo fix | Why it works |
|---|---|---|
| CI runs every test on every PR | nx affected against the base branch |
Only projects reachable from changed files in the project graph get built and tested |
| Repeated builds of unchanged code | Local and remote computation caching | Tasks with identical input hashes replay stored outputs instead of re-executing |
| Cache misses on trivial edits | namedInputs, targetDefaults, and dependsOn in nx.json |
Excluding docs, test files, or unrelated config from production inputs keeps hashes stable |
| Reviewers pinged on unrelated PRs | CODEOWNERS scoped to project directories |
Review routing follows ownership, not repo membership |
| Teams reaching into each other's internals | Project tags plus @nx/enforce-module-boundaries |
Lint fails on disallowed imports, so boundaries are checked on every change |
Apply these before you draw any repo line. If they remove the pain, a split adds release coordination, version skew, and duplicated tooling, and you get nothing back for that cost.
The table also explains why splitting so often fails to fix slow CI. When a shared utils library sits under most projects, or when inputs are so broad that any root file change invalidates everything, the slowness comes from the dependency graph and the hashing configuration. Moving half the projects into a new repository brings those same dependencies and inputs along. The new CI pipeline then rebuilds the shared code itself, or pulls it in as a package that is just as broad. Fix the graph first. A split decided after that is based on how the products actually relate, not on build times.
#!/usr/bin/env bash
# CI step for a pull request: run only what the change can affect.
set -euo pipefail
# Diff against the point where this branch left main, not main's tip,
# so unrelated commits merged to main do not widen the affected set.
BASE=$(git merge-base origin/main HEAD)
# List affected projects first. If a one-line change lists most of the
# workspace, the cause is the dependency graph or overly broad inputs
# (for example, a shared utils lib or root files in every hash), and a
# repo split would carry that problem with it.
npx nx show projects --affected --base="$BASE" --head=HEAD
# Lint includes @nx/enforce-module-boundaries, so disallowed
# cross-team imports fail here on every change.
# Unchanged task hashes replay from the local or remote cache
# instead of re-executing.
npx nx affected -t lint test build --base="$BASE" --head=HEAD
A CI step that lists affected projects, then runs lint, test and build only for them, with cached results reused and module boundaries enforced through lint.
How do you use the Nx project graph to find a real split line?
The project graph is the best evidence you have, because it records what the code imports rather than what the org chart says. Export it with nx graph --file=graph.json. The resulting JSON has a graph object with nodes, which are the projects and their tags, and dependencies, which map each project to the projects it depends on. Those two structures are enough to test a proposed split line.
Start by tagging the candidate halves, for example scope:billing and scope:catalog, if your module-boundary rules don't already do it. Then count three things:
- Edges inside each group. High internal density shows that a cluster really is a unit.
- Edges that cross between the groups. Each one becomes a published artifact, a versioned API, or a duplicated module after the split.
- Shared libraries that both groups depend on. These are projects outside either tag that have inbound edges from both sides.
The script that follows does the edge count by reading graph.json and classifying each dependency by the tags on its source and target.
Shared libraries are where splits get expensive. Cross-group edges are visible, and you can remove them one at a time. A shared library is less obvious. After the split it must be published, versioned, and kept compatible for two consumers that release on different schedules. Every breaking change then requires coordination that a single commit used to handle.
The signal to look for has three parts. There should be few cross-group edges and a short, stable list of shared libraries. Each side should also have its own owners in CODEOWNERS and its own release cadence. If the edges are few but the same people ship both sides together, the boundary is not real yet.
// count-edges.js: classify graph.json dependency edges by scope tag.
// Usage: nx graph --file=graph.json && node count-edges.js graph.json
const fs = require('fs');
const { graph } = JSON.parse(fs.readFileSync(process.argv[2] || 'graph.json', 'utf8'));
const groups = ['scope:billing', 'scope:catalog']; // candidate split halves
// Map each project to the candidate group it belongs to, or null if neither.
const groupOf = {};
for (const [name, node] of Object.entries(graph.nodes)) {
const tags = (node.data && node.data.tags) || [];
groupOf[name] = groups.find((g) => tags.includes(g)) || null;
}
const internal = Object.fromEntries(groups.map((g) => [g, 0]));
const cross = []; // edges that must become published APIs after a split
const sharedUsers = {}; // untagged project -> set of groups that depend on it
for (const [source, deps] of Object.entries(graph.dependencies)) {
const from = groupOf[source];
if (!from) continue; // only edges that start inside a candidate group
for (const { target } of deps) {
if (!(target in groupOf)) continue; // skip external npm packages
const to = groupOf[target];
if (to === from) internal[from]++;
else if (to) cross.push(`${source} -> ${target}`);
else (sharedUsers[target] ||= new Set()).add(from);
}
}
// Shared libraries are the ones both sides depend on.
const shared = Object.keys(sharedUsers).filter((p) => sharedUsers[p].size === groups.length);
console.log('Internal edges:', internal);
console.log(`Cross-group edges (${cross.length}):`, cross);
console.log(`Shared libraries (${shared.length}):`, shared);
A Node.js script that reads the exported Nx graph.json and reports three counts: internal edges per tagged group, the cross-group edges, and the untagged libraries that both groups depend on.
How should you design repo boundaries as API contracts?
Once the split line is chosen, every shared library that crosses it needs a new form. Inside the workspace, the type checker and the affected graph caught breaking changes before merge. Across repos, those same breakages show up later, as runtime failures or as version skew between consumers. Decide each library's fate explicitly. There are three options.
| Option | Coupling | Release ceremony | Drift risk |
|---|---|---|---|
| Versioned package | High: consumers import code and its transitive deps | Publish, tag, bump in every consumer | Medium: consumers pin different versions |
| Duplicate the code | None after the copy | None | High: copies diverge silently |
| Service or schema contract (OpenAPI, protobuf, event schemas) | Low: only the wire format is shared | Schema review and compatibility checks | Low if compatibility is enforced, high if not |
Duplication suits small, stable utilities where divergence is harmless. Versioned packages suit pure logic both sides must run identically. Schema contracts suit anything that crosses a process boundary anyway, because the wire format is the real dependency.
Whichever you pick, you need something to replace the guarantees the compiler used to give you. Use consumer-driven contract tests or schema compatibility checks in CI. Follow semantic versioning strictly, and deprecate before you remove.
Watch for diamond dependencies. Suppose service A depends on shared-auth@2 and also on billing-client, which still pins shared-auth@1. The two versions may then disagree on token formats or types at runtime. Keep the number of versioned packages small, and make widening a version range a routine, automated chore.
How do you split an Nx workspace incrementally and reversibly?
Treat the split as a sequence of steps you can stop at. Each step before extraction can be undone with an ordinary revert.
1. Make the boundary lint-enforced. Tag every project on both sides, for example scope:billing and scope:platform, plus type:shared for the libraries both will consume. In the @nx/enforce-module-boundaries rule, add depConstraints entries so that sourceTag: "scope:billing" may only use onlyDependOnLibsWithTags: ["scope:billing", "type:shared"], and mirror it for the other side. Fix violations until lint passes. The proposed split line is now a rule CI checks on every change, rather than a diagram.
2. Operate as if already separate. For several release cycles, allow no cross-boundary imports except through type:shared libraries. Treat those libraries as if they were published: change them only through additive, versioned interfaces, and never edit a consumer in the same commit. If this feels unworkable, you have learned that cheaply, and removing the tags reverses it.
3. Extract with history. In a fresh clone, run git filter-repo --path apps/billing --path libs/billing to keep only those paths. Alternatively, run git subtree split --prefix=apps/billing -b billing-split and push that branch. This is the first step that is hard to undo, so take it only after step 2 has stayed quiet.
4. Rebuild the workspace. Recreate nx.json, the root tsconfig paths and the project configuration in the new repo. Replace source imports of shared libraries with published package versions. Then move CI pipelines, remote cache configuration and release tooling. Delete the extracted code from the original repo only after the new repo has shipped on its own.
// eslint.config.js at the workspace root (ESLint flat config)
const nx = require('@nx/eslint-plugin');
module.exports = [
...nx.configs['flat/base'],
...nx.configs['flat/typescript'],
{
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
rules: {
'@nx/enforce-module-boundaries': [
'error',
{
allow: [],
depConstraints: [
// Billing may use its own projects and shared libs, never platform code.
{
sourceTag: 'scope:billing',
onlyDependOnLibsWithTags: ['scope:billing', 'type:shared'],
},
// Mirror rule: platform cannot reach into billing.
{
sourceTag: 'scope:platform',
onlyDependOnLibsWithTags: ['scope:platform', 'type:shared'],
},
// Shared libs depend only on other shared libs, so they can later
// be published as packages without pulling either side along.
{
sourceTag: 'type:shared',
onlyDependOnLibsWithTags: ['type:shared'],
},
],
},
],
},
},
];
// Tags are set per project, e.g. in apps/billing/project.json:
// "tags": ["scope:billing"]
// Removing these constraints and tags reverts step 1 completely.
An ESLint flat config for @nx/enforce-module-boundaries that makes the proposed billing/platform split a lint-checked rule. Shared libraries are limited to depending on other shared libraries so they can be published independently later.
What do you lose at the repo boundary, and when should you avoid splitting?
Once the seam exists, several things the monorepo gave you for free stop working across it.
| Lost at the boundary | Replacement you now have to build |
|---|---|
| Atomic cross-cutting commits | Coordinated PRs merged in a fixed order, with releases sequenced producer-first |
| Single-version dependency policy | Dependency update automation in both repos, plus agreed version ranges |
| Cheap repo-wide refactors | Publishing pipelines and deprecation windows for breaking changes |
| Affected detection across repos | Contract tests that run in the consumer's CI against published versions |
The quiet cost is drift. Two workspaces with separate lint rules, tsconfig bases and CI templates will diverge within months. Each Nx upgrade then becomes two manual migrations that hit different breakages. Put the shared configuration in a versioned preset package that both workspaces consume. An upgrade then becomes a version bump plus migrations, rather than two separate investigations.
Avoid splitting when:
- The project graph is dense across your proposed line.
- Both halves ship together on the same release cadence.
- The pain is slow CI that remote caching, better task inputs or distributed execution would fix.
In each case you pay the boundary costs above and get no autonomy in return.
Compliance or access control can still force a split even when the graph argues against it. If certain code must sit behind a separate permission boundary or audit scope, that requirement outranks coupling metrics.
Weigh timing in both directions. Reversing a split means reconciling divergent histories, tooling and dependency versions, which is harder than splitting was. Delaying a split you have already justified keeps teams queued behind each other's reviews and releases.
Who should split, and does it save engineering time? A decision checklist
Decision checklist
Score each signal against your own project graph. A split is justified when most rows land in the right-hand column. One or two is not enough.
| Signal | Stay in one workspace | Consider splitting |
|---|---|---|
| Ownership | Teams edit each other's projects weekly | Each cluster has one owning team |
| Release cadence | Shared release train | Independent trains, different schedules |
| Toolchain | Same runtime and build tooling | Divergent runtimes or major framework versions |
| Cross-cluster edges | Many, and still growing | Few, stable, one-directional |
| Shared libraries | Many, frequently changed | A handful, rarely changed |
| Compliance | No access or audit separation required | Mandated separation of code or history |
| In-repo remedies | Not yet tried | Affected builds, caching and module boundaries already exhausted |
The split suits platform or backend groups that ship on their own release trains behind stable interfaces. It does not suit product teams whose features routinely touch both clusters. For them, every change becomes a multi-repo publish-and-bump sequence.
Illustrative estimate (assumed numbers, not a benchmark). Assume the split saves 20,000 CI minutes per month at $0.008 per minute, which is $160. It adds 6 hours of publishing, 10 hours of version coordination and 8 hours of duplicated maintenance, so 24 hours at $100 per hour, which is $2,400.
Net monthly value = (CI minutes saved × cost per minute) + (queue hours saved × hourly rate) − (publish + coordination + maintenance hours) × hourly rate
With these inputs, the split only pays off if it removes more than about 22 hours of engineers waiting on each other each month. CI minutes alone rarely justify it. Substitute your own minutes, rates and hours before deciding.
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 split nx monorepo, 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.