What is an Nx database migration target and why model migrations per service?

An Nx database migration target is an ordinary Nx task, defined on a single service project, that wraps a migration CLI such as Prisma Migrate. It declares explicit inputs: the service's schema file and its migrations directory. Nx then treats "this service's database changed" as something it can reason about. It can tell when the target's inputs changed, which projects are affected, and whether a cached result is still valid.

The model only works when ownership is settled first. Each service project owns exactly one schema file and one migrations directory, and that service is the only project that writes migrations against its database. Nx's affected logic works on project boundaries. If a change to orders/prisma/migrations marks orders as affected, that is correct only if no other project's state depends on the same tables.

Shared-database layouts break this. Suppose two services write migrations against one database. A migration in service A can conflict with schema assumptions in service B, but Nx sees no change in B's inputs and leaves B out of the affected set. You can wire up implicit dependencies to compensate, but at that point the project graph no longer describes the system honestly, and the per-project checks give false confidence.

The pattern fits multi-service monorepos that already run database-per-service, or are moving toward it. In those repositories, per-service targets let pull request CI validate only the schemas that changed, and each service's migration history stays reviewable on its own.

 PER-SERVICE OWNERSHIP (affected logic holds)

 +---------------------------+      +---------------------------+
 | project: orders           |      | project: billing          |
 |  target: migrate          |      |  target: migrate          |
 |  inputs:                  |      |  inputs:                  |
 |   prisma/schema.prisma    |      |   prisma/schema.prisma    |
 |   prisma/migrations/**    |      |   prisma/migrations/**    |
 +-------------+-------------+      +-------------+-------------+
               |                                  |
               v                                  v
        +-------------+                    +-------------+
        | orders DB   |                    | billing DB  |
        +-------------+                    +-------------+

 change in orders/prisma/migrations --> affected: orders only (correct)

 SHARED DATABASE (affected logic breaks)

 +-------------------+          +-------------------+
 | project: svc-a    |          | project: svc-b    |
 |  writes migration |          |  inputs unchanged |
 +---------+---------+          +---------+---------+
           |                              |
           +-------------+  +-------------+
                         |  |
                         v  v
                  +---------------+
                  |  shared DB    |
                  +---------------+

 change in svc-a migrations --> affected: svc-a only
 svc-b depends on the same tables, but is never re-checked

With one owning project per database, a migration change maps to exactly one affected project; when two projects share a database, a migration in one can break the other while Nx leaves it out of the affected set.

How do you define migrate-check and migrate-deploy targets with Prisma in Nx?

Each service project gets its own targets, all built on the nx:run-commands executor and each passing an explicit --schema path, such as apps/orders/prisma/schema.prisma. The explicit path matters because Prisma's default schema discovery is relative to the working directory. In a monorepo, relying on it means a target can silently pick up the wrong service's schema.

The three migration commands

  • migrate-check runs prisma validate and then prisma migrate diff. The diff compares the service's migrations directory against its schema file, using --exit-code so the command fails when they differ. A failure means someone edited the schema without generating a migration. Diffing from the migrations directory needs a shadow database, so give this target a throwaway database URL, never a real one.
  • migrate-deploy wraps prisma migrate deploy. It applies pending migrations in order and never generates new ones, which makes it the only migration command that belongs in a pipeline.
  • prisma migrate dev stays a local-only target. It can create migrations and may prompt to reset the database, so it should never run in CI.

Ordering with dependsOn

Use dependsOn to make the ordering explicit:

  • build depends on a prisma-generate target, so the typed client always matches the schema being compiled.
  • test depends on migrate-check, so a drifted schema fails fast instead of surfacing later as confusing test errors.

Integration tests

Integration tests should run against an ephemeral database: a container started per CI job, with migrate-deploy applied before the suite runs. A shared test database collects state from other branches and parallel jobs, and that hides exactly the migration-ordering bugs these tests exist to catch.

{
  "name": "orders",
  "targets": {
    "prisma-generate": {
      "executor": "nx:run-commands",
      "options": { "command": "prisma generate --schema=apps/orders/prisma/schema.prisma" }
    },
    "migrate-check": {
      "executor": "nx:run-commands",
      "options": {
        "commands": [
          "prisma validate --schema=apps/orders/prisma/schema.prisma",
          "prisma migrate diff --from-migrations apps/orders/prisma/migrations --to-schema-datamodel apps/orders/prisma/schema.prisma --shadow-database-url \"$SHADOW_DATABASE_URL\" --exit-code"
        ],
        "parallel": false
      }
    },
    "migrate-deploy": {
      "executor": "nx:run-commands",
      "options": { "command": "prisma migrate deploy --schema=apps/orders/prisma/schema.prisma" }
    },
    "migrate-dev": {
      "executor": "nx:run-commands",
      "options": { "command": "prisma migrate dev --schema=apps/orders/prisma/schema.prisma" }
    },
    "build": {
      "dependsOn": ["prisma-generate"]
    },
    "test": {
      "dependsOn": ["migrate-check"]
    },
    "integration-test": {
      "executor": "nx:run-commands",
      "dependsOn": ["migrate-deploy"],
      "options": { "command": "jest --config apps/orders/jest.integration.config.ts" }
    }
  }
}

An orders service project.json where every Prisma command passes an explicit --schema path. migrate-check validates and diffs against a throwaway shadow database, and integration tests run only after migrate-deploy has migrated an ephemeral database.

How should inputs and caching be configured for migration targets?

A target's inputs decide two things: when nx affected considers the project touched, and what Nx hashes for the cache key. For a migration target, the inputs should be the Prisma schema file, the migrations folder, and any configuration that changes how migrations resolve, such as the environment variable naming the database provider or the shadow database. Define these once as a named input, for example migrations, using project-relative patterns like {projectRoot}/prisma/**/*. Then reference that named input from migrate-check and migrate-deploy.

