Why is nx typecheck slow in a large backend workspace, and how do you measure it?
This checklist is for backend and platform engineers who own CI pipelines and workspace configuration. It applies when typecheck or lint time keeps growing as projects are added, even though no single project changed much. That pattern rarely means the machines are too small. More often, each project's tsc run is loading far more of the workspace than it needs, or caching is missing for reasons nobody has looked at.
Measure before changing anything. First, time one representative project and then the full workspace, with and without --skip-nx-cache. That gives you the true cold cost and shows how often the cache actually saves work. Nx's run summary reports how many tasks were read from cache. If a "no-change" rerun still produces misses, the problem is in your inputs, not in TypeScript.
For slow cache misses, run tsc --noEmit --extendedDiagnostics against the project's tsconfig. Then use --generateTrace <dir> for a timeline you can open in a trace viewer. For lint, set TIMING=1 when running ESLint to list the slowest rules.
| Signal | Where to read it | What it usually points to |
|---|---|---|
| High file and line counts | --extendedDiagnostics |
Program pulls in too much of the workspace |
| High instantiation count, long check time | --extendedDiagnostics, trace |
Expensive generic or conditional types |
| High I/O or read time | --extendedDiagnostics |
Broad include globs, large node_modules resolution |
| A few rules dominate lint time | TIMING=1 |
Type-aware rules rebuilding a program |
| Misses on unchanged code | Nx run summary | Inputs that are too broad or unstable |
#!/usr/bin/env bash
# Baseline measurements before changing any workspace config.
# Assumes a 'typecheck' target exists; 'orders-api' and paths are placeholders.
set -euo pipefail
PROJECT=orders-api
TSCONFIG=apps/orders-api/tsconfig.app.json
OUT=perf-baseline
mkdir -p "$OUT"
# 1. Cold cost of one project, then the whole workspace (cache bypassed).
time npx nx run "$PROJECT":typecheck --skip-nx-cache
time npx nx run-many -t typecheck --skip-nx-cache
# 2. Rerun with no code changes. Every task should come from cache;
# any miss in the run summary means the task inputs are too broad or unstable.
time npx nx run-many -t typecheck
# 3. For a slow miss, ask tsc where the time goes.
# Look at Files, Lines, Instantiations, I/O Read time and Check time.
npx tsc -p "$TSCONFIG" --noEmit --extendedDiagnostics \
| tee "$OUT/$PROJECT-diagnostics.txt"
# 4. Per-file timeline (trace.json + types.json) to open in a trace viewer.
npx tsc -p "$TSCONFIG" --noEmit --generateTrace "$OUT/$PROJECT-trace"
# 5. Slowest ESLint rules for the same project.
TIMING=1 npx eslint apps/orders-api/src | tee "$OUT/$PROJECT-lint-timing.txt"
A baseline script that times cold and cached typecheck runs, then captures tsc extended diagnostics, a tsc trace, and ESLint rule timings for one project before any configuration change.
How should a dedicated Nx typecheck target be set up?
When typechecking only happens inside build or test, you cannot run it, cache it or parallelize it separately. A test failure masks a type error, and a build that bundles with a transpile-only tool may never typecheck at all. A standalone typecheck target on every project lets nx affected -t typecheck check exactly what changed, with its own cache entry.
- One target per project, one tsconfig per target. Run
tsc --noEmit -p <project>/tsconfig.jsonfor leaf projects. If you use project references, runtsc --buildwithemitDeclarationOnly. Composite projects must emit, so declaration-only output gives--buildthe.d.tsand.tsbuildinfofiles it needs without writing JavaScript. - Point it at a dedicated config. Use a
tsconfig.jsonscoped to the project, not the workspace root config. - Audit
include. A glob like**/*.tsat the project root pulls in scripts, fixtures and anything else in the folder. - Check path aliases. An alias in the base config that maps
@org/billingtolibs/billing/src/index.tsmakes each consumer re-typecheck billing's source. Resolve to declarations, or rely on references. - Exclude what isn't yours. Add explicit excludes for
dist, coverage output and generated clients. Give*.spec.tsits own tsconfig and its own target. - Verify the real file list.
tsc --listFilesprints every file in the program.--explainFilesadds why each file was included, which is how you find the import or glob dragging in half the monorepo.
Trade-off: narrow configs can make the editor and CI disagree. If the IDE picks up a root tsconfig.json that includes everything, a developer can see no errors locally while CI fails, or the reverse. Keep the root config as a references-only solution file so the editor resolves each file to the same project config CI uses.
# 1. Typecheck only the projects affected by this change.
# 'typecheck' is its own cacheable target, separate from build and test.
npx nx affected -t typecheck
# 2. The command the target runs for a leaf project.
# It uses the project's own config, never the workspace root.
npx tsc --noEmit -p libs/billing/tsconfig.lib.json
# 2b. With project references, use build mode instead.
# The config sets composite + emitDeclarationOnly, so it writes
# .d.ts and .tsbuildinfo files but no JavaScript.
npx tsc --build libs/billing/tsconfig.lib.json
# 3. Audit how big the program really is.
# This counts files outside node_modules.
npx tsc --noEmit -p libs/billing/tsconfig.lib.json --listFiles \
| grep -v node_modules | wc -l
# 4. Find files from other libraries' source that ended up in this program.
# A path alias that resolves to libs/<other>/src usually causes this.
npx tsc --noEmit -p libs/billing/tsconfig.lib.json --explainFiles \
| grep -E 'libs/[^/]+/src/' | grep -v 'libs/billing/'
# 5. Check that specs, dist and generated code are excluded.
# Each of these greps should print nothing.
npx tsc --noEmit -p libs/billing/tsconfig.lib.json --listFiles \
| grep -E '\.spec\.ts$|/dist/|/generated/'
Shows how to run a standalone typecheck target under nx affected, the tsc commands it wraps with and without project references, and how to use --listFiles and --explainFiles to find out-of-scope files in a project's program.
How do incremental tsc and TypeScript project references work?
Project references split type checking along library boundaries. Each library's tsconfig sets composite: true, which forces declaration output and requires every source file to be covered by include or files. Dependents list it under references. tsc --build then walks that graph in dependency order, checks each library once, and skips any project whose inputs have not changed since its last build.
The speedup comes from what dependents read. A consumer does not re-parse a library's source. It loads the library's emitted .d.ts files, which are smaller and contain no function bodies to check:
libs/dbchecks its source and emitsdb/*.d.tslibs/ordersreadsdb/*.d.ts, checks its own source, and emitsorders/*.d.tsapps/apireadsdb/*.d.tsandorders/*.d.ts, then checks only its own source
Each .tsbuildinfo file records the hash and version of every input file, the signature of each file's declaration output, the import relationships between files, and any cached diagnostics. On a rebuild, tsc re-checks only the files whose inputs or upstream signatures changed. Place the file with tsBuildInfoFile at a stable path and declare that path in the target's Nx outputs. If you don't, a cache restore or a fresh CI runner has no record of the previous build, and tsc checks everything again.
There are two costs. The first is configuration: every library needs its own composite config and a declared output location. The second is drift. Nx infers dependencies from imports, but references are maintained by hand. If a reference is missing, tsc may build projects in the wrong order and use stale declarations, which produces type errors that don't match the source. Run Nx's sync tooling (nx sync locally, nx sync:check in CI) or a lint rule that fails when the two graphs disagree.
In a workspace with only a handful of libraries, a single tsc --noEmit usually finishes fast enough that this setup costs more than it saves.
// libs/orders/tsconfig.lib.json (tsconfig files accept comments)
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
// Enables project references and forces declaration output
"composite": true,
"declaration": true,
// Typecheck only needs .d.ts files for dependents, not JS
"emitDeclarationOnly": true,
"rootDir": "src",
"outDir": "../../dist/out-tsc/libs/orders",
// Stable path that the Nx target lists in `outputs`, so cache
// restores and fresh CI runners get the previous build state back
"tsBuildInfoFile": "../../dist/out-tsc/libs/orders/tsconfig.lib.tsbuildinfo"
},
// composite requires every source file to be matched here
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts"],
// Must match the Nx graph: orders imports db, so it references db.
// tsc --build checks db first, then reads db's emitted .d.ts
// instead of re-parsing libs/db/src.
"references": [{ "path": "../db/tsconfig.lib.json" }]
}
A composite library tsconfig for libs/orders that emits only declarations, writes its .tsbuildinfo to a fixed cacheable path, and references libs/db so tsc --build checks db first and reads its .d.ts output.
Which Nx inputs and outputs make typecheck and lint caching trustworthy?
Caching only pays off if the cache key captures everything that can change the result and nothing else. Define namedInputs once in nx.json and reference them from targetDefaults. Keep a production set that excludes *.spec.ts, test setup files and the test tsconfig. Dependents should consume ^production so a spec edit in a library re-runs only that library's own typecheck and lint, not every consumer's.
For typecheck, the cache key must cover the full tsconfig chain, including the shared base config every project extends, along with the project's sources and ^production. Declare the .tsbuildinfo files and any emitted declaration files as outputs. If they are left out, a remote cache restore brings back the terminal log but not the incremental state, and the next tsc --build starts cold.
| Item | Include as | Why | Risk if wrong |
|---|---|---|---|
| Project sources | input | Core of the cache key | Omitted folders cause false greens |
| Base and project tsconfigs | input | Compiler options change results | Stale incremental output |
| Root and project ESLint configs | input (lint) | Rule changes must re-lint | Old warnings replayed |
^production |
input | Dependency API changes | Missed type breaks |
| Root lockfile, global configs | avoid | Change often | Remote hit rate drops toward zero |
.tsbuildinfo, .d.ts |
output | Makes restores useful | Cold rebuild after every hit |
Run lint per project, with each project's lint target covering only its own root. A single root-level lint target walks the whole repo and gets one cache entry that any change invalidates. Turn on ESLint's --cache only for targets that Nx does not cache, such as local editor or pre-commit runs. Inside Nx it duplicates work and adds one more source of stale state.
{
"namedInputs": {
"sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/*.spec.ts",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/src/test-setup.ts",
"!{projectRoot}/jest.config.ts"
]
},
"targetDefaults": {
"typecheck": {
"cache": true,
"inputs": ["default", "^production"],
"outputs": ["{workspaceRoot}/dist/out-tsc/{projectRoot}"]
},
"lint": {
"cache": true,
"inputs": [
"default",
"{workspaceRoot}/eslint.config.mjs"
]
}
}
}
An nx.json sketch: a production set without spec files that dependents use via ^production, the base tsconfig and root ESLint config as inputs, and a typecheck output folder that holds the .tsbuildinfo and .d.ts files. Each project's tsconfig must set tsBuildInfoFile and outDir to that folder.
When should you avoid type-aware ESLint, and what are the alternatives?
Type-aware rules from typescript-eslint need a full TypeScript program to answer questions such as "is this expression a Promise?" When parserOptions points at a tsconfig, ESLint asks the compiler to load and check every file that config includes, along with its dependencies. In practice the lint target repeats most of the work your typecheck target just finished, and neither target can reuse the other's in-memory program.
Before you remove typed linting, check what it actually catches. List the typed rules enabled in your shared config, then look at your issue tracker and recent review comments to see which ones have found real bugs. In backend code the rules that usually pay off are no-floating-promises, no-misused-promises and await-thenable. Many stylistic typed rules flag things nobody acts on.
Keep those few rules and drop the rest. Move them into a separate lint-typed target, or turn them off for test files with an override. Point parserOptions at each project's own tsconfig rather than a root config that includes the whole workspace, so each lint run loads only one project's program.
| Approach | Speed | What you lose |
|---|---|---|
| Syntax-only lint | Fastest; no program built | All type-aware checks |
| Typed lint in a separate target | Main lint stays fast; typed target caches independently | Nothing, if CI runs the target |
Rely on tsc strict flags |
No extra cost beyond typecheck | Floating-promise and misused-promise detection |
The last row carries the most risk. tsc has no flag that reports an unawaited Promise. In a service, a missing await before a database write or queue publish compiles cleanly. It then fails silently, or the rejection goes unhandled at runtime. For backend workspaces, keep at least the promise rules running somewhere in CI.
How does the project graph decide how much nx affected has to check?
nx affected works at the project level, not the file level. It diffs your branch against the base, maps each changed file to the project that owns it, and then marks every project that depends on that project, directly or transitively. A one-line change in a library imported by forty services means forty typecheck and lint tasks, however small the edit.
What inflates the affected set
- Catch-all shared libraries. A
sharedorcommonlibrary holding DTOs, logging, config parsing and date helpers becomes a dependency of nearly everything. Any edit to it invalidates the cache for most of the workspace. - Barrel files. An
index.tsthat re-exports everything hides how little each consumer uses. Because the whole library is one project, every importer is treated as dependent on all of it. Each consumer's typecheck also loads the full barrel. - Circular or overly wide dependencies. A cycle between two libraries merges their blast radius: a change to either one affects the dependents of both. Libraries that import "just one helper" from a peer slowly connect the graph until nearly every project depends on every other.
Run nx graph and look for nodes with very high fan-in. Split them by change frequency and domain. Stable types and contracts go in one library, fast-moving utilities in another. Then use the @nx/enforce-module-boundaries lint rule with project tags to stop the graph from collapsing again. This change often saves more time than any compiler flag.
There is a limit. Each new project adds configs to maintain, cache entries to store and per-task startup overhead. Graph computation also grows with project count. If a library is split until its tasks finish faster than Nx can schedule them, the split adds overhead instead of saving time.
Compiler flags, type hotspots and CI parallelism: what each saves and costs
Once the graph is sized sensibly, the remaining levers are compiler settings, expensive types and how many tasks run at once.
| Lever | What it saves | What it costs |
|---|---|---|
skipLibCheck |
Skips checking every .d.ts file, including large node_modules typings |
Hides conflicting dependency types and errors in your own emitted declarations |
isolatedModules |
Lets each file be transpiled alone, which suits fast single-file transpilers | Forces rewrites around const enum and type-only re-exports (export type) |
| Fixing type hotspots | Removes the few types that dominate check time | Engineering time to simplify generics or add explicit annotations |
Lower --parallel |
Prevents swapping and out-of-memory kills | Less concurrency on machines with spare RAM |
Use tsc --generateTrace and --extendedDiagnostics on the slowest projects from your per-target timings. Hotspots are usually deep conditional generics, very large unions, and ORM or validation schemas whose types are inferred across many files. An explicit type annotation at the boundary often cuts inference cost.
Both tsc and type-aware ESLint keep a full program in memory. If too many Nx tasks run in parallel, the machine swaps or a task gets OOM-killed, and that looks like slowness. Set parallelism from peak memory per task, not CPU count. For example, divide available RAM by the largest task's peak memory.
Illustrative estimate (assumed numbers, not a benchmark). Weekly hours saved = engineers × waits per day × minutes saved per wait × 5 days ÷ 60. With an assumed 30 engineers, 4 waits per day and 2 minutes saved per wait: 30 × 4 × 2 × 5 ÷ 60 = 20 hours per week. Set that against the one-off cost, for example an assumed 3 engineer-days to fix isolatedModules errors.
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 typecheck slow, 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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
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.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- 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.