How does Nx compute a task hash, and what does a cache miss actually mean?
Before Nx runs a target, it computes a task hash from every input it has resolved for that task. It then looks up that hash in the local cache, and in the remote cache if one is configured. A hit replays the stored terminal output and restores the declared outputs. A miss runs the task and stores the result under the new hash.
project files matched by inputs ──┐
^ dependency inputs / outputs ────┤
external dependency versions ─────┼──► task hash ──► cache lookup ──┬─ hit: restore outputs + logs
env and runtime inputs ───────────┤ └─ miss: run task, store result
target configuration/options ─────┘
The inputs fall into these groups:
- Project files are the files that match the target's input patterns.
- Dependency inputs come from
^references. These pull in the inputs or outputs of upstream projects. - External dependencies are the resolved package versions recorded in your lockfile.
- Environment and runtime inputs are declared environment variables and the output of declared commands.
- Target configuration covers the executor, options, and arguments.
The model is deterministic, which shapes how you debug. A miss means at least one resolved input differs from the last run that produced a cached entry. The cause is never bad luck. Running nx reset or rerunning CI only discards evidence. The reliable method is to compare the resolved inputs from two runs and find the one that changed.
This guide is for backend and platform engineers who own CI spend and monorepo health. An unstable hash costs you twice: compute on every pipeline, and waiting time for every engineer whose pull request rebuilds work that hasn't changed.
Resolved task inputs
+------------------------------+
| Project files |---+
| (matched by input patterns) | |
+------------------------------+ |
| ^ dependency inputs/outputs |---+
| (from upstream projects) | |
+------------------------------+ | +----------------+
| External dependency versions |---+----->| Task hash |
| (resolved from lockfile) | | +-------+--------+
+------------------------------+ | |
| Declared env vars and |---+ v
| runtime command output | | +----------------+
+------------------------------+ | | Cache lookup |
| Target configuration: |---+ | local, then |
| executor, options, args | | remote if set |
+------------------------------+ +---+--------+---+
hit | | miss
v v
+-----------------+ +-----------------+
| Restore outputs | | Run task, store |
| and replay logs | | under new hash |
+-----------------+ +-----------------+
Nx combines every resolved input into a single task hash and looks it up in the local cache, then the remote cache if one is configured. A hit restores outputs and replays logs, and a miss runs the task and stores the result under the new hash.
Who should use this debugging approach?
This method is for anyone responsible for an Nx workspace where caching is enabled but doesn't deliver the expected hits:
- Platform and DevOps engineers who maintain CI pipelines and see the same targets rebuild on every run even though the code hasn't changed.
- Monorepo maintainers and tech leads who own
nx.json, review changes tonamedInputsandtargetDefaults, and need to explain why a change invalidated half the workspace. - Backend and frontend engineers whose local runs miss the cache after switching branches, or whose results differ between a laptop and CI.
It is less useful if caching is disabled on purpose, if the workspace is small enough that a full run takes about as long as a cache restore, or if every task is non-deterministic by design (for example, targets that call external services). In those cases, the time spent stabilizing hashes may not pay back.
How does the debugging method work?
The method rests on the deterministic hash model above. If identical inputs always produce an identical hash, then a miss can be traced to a specific input. The work has three parts:
- Find out what Nx actually hashes. Read the resolved inputs for the target with
nx show project. This shows the merged result of project config,nx.jsondefaults, named inputs, and plugin-inferred settings, rather than what any single file says. - Reproduce the miss in a controlled way. Hash the same task twice on an unchanged checkout. If the hashes differ, the instability is inside the workspace. If they match locally but differ between machines, it lives in the environment.
- Isolate and fix the input. Narrow the inputs by bisection until the hash stabilizes, then fix the cause: ignore a generated file, move outputs out of input globs, remove a volatile env var, or make a generator produce deterministic output.
The sections below walk through each part, then cover how to design inputs so the problem doesn't come back, and where narrowing inputs goes too far.
How do you see the inputs Nx really applies with nx show project?
Before you change any configuration, find out what Nx is actually hashing. The project.json or package.json you're reading is only one layer. Nx merges it with targetDefaults and namedInputs from nx.json, and with any targets that plugins infer from tool config files such as a test runner or bundler config. The definition that runs is the result of that merge. It often differs from what anyone typed.
Running nx show project <name> --json prints the resolved project configuration. For each target, look at the inputs array. That is where the difference between configured and resolved inputs shows up:
- Configured inputs may refer to a named input like
productionordefault. - Resolved inputs show what that name expands to. This can include file globs,
^dependency references, runtime commands, environment variables and external dependency entries contributed by a plugin.
Many unexplained misses come from an entry nobody wrote by hand. A typical case is a plugin-inferred target that includes a broad glob, or a targetDefaults entry that silently overrides a project's narrower setting.
In many setups, nx show project <name> --web (or the project detail view in the graph UI) presents the same data visually. It also annotates where each value came from, which helps you trace an input back to the file that set it.
The JSON shape, the available flags, and whether the web view exists all vary across Nx versions and plugins. Run nx show project --help against your installed version rather than relying on a field layout you saw elsewhere. Save the output. Section 3 compares it across runs.
PROJECT=my-app
TARGET=build
npx nx show project --help
jq --arg t "$TARGET" '.targets[$t].inputs' "apps/$PROJECT/project.json"
jq --arg t "$TARGET" '.targetDefaults[$t].inputs' nx.json
jq '.namedInputs' nx.json
npx nx show project "$PROJECT" --json > "resolved-$PROJECT.json"
jq --arg t "$TARGET" '.targets[$t].inputs' "resolved-$PROJECT.json"
cp "resolved-$PROJECT.json" "resolved-$PROJECT.$(date +%Y%m%d-%H%M%S).json"
npx nx show project "$PROJECT" --web
Compares a target's configured inputs in project.json and nx.json with the resolved inputs from nx show project --json, then saves the resolved output so it can be diffed across runs.
A reproducible procedure for nx cache miss debugging
Each step below narrows where the instability lives, so do them in order.
-
Hash the same task twice on an unchanged checkout. Start from a clean working tree, run the target, then run it again without touching anything. Record the task hash each time. Where Nx surfaces the hash depends on your version and setup, so use whatever your installed version reports. The comparison is the point: two runs of identical code should produce identical hashes.
-
Interpret the result. If the two local hashes differ, something inside the workspace changes between runs. Typical causes are a generated file, a timestamp written by a build step, or an output directory that also counts as an input. If the local hashes match but differ between CI and laptops, or between two CI runners, the workspace is probably fine. Look instead at environment variables, the runtime version, or OS-level inputs that differ by machine.
-
Bisect on a scratch branch. Pick the smallest affected project, because every iteration re-hashes everything in scope and a large workspace makes each round slow. Using the saved
nx show projectoutput, remove or narrow roughly half the inputs and re-run. When the hash stabilizes, the culprit is in the half you removed. Restore inputs until you isolate it. -
Rule out tooling state. Run once with
NX_DAEMON=false, or afternx reset. Treat this as a check on your diagnosis, not as a fix. If the miss disappears here, stale daemon or cache state was involved. But resetting only hides the symptom, and an unstable input you haven't found will come back.
#!/usr/bin/env bash
set -euo pipefail
PROJECT="my-small-lib" # start with the smallest affected project
TARGET="build"
hash_of() {
# Placeholder: print the task hash for $PROJECT:$TARGET using whatever
# your installed Nx version exposes. Adapt this to your setup.
echo "REPLACE_WITH_HASH_LOOKUP"
}
git diff --quiet && git diff --cached --quiet || { echo "tree not clean"; exit 1; }
npx nx show project "$PROJECT" --json > "/tmp/${PROJECT}-project.json"
npx nx run "$PROJECT:$TARGET"
H1=$(hash_of)
npx nx run "$PROJECT:$TARGET" # second run, nothing touched in between
H2=$(hash_of)
if [ "$H1" != "$H2" ]; then
echo "Local hashes differ: look inside the workspace (generated files, timestamps, outputs counted as inputs)"
git status --porcelain # did the build leave anything behind?
else
echo "Local hashes match: compare env vars, runtime version and OS inputs across machines"
node --version # record and diff this against CI and other runners
fi
npx nx reset
NX_DAEMON=false npx nx run "$PROJECT:$TARGET"
A shell sketch that runs one task twice on a clean checkout, compares the two hashes to decide whether the instability is in the workspace or the environment, saves the project inputs for bisecting, and then re-runs with no daemon after a reset to confirm the diagnosis.
Which file and non-file inputs most often cause unstable task hashes?
An unstable input you haven't found will produce the same miss on the next change. The culprits below cover most cases. When you compare two runs' hash details, the input whose value differs usually points to one row.
| Symptom | Likely cause | Fix |
|---|---|---|
| A file you never edited changes the hash | Generated file inside the project root that is not in .gitignore or .nxignore |
Ignore it, or exclude it with a negated pattern in the named input |
| Hash changes after every build | Build output lands inside an input glob such as {projectRoot}/**/* |
Move outputs outside the project root, or exclude the output directory from inputs |
| Hash changes on every run | Timestamped artifact, such as a build-info file or report with a date | Stop writing the timestamp, or exclude the file |
| Hash changes with no source change | Codegen emits keys or files in non-deterministic order | Sort the generator's output so identical input gives identical bytes |
| Many projects miss at once | Root lockfile is a shared input and churns on unrelated installs | Remove it from shared globals and rely on Nx's external dependency hashing |
| Hash differs on every CI run | Env input bound to a build number, commit SHA or timestamp | Drop the variable from inputs, or inject it in a task whose output is not cached |
| Hash differs between machines | Runtime input output varies by tool version, absolute path or hostname | Run commands that print only stable values, such as a pinned major version |
Your task can still miss when its own inputs are stable. If a downstream task hashes upstream outputs, for example through dependentTasksOutputFiles, then any non-deterministic byte in those outputs changes the downstream hash. To check, build the upstream project twice and diff the two outputs.
How should you design namedInputs and targetDefaults to avoid needless misses?
Start with two named sets in nx.json. default covers everything a project owns: {projectRoot}/**/* plus a small sharedGlobals set for files that truly affect every task, such as the root lockfile or a base TypeScript config. production starts from default and adds negations for spec and test files, test runner config, Markdown docs, and lint config like .eslintrc.json. Those files never reach a built artifact, so they should not invalidate a build.
The dependency side matters most. In targetDefaults, give build the inputs production and ^production, and give test the inputs default and ^production. The ^ prefix applies the set to a project's dependencies. With this setup, editing a spec file in a shared library reruns that library's tests, but every downstream build and test still hits the cache. A dependent's tests also stop rerunning when you only edit an upstream test.
How one broad pattern defeats this
A single {workspaceRoot}/** entry, often added to sharedGlobals to "be safe," pulls every file in the repository into every hash. A README edit, a CI YAML tweak, or a change in an unrelated app then misses the cache for every task in the workspace. Name root files explicitly instead.
When this pays off
This layout helps most in workspaces where shared libraries have many dependents and CI runs affected or full graphs on every push. Illustrative estimate: if 30 projects depend on one library, a test-only edit to that library reruns 1 project's tests instead of 31 builds and test suites. Small repos with few dependency edges gain less.
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"namedInputs": {
"sharedGlobals": [
"{workspaceRoot}/package-lock.json",
"{workspaceRoot}/tsconfig.base.json"
],
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": [
"default",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/jest.config.[jt]s",
"!{projectRoot}/src/test-setup.[jt]s",
"!{projectRoot}/**/*.md",
"!{projectRoot}/.eslintrc.json"
]
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"inputs": ["default", "^production"],
"cache": true
},
"lint": {
"inputs": ["default", "{workspaceRoot}/.eslintrc.json"],
"cache": true
}
}
}
An nx.json where sharedGlobals names root files explicitly instead of using {workspaceRoot}/**. production removes specs, test config, docs and lint config from build hashes. The ^production input on build and test means a test-only edit in a library does not invalidate downstream builds or tests.
When should you avoid narrowing inputs, and what are the trade-offs?
Narrowing inputs has an opposite failure mode: the false cache hit. If a task reads a file or environment variable that its inputs don't list, Nx computes the same hash after that value changes and replays the old output. A common case is a build that reads API_BASE_URL or a root .babelrc that sits outside the declared inputs.
You can recognize it by artifacts that look stale. Examples are a bundle with last week's config, or a test that passes from cache but fails when you run it with --skip-nx-cache. If behaviour changes only when the cache is bypassed, an input is missing. For release and deploy targets this is worse than a miss. A miss costs minutes. A false hit ships the wrong artifact, and nothing in the logs flags it.
Each narrowing choice has a cost:
- Excluding the root lockfile. This stops one dependency bump from invalidating every project. It can also skip a rebuild that an upgrade actually needed.
- Adding runtime inputs such as the Node version or OS. These make hits correct across mixed machines, but each distinct value gets its own cache entries, so hit rates drop.
| Approach | Cost | Hit rate | Correctness risk |
|---|---|---|---|
| Standardize toolchains (pinned versions, shared CI images) | Upfront setup and ongoing upkeep | High | Low |
| Broader inputs on release targets only | More rebuilds at release time | Medium | Low |
| Runtime inputs everywhere | Fragmented cache | Lower | Low |
| Disable caching for specific targets | Full run every time | None | Lowest |
| Aggressively narrowed inputs | Cheap | Highest | High |
A practical split is to keep inputs narrow for lint and test, and broad for anything that produces a deployable artifact.
What are the alternatives to debugging task hashes?
Tracing a miss to a specific input takes effort. Teams often try one of these instead. Each has a place, but none removes the underlying cause:
- Clearing the cache with
nx resetor rerunning the pipeline. This is fast and sometimes clears a stale daemon or corrupted local cache. If an input is genuinely unstable, the miss returns on the next run, and you have discarded the cached entries you could have compared. - Bypassing the cache with
--skip-nx-cache. This is useful as a diagnostic, because it tells you whether a cached result is wrong. As a standing workaround, it gives up caching for that run entirely. - Disabling caching for the affected target (setting
cache: false). This is a reasonable choice for targets that are non-deterministic by nature, such as tasks that call external services or deploy. For ordinary build and test targets, it turns every run into a full run. - Widening inputs until the problem disappears. Adding broad globs avoids false hits but usually makes misses more frequent, not less, because unrelated changes now invalidate the hash.
- Accepting the misses. In a small workspace where a full run is short, the time spent investigating may cost more than the rebuilds. This is a legitimate choice when it's made deliberately.
- Standardizing the environment first. Pinning runtime versions and using a shared CI image removes a whole class of machine-to-machine differences. It complements hash debugging rather than replacing it, since it doesn't help with generated files, timestamps, or outputs inside input globs.
Hash-level debugging is the only option on this list that identifies which input changed. The others either hide the symptom or trade cache hits for simplicity.
How can fixing unstable hashes save engineering time?
The savings come from three places:
- CI compute. Every unnecessary miss reruns a task whose result already exists. Fixing a single unstable input in a widely shared library can turn many misses across the dependency graph back into hits.
- Waiting time. Engineers wait on pipelines before they can merge or move on. Cache hits shorten that wait for everyone whose change doesn't touch the affected projects.
- Repeated investigations. Without the procedure and the CI check described here, each slow-pipeline complaint starts a new investigation. A documented method and an automated guard keep the fix from being lost.
Illustrative estimate, with assumed inputs: assume a team merges 40 pull requests a day, each pipeline spends 8 minutes rebuilding targets that should have been cache hits, and an engineer waits on half of those pipelines. That is 40 × 8 = 320 runner-minutes a day of avoidable compute, and 20 × 8 = 160 minutes a day of engineer waiting time. Under those assumed numbers, a fix that takes a day to find and apply would pay back within the first few days. Your own inputs will differ, so measure your pipeline durations and miss rates before and after the fix rather than relying on these figures.
The savings are smaller when the workspace is small, when few projects share dependencies, or when most misses are legitimate because the code really changed.
How do you keep the cache stable after fixing it?
Put the corrected namedInputs and targetDefaults in nx.json, not in individual project.json files. When the rules live in one file, a reviewer can see every input definition in one diff. Per-project overrides then stand out as deliberate exceptions. If the definitions are scattered across projects, the same unstable input tends to come back in a project nobody checked.
Next, add a CI step that proves the cache still works. Choose one representative cacheable target, such as api:build. Run npx nx run api:build once to fill the cache. Then run it again with the output saved to a file, for example npx nx run api:build | tee second.log. Fail the job if the log does not contain the cache-hit message. Nx prints a line saying it read the output from the cache, so grep -q "from the cache" second.log || exit 1 works. Match the exact wording your Nx version prints. Both runs happen on the same machine with the same checkout. If the second run misses, something nondeterministic has entered the hash: a timestamp, an unpinned env var, or a generated file. The check catches it in the pull request that introduced it, before anyone notices slow pipelines weeks later and has to repeat the same investigation.
Finally, write down which environment variables each target may depend on. The best place is the target's inputs, using { "env": "NAME" } entries, with a short comment in the repo docs explaining why each one is there. That gives reviewers a simple rule: if a change makes a target read a new file or variable, the same pull request must add it to inputs. If it doesn't, the reviewer requests changes.
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 cache miss debugging, 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.