Getting the scope wrong fails in one of two ways. If the inputs are too broad, such as the default that covers every file in the project, a change to a controller or test file marks the migration target as affected. CI then spends time on database work that cannot have changed, and engineers learn to ignore the results. If the inputs are too narrow, such as the schema file alone, a hand-edited SQL migration or a renamed migration folder never triggers a check. That miss is silent, and it is worse than the wasted CI time.

Caching is a separate decision. A cache hit replays stored output and skips the command. For validation, skipping is correct because identical inputs produce an identical result. For migrate-deploy, a cache hit means the database was never touched, even though the target reports success. Set cache: false on every target that mutates a database.

Target type Mutates a database? Cacheable
Schema validate / format check No Yes
Lint of migration SQL No Yes
Prisma client generation No Yes
migrate-check against an ephemeral database Creates and discards one Only if the database is fully disposable
migrate-deploy Yes No (cache: false)
Seed or reset Yes No (cache: false)
{
  "name": "orders-service",
  "namedInputs": {
    // Only schema, migration SQL and resolution-affecting env vars count
    "migrations": [
      "{projectRoot}/prisma/**/*",
      { "env": "DATABASE_PROVIDER" }
    ]
  },
  "targets": {
    "schema-validate": {
      "executor": "nx:run-commands",
      "inputs": ["migrations"],
      "cache": true,
      "options": { "command": "prisma validate", "cwd": "{projectRoot}" }
    },
    "prisma-generate": {
      "executor": "nx:run-commands",
      "inputs": ["migrations"],
      "outputs": ["{projectRoot}/src/generated/prisma"],
      "cache": true,
      "options": { "command": "prisma generate", "cwd": "{projectRoot}" }
    },
    "migrate-check": {
      "executor": "nx:run-commands",
      "inputs": ["migrations"],
      // Touches a shadow database; keep uncached unless it is fully disposable
      "cache": false,
      "options": { "command": "prisma migrate diff --from-migrations prisma/migrations --to-schema-datamodel prisma/schema.prisma --shadow-database-url \"$SHADOW_DATABASE_URL\" --exit-code", "cwd": "{projectRoot}" }
    },
    "migrate-deploy": {
      "executor": "nx:run-commands",
      "inputs": ["migrations"],
      // Mutates a real database: a cache hit would report success and skip the work
      "cache": false,
      "options": { "command": "prisma migrate deploy", "cwd": "{projectRoot}" }
    }
  }
}

