How does Nx decide a task is affected or a cache hit?

Nx answers two separate questions for every run. nx affected asks which projects changed. The task cache asks whether a specific target has already run with identical inputs. The two use different mechanisms, and SQL and .proto files can slip past each one differently.

To decide whether a project is affected, Nx maps each changed file to the project whose root contains it, then follows the project graph to dependents. A file at the workspace root that belongs to no project, such as a shared protos/ directory, marks nothing affected unless you configure it to.

For caching, Nx computes a hash for each task from the inputs its target declares: file globs, the hashes of dependency inputs, environment and runtime values, and the target's own configuration. A file that matches no input pattern contributes nothing to the hash. If a project's production input set was written with TypeScript in mind and excludes or never includes migrations/**/*.sql, then editing a migration produces the same hash. Nx replays the cached output, and the integration test never runs against the new schema.

Flow from file change to decision:

  • Changed file → owned by a project? → yes: project marked affected → no: ignored by affected
  • Affected task → file matches a declared input? → yes: hash changes → task runs → no: hash unchanged → cache hit, stale result

In a polyglot monorepo, this is the dangerous case. Nx reports success with no warning, so the gap shows up only in staging or production.

 ┌──────────────────────────────┐
 │ Changed file                 │
 │ e.g. migrations/002_add.sql  │
 │      protos/user.proto       │
 └──────────────┬───────────────┘
                ▼
 ┌──────────────────────────────┐  no   ┌─────────────────────────────┐
 │ Inside a project root?       ├──────►│ nx affected: nothing marked │
 └──────────────┬───────────────┘       │ (root-level protos/ etc.)   │
                │ yes                   └─────────────────────────────┘
                ▼
 ┌──────────────────────────────┐
 │ Project + dependents marked  │
 │ affected (project graph)     │
 └──────────────┬───────────────┘
                ▼
 ┌──────────────────────────────┐  no   ┌─────────────────────────────┐
 │ Matches a glob in target's   ├──────►│ File adds nothing to hash   │
 │ inputs / namedInputs?        │       └──────────────┬──────────────┘
 └──────────────┬───────────────┘                      ▼
                │ yes                   ┌─────────────────────────────┐
                ▼                       │ Hash same as previous run   │
 ┌──────────────────────────────┐       │ CACHE HIT: stale output     │
 │ Task hash = matched files +  │       │ replayed; tests never see   │
 │ dep inputs + env + config    │       │ the new .sql / .proto.      │
 └──────────────┬───────────────┘       │ No warning is printed.      │
                ▼                       └─────────────────────────────┘
 ┌──────────────────────────────┐
 │ Hash changed: task runs      │
 └──────────────────────────────┘

A changed .sql or .proto file can be missed in two places: nx affected ignores it if no project root contains it, and the cache ignores it if no declared input glob matches it, which leads to a silent cache hit with stale output.

What are nx namedInputs and how do default, production, {projectRoot} and {workspaceRoot} work?

namedInputs is a map in nx.json that gives a name to a list of input definitions. Each entry can hold file globs, other named inputs, exclusions prefixed with !, and in many versions non-file inputs such as environment variables or runtime commands. You define a set once, for example "everything a build depends on", and then reference it by name from many targets. Without named sets, every target would carry its own copy of the glob list, and those copies would drift apart.

Most workspaces use two names by convention:

  • default: every file in the project plus a few shared workspace files. This is the broad, safe set.
  • production: default minus test files, lint configs, and other material that does not affect shipped output. Build targets use production so that editing a spec file does not invalidate a build cache.

Nx does not reserve these names or give them special behaviour. They are a convention.

Globs are anchored with tokens. {projectRoot} resolves to the directory of the project that owns the target, so a single definition in nx.json works for every project. {workspaceRoot} resolves to the repository root and is how you pull in root-level files.

Targets reference named inputs through their inputs array, usually set in targetDefaults. A plain name refers to the current project's files. A ^ prefix refers to the same named input on the project's dependencies. A project can also define its own namedInputs in project.json, which overrides the workspace definition with the same name for that project only.

Field names, token syntax, and the supported input types have changed across Nx releases. Check the documentation for the version you have installed.

{
  "namedInputs": {
    "sharedGlobals": ["{workspaceRoot}/tsconfig.base.json"],
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/.eslintrc.json"
    ]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production"],
      "cache": true
    }
  }
}

An nx.json fragment defining default and production named inputs with {projectRoot} and {workspaceRoot} tokens, referenced from targetDefaults; ^production pulls in dependencies' production files.

How do you configure namedInputs for SQL migrations and proto files?

