How does nx run-many -t serve start multiple backend services?

nx run-many runs one or more targets across a set of projects in a single invocation. The baseline command nx run-many -t serve -p api-gateway orders-service users-service asks Nx to run the serve target for three named projects. Nx takes each selected project and each requested target, builds a task graph from those pairs, and schedules the tasks. Without run-many, you would open three terminals and run nx serve in each.

The two flags control different things:

  • -t / --targets chooses what to run. You can pass more than one target, such as -t lint test. A selected project that does not define the target is skipped, not treated as an error.
  • -p / --projects chooses where to run it. If you omit it, Nx runs the target in every project that defines it. In a mixed workspace, that usually includes frontend dev servers you don't want.

Listing project names works, but someone has to update the command every time a service is added. Two selectors remove that step. A tag selector such as -p tag:type:service matches every project whose tags array includes that value. A name pattern such as -p '*-service' matches by naming convention. Quote the pattern so your shell doesn't expand it. You can also exclude projects with --exclude. Tags are usually the more reliable choice because they record intent rather than depending on how a project happens to be named.

This approach suits backend and platform engineers who keep several services in one Nx workspace and want a single command to bring up their local environment.

# Baseline: run the serve target for three named projects in one invocation.
# Nx builds a task graph from (project, target) pairs and schedules them.
npx nx run-many -t serve -p api-gateway orders-service users-service

# Select by tag. This matches every project whose project.json contains:
#   "tags": ["type:service"]
# A new service is included as soon as it carries the tag. No command edit needed.
npx nx run-many -t serve -p tag:type:service

# Select by naming convention. Quote the glob so the shell doesn't expand it.
npx nx run-many -t serve -p '*-service'

# Combine a selector with --exclude to skip a service you don't need right now.
npx nx run-many -t serve -p tag:type:service --exclude=users-service

# serve tasks are long-running, and run-many runs 3 tasks at a time by default.
# A fourth service would wait for a slot that never frees up. Raise the limit
# so it is at least the number of services you start.
npx nx run-many -t serve -p tag:type:service --parallel=6

Ways to start several backend services with nx run-many: by explicit project list, by tag, by name pattern and with exclusions, plus raising --parallel so every long-running serve task gets a slot.

Why does --parallel matter when serving many services?

Every serve target starts a process that is designed to keep running. It binds a port, watches files, and waits for requests. From the task runner's point of view, that task never completes. This collides with how run-many schedules work: Nx runs tasks in a pool, and the --parallel flag sets how many can occupy that pool at once. A slot is freed only when a task exits.

With build or test targets, a low limit just makes the run slower, because tasks finish and hand their slot to the next one. With dev servers, nothing finishes. If you serve six services with a limit of three, the first three start and hold their slots indefinitely. The other three wait in the queue forever. There is no error. The terminal looks busy, and you only notice when a request to the fourth service gets a connection refused.

The fix is to pass --parallel with a value at least equal to the number of servers you are starting, for example --parallel=6 for six services. If some of those targets pull in non-continuous dependencies such as library builds, add headroom so those tasks don't compete with the servers for slots. You can also set a default in nx.json, but a per-command flag makes the intent obvious.

Raising the limit has a cost. Each server is a separate runtime with its own heap, file watchers and compilation step. Memory use grows roughly linearly with the number of services. CPU usage spikes during startup and again on every rebuild that touches shared code.

# Six backend services, each with a long-running serve target.
# Each one holds a slot in the task pool for as long as it runs.

# Broken: limit of 3. The first three servers start and never exit,
# so the other three stay queued and never start. Nx reports no error.
npx nx run-many -t serve -p api-gateway,auth,orders,payments,inventory,notifications --parallel=3

# Fixed: the limit equals the number of servers, so all six start.
npx nx run-many -t serve -p api-gateway,auth,orders,payments,inventory,notifications --parallel=6

# If serve depends on library builds (dependsOn: ["^build"]), those
# build tasks also need slots. Add headroom so they don't wait behind
# servers that never finish.
npx nx run-many -t serve -p api-gateway,auth,orders,payments,inventory,notifications --parallel=8

# Cost check: every server is its own process with its own heap and
# file watchers. Watch memory and CPU while the services start up.
free -h
ps -eo pid,rss,pcpu,args --sort=-rss | grep -i node | head -n 10

Setting --parallel to at least the number of serve targets, plus headroom for dependency builds, lets every long-running server start, and standard Linux tools show how much memory and CPU each one uses.