A project.json (Nx accepts comments in it) that defines a shared 'migrations' named input scoped to the prisma folder and one env var, caches the pure validation and generation targets, and sets cache: false on the targets that touch a database.

How does nx affected -t migrate-check work in pull request CI?

On a pull request, the comparison base should be the merge-base with the target branch, not the tip of main. nx affected passes --base and --head to git and computes the merge-base itself, so a PR that hasn't been rebased is still compared against the commit it branched from. You can also set the NX_BASE and NX_HEAD environment variables instead of passing flags.

Git history and shallow clones

That merge-base calculation only works if the commit actually exists locally. Many CI checkouts default to a shallow clone, so git cannot find the base and the affected calculation either fails or quietly falls back to a wider comparison. Fetch full history, or at least enough to include the target branch, before running affected commands.

If your pipeline compares against the "last successful run" rather than the target branch, two cases can leave that SHA missing:

  • First run: there is no previous successful run yet.
  • After a force-push: the previous SHA was rewritten and no longer exists.

For migration checks, the safe fallback in both cases is to run every migrate-check target. Running too few would let a broken migration through.

Reading the graph and limiting parallelism

A change to a shared data library can mark a dozen services affected. Before the jobs run, list them with nx show projects --affected or inspect them with nx graph --affected, so a surprising fan-out is visible up front.

Each check gets its own throwaway database, so cap concurrency with --parallel to stay below the database server's connection limit.

Cost

Ephemeral databases are not free. Every affected service pays for provisioning time and compute on every PR. That cost is the reason to keep affected detection accurate rather than running every check on every pull request.

#!/usr/bin/env bash
# PR job: run migrate-check only for affected services, each against its own throwaway DB.
set -euo pipefail

TARGET_BRANCH="${TARGET_BRANCH:-main}"
MAX_DBS=3   # stay well below the DB server's connection limit

# Shallow checkouts hide the merge-base, so fetch full history first.
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
  git fetch --unshallow --no-tags origin
fi
git fetch --no-tags origin "$TARGET_BRANCH"

# Prefer the last successful SHA if the pipeline provides one, otherwise the target branch.
BASE="${LAST_SUCCESS_SHA:-origin/$TARGET_BRANCH}"
export NX_HEAD="$(git rev-parse HEAD)"

# First run or force-push: the base SHA may not exist. Fail safe by checking everything.
if ! git cat-file -e "${BASE}^{commit}" 2>/dev/null; then
  echo "Base '$BASE' not found; running migrate-check for all projects"
  npx nx run-many -t migrate-check --parallel="$MAX_DBS"
  exit 0
fi
export NX_BASE="$BASE"   # nx computes the merge-base with HEAD itself

# Show the fan-out up front, e.g. when a shared data library touches many services.
echo "Affected projects with a migrate-check target:"
npx nx show projects --affected --with-target migrate-check

# Each check provisions its own ephemeral DB, so --parallel caps concurrent databases.
npx nx affected -t migrate-check --parallel="$MAX_DBS"

A CI script that fetches enough git history, resolves the base SHA, falls back to checking every project when that SHA is missing, lists the affected migration targets, and caps parallel runs so the ephemeral databases stay under the connection limit.

Why shouldn't nx affected decide which migrations to apply at deploy time?

Accurate affected detection is useful in pull requests because the cost of a wrong answer is small: a missed check means one PR gets less coverage. At deploy time, a wrong answer leaves a database schema out of step with the code running against it.

