How does nx affected decide what changed?
nx affected does not deploy anything. It answers one question: given two commits, which projects might behave differently? Running nx affected -t deploy takes that answer and runs the deploy target on each project in it. The deploy logic lives in your target. Nx only supplies the list, so treat the list as a change-detection signal.
From commits to files
Nx compares a base revision with a head revision, which you set with --base and --head, and collects the files that differ between them. The quality of the result depends on the base you choose, because every later step works from this file list.
From files to projects
Each changed file is mapped to the project whose root contains it. A file under apps/billing/ marks billing as touched. A file that sits outside every project root does not map to any one project. If it is covered by your workspace's global inputs, it can mark every project affected. This is why a change to the root lockfile, the root package.json, nx.json or a shared TypeScript base config can expand one small commit into a deploy of most of the monorepo. Nx inspects some of these files, the lockfile for example, to narrow the effect, but you should not assume it always can.
From projects to dependents
Nx then walks the project graph in reverse. If billing imports libs/money, a change to money marks billing affected too. Edges come from static import analysis and from implicitDependencies that you declare yourself.
Why misses are the real risk
If a dependency is not represented in the graph, Nx produces no warning. The service is left out of the list, the pipeline goes green, and production keeps running stale code. An unnecessary deploy only costs some CI time. A missed deploy can leave services out of sync, so err toward over-inclusion.
#!/usr/bin/env bash
set -euo pipefail
# Base and head define the comparison. Use the last commit that was
# deployed successfully, not just the previous commit, or changes from
# earlier failed runs are silently dropped.
BASE="origin/main"
HEAD="HEAD"
# Step 1: the raw input. Every later step is derived from this file list.
echo "Changed files:"
git diff --name-only "$BASE" "$HEAD"
# Step 2: files mapped to projects, then expanded to dependents through
# the project graph. Print the result before acting on it.
echo "Affected projects:"
npx nx show projects --affected --base="$BASE" --head="$HEAD"
# Root-level files such as the lockfile, package.json or nx.json can
# mark most projects affected. Surface that case so it is not a surprise.
if git diff --name-only "$BASE" "$HEAD" \
| grep -qE '^(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|package\.json|nx\.json|tsconfig\.base\.json)$'; then
echo "Note: a root-level file changed; expect a wide affected set."
fi
# Step 3: only now run the deploy target. Nx supplies the list; the
# deploy logic itself lives in each project's 'deploy' target.
npx nx affected -t deploy --base="$BASE" --head="$HEAD"
A CI script that prints the changed files and the resulting affected project list before running the deploy target, so the change-detection signal can be checked before anything is released.
Who should use selective deploys, and when should you avoid them?
Selective deploys pay off in monorepos with many independently deployable services, where a full rollout is slow or expensive. Without them, a typo fix in one service's README can trigger a rollout of every service in the repo. The more services you have and the more often you merge, the more that waste adds up.
Illustrative estimate (assumed inputs, not a measurement): assume 30 services, 4 minutes of serial deploy time per service, 20 merges a day, and an average of 3 affected services per merge. Deploying everything costs 120 minutes per merge. Deploying only affected services costs 12 minutes. Across a day, that is roughly 36 hours of runner time saved, plus shorter queues for everyone waiting to merge.
That saving has a cost. When a service fails to deploy, someone has to trace why: a missing implicit dependency, a Helm values file outside the project's inputs, or a base SHA pointing at the wrong commit. If that happens weekly and takes an afternoon to track down, the estimate above shrinks quickly.
| Situation | Selective deploys | Deploy everything |
|---|---|---|
| Dozens of services, frequent merges | Strong fit | Slow, costly |
| Fewer than about five services | Little gain | Simpler, fast enough |
| Services must ship in lockstep | Risky | Safer |
| No one owns graph inputs | Silent misses likely | Predictable |
Skip selective deploys if your services share runtime contracts that must change together, or if no team can keep the project graph accurate as the repo changes.
Why is the base SHA the most important decision?
nx affected only compares two commits. The --head is usually the commit being built. The --base decides which changes count, and choosing it badly drops services without any error.
| Base choice | What it compares | How it fails |
|---|---|---|
main~1 |
Only the last commit | A failed or cancelled run means the next run never sees that commit's changes |
| PR merge base | The branch against where it forked | Fine for CI checks, but it says nothing about what is actually running in an environment |
Moving branch (e.g. deployed) |
Whatever the branch points to | Concurrent pipelines race. The slower one moves it backwards or past work it never shipped |
| Last successful deploy per environment | The live state against HEAD | Needs stored state that you maintain |
Only the last option reflects reality. Take this sequence: commit A changes billing, the pipeline fails, and commit B changes orders. With main~1, B's run deploys orders and skips billing permanently.
Store the base per environment. You can use a git tag such as deployed/prod, or a value in your CI system's variable store. Move it only after the rollout is confirmed, for example after helm upgrade --wait or kubectl rollout status succeeds for every affected service. Serialize deploys per environment so two runs never advance the marker at the same time.
The stored base can drift or break. Someone deletes the tag, a force-push rewrites history, or a manual hotfix bypasses CI. Guard against this before every run:
- Check that the stored base is an ancestor of HEAD with
git merge-base --is-ancestor. - If the check fails or the marker is missing, fall back to deploying everything.
- Periodically compare the image tags running in the cluster against the marker.
#!/usr/bin/env bash
# Deploy only services changed since the last successful prod rollout.
# Run with one deploy at a time per environment (CI concurrency lock).
set -euo pipefail
ENV=prod
MARKER="deployed/${ENV}"
HEAD_SHA=$(git rev-parse HEAD)
# Fetch the marker. A missing tag is allowed and handled below.
git fetch origin "+refs/tags/${MARKER}:refs/tags/${MARKER}" 2>/dev/null || true
BASE_SHA=$(git rev-parse -q --verify "refs/tags/${MARKER}^{commit}" || true)
# Use the marker only if it exists and is an ancestor of HEAD.
# A deleted tag or rewritten history falls back to deploying every app.
if [[ -n "$BASE_SHA" ]] && git merge-base --is-ancestor "$BASE_SHA" "$HEAD_SHA"; then
SERVICES=$(npx nx show projects --affected --type=app --base="$BASE_SHA" --head="$HEAD_SHA")
else
echo "Marker ${MARKER} missing or not an ancestor of HEAD; deploying all apps" >&2
SERVICES=$(npx nx show projects --type=app)
fi
for svc in $SERVICES; do
# --wait blocks until resources are ready. With set -e, any failure exits
# here and the marker stays put, so the next run retries this service.
helm upgrade --install "$svc" "./charts/${svc}" \
--namespace "$ENV" \
--set image.tag="$HEAD_SHA" \
--wait --timeout 5m
done
# Move the marker only after every rollout has succeeded.
git tag -f "$MARKER" "$HEAD_SHA"
git push -f origin "refs/tags/${MARKER}"
echo "${MARKER} -> ${HEAD_SHA}"
A prod deploy script that reads a per-environment git tag as the Nx base and checks that it is an ancestor of HEAD, falling back to deploying every app if it is not, then advances the tag only after every Helm rollout succeeds.
How do you define a deploy target in project.json?
Give every deployable project three targets that form a chain. docker-build declares dependsOn: ["build"], and deploy declares dependsOn: ["docker-build"]. Running nx affected -t deploy then builds, packages and releases each changed service in order, and nothing else runs. The deploy target is usually an nx:run-commands invocation of helm upgrade --install with --wait and an explicit --timeout. --wait makes Helm block until the new pods are ready, so a crash-looping rollout exits non-zero and fails the CI job. Without it, the job reports success as soon as the manifests are accepted. Add --atomic if you want Helm to roll back automatically on failure. The cost is that the broken pods are gone before anyone can inspect them.
Tag images immutably, using the commit SHA or a hash of the build inputs, and pass that tag to Helm with --set. Mutable tags like latest make rollbacks ambiguous. They also stop Kubernetes from noticing that anything changed.
Set cache: true on build and docker-build, because their outputs are a pure function of their inputs. Keep deploy uncached. Its real output is the state of a cluster that Nx cannot see. A cache hit would print "success" and skip the release entirely, even if someone had scaled the deployment to zero or the namespace had been recreated.
On concurrency, image builds can run in parallel. Deploys are often safer with --parallel=1, or a small number, for three reasons:
- Simultaneous rollouts compete for node capacity.
- Concurrent image pulls can hit registry rate limits.
- Many concurrent Helm clients put load on the API server.
{
"name": "orders-api",
"projectType": "application",
"targets": {
"build": {
"executor": "nx:run-commands",
"cache": true,
"inputs": ["production", "^production"],
"outputs": ["{workspaceRoot}/dist/apps/orders-api"],
"options": {
"command": "tsc -p apps/orders-api/tsconfig.app.json --outDir dist/apps/orders-api"
}
},
"docker-build": {
"executor": "nx:run-commands",
"dependsOn": ["build"],
"cache": true,
"inputs": ["production", "^production", { "env": "GIT_SHA" }],
"options": {
"commands": [
"docker build -f apps/orders-api/Dockerfile -t registry.example.com/orders-api:$GIT_SHA .",
"docker push registry.example.com/orders-api:$GIT_SHA"
],
"parallel": false
}
},
"deploy": {
"executor": "nx:run-commands",
"dependsOn": ["docker-build"],
"cache": false,
"options": {
"command": "helm upgrade --install orders-api charts/orders-api --namespace orders --set image.tag=$GIT_SHA --wait --timeout 5m --atomic"
}
}
}
}
A project.json chaining build, docker-build and deploy via dependsOn, caching only build and image steps, tagging with GIT_SHA, and deploying with helm --wait so CI fails on an unhealthy rollout; run with nx affected -t deploy --parallel=1.
How do you make Helm charts, Dockerfiles and config visible to the project graph?
nx affected decides which projects are touched by mapping each changed file to the project whose root contains it. Task inputs serve a different purpose: they decide whether a cached result can be reused. Deploy correctness depends on both.
Put deploy artifacts inside the project root
Keep each service's Dockerfile, Helm chart and per-environment values files under that service's directory. A commit that only edits values-prod.yaml then marks the service as affected, and its deploy target runs. A chart kept in a top-level charts/ folder belongs to no project, so a values-only change there can produce no deploys at all.
Declare inputs for the image build
Define a named input, for example docker, that includes the Dockerfile, the chart directory and the production source set. Add env inputs for build-time variables and externalDependencies for tools whose version affects the output. Use dependentTasksOutputFiles for generated code, so that a regenerated client invalidates the hash. If inputs are too narrow, a changed Dockerfile can return a cached, stale image. If they are too broad, for example {workspaceRoot}/**/*, every build misses the cache and you lose the time selective deploys were meant to save. Never cache the deploy target itself.
Control root-level files
For shared base charts or cluster config, create a small project that owns those files. Have each service list it in implicitDependencies. The fan-out is now explicit and reviewable, and an unrelated root file does not trigger a deploy of every service.
{
"name": "orders",
"root": "apps/orders",
"implicitDependencies": ["deploy-shared"],
"namedInputs": {
"docker": [
"production",
"{projectRoot}/Dockerfile",
"{projectRoot}/chart/**/*",
{ "env": "BUILD_REGION" },
{ "externalDependencies": ["typescript"] }
]
},
"targets": {
"docker-build": {
"executor": "nx:run-commands",
"dependsOn": ["^build"],
"cache": true,
"inputs": [
"docker",
"^production",
{ "dependentTasksOutputFiles": "**/*.ts", "transitive": true }
],
"options": {
"command": "docker build -t registry.example.com/orders:$GIT_SHA {projectRoot}"
}
},
"deploy": {
"executor": "nx:run-commands",
"dependsOn": ["docker-build"],
"cache": false,
"options": {
"command": "helm upgrade --install orders {projectRoot}/chart -f {projectRoot}/chart/values-prod.yaml --set image.tag=$GIT_SHA"
}
}
}
}
An apps/orders/project.json with a 'docker' named input covering the Dockerfile, chart, env and tooling, generated-code hashing, an explicit shared-config dependency, and an uncached deploy target.
Per-service Helm releases vs an umbrella chart: what are the alternatives?
Once the graph knows which services changed, your chart layout decides whether you can actually ship them independently.
| Model | Deploy granularity | Main cost |
|---|---|---|
| One release per service, chart inside the project | Per service | Duplicated templates across charts |
| Shared library chart, per-service releases | Per service | A library edit marks every consumer affected |
| Umbrella chart | All-or-nothing | Every upgrade re-renders all subcharts |
An umbrella chart defeats selective deploys. It is a single release, so one upgrade touches every service, and a rollback reverts services nobody changed. The library chart is the usual compromise. Shared templates live in one Nx project that each service lists as an implicit dependency, so a template change correctly fans out to all services.
Keep each environment's values file inside the service's project directory, not in a central environments/ folder. A central file belongs to no project. A change there either triggers nothing or, if every service declares it as an input, triggers everything.
The trade-offs are real. You get more releases to inspect and more upgrade calls in CI. You also lose atomic changes across services, so each change must stay backward compatible on its own.
There are two alternatives to nx affected:
- Deploy everything on every merge. This is simple and always correct. Unchanged pod specs don't restart, but you still pay pipeline time.
- Use a GitOps-style reconcile. CI commits image tags or rendered manifests to git, and an in-cluster controller applies only the diff. Nx then only decides which images to build.
How do you handle migrations, runtime contracts and deploy-all escape hatches?
The project graph knows that orders-api imports shared-dto. It does not know that billing-worker consumes events orders-api publishes, or that both read the same Postgres schema. Those runtime contracts sit outside the graph, so treat them as rules your team follows.
Migrations and contracts
Run migrations as their own step before the service rollout, for example as a Helm pre-upgrade hook or a separate job. Write them expand-then-contract: add columns first and drop them in a later release. The reason is that an unaffected service still running the old code must keep working against the new schema.
The same logic applies to APIs. When only the producer is affected, its change must accept old consumers, because those consumers will not redeploy.
Drift and escape hatches
Selective deploys leave each environment running a mix of commits. Plan for that and keep a few escape hatches:
- Full reconciliation. Schedule or manually trigger
nx run-many -t deployto bring every service back to one SHA. - Forced single deploy. Run
nx run orders-api:deploywhen a change sits outside the graph, such as a rotated secret. - New cluster. A new cluster has no last-deployed SHA, so fall back to
run-manyinstead of guessing a base.
End-to-end CI flow
- Read the last successfully deployed SHA for the target environment. If it is missing, deploy everything.
- Run
nx affected -t deploy --base=<that SHA> --head=HEAD. - Each deploy target builds its image, runs migrations, then runs
helm upgrade --install. - Record HEAD as the new deployed SHA only if every target succeeded.
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 affected deploy, 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.