How does nx affected decide which services to deploy?

Selective deployment means your CI pipeline builds and releases only the services whose code, or whose dependencies' code, changed in a given commit range. Everything else stays on its currently deployed version. This matters most for backend and platform teams running several deployable services in one monorepo. Redeploying every service on every merge wastes CI minutes, widens the blast radius of each release, and makes it harder to tell which change caused a regression.

Nx works out what changed in three steps:

  1. Diff files. Nx asks git for the files that differ between a base ref and a head ref. By default it uses the base branch configured in your workspace and the current working tree. You can override both with --base and --head.
  2. Map files to projects. Each changed file is assigned to the project whose root contains it. Workspace-level files such as the root package.json or the lockfile get special handling. Nx tries to work out which projects depend on the specific packages that changed, rather than marking everything affected.
  3. Walk the project graph. Starting from the directly changed projects, Nx follows dependency edges in reverse to find every project that imports them. A change to a shared auth library therefore pulls in every service that depends on it.

The third step is why the graph's accuracy decides whether selective deployment is safe. Before wiring up any deploy job, inspect the graph:

  • Run nx graph to view the dependency graph and confirm the edges match what your services actually import.
  • Run nx graph --affected to highlight what a given diff touches.
  • Run nx show projects --affected to print the affected list as plain names.
  • Add --type app to nx show projects --affected to narrow that list to deployable applications.
#!/usr/bin/env bash
# Preview what Nx would deploy for a commit range, before any deploy job exists.
set -euo pipefail

BASE="origin/main"   # last known-good ref, e.g. the main branch tip
HEAD_REF="HEAD"      # the commit CI is building

# Make sure the base ref exists locally (CI checkouts are often shallow).
git fetch --no-tags origin main

# Step 1: the raw file diff. Nx compares against the merge base,
# which is what the three-dot syntax shows here.
echo "Changed files:"
git diff --name-only "${BASE}...${HEAD_REF}"

# Steps 2 and 3: Nx maps those files to projects, then walks the graph
# in reverse to add every dependent project.
echo "All affected projects:"
npx nx show projects --affected --base="${BASE}" --head="${HEAD_REF}"

# Narrow the list to deployable applications only, skipping libraries.
echo "Affected apps (deploy candidates):"
npx nx show projects --affected --type app \
  --base="${BASE}" --head="${HEAD_REF}"

# Optional, run locally: open the graph with the affected set highlighted
# to confirm the edges match what each service really imports.
# npx nx graph --affected --base="${BASE}" --head="${HEAD_REF}"

A dry-run script that shows the git diff Nx starts from, the full affected project list, and the affected apps that would be deployed, so you can check the graph before wiring up deployment.

How do you add a deploy target so only apps get deployed?

…applications only, which is the starting point for deciding what to ship.

Put the target on apps, never on libraries

nx affected -t deploy runs the deploy target on every affected project that defines one and skips the rest without error. That means where you define the target is where you define what gets deployed. Add deploy to each deployable application's project.json, or under the nx.targets key in its package.json. Leave it off libraries. A changed library still counts as affected, but because it has no deploy target it can't be deployed. Its consuming apps are affected through the graph, and those are what ship.

On the deploy target, set dependsOn to include the app's own build, so Nx never deploys a stale or missing artifact. If the build needs dependency libraries built first, the app's build target should depend on ^build. Then the order holds without anyone running steps manually.

Separate "what" from "how"

Don't put registry credentials, rollout strategy, and environment promotion inside the Nx target. Use Nx to answer one question: which services changed? Run nx show projects --affected --type app --json, save the array as a job output, and use it to drive a CI matrix with one job per service.

This split has three benefits:

  • Each service gets its own logs, retries, approvals, and secrets scope.
  • A failed rollout for one service doesn't block the others.
  • Deployment tooling can change without touching the project graph.

In this setup, the deploy target stays thin. It can wrap a script, or exist only to mark a project as deployable.