Start in nx.json. Add a migrations entry under namedInputs that globs {projectRoot}/migrations/**/*.sql. Then, in targetDefaults, list migrations in the inputs of migration-lint, integration-test and schema-diff. Those three targets read the SQL files directly, so a cached result is only valid if the SQL is unchanged.

Leave migrations out of targets such as build and unit test. A compiled service binary or a mocked unit suite does not depend on migration text. Including it would turn every column rename into a full rebuild and retest of each project that owns a migrations folder.

Define protos the same way. Cover {projectRoot}/proto/**/*.proto along with the generator configuration: {projectRoot}/buf.yaml, {projectRoot}/buf.gen.yaml and {projectRoot}/buf.lock if you use buf, or whatever options file your protoc wrapper reads. Reference protos from the codegen target.

Generated code depends on both the schema and the instructions for turning it into code. Changing a plugin version, an output path or a language option in buf.gen.yaml produces different files even when no .proto file changed. If only the .proto files are hashed, Nx restores stale generated code from cache and reports success.

Keeping these definitions in targetDefaults means every project picks them up without repetition. The convention breaks for projects that keep SQL in db/ or protos in api/. A glob that matches no files does not raise an error. It hashes to the same empty value on every run, so edits in those directories never invalidate the cache.

For each nonconforming project, redefine migrations or protos under namedInputs in its project.json, pointing at the real directory. The targets keep referencing the same input name, and only the path behind it changes.

# nx.json: shared named inputs and target defaults.
# migrations is deliberately absent from build and test.
cat > nx.json <<'EOF'
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "migrations": ["{projectRoot}/migrations/**/*.sql"],
    "protos": [
      "{projectRoot}/proto/**/*.proto",
      "{projectRoot}/buf.yaml",
      "{projectRoot}/buf.gen.yaml",
      "{projectRoot}/buf.lock"
    ]
  },
  "targetDefaults": {
    "migration-lint": { "inputs": ["migrations"], "cache": true },
    "schema-diff": { "inputs": ["migrations"], "cache": true },
    "integration-test": { "inputs": ["default", "migrations"], "cache": true },
    "codegen": { "inputs": ["protos"], "cache": true }
  }
}
EOF

# This project keeps SQL in db/ and protos in api/. Without these overrides
# the shared globs match nothing and hash to the same empty value every run.
# Targets still reference "migrations" and "protos" by name.
cat > services/billing/project.json <<'EOF'
{
  "name": "billing",
  "namedInputs": {
    "migrations": ["{projectRoot}/db/**/*.sql"],
    "protos": [
      "{projectRoot}/api/**/*.proto",
      "{projectRoot}/buf.yaml",
      "{projectRoot}/buf.gen.yaml",
      "{projectRoot}/buf.lock"
    ]
  }
}
EOF

The nx.json file defines shared migrations and protos named inputs and wires them into targetDefaults, and a project-level override redirects both names to a project that uses db/ and api/ instead of the convention.

How do proto changes in one project mark consuming services as affected?

Nx builds its project graph largely from source analysis: for TypeScript it follows imports. A .proto file under project A that service B compiles at build time produces no such edge. When you edit libs/payments-api/proto/charge.proto, nx affected maps the change to payments-api, finds no dependents, and stops. B is skipped, and its cached build is reused even though the generated stubs it would produce have changed.

Two pieces of configuration close this gap, and they do different jobs.

The graph edge. Add implicitDependencies: ["payments-api"] to B's project.json. Affected detection walks this edge, so any change to A, including its .proto files, now marks B as affected. If B already imports code from A, that edge may already exist, so check the graph before adding a redundant one.

The hash input. In B's build target, add ^protos to inputs. The ^ prefix tells Nx to resolve the protos named input against each of B's dependencies and fold those files into B's task hash. Without it, B can be marked affected but still get a cache hit, because none of B's own inputs changed. ^protos does nothing on its own, though. It only reaches projects that are already connected by an edge, so you need both.

The cost is fan-out. If ten services depend on a shared common-types proto project, a one-line comment change in that project rebuilds and retests all ten. That result is correct, but CI runs can get noticeably larger than teams expect. Section 5 covers how to narrow it.

// nx.json (Nx accepts comments in its JSON config files)
{
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    // {projectRoot} resolves per project, so for payments-api this
    // matches libs/payments-api/proto/**/*.proto
    "protos": ["{projectRoot}/proto/**/*.proto"]
  }
}

