How does Nx compute a task hash, and what does a cache miss actually mean?
Before Nx runs a target, it computes a hash from everything the target declares as an input. It then looks that hash up in the local cache and, if one is configured, the remote cache. A cache miss means no stored entry has that exact hash, so at least one input differs from every previous run. The cache store is almost never at fault. The cause is a different hash.
The hash combines:
- Project file inputs: the files matched by the target's
inputs, usually expanded fromnamedInputssuch asdefaultorproduction. - Dependency inputs: entries prefixed with
^, which pull in the named inputs of every project this one depends on. One edit in a shared library changes the hash of every dependent target. - Runtime and env inputs: environment variable values and the output of declared commands, such as a tool version check.
- External dependencies: resolved package versions from the lockfile.
- Command and options: the executor, its options, and any arguments passed on the command line.
project files ──┐
^dep inputs ────┤
env / runtime ──┼──► task hash ──► local cache ──hit──► restore outputs
lockfile deps ──┤ │ miss
cmd + options ──┘ ▼
remote cache ──hit──► restore outputs
│ miss
▼
run target, store result
If a backend target reruns on every invocation, start with the hash. Find out which inputs fed into it and which one changed. Clearing or inspecting the cache directory only hides the symptom. The changed input is still there, and it will cause another miss on the next run.
INPUTS HASH AND CACHE LOOKUP
+--------------------------+
| project files |---+
| (inputs / namedInputs) | |
+--------------------------+ |
| ^ dependency inputs |---+
| (deps' named inputs) | | +--------------+
+--------------------------+ +---->| task hash |
| env vars / runtime cmds |---+ +------+-------+
+--------------------------+ | |
| lockfile: external deps |---+ v
+--------------------------+ | +--------------+ +---------+
| executor + options + args|---+ | local cache |--hit->| restore |
+--------------------------+ +------+-------+ | outputs |
| miss +----+----+
v ^
+--------------+ |
| remote cache |-----hit----+
| (optional) |
+------+-------+
| miss
v
+--------------+
| run target, |
| store result |
+--------------+
Nx combines a target's file, dependency, environment, lockfile and command inputs into a single task hash. It looks that hash up in the local cache, then the remote cache, and runs the target only when neither cache has an entry for that hash.
Who should debug cache misses, and when is it worth the time?
This work usually falls to the backend or platform engineer who owns CI minutes, the shared nx.json, or the project configuration for a heavy service. Application developers notice the slowdown first, but they rarely have the context to change shared inputs safely.
Start digging when you see one of these signals:
- A target reruns when you run it twice on an unchanged working tree.
- Remote cache hit rates stay low even though most pull requests touch only a few files.
- CI takes nearly as long on a one-line diff as on a full rebuild.
Each signal points to an input that changes when it shouldn't. That input taxes every pipeline until someone removes it.
To judge whether the fix is worth the time, compare the hours spent tightening inputs with the compute and waiting time you recover.
Illustrative estimate (assumed numbers, not a benchmark)
- Assumed: a backend build takes 6 minutes, a team of 8 triggers 15 avoidable reruns per day, and a month has 20 working days.
- Daily waste = reruns per day × build duration = 15 × 6 = 90 minutes.
- Monthly waste = 90 × 20 = 1,800 minutes, or 30 hours.
- If the fix takes 8 hours, payback = 8 ÷ 1.5 hours per day ≈ 5 working days.
Don't tune aggressively when misses happen across machines because of real differences. A different Node major version, operating system, CPU architecture, or compiled native module produces artifacts that won't work elsewhere. In those cases the cache miss is correct behavior. If you force a hit by dropping runtime inputs, Nx restores binaries built for a different environment, and the failures that follow are harder to debug than a slow build.
How do you see what Nx thinks a target depends on with nx show project?
Before changing any configuration, find out what Nx is actually hashing. project.json shows only part of the picture. The effective target config combines three things: targets inferred by plugins from files like tsconfig.json or a build tool's config, the targetDefaults and namedInputs in nx.json, and whatever the project declares locally. A target can have inputs you never wrote, or be missing ones you assumed it had.
Running nx show project <name> prints the resolved configuration after that merge. Adding --json gives output you can diff. Many installed versions also support --web, which opens a browser view that shows, for each target, where each setting came from. If your version lacks the flag, the JSON output still contains everything you need.
For the target that keeps rerunning, check four fields:
inputs: Look for a broad default such as{projectRoot}/**/*, which also matches logs, local.envfiles and test fixtures. Also check whetherdependentTasksOutputFilesorexternalDependenciesappear.- Referenced
namedInputs: Expand each name, becauseproductionin one workspace can mean something very different in another. outputs: If these are wrong, Nx caches the wrong files, and later restores look like misses.dependsOn: Every upstream task's hash becomes part of this target's hash.
Inferred targets reduce the amount of config you write, but they make the effective inputs harder to see. You find out what is being hashed only by asking Nx. Overriding inferred inputs explicitly makes them visible again, but you then own that config. When the plugin's defaults change, your override does not change with them, and it can drift without anyone noticing.
# Project 'api' and target 'build' are placeholders; substitute your own.
# 1. Dump the fully resolved project config: plugin inference + nx.json merged in.
npx nx show project api --json > /tmp/api-resolved.json
# 2. Pull out the four fields that decide the hash for the rerunning target.
jq '.targets.build | {inputs, outputs, dependsOn}' /tmp/api-resolved.json
# 3. Compare with what project.json declares locally.
# Fields that appear in step 2 but not here came from inference or targetDefaults.
jq '.targets.build // "no local build target (inferred only)"' apps/api/project.json
# 4. Expand the named inputs referenced in step 2 (e.g. "production", "default").
# The same name can mean different file sets in different workspaces.
jq '.namedInputs' nx.json
# 5. Check the workspace-wide defaults that were merged into the target.
jq '.targetDefaults' nx.json
# 6. If your Nx version supports it, open the browser view, which shows
# where each setting came from.
npx nx show project api --web
# 7. After editing config, re-dump the resolved config and diff it to confirm
# the effective inputs changed the way you intended.
npx nx show project api --json > /tmp/api-resolved-after.json
diff <(jq -S '.targets.build' /tmp/api-resolved.json) \
<(jq -S '.targets.build' /tmp/api-resolved-after.json)
Uses nx show project with --json and jq to read the effective inputs, outputs and dependsOn for one target, compares them with project.json and nx.json, and diffs the resolved config before and after a change.
How do you reproduce a cache miss and find which input changed?
Before reading any config, make the miss happen on demand. A miss you cannot reproduce is one you cannot diff. Run the target twice in a row on a tree with no edits. Then run it in a fresh clone, and if you can, inside the CI image. Each step rules out a class of cause, so the order matters.
| Where the miss appears | Likely cause | What to check first |
|---|---|---|
| Second run on an unchanged tree | The task writes files that are also its inputs, or an input changes on every run | Generated sources, timestamps or build IDs written into tracked paths, env vars that change per run |
| Clean checkout only | Untracked or ignored files that your working copy has and a fresh clone does not | Local .env files, leftover build artifacts, files missing from the ignore rules that inputs rely on |
| Across machines or CI only | Environment differences | OS and architecture, absolute paths in config, env and runtime inputs, Node or compiler versions |
A miss on an unchanged tree is the most useful result because it is deterministic. Something in the run itself is changing an input.
To find which input moved, capture the hash details for a hit and for a miss, then diff them. Nx breaks a task hash into per-input components: files, dependencies' hashes, runtime and env values, and so on. You can get these from the task graph or hash output, or from run summaries written to the cache or workspace data directory. Do not diff the top-level hashes. Diff the per-input breakdown, because only that tells you which input moved.
Where these details live, and which flags expose them, has changed between Nx releases. Check your installed version's CLI help and docs instead of copying a flag from an old answer.
#!/usr/bin/env bash
# Reproduce an Nx cache miss before reading any config.
set -euo pipefail
PROJECT=api # placeholder project name
# 1. Start from a tree with no edits, so any miss comes from the run itself.
test -z "$(git status --porcelain)" || { echo 'tree is dirty'; exit 1; }
npx nx run "$PROJECT:build" # first run, populates the cache
npx nx run "$PROJECT:build" # second run, should be a cache hit
# Anything listed here was written by the task into tracked paths,
# such as generated sources or stamped build IDs that may also be inputs.
git status --porcelain
# 2. Preview what a fresh clone would not have: untracked and ignored files
# such as local .env files or leftover artifacts. -n means dry run, so nothing is deleted.
git clean -ndx
# 3. Record environment facts on each machine and compare them across machines.
uname -sm
node --version
npx nx --version
# 4. Find out what this Nx version exposes for hash details.
# Do not copy a flag from an old answer.
npx nx run --help | grep -iE 'graph|hash|verbose|summary' || true
# 5. Save the per-input hash breakdown from a hit and from a miss
# (hit.json, miss.json), then diff them with sorted keys so only real changes show.
jq -S . hit.json > hit.sorted.json
jq -S . miss.json > miss.sorted.json
diff hit.sorted.json miss.sorted.json || true
A reproduce-first script that runs a target twice on a clean tree, lists files the task wrote and files a fresh clone would lack, records environment details, checks which hash-inspection options the installed Nx version offers, and diffs the per-input breakdown of a hit against a miss.
What commonly invalidates the cache in backend projects?
Most backend misses come from files or values that change on every run, sitting where the default {projectRoot}/**/* style input glob picks them up.
| Culprit | Why it changes the hash | Symptom |
|---|---|---|
| Generated code in the project root (Prisma client, OpenAPI or gRPC stubs, compiled protobufs) | The generator rewrites files, sometimes with embedded paths or headers | Misses right after install or a codegen step |
.env and secret files |
Matched by default globs | Misses on every machine with different local values |
| Timestamp or build-info files | Content differs on every build | Every run misses, even with no edits |
| Coverage output, JUnit XML | Test outputs are written into input paths | build misses after test runs |
| Logs, SQLite databases | Written at runtime next to source | Misses after starting the service locally |
Configured inputs cause misses too. An env input on a per-run value such as a CI build number, commit SHA or random port guarantees a miss on every run. A runtime input whose command prints non-deterministic output, such as a date or a temp path, does the same. To audit, read the inputs arrays in targetDefaults in nx.json and in each project's configuration. Flag any input that resolves to a value you would not expect to be identical across two consecutive runs.
.env needs a deliberate choice. Excluding it from inputs keeps secrets out of hash computation and improves hit rate. The cost is that changing a variable your tests depend on can replay a stale passing result. A better middle ground is often to exclude the file and declare the specific variables that affect behaviour as env inputs.
// nx.json (Nx parses comments in its JSON config files)
{
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"sharedGlobals": [],
"production": [
"default",
// Generated clients and stubs: hash their sources (schema.prisma, *.proto) instead
"!{projectRoot}/src/generated/**/*",
// Secrets stay out of the hash; specific variables are declared as env inputs below
"!{projectRoot}/.env*",
// Runtime and test artifacts written next to source
"!{projectRoot}/coverage/**/*",
"!{projectRoot}/reports/**/*.xml",
"!{projectRoot}/**/*.log",
"!{projectRoot}/**/*.sqlite",
"!{projectRoot}/build-info.json"
]
},
"targetDefaults": {
"build": {
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"inputs": [
"default",
"^production",
"!{projectRoot}/.env*",
// Only variables that change test behaviour, so edits still invalidate the cache
{ "env": "FEATURE_FLAGS" },
{ "env": "PAYMENTS_API_MODE" },
// Deterministic runtime input; never use `date`, a temp path or a random port here
{ "runtime": "node --version" }
// Deliberately absent: CI build number, commit SHA, PORT
],
"cache": true
}
}
}
An nx.json that excludes generated code, .env files and runtime artifacts from input globs, declares only behaviour-relevant variables as env inputs, and keeps runtime inputs deterministic.
How do you fix cache misses with namedInputs and correct outputs?
Those variable-level inputs work better once the project has a sound baseline set of inputs, which is what namedInputs provides.
Define a production input
In nx.json, define a production named input that starts from everything in the project, {projectRoot}/**/*, and then subtracts with negated globs: !{projectRoot}/**/*.spec.ts, !{projectRoot}/test/fixtures/**, local-only config such as !{projectRoot}/.env.local, and generated or volatile paths like !{projectRoot}/src/generated/**. Point the build target's inputs at production and ^production. The caret form means "the production inputs of my dependencies." A new spec file in a shared library then leaves the build hash of every downstream service unchanged. Tests still use the default inputs, so they rerun when specs change.
Declare outputs precisely
Outputs control what Nx stores and restores. If they are missing or point to the wrong path, you get a cache hit that restores nothing, and later steps fail or quietly ship old artifacts. If outputs fall inside an input glob, every build writes files that change the next hash, and the target misses forever. For example, a build that writes to {projectRoot}/dist while dist is still inside {projectRoot}/**/* invalidates itself. Place outputs outside the input set, or exclude them explicitly.
Treat every exclusion as a claim
Each negated glob asserts that the task never reads that file. Migrations bundled into the image, schemas read at build time, and runtime config that gets copied into the artifact all break that assertion. A slow build costs minutes. A false cache hit ships the wrong binary, so when you are unsure whether a task reads a file, keep it as an input.
What are the alternatives for handling generated code and volatile inputs?
Volatile inputs force a trade-off between hit rate and the risk of a false hit. The four common approaches differ in where they put that risk.
| Approach | Correctness risk | Hit rate | Maintenance cost | Choose it when |
|---|---|---|---|---|
Generation as its own cached target with declared outputs, and downstream targets depending on it |
Low. The schema or spec is a hashed input, so a changed source produces new code. | High. Codegen reruns only when its source changes. | Medium. You add a target, a dependsOn edge and an outputs path that must stay accurate. |
Generation is slow or many projects consume the result |
| Exclude generated files from inputs and regenerate on every run | Medium. Drift between the committed spec and the generated code goes unnoticed because nothing hashes the result. | High for the build, but you pay the codegen time on every run. | Low | Generation is fast and only one project uses it |
Declare specific env inputs instead of hashing whole config files |
Low if the list is complete. An undeclared variable the build reads causes false hits. | High. Only the values that matter affect the hash. | Medium. Someone has to update the list when the code reads a new variable. | Config files change often for reasons the build ignores |
| Accept some misses, such as hashing the OS or toolchain through runtime inputs | Lowest | Lower across machines | Low | Artifacts differ by platform or architecture, so sharing them would be wrong |
The last row describes a cache doing its job, not a bug to fix. If a Linux CI agent and a macOS laptop produce different native binaries, a shared hit between them would be the actual defect.
How do you validate the fix and avoid stale daemon or graph results?
A fix is only confirmed when the cache behaves correctly across all four of these conditions, in order:
- Run the target once so it populates the cache with the new configuration.
- Run it again unchanged and confirm Nx reports a local cache hit. A miss here means some input still changes between identical runs, often a timestamp or an absolute path.
- Run it in a clean, CI-like environment, such as a fresh clone or a container. If remote caching is enabled, expect a remote hit. This catches inputs that only stayed stable because of something on your machine.
- Run
nx resetand repeat steps 1–2. This clears the local cache and the daemon's state, so the result no longer depends on anything computed before your edit.
Why the daemon can hide config edits
The Nx daemon keeps the project graph in memory and watches files to update it. Usually that works. During debugging, though, a missed file event or a plugin that reads files the watcher doesn't track can leave the daemon serving a graph built from your old namedInputs. The hash then looks fixed, or still broken, for reasons unrelated to your change. If nx show project output doesn't reflect an edit you just made, restart the daemon or run nx reset before you draw any conclusions.
The CI trade-off
Setting NX_DAEMON=false makes each CI run compute the graph from scratch. Results are predictable, but every invocation pays the graph computation cost. Keeping the daemon on is faster but can mask stale-graph problems while you are still investigating. A practical approach is to disable the daemon while you debug, then decide based on how long graph computation takes in your workspace.
Hash detail output differs across Nx versions and plugins. Record the exact commands that produced useful output in your workspace, so the next person debugging a cache miss starts from known-good steps.
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.
- 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.