Why does dependsOn hang on a dev server, and how do continuous tasks fix it?

Startup cost is one problem; ordering is a different one. It usually appears when someone adds dependsOn so the gateway doesn't start before the services it proxies to.

By default, dependsOn means "finish first." Nx treats each task as a unit of work that completes and exits with a status code. A dependent task is scheduled only after all of its dependencies have succeeded. That model fits build depending on ^build: the library compiles, exits zero, and the application build starts.

A dev server never exits. If gateway:serve declares a dependency on orders:serve, Nx starts the orders service and then waits for it to complete. The orders service keeps running and watching files, so the gateway never starts. The terminal shows healthy orders logs and no gateway output. There is no error, so it looks like a slow startup when it is actually a deadlock.

Continuous tasks address this. You mark a target such as serve as continuous in its target configuration. Nx then knows the task is long-lived. When another task depends on it, Nx starts it, treats it as a running dependency, and starts the dependent task without waiting for an exit. Support and exact syntax depend on your Nx version, so check the documentation for the version your workspace uses before relying on it.

Older workspaces without continuous tasks need a different approach. Remove the serve-to-serve dependency edges and launch everything together with run-many. Then handle ordering in the application code: the gateway retries upstream connections or waits on a health check instead of assuming its dependencies are already up.

{
  "name": "gateway",
  "targets": {
    "serve": {
      "executor": "@nx/js:node",
      "continuous": true,
      "dependsOn": [
        {
          "projects": ["orders"],
          "target": "serve"
        }
      ],
      "options": {
        "buildTarget": "gateway:build"
      }
    }
  }
}

A gateway project.json, in a workspace on an Nx version that supports continuous tasks, that declares a dependency on orders:serve; the orders project's serve target must also set "continuous": true so Nx starts it and then launches the gateway without waiting for orders to exit.

How should you separate build dependencies from runtime dependencies?

A dependency edge in Nx means one of two things, and the config looks the same for both. A build edge says "this artifact must exist before I start." A runtime edge says "this process must be up while I run." Keep them as separate entries so you can see which is which.

For shared libraries, use dependsOn: ["^build"] on the service's build and serve targets. Nx then compiles every library the service imports, finishes, and moves on. For "service B must be running," point the gateway's serve target at service-b:serve and mark that target continuous: true. Nx starts it and does not wait for it to exit.

If you mix the two, a long-running process ends up in the build graph. A build target that depends on a serve target will either hang or start servers inside CI builds. A serve that depends on another project's build when it really needs that project running starts without its upstream.

Build edge (^build) Runtime edge (continuous serve)
Completes when The task exits successfully Never. It runs until you stop it
Caching Cacheable, with outputs restored on a hit Set cache: false, because a running process has no output to replay
Typical targets build, compile, generate serve, watch, a local queue or broker

Leave caching on for builds, because unchanged libraries are the bulk of every restart. Turn it off for every serve target. A cache hit on serve would skip starting the process, so nothing would be running.

There is a coupling risk. These runtime edges describe your laptop, not production. If the deployed gateway stops calling service B, or starts calling a new service C, nothing in project.json fails. Review runtime edges whenever you change the deployment topology, and don't rely on Nx config to tell you what depends on what in production.

// apps/gateway/project.json (Nx parses comments in project.json)
{
  "name": "gateway",
  "targets": {
    "build": {
      "executor": "nx:run-commands",
      "options": { "command": "tsc -p apps/gateway/tsconfig.app.json" },
      // Build edge: compile every library gateway imports first.
      // Only build targets live here. Never point build at a serve target.
      "dependsOn": ["^build"],
      "outputs": ["{workspaceRoot}/dist/apps/gateway"],
      "cache": true
    },
    "serve": {
      "executor": "nx:run-commands",
      "options": { "command": "node dist/apps/gateway/main.js" },
      // Long-running process: Nx should not wait for it to exit.
      "continuous": true,
      // A cache hit would skip starting the process.
      "cache": false,
      "dependsOn": [
        // Build edge: libraries must be compiled before we start.
        "^build",
        // Runtime edge: service-b must be running while gateway runs.
        // service-b's own serve target must also set "continuous": true,
        // or Nx will wait for it to exit and gateway never starts.
        // This mirrors local dev only. Re-check it when deployed call paths change.
        { "projects": ["service-b"], "target": "serve" }
      ]
    }
  }
}

