How does nx affected decide which services to deploy?
nx affected answers one question: which projects could behave differently between two commits? You pass a base ref and a head ref (--base and --head). Nx diffs them, maps each changed file to the project whose root contains it, and then walks the project graph in reverse. If libs/auth changed, every service that imports it, directly or transitively, joins the affected set even though none of its own files changed. Changes to workspace-level files such as the lockfile can mark many projects affected at once.
In CI, compute that set once at the start of the pipeline and pass it to every later stage. Recomputing it per stage risks each stage seeing a different set if refs move. The full pipeline runs in four steps:
- Resolve base and head, then list the affected services.
- Build and push an image for each one, tagged with the head SHA.
- Deploy each one to each environment in order.
- Record the SHA that each environment now runs.
The choice of base decides whether this stays correct. The merge-base with main is the usual default. It works for pull request checks, but it is risky for deploys. Suppose commit A changes orders, and its pipeline fails or is cancelled before deploying. Commit B then changes only billing. Diffed against A, B's affected set is billing alone, so orders is never released. Nothing reports an error, and the cluster drifts from git.
Using the last successfully deployed SHA for each environment as the base avoids this. The diff spans every commit that has not yet reached that environment, so failed runs are picked up by the next successful one. This is why step 4 is required: the next run's base comes from that record.
+-------------------+ +------------------------------+
| deploy record | | 1. resolve refs |
| env -> last SHA |------->| base = last deployed SHA |
+-------------------+ | head = commit to deploy |
^ +------------------------------+
| |
| v
| +------------------------------+
| | nx affected --base --head |
| | changed files -> projects |
| | + dependents via graph |
| | libs/auth -> orders |
| +------------------------------+
| | affected set, computed once
| v
| +------------------------------+
| | 2. build + push images |
| | tag = head SHA |
| +------------------------------+
| |
| v
| +------------------------------+
| | 3. deploy per environment |
| | helm per project, staged |
| +------------------------------+
| |
| 4. record head SHA per env |
+----------------------------------+
Using the last deployed SHA as the base means changes from failed or cancelled runs are deployed on the next successful run. A merge-base with main would skip them, and the cluster would drift from git.
Who should treat deployment as an Nx target, and when is it the right fit?
The pattern is simple. deploy becomes a project target, just like build or test. It has its own inputs, its own dependsOn chain, and its own executor. Because it is a target, nx affected -t deploy runs it only for projects the project graph marks as changed against that base. Nx needs no deploy-specific logic. The same graph that decides what to rebuild also decides what to release.
This fits platform and backend engineers who run several independently deployable services in one Nx monorepo, where each service ships to Kubernetes as its own Helm release. The word "independently" is the important one. If your services must always roll out together because of lockstep schema changes or tightly coupled APIs, per-project deploys add ceremony without saving anything.
Signals it is worth doing
- Full deploys are slow. Every merge rebuilds images and runs
helm upgradefor services nobody touched. - Rollouts are noisy. Unchanged services restart, pods cycle, and alerts fire for code that did not change.
- Shared libraries have clear dependents. A change to an auth or logging library should redeploy the services that import it, and the graph already knows which ones those are.
The time savings come from three places. Pipelines get shorter because unaffected services skip image builds and Helm upgrades. The blast radius shrinks because a bad change can only reach the services that depend on it. On-call engineers have fewer unrelated rollouts to watch, so when something breaks, the list of suspects is already short.
Defining a deploy target per service with dependsOn and SHA-tagged images
Each deployable service gets a deploy target in its own project.json. The simplest form uses the nx:run-commands executor to call a short shell script that runs helm upgrade --install against that service's chart. A script is easier to test locally and keeps Helm flags out of JSON strings.
Chain the target with dependsOn
Set dependsOn on deploy to the project's own build and container image targets (for example docker-build). Nx then runs them in order within the same invocation. The image you ship comes from the code in this commit, not from an earlier pipeline run that happened to leave an artifact behind. Use plain target names rather than the ^ prefix here. You want this project's image built, not every upstream library "deployed".
Tag images with the commit SHA
Have CI export the commit SHA as an environment variable. The image target uses it as the tag, and the deploy script passes the same value to Helm, for example --set image.tag=$GIT_SHA. Avoid latest. With a mutable tag, Kubernetes may not notice a change, nodes can hold stale copies, and a rollback has no fixed image to return to. A SHA tag lets you redeploy any commit exactly.
Let libraries fall out naturally
When you run nx affected -t deploy, Nx only schedules projects that define a deploy target. Shared libraries change, mark their consumers affected, and are skipped themselves. You don't need any filtering logic.
Never cache deploy
Leave deploy out of cacheable operations, or set cache: false on it explicitly. A cache hit replays stored output and returns success without running the command. For a deploy, that would report a release that never reached the cluster.
{
"name": "orders-api",
"projectType": "application",
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"command": "tsc -p apps/orders-api/tsconfig.app.json"
}
},
"docker-build": {
"executor": "nx:run-commands",
"dependsOn": ["build"],
"cache": false,
"options": {
"command": "docker build -f apps/orders-api/Dockerfile -t registry.example.com/orders-api:$GIT_SHA . && docker push registry.example.com/orders-api:$GIT_SHA"
}
},
"deploy": {
"executor": "nx:run-commands",
"dependsOn": ["build", "docker-build"],
"cache": false,
"options": {
"command": "./apps/orders-api/deploy.sh"
}
}
}
}
A service's project.json where deploy depends on its own build and docker-build targets, the image is tagged with the CI-provided $GIT_SHA, and deploy has cache disabled; deploy.sh runs helm upgrade --install with --set image.tag=$GIT_SHA.
How do you structure Helm releases per project?
Each affected project gets its own Helm release, named after the Nx project, so a single rollout can be inspected, rolled back, or uninstalled without touching any other service. There are two common ways to lay out the charts.
| Layout | Where config lives | Maintenance cost | Blast radius of a chart change |
|---|---|---|---|
| One chart per service | apps/orders/chart/ |
High: N templates drift apart | One service |
| Shared chart built on a library chart, values per service | charts/service/ plus apps/orders/deploy/values.yaml |
Low: fix a template once | Every service that uses it |
In either layout, the deploy command should name everything explicitly. A typical command is helm upgrade --install orders <chart> --namespace orders -f apps/orders/deploy/values.yaml --set image.tag=<sha> --atomic --timeout 5m.
--installmakes the first deploy and later deploys the same command.--atomicimplies--wait. If the pods never become ready, Helm rolls the release back and exits non-zero. That non-zero exit fails the Nx task, so CI goes red instead of reporting a release that never became healthy.- The SHA tag ties the release to the exact image the build target produced.
One chart per service isolates risk, but templates diverge. A security fix to the pod spec then becomes many separate edits that are easy to miss.
A shared chart keeps templates consistent, and small values files are cheap to review. The cost is that one bad template edit reaches every service at once. Section 5 covers how to make that change mark every dependent project affected, so the risk is at least deployed and tested deliberately.
#!/usr/bin/env bash
# tools/deploy.sh - one Helm release per Nx project, shared-chart layout.
# Wired up as each project's "deploy" target, e.g. in apps/orders/project.json:
# "deploy": { "executor": "nx:run-commands",
# "options": { "command": "tools/deploy.sh orders" } }
# CI then runs: npx nx affected -t deploy
set -euo pipefail
PROJECT="$1" # Nx project name, reused as release name and namespace
IMAGE_TAG="${GIT_SHA:?GIT_SHA must be set to the commit the image was built from}"
CHART="charts/service" # shared chart that depends on the library chart
VALUES="apps/${PROJECT}/deploy/values.yaml" # per-service values, reviewed with the service
# Fail early with a clear message instead of deploying chart defaults.
if [[ ! -f "$VALUES" ]]; then
echo "missing $VALUES for project $PROJECT" >&2
exit 1
fi
# Pull the library chart into charts/service/charts/ as declared in Chart.yaml.
helm dependency build "$CHART"
# --install: first deploy and every later deploy use the same command.
# --atomic: implies --wait; if pods never become ready, Helm rolls back and
# exits non-zero, which fails this Nx task and turns CI red.
# image.tag: pins the release to the exact image the build target pushed.
helm upgrade --install "$PROJECT" "$CHART" \
--namespace "$PROJECT" \
--create-namespace \
-f "$VALUES" \
--set image.tag="$IMAGE_TAG" \
--atomic \
--timeout 5m
# Each release can be inspected or rolled back on its own:
# helm history orders -n orders
# helm rollback orders <revision> -n orders
A per-project deploy script, invoked as each project's Nx deploy target, that installs or upgrades one Helm release per project from the shared chart, uses the service's own values file and image SHA, and relies on --atomic so a failed rollout exits non-zero and fails the Nx task.
How do you make Helm values, Dockerfiles and shared charts mark a service affected?
Nx decides that a project is affected by file ownership. A changed file belongs to the project whose root contains it. Keep each service's Dockerfile, chart/ directory and per-environment values files inside that project's root. A values-only edit then marks the service affected with no extra configuration. If a values file lives in a central deploy/ folder, Nx cannot link it to any service, and the change does not trigger a release.
namedInputs and per-target inputs handle a separate problem: cache hashing. Define a named input such as deployInputs that includes {projectRoot}/chart/**/*, the values files and the Dockerfile, and use it in the image-build target's inputs. Without it, a chart or Dockerfile edit can reuse a cached image or tag even though the project shows as affected. The deploy target itself should not be cacheable, because a cached deploy is a skipped deploy.
Some dependencies the project graph cannot infer from imports, such as a shared Helm library chart or a common base image. Give each of these its own Nx project with its own project.json, then list it in every consuming service's implicitDependencies. A template change in the library chart then marks every dependent service affected, which is the behavior the previous section relied on.
Root-level files work in the opposite direction. Lockfiles, sharedGlobals-style global inputs and CI pipeline scripts can make every project affected, or invalidate every hash. Excluding them with negation patterns cuts down on noisy full releases. Exclude too much, though, and a base-image bump or a lockfile security fix will merge without deploying anything. Exclude only files you can show have no effect on runtime artifacts.
// apps/orders-api/project.json (Nx accepts comments in project.json)
{
"name": "orders-api",
// Shared chart and base image are separate Nx projects the graph cannot infer
"implicitDependencies": ["helm-lib-chart", "base-image"],
"namedInputs": {
// Everything that shapes the image or the release, all under the project root
"deployInputs": [
"{projectRoot}/Dockerfile",
"{projectRoot}/chart/**/*"
]
},
"targets": {
"docker-build": {
"executor": "nx:run-commands",
// Chart or Dockerfile edits change the hash, so no stale cache hit
"inputs": ["production", "deployInputs", "^production"],
"cache": true,
"options": {
"command": "docker build -t registry.example.com/orders-api:{args.tag} apps/orders-api"
}
},
"deploy": {
"executor": "nx:run-commands",
"dependsOn": ["docker-build"],
// A cached deploy is a skipped deploy
"cache": false,
"options": {
"command": "helm upgrade --install orders-api apps/orders-api/chart -f apps/orders-api/chart/values-{args.env}.yaml --set image.tag={args.tag}"
}
}
}
}
A service project.json that keeps chart and Dockerfile in the project root, hashes them via a named input, links shared charts and base images with implicitDependencies, and disables caching on deploy.
When should you avoid relying on nx affected for deploys?
The project graph only knows about imports and declared implicitDependencies. It has no view of what happens at runtime, and that gap is where affected-only deploys go wrong.
Runtime coupling is invisible
If orders calls billing over HTTP, no graph edge connects them. Suppose you rename a field in billing's response. Only billing is affected, so it deploys alone, and orders starts failing in production even though nothing in its project changed. The same applies to message schemas on a queue and shared database tables. You can reduce the risk in three ways:
- Run consumer-driven contract tests so a breaking change fails CI before deploy.
- Make API changes backward compatible: add the new field, migrate consumers, then remove the old one in a later release.
- Treat schema migrations as an explicitly ordered step that runs before any dependent service rolls out, instead of letting them race.
Set --parallel for the deploy run separately from the build run. Builds are safe to fan out. Concurrent rollouts against one cluster can exhaust capacity or make a failing release hard to isolate.
Infrastructure drift doesn't trigger anything
Several changes never touch a project file, so they never mark anything affected: a cluster upgrade, a Secret or ConfigMap edited outside the repo, or a patched base image published for a CVE. Each one needs its own scheduled or manual redeploy path.
Mixed versions complicate operations
After a few partial deploys, every service runs a different SHA. "What's in production?" no longer has a one-line answer, and a rollback has to happen per service, each to its own previous revision.
What are the alternatives, escape hatches and verification steps?
Three delivery models fit an Nx monorepo, and you can move between them without changing how projects are defined.
| Model | Who talks to the cluster | Strength | Cost |
|---|---|---|---|
Push: affected helm upgrade from CI |
CI, with cluster credentials | Simple, fast feedback | Credentials live in CI; drift goes unnoticed |
| Pull: affected writes per-service image tags to git, a controller reconciles | The in-cluster controller | Git history is the deploy log; drift is corrected | Extra repo, controller and tooling to run |
| Deploy everything on every merge | CI | Production always matches one commit | Longest pipeline; SHA tags restart every pod |
Keep two escape hatches in the pipeline as manual jobs. Use nx run-many -t deploy for cluster rebuilds, drift and secret rotation, because a rotated secret changes nothing in git, so affected never selects the services that consume it. Use nx run <project>:deploy for targeted fixes and rollbacks, run from an older commit or with a pinned tag. A scheduled full deploy, nightly or weekly, puts a ceiling on how far any service can lag behind main.
For review, have the PR job post the output of nx show projects --affected and render each listed chart with helm template, so reviewers can see which services ship and what their manifests become.
The trade-off is development cost. You save pipeline minutes and avoid restarting services that didn't change. In exchange, you maintain implicit dependency configuration, one Helm release per service, and either CI credentials or a GitOps controller.
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 deploy affected services, 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.