// services/billing/project.json (service B)
{
  "name": "billing",
  // Graph edge: a change anywhere in payments-api, including its
  // .proto files, now marks billing as affected.
  "implicitDependencies": ["payments-api"],
  "targets": {
    "build": {
      "inputs": [
        // billing's own sources
        "default",
        // Hash input: fold the 'protos' files of every dependency
        // (here payments-api) into billing's build hash so an edited
        // .proto causes a cache miss instead of a stale hit.
        // This only reaches projects connected by a graph edge.
        "^protos"
      ]
    }
  }
}

A shared protos named input in nx.json plus an implicit dependency and a ^protos build input in service B's project.json, so an edit to payments-api's .proto files marks billing as affected and invalidates its cached build.

What are the alternatives for shared root-level protos, SQL fixtures and generated code?

A {workspaceRoot} glob such as {workspaceRoot}/protos/**/*.proto added to each consumer's inputs is quick to set up, but it is all-or-nothing. Every project that includes the glob is affected by any change under that directory, even when a service imports only one file. The glob also adds no edge to the project graph, so the graph view and dependency-based tooling do not show the relationship.

Moving the directory into its own Nx project, or into several small ones split by domain, makes the dependency explicit. Consumers then pick up proto or fixture changes through ^-prefixed inputs, which resolve against their dependencies. Only projects that depend on the changed project are affected. Splitting further narrows that set, which the glob approach cannot do.

Concern Cached as target outputs Committed to the repo
Source of truth .proto files only .proto files plus generated code
Downstream access Restored from cache via dependsOn Always present on checkout
Main failure mode Partial restore if an outputs path is wrong Drift between protos and stubs
Required guard Outputs that match the generator's real write paths CI regeneration plus a diff check

When stubs are declared outputs, a cache hit on the codegen target writes them back to disk before downstream builds run. If the generator writes to a directory that outputs does not list, the cache hit still succeeds but those files are not restored. The downstream build then fails or compiles against stale files left on disk.

Committing stubs removes that risk but introduces drift. CI should regenerate the stubs and fail if the working tree changes.

When should you avoid broad inputs, and what can file hashing not see?

Getting inputs wrong fails in two directions, and only one of them is visible.

Input scope Symptom Visible?
Too broad (e.g. {workspaceRoot}/**/*) Every commit affects every project; cache hit rate collapses Yes: CI gets slow
Too narrow (e.g. only *.ts in a service that reads .proto) Stale cache hits; tests skipped for changed contracts No: tasks report success
Correct files, missing toolchain Upgrading the generator or migration tool reuses old outputs No

Broad inputs are easy to spot because the cost shows up in pipeline duration. Narrow inputs are worse because Nx has nothing to warn about. It hashed what you declared, the hash matched, and it replayed a cached success. If a proto field was renamed and the consumer's inputs never included that file, the broken build stays hidden until someone runs it without the cache.

File hashing sees file contents only. It cannot tell whether a migration has already been applied to staging, or whether someone altered a table by hand in production. Schema drift needs its own check against the live database. A clean affected run does not prove the database is in a good state.

Toolchain versions are the other blind spot. Changing the protoc or buf version, or upgrading the migration CLI, can change generated output while the source files stay identical. Nx supports runtime inputs (the output of a command, such as a version flag) and env inputs. You can also list the lockfile, buf.yaml, or a pinned tool-version file as inputs. Check which input types your Nx version supports, and confirm the change by bumping a version and watching the target miss the cache.

How do you verify the setup, and how does it affect CI cost and engineering time?

Run the check before CI depends on it. First, run nx show project <name> for a service that consumes protos and one that owns migrations. Read the resolved inputs for the relevant targets. Make sure the patterns point at the paths you expect. A typo in a glob does not raise an error. It just matches nothing.

Next, create a scratch branch and change one line in a single .proto file. Commit it, then run nx affected -t build --base=main. The owning project and every consumer should appear in the output, and nothing unrelated should. Repeat with a one-line .sql migration change. If a consumer is missing, the dependency edge is wrong. If half the repo appears, an input is too broad. Run the same command twice to confirm the second run is a cache hit.

The costs are the setup work, which is usually a day or less, plus keeping file conventions consistent and reviewing fan-out when a new consumer is added. You get two things in return: CI skips unaffected work, and builds no longer pass stale because a proto edit went unnoticed.

Illustrative estimate (assumed numbers, not a benchmark)

Weekly CI minutes saved = PRs per week × (full run minutes − affected run minutes)

Assume 30 PRs, a 40-minute full run, and a 12-minute average affected run:

30 × (40 − 12) = 840 runner-minutes per week

Against that, assume 8 hours of setup and 1 hour per week of upkeep.

The setup pays off most in monorepos where several services share protos or a database schema. Fan-out is common there, and a missed dependency is expensive.

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 namedInputs, 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 .env by 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.