A gateway project.json that keeps the cacheable ^build edge for shared libraries separate from a non-cached, continuous runtime edge on service-b's serve target.

Worked example: a gateway, two services, a shared library and a queue worker

This layout is an illustration, not a recommended structure. It has four apps: gateway, orders, billing and worker (a queue consumer). It also has one library, shared-contracts, which every app imports.

            build edges (finish first)          runtime edges (continuous)
shared-contracts:build ──► orders:build      gateway:serve ──► orders:serve
                       ──► billing:serve     gateway:serve ──► billing:serve
                       ──► worker:serve      worker:serve  ──► (external queue)
                       ──► gateway:serve

Target configuration

Each app's serve target is marked continuous: true and declares dependsOn: ["^build"]. As a result, shared-contracts compiles once and exits before any server starts.

The gateway's serve target also lists orders:serve and billing:serve in its dependsOn. Because those targets are continuous, Nx starts them alongside the gateway instead of waiting for them to exit.

Ports are fixed and unique, and each one is set in the target's options:

  • gateway: 3000
  • orders: 3001
  • billing: 3002
  • worker: 3003, used only for a health endpoint

Service-specific values live in an env file at each project's root, such as the queue URL for worker or the database name for orders. They are not shell exports.

A developer runs one command:

nx run-many -t serve -p gateway orders billing worker

Why this holds up across machines

Everything a service needs to start is stored in the repository. That includes ports, environment, start order and build prerequisites. Two developers running the same command get the same processes on the same ports.

When a developer hits a port conflict or a missing variable, the cause is visible in a reviewed file. It is not in someone's shell profile.

Onboarding comes down to cloning the repo, installing dependencies, starting the queue and running the command. A new service is added once in project.json and becomes available to everyone on their next pull.

What happens when a service isn't ready, crashes or floods the logs?

Nx considers a continuous dependency "started" once its process launches. That says nothing about whether the port is accepting connections yet. A gateway that starts a few hundred milliseconds after orders-service can still hit a refused connection while the service is compiling or connecting to its database. Handle readiness in code rather than in task configuration:

  • Retry with exponential backoff and a cap on outbound clients, so the first failed call does not kill the process.
  • Wait on a health endpoint in a small wrapper script that polls before running the dependent process.
  • Treat "dependency unavailable" as a normal state. The same code then holds up in staging, where services also restart out of order.

With five processes writing to one terminal, startup logs interleave into noise. Running with --output-style=stream prefixes each line with its project name, so you can follow it or grep it. If you are debugging one service closely, give that service its own terminal and leave the rest in the combined run. A process manager with per-process panes is worth considering when the combined output still slows you down.

If one service crashes, the others may keep running. That leaves the stack quietly degraded: the gateway responds, but every order request fails. Check the terminal output before assuming your change broke something.

Shared libraries create a different problem. Editing shared-types can trigger a rebuild and restart in every service that imports it, all at once. Your CPU spikes and requests fail while the restarts finish. If this keeps happening, serve only the services you are actively changing and run the rest from built output.

When should you avoid serving everything with Nx, and what are the alternatives?

Nx is a task runner. It decides what starts and in what order, then streams output. It does not check whether a service is healthy, restart one that crashed, or own the lifecycle of databases and message brokers. Starting every service on every run also costs you twice. Each service pays its own startup and compile time, and each one holds memory while it runs, even when you are not touching it. Once a laptop is running a dozen watchers, file-system events and garbage collection compete with your editor and test runs.

Option Startup cost Resource use Isolation Setup effort
One service plus its continuous dependencies Low Low Shared host Minimal, uses existing Nx config
Shared remote instances of other services Lowest Lowest Poor, others' data and deploys affect you Moderate, needs routing and access
Containers or compose-style tooling for infrastructure Medium on first run, fast after Medium Good for stateful dependencies Moderate
Separate process manager Medium High if everything runs Shared host Moderate, duplicates some Nx config

Choose based on team size and service count:

  • A small team with a handful of services can keep run-many for everything. The overhead stays tolerable, and one command is easier to keep correct than several tools.
  • Once you pass roughly ten services, or share a laptop's memory with heavy IDEs, serve only the service you are changing plus its continuous dependencies. Run databases and brokers in containers so their state survives restarts.
  • Larger organizations usually get the most back from shared remote instances for stable services. The trade-off is that someone must own those environments.
  • Reach for a separate process manager only when you need automatic restarts. It adds a second source of truth for how services start.

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 run-many serve, 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.