name: deploy
on:
  push:
    branches: [main]

jobs:
  # Nx answers one question: which deployable apps changed?
  affected:
    runs-on: ubuntu-latest
    outputs:
      projects: ${{ steps.list.outputs.projects }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # full history so Nx can diff base..head
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      # Apps only, and only those that define a deploy target. Prints a JSON array.
      # HEAD~1 keeps the example simple. Prefer the SHA of the last successful deploy.
      - id: list
        run: echo "projects=$(npx nx show projects --affected --type app --withTarget deploy --base=HEAD~1 --head=HEAD --json)" >> "$GITHUB_OUTPUT"

  # CI owns the rollout: one job per service, each with its own logs, retries and secrets.
  deploy:
    needs: affected
    if: needs.affected.outputs.projects != '[]'  # skip when nothing deployable changed
    strategy:
      fail-fast: false  # one failed rollout does not cancel the others
      matrix:
        project: ${{ fromJSON(needs.affected.outputs.projects) }}
    runs-on: ubuntu-latest
    environment: production  # approvals and secrets scoped here, not in Nx
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      # Thin target: dependsOn ["build"] makes Nx build the app first, then run its deploy script.
      - run: npx nx run ${{ matrix.project }}:deploy

A GitHub Actions workflow in which Nx outputs the affected apps that define a deploy target as a JSON array, and that array drives a matrix with one independent deploy job per service.

Which base commit should nx affected deploy compare against?

Most broken selective deployments come from the wrong --base. The affected set is computed from the diff between --base and --head, so the base determines which changes get deployed and which ones are silently skipped.

On a pull request, the base is the merge-base of the PR branch and its target branch. The diff then covers only the PR's own commits, not unrelated work that landed on the target branch after the PR branched off.

On main, the base should be the last commit that deployed successfully. HEAD~1 only works if every pipeline runs and succeeds. If a run fails, gets cancelled, or several merges are batched into one run, the next HEAD~1 diff misses those earlier changes and they never ship. You can record the last good commit by moving a git tag after a successful deploy, or by asking your CI system for the SHA of the last green run on main.

The diff also needs the base commit to exist locally. Shallow clones often don't include it, and Nx then either fails or falls back to deploying everything. Configure the checkout to fetch full history, or at least enough depth to reach the marker, and fetch tags explicitly.

Concurrent merges create a race on the marker. If two pipelines read the same base and the older one writes the marker last, the marker moves backwards. To prevent this, run main pipelines one at a time, or keep a separate marker for each service.

Base strategy Use case Failure mode
HEAD~1 Never on main Drops changes from failed, cancelled, or batched runs
Merge-base with target Pull requests Fails on shallow clones
Last-deployed git tag Main, serialized Concurrent runs can move the tag backwards
CI's last successful run Main Depends on the CI API, and history must reach that SHA
Per-service markers Main, parallel deploys More state to manage, and a failed service has to catch up on its own
#!/usr/bin/env bash
# Main-branch deploy: diff against the last successfully deployed commit, not HEAD~1.
set -euo pipefail

MARKER="deployed/main"   # git tag that records the last good deploy

# Shallow clones may not contain the marker commit, so fetch full history and tags.
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
  git fetch --unshallow origin
fi
git fetch --force --tags origin

# Resolve the base. Fail loudly instead of guessing, which could skip changes.
if ! BASE=$(git rev-parse --verify --quiet "refs/tags/${MARKER}^{commit}"); then
  echo "Marker ${MARKER} not found; bootstrap it before using affected deploys." >&2
  exit 1
fi
HEAD_SHA=$(git rev-parse HEAD)

# The marker must be an ancestor of HEAD. Otherwise it was moved by a newer run
# or points at rewritten history, and the diff cannot be trusted.
if ! git merge-base --is-ancestor "$BASE" "$HEAD_SHA"; then
  echo "Marker ${BASE} is not an ancestor of ${HEAD_SHA}; refusing to deploy." >&2
  exit 1
fi

# Deploy every project affected since the last good deploy, including batched or
# previously failed commits.
npx nx affected -t deploy --base="$BASE" --head="$HEAD_SHA"

# Move the marker only after success. --force-with-lease rejects the push if
# another pipeline moved the tag since we read it, so it cannot move backwards.
# Serializing main pipelines is still the primary guard.
git tag -f "$MARKER" "$HEAD_SHA"
git push origin "refs/tags/${MARKER}" \
  --force-with-lease="refs/tags/${MARKER}:${BASE}"

A main-branch CI script that unshallows the clone, uses a last-deployed git tag as the Nx base, and moves that tag only after a successful deploy, with a lease check that stops a stale run from moving the marker backwards.

How do you make the project graph reflect real dependencies?

Nx builds the graph from source imports and file ownership. A changed file marks the project whose root contains it as affected, and that change then propagates to its dependents. Anything outside that model is invisible, so you have to describe it explicitly.

Files Nx can't attribute

  • Files inside a service's folder. Put each service's Dockerfile, Helm chart, env templates and generated clients under its project root. They are then owned automatically, and editing them marks that service affected.
  • Shared files outside any project. Shared Terraform modules or a common base image fit here. Wrap them in a small project of their own, then list it in implicitDependencies for every service that consumes it.
  • Lockfile changes. Nx analyses these per package, so only projects that use a bumped dependency should be affected. Verify this in your setup instead of assuming it.
  • Root configuration. Some root files mark everything affected when they change. Edit each root file on a scratch branch and check what Nx reports before trusting a pipeline.

namedInputs and target inputs serve a different purpose. They define what goes into a task's cache hash. If a Dockerfile or env file is missing from the deploy target's inputs, Nx can restore a cached result after that file changes. Affected detection can be correct while the deployed artifact is stale.

Runtime coupling

Services that talk over HTTP, queues or a shared database schema without importing each other have no edge in the graph. You can create one in three ways:

  • Declare it. Add an explicit implicitDependencies entry from consumer to producer.
  • Model the contract. Make contract tests their own project, depending on both sides, so a change to either runs them.
  • Share a library. Move the schema or message types into a library that both services import, which creates a real graph edge.

A missing edge or input fails silently. CI goes green, nothing is deployed, and the cache adds a matching success record. The team gets more confident at the moment the pipeline is wrong.

{
  "name": "orders-service",
  "root": "apps/orders-service",
  "implicitDependencies": ["infra-terraform-shared", "billing-api", "orders-contract-tests"],
  "targets": {
    "docker-build": {
      "executor": "nx:run-commands",
      "cache": true,
      "inputs": [
        "production",
        "^production",
        "{projectRoot}/Dockerfile",
        "{projectRoot}/.env.template",
        "{projectRoot}/src/generated/**/*",
        "{workspaceRoot}/docker/base.Dockerfile",
        { "env": "DEPLOY_ENV" }
      ],
      "outputs": ["{workspaceRoot}/dist/images/orders-service.txt"],
      "options": {
        "command": "docker build -f apps/orders-service/Dockerfile -t registry.example.com/orders-service:$GIT_SHA . && mkdir -p dist/images && echo $GIT_SHA > dist/images/orders-service.txt"
      }
    },
    "deploy": {
      "executor": "nx:run-commands",
      "cache": false,
      "dependsOn": ["docker-build"],
      "options": {
        "command": "helm upgrade --install orders-service apps/orders-service/chart --set image.tag=$GIT_SHA"
      }
    }
  }
}

A service project.json that declares runtime and infra edges via implicitDependencies and lists the Dockerfile, env template, generated code, shared base image and DEPLOY_ENV in the build inputs so a change to any of them invalidates the cache.

A complete CI pipeline for selective deployment

The pipeline below guards against that failure by making every decision visible and leaving a way to override it. The pseudo-YAML is not tied to any CI product. Map each step onto whatever runner you use.

The stages

  1. Checkout with enough history. A shallow clone often lacks the base commit, so the comparison either fails or quietly falls back to something you did not intend. Fetch full history, or at least deep enough to reach the last recorded deploy.
  2. Compute base and head. Resolve both to explicit SHAs and pass them as --base and --head. Do not rely on branch names, which can move while the job runs.
  3. Log the affected set. Print the base SHA, the head SHA, and the output of nx show projects --affected on every run, including pull requests. When a service fails to ship, this log shows whether the graph left it out or the deploy step failed.
  4. Run nx affected -t lint test build on every branch.
  5. Deploy only on main. Run nx affected -t deploy with a low --parallel value. Shared resources such as cloud API rate limits, database migrations and registry pushes handle a few concurrent deploys better than twenty.
  6. Record deployed commits. After each service deploys successfully, store its SHA, for example as a per-service git tag. That record becomes the next base for that service.

Escape hatches

Add a manually triggered job that runs nx run-many -t deploy, either for every project or for a named list passed with --projects. Also schedule a full redeploy, such as weekly. The scheduled run catches config drift, expired credentials and graph edges that affected never knew about.

How much engineering time does nx affected deploy save?

The saving comes from deploy work you no longer do on every merge. It is easy to estimate, and it depends heavily on the shape of your graph.

Illustrative estimate (assumed numbers, not a benchmark)

  • Assumed: 20 deployable services, 6 minutes per service deploy, 3 services affected per merge on average.
  • Full deploy: 20 × 6 = about 120 minutes of deploy work per merge.
  • Affected deploy: 3 × 6 = about 18 minutes per merge.
  • Formula: saved minutes per merge = (total services − affected services) × minutes per deploy.

These figures are runner time before parallelism. If you already deploy across several parallel agents, wall-clock time improves less, but compute cost and deploy risk still drop. Multiply by merges per day to get a daily figure for your own repo.

The average hides the distribution. A change to a shared core library, such as auth, logging or a database client, marks every dependent service as affected. If many merges touch such libraries, your real affected count moves toward 20 and the saving shrinks. Check the distribution of affected counts over recent merges before you assume the average holds.

Selective deployment also adds costs:

  • Deployment records: you need a record of which commit each service is running, because the services are no longer all on the same commit.
  • Rollbacks: a rollback now targets specific services, and you have to work out which ones shipped together.
  • Logging: CI output should list the affected projects and the base commit used to compute them.
  • Documentation and onboarding: engineers will ask "why didn't my service deploy?" Write a short runbook that explains the graph, the base commit and how to force a deploy.

When should you avoid selective deployment, and what are the alternatives?

Selective deployment assumes each service can go live on its own schedule without breaking its neighbours. If that is false, nx affected deploy hides the problem until production.

Avoid it when:

  • Services are tightly coupled at runtime. If service A cannot start or serve traffic unless service B is on a matching build, deploying only A creates a broken pair.
  • APIs and migrations are not backward compatible. With independent deploys, version skew is the normal state and there is no single moment when everything switches over. Every contract change needs expand-and-contract migrations and tolerant readers. Without them, partial deploys fail.
  • The graph is heavily shared. When most apps depend on one core library, nearly every commit marks nearly every app as affected. You keep the complexity and gain little speed.
  • Nobody maintains inputs. Stale implicitDependencies or missing file inputs mean real changes go unshipped, and nothing flags it.

Alternatives

Approach Safety Speed Maintenance effort
Deploy everything on every merge High; all services always run the same commit Slow; cost grows with service count Low
Path-based CI triggers Medium; misses transitive dependencies Fast Medium; path lists drift from the code
Per-service repositories Medium; dependencies become versioned packages Fast per service High; cross-repo changes need coordination
Manual or release-train deployment High for coupled systems; one atomic, reviewed release Slow; changes wait for the next train Medium; needs release ownership

If coupling is the real problem, start with deploy-everything or a release train. Move to selective deployment once your contracts can tolerate version skew.

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.