nx affected compares two git commits and walks the project graph. It knows what changed between --base and --head. It has no knowledge of what any database has already applied. "Unaffected" means "no relevant files changed in this diff," not "this environment is up to date." Several ordinary situations break the assumption that the two are the same:

  • Wrong base SHA. A deploy fails after the build but before migrations run. If the next deploy uses the failed commit as its base, the migration from that commit is outside the diff and never runs.
  • Shallow clones. CI checkouts with limited history may not contain the base commit. Depending on how the pipeline handles that, the comparison fails or falls back to a base that hides changes.
  • Reverts and squashes. A range containing a commit and its revert can show no net change, even if an environment received the original commit in an earlier deploy.

The safer approach is to run the idempotent apply command, such as prisma migrate deploy, for every service being deployed. It reads the migration history table, applies only pending migrations, and does nothing if none are pending. If you need to skip services to save time, record the last successfully migrated commit per environment and diff from that commit, not from the previous pipeline run. In both cases, the history table remains the source of truth.

Keeping the two decisions separate saves debugging time. When a schema drifts, you check one table per database and compare it to the migrations directory. You do not have to reconstruct which CI run computed which diff from which base.

How do you run migrations safely once per environment and across services?

Run migrate-deploy exactly once per environment per release, as a dedicated CI job or pre-deploy step that must succeed before new application replicas roll out. Avoid running migrations in every replica at startup. With ten pods starting together, ten processes race for the same _prisma_migrations table. A slow migration can also fail health checks and trigger restarts mid-change. Prisma Migrate takes a database advisory lock on some databases, but treat that as a backstop. Add pipeline-level concurrency control so that only one deploy per environment can run at a time.

Where the job runs

You can run the migration job from CI or from inside the cluster:

  • From a CI runner. This is simple, but the runner then needs production database credentials and network access. That widens the blast radius of a compromised pipeline.
  • As an in-cluster job before rollout. The job uses the same secrets and network policy as the service, so credentials never leave the environment. The cost is more orchestration and harder log access.

Pick one approach deliberately and scope the migration role's privileges to DDL on that service's schema.

Ordering across services

Nx dependsOn orders tasks inside a single run. It says nothing about release order across separate databases and deploys. Do not rely on the task graph to coordinate them. Use expand/contract instead:

  1. Add new columns or tables in one release.
  2. Deploy code that writes both shapes.
  3. Backfill existing data.
  4. Remove the old shape in a later release.

At every step, the schema must stay compatible with the code that is already running.

Destructive and long-running changes

Drops, type changes and large backfills still need manual review and a phased rollout. They also need a written rollback plan. Prisma does not generate down migrations automatically, so rolling back usually means writing a new forward migration or restoring from backup.

When should you avoid per-service migration targets, and what are the alternatives?

Per-service targets pay off only when each service owns a separate schema or database. If several services write to one shared database, splitting migrations by project creates ordering problems. Migration B in one project may depend on a column added by migration A in another, and Nx has no way to know that. A small team that touches every service in most pull requests gains little from affected filtering, because nearly everything is affected anyway. The same applies if you cannot cheaply provision ephemeral databases for CI. Without a throwaway database to apply against, migrate-check degrades into a syntax check.

Approach Development cost Time saved Fits when
Per-service affected targets Per-project config, apply steps that cannot be cached, more pipeline logic Faster PR feedback, fewer wasted runs, clear ownership Many services, each owning its own database
One central migration project One schema folder and one target, with ownership enforced by code review Little; every schema change runs one check Shared database, or teams that want strict ordering
Migrations on app startup Almost none upfront No separate deploy step A single replica in a low-risk environment; it races or slows startup once you scale out
Run all migrations on every pipeline No affected logic to maintain None, but the cost stays predictable Few services and fast checks

A reasonable path is to start with one central project or a run-everything pipeline. Move to per-service targets once total CI time spent on unchanged schemas becomes noticeable and service boundaries match database boundaries.

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 database migration target, 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.