How does Nx decide which tasks run and in what order?
Nx builds two graphs. The project graph records which projects depend on which. Nx derives it by analyzing source imports, reading package.json dependencies between workspace packages, and adding any implicitDependencies you declare. This graph is about projects only. It says nothing about tasks.
When you run something like nx run-many -t build or nx affected -t test, Nx creates one task per project and target pair. It then turns those tasks into a task graph by applying each target's dependsOn rules to the project graph. A rule might say "before building this project, build the projects it depends on." Each such rule becomes an edge, and the edges decide what runs first, what waits, and what runs in parallel.
Nx does not infer ordering from target names. A target called build gets no special treatment, and neither does test or compile. Suppose dependsOn is not configured. If api imports shared-db, Nx can still run api:build at the same moment as shared-db:build, or before it. That holds even though Nx knows one project depends on the other.
This matters to backend and platform engineers who own monorepo CI. Missing edges rarely fail in an obvious way:
- Failed builds: A service may compile against a library's output directory that doesn't exist yet.
- Inconsistent results: A service may read stale output left by an earlier run, so the same commit passes locally and fails in CI.
- Wrong cache entries: Nx computes cache keys from declared inputs. If a dependency's output is consumed without a declared relationship, the cache can return results that no longer match the code. Engineers then tend to clear the cache or skip it, which removes the speedup caching was meant to provide.
+----------------+ +-------------------+ +----------------------+
| source imports | | package.json deps | | implicitDependencies |
+-------+--------+ +---------+---------+ +-----------+----------+
| | |
+---------------------+------------------------+
|
v
+----------------------------------------+
| PROJECT GRAPH: projects only, no tasks |
| api ----imports----> shared-db |
+--------------------+-------------------+
|
+---------------------+ | +-----------------------+
| nx run-many -t build| | | dependsOn per target |
| one task per project|---->+<----| ^build: deps first |
+---------------------+ | +-----------------------+
v
+---------------------------------------------------+
| TASK GRAPH: edges decide order and parallelism |
| shared-db:build --dependsOn ^build--> api:build |
+---------------------------------------------------+
+---------------------------------------------------+
| WITHOUT dependsOn: no edge between the two tasks |
| shared-db:build api:build (any order) |
| -> missing output, stale reads, wrong cache hits |
+---------------------------------------------------+
Nx builds the project graph from imports, package.json dependencies and implicitDependencies, then applies each target's dependsOn rules to the tasks you request to produce the task graph; without a dependsOn rule there is no edge, so related tasks can run in any order.
How does dependsOn work, step by step?
The mechanism is a graph expansion followed by a scheduler. Conceptually, when you run a command, Nx does the following:
- Collect the requested tasks.
nx test apirequests one task,api:test.nx run-many -t testrequeststestfor every project that has that target. - Resolve each task's configuration. For each task, Nx takes the target's settings from
targetDefaultsinnx.jsonand merges the project's own target configuration over them. The resultingdependsOnarray is what counts. - Expand each
dependsOnentry into tasks. An entry without a caret, such as"build", adds the same project'sbuildtask. An entry with a caret, such as"^build", adds thebuildtask of every project this one depends on in the project graph. An object entry withprojectsadds that target on the named projects. Projects that lack the referenced target are skipped. - Repeat for the new tasks. Every task added in step 3 has its own
dependsOn, so Nx expands those too, until no new tasks appear. A task reached through several paths is added once, not once per path. - Schedule the result. The finished task graph must be acyclic. Nx starts every task whose prerequisites are complete, up to the parallelism limit, and starts more as tasks finish. Tasks with no path between them can run at the same time.
- Check the cache before running. For each task, Nx hashes its inputs. On a hit it replays the stored terminal output and restores the declared
outputsinstead of running the command.
Two consequences follow. First, running a single target can run many tasks, because prerequisites are pulled in automatically; you never have to request them by hand. Second, dependsOn only describes ordering and inclusion. It does not by itself make a dependency's output part of another task's cache key; that is the job of inputs and outputs.
What is the difference between '^build' and 'build' in dependsOn?
The caret is the whole distinction. ^build points across the project graph: before this target runs, run build on every project this one depends on. build without the caret stays inside the project: before this target runs, run this same project's build target.
Consider a minimal nx.json where targetDefaults sets build to depend on ^build and test to depend on build. Suppose a service api imports two libraries, shared-models and shared-db, and you run nx test api.
The test line tells Nx that api:test needs api:build first. The build line then tells Nx that api:build needs shared-models:build and shared-db:build first. Each of those builds carries the same ^build rule, so the requirement continues down the graph until it reaches projects with no dependencies. Nx schedules the libraries first, then api:build, then api:test. Dependencies that have no build target are skipped instead of causing an error.
Nx does not schedule shared-models:test or shared-db:test. The test rule has no caret, so it never reaches into dependencies. That is usually the behavior you want: a service's tests need its libraries compiled, but they do not need the libraries' test suites to pass first.
| Form | Scope | Scheduled before api:test in the example |
|---|---|---|
^build |
Every upstream dependency, transitively | shared-models:build, shared-db:build |
build |
The same project only | api:build |
{
"targetDefaults": {
"build": {
"dependsOn": ["^build"]
},
"test": {
"dependsOn": ["build"]
}
}
}
A minimal nx.json where every project's build first builds its dependencies ("^build"), and every project's test first runs that same project's build ("build"). Running nx test api therefore schedules shared-models:build and shared-db:build, then api:build, then api:test.
Why should targetDefaults in nx.json be the single source of truth?
If every project.json declares its own dependsOn, the pipeline exists in dozens of places and drifts as soon as one team edits theirs. Putting it in targetDefaults in nx.json defines it once. The defaults are keyed by target name, so a build entry with dependsOn: ["^build"] and a test entry with dependsOn: ["build"] apply to every project that has a build or test target. New services inherit the ordering without anyone remembering to copy it.
When a project defines a target with the same name, Nx merges the project's configuration over the default. The merge does not combine arrays. A project-level dependsOn replaces the default array. If api sets dependsOn: ["generate-client"] on test, it loses the inherited build dependency, and its tests can run against stale output. To add an entry, restate the inherited ones alongside it: ["build", "generate-client"].
This approach has a cost. Someone reading only project.json cannot see the full pipeline, because most of it lives in nx.json. They also cannot tell from a short local array that it replaced the shared one. Handle this with a review convention, such as requiring a comment or reviewer sign-off on any project-level dependsOn, or with a lint check that confirms each override still contains the default entries.
Merge semantics and the way plugin-inferred targets interact with targetDefaults have changed across releases. Check both against the documentation for the Nx version you have installed.
{
"targetDefaults": {
"build": {
"dependsOn": ["^build"]
},
"test": {
"dependsOn": ["build"]
}
}
}
{
"targets": {
"test": {
"dependsOn": ["generate-client"]
}
}
}
{
"targets": {
"test": {
"dependsOn": ["build", "generate-client"]
}
}
}
A shared build and test pipeline defined in nx.json targetDefaults, and how a project-level test.dependsOn override must restate the inherited "build" entry, because the override replaces the default array instead of appending to it.
When do you need the object form of dependsOn?
The string forms cover most pipelines, but each one compresses a choice into a single character. The object form spells that choice out. { "target": "build", "dependencies": true } means the same as "^build". The two are interchangeable, and some teams prefer the longer form because readers do not need to know the caret convention.
The object form becomes necessary when the dependency is not in the project graph. Suppose every service build needs generated API types from a shared api-schema project, but no service imports it directly. The generated files might be copied into place, or the services might talk to it over the network. In that case "^codegen" never reaches api-schema, because the graph has no edge pointing there. An entry such as { "target": "codegen", "projects": ["api-schema"] } names the project directly, so Nx schedules its codegen task before the build whether or not a graph edge exists.
The two approaches fail in different ways:
| Form | What decides the upstream tasks | Where it breaks |
|---|---|---|
"^build" / dependencies: true |
The project graph | Misses undeclared or dynamic dependencies: runtime-loaded modules, non-JS assets, services called over the network |
projects: [...] |
A hand-maintained list | Goes stale when projects are renamed, split, or removed |
Use the explicit list as a narrow patch for a known gap, and leave a comment explaining why the edge cannot be inferred. If that gap shows up across many projects, fix the graph itself. You can declare the missing dependency so the caret form picks it up, which avoids spreading project names through nx.json.
// nx.json (Nx parses this file with comment support)
{
"targetDefaults": {
"build": {
"dependsOn": [
// Same as "^build": build every project this one depends on
// in the project graph before building it.
{ "target": "build", "dependencies": true },
// Services consume types generated by api-schema, but none of them
// import it. The files are copied in, so the graph has no edge and
// "^codegen" would never reach api-schema. Naming the project
// directly makes Nx run api-schema:codegen before any build.
// Remove this entry if api-schema is renamed or the dependency
// gets declared in the graph.
{ "target": "codegen", "projects": ["api-schema"] }
]
}
}
}
A build target default that pairs the graph-driven object form, which is equivalent to "^build", with an explicit projects entry that schedules codegen in a shared api-schema project that the project graph cannot see.
Worked example: ordering tests across shared libraries and services
For this repo, assume four projects. shared-types has no internal dependencies. db-client imports shared-types. orders-api and billing-api both import db-client and shared-types. In targetDefaults, build declares dependsOn: ["^build"] and test also declares dependsOn: ["^build"]. Tests run against the compiled output of their dependencies, not against their sources. A project's own build is not a prerequisite for its tests, because the test runner compiles that project's code itself.
Running nx run-many -t test produces roughly three waves:
shared-types:buildandshared-types:test.shared-typeshas no dependencies, so^buildresolves to nothing for it. Both tasks are ready immediately and can run side by side.db-client:buildanddb-client:test. Each waits only forshared-types:build. They do not depend on each other, so they run in parallel. They can also overlap withshared-types:testif it is still running.orders-api:testandbilling-api:test. These wait fordb-client:build. Nx has already scheduledshared-types:buildfor the first wave, so it is not run again. The two services share no edge, so their tests run concurrently.
Neither service gets a build task. Nothing depends on orders-api:build or billing-api:build, and ^build only pulls in dependencies, never the project itself.
A failing shared-types:test blocks no other task, because no task depends on it. A failing shared-types:build blocks everything downstream. This is the intended behavior: other tests can't run without compiled types, but they don't need the library's tests to pass first.
How do you verify the task pipeline instead of guessing?
The worked example rests on specific rules: a service's tests need their dependencies compiled, they don't need the service's own build, and they don't need the tests of the libraries they import. Rules like that are easy to state and easy to get wrong in nx.json, so check them before pushing.
Read the graph, not the config
Running nx graph opens an interactive view of the project graph: which projects depend on which, inferred from imports and package.json dependencies. Check this first. If api doesn't show an edge to shared-types, no ^build rule will ever order them, because ^ only follows edges that exist. A missing edge usually means an import path that Nx can't resolve, such as a relative path that reaches into another project's source folder.
The task graph is the more useful view for dependsOn. Append --graph to a real invocation, for example nx test api --graph or nx run-many -t test --graph. Nx renders the tasks it would schedule and the dependency arrows between them, without executing anything. You see exactly what targetDefaults and any project-level overrides produce after they are merged. Reading the files yourself means doing that merge in your head.
Confirm with a single-project run
Next, run the target for one leaf project, such as nx test api. The terminal output lists every upstream task Nx pulls in. If shared-types:build is missing from that list, your pipeline has a gap. If half the workspace builds, a dependency is too broad.
Both checks take seconds on a laptop. Finding the same problem in CI means a failed pipeline, reading logs to work out the task order, a fix, and another full run.
How does dependsOn affect caching, parallelism, and CI cost?
That loop is slow, but the larger cost of a wrong dependsOn shows up on every CI run.
When the graph is correct, Nx runs tasks with no edge between them in parallel and replays upstream tasks from cache. A cache hit only helps if the target's outputs are declared. Without them, Nx restores the terminal log but not the files, so the build reports success and dist stays empty. The next task then fails with "module not found," but only on CI, where the workspace starts clean. Locally, the stale dist from an earlier build hides the bug.
Missing edges cause a different failure. If test reads a library's compiled output but does not depend on ^build, Nx may schedule both at once. The test passes when the build happens to finish first and fails when it doesn't. The result depends on runner speed and the --parallel setting.
| Approach | Correctness | Parallelism | CI time |
|---|---|---|---|
Over-declared (test → ^build everywhere) |
Safe | Tests wait on the full upstream chain | Higher on cache misses |
| Under-declared | Racy, intermittent failures | Maximal | Low until it flakes |
Precise, with outputs declared |
Safe | Only real dependencies serialize | Lowest stable |
Illustrative estimate (assumed numbers, not a benchmark): assume a dependency chain depth d = 3, build time b = 60 s per library, and test time t = 90 s. On a cold cache, the over-declared critical path is d × b + t = 270 s. If tests resolve source through path aliases, they need no upstream build, and the path drops to t = 90 s. In that case, drop ^build from test entirely.
How can a correct pipeline save engineering time?
The savings come from removing work that people otherwise do by hand or repeat for no reason:
- No manual ordering. Without
dependsOn, CI scripts tend to grow hand-written sequences such as "build libraries, then build services, then test." Those scripts go stale as projects are added. With the pipeline intargetDefaults,nx affected -t testworks out the order itself, and new projects inherit it. - Less flake investigation. Race conditions from missing edges produce failures that don't reproduce on rerun. Each one costs someone time reading logs before they find that a build and a test overlapped. Correct edges remove that class of failure.
- Trustworthy caching. When edges and
outputsare right, nobody needs to clear the cache or disable it "to be safe," so unchanged upstream builds are restored instead of rerun, both locally and in CI. - Smaller review surface. One
targetDefaultsblock is reviewed once. Per-project copies have to be reviewed in every change that touches them, and drift between them has to be noticed by a person.
Illustrative estimate (assumed numbers, not a measurement): assume a team sees 3 intermittent CI failures per week caused by missing edges, and each takes an engineer an assumed 40 minutes to investigate, rerun and dismiss. That is 2 hours per week spent on a problem a few lines of nx.json prevent. Add the CI runner time from the previous section's estimate on each affected run, and the cost of an incorrect pipeline grows with team size and commit volume. Substitute your own failure rate and investigation time; the shape of the calculation is the point, not these inputs.
Who should use dependsOn and targetDefaults?
These settings are worth configuring deliberately if any of the following describe your workspace:
- Libraries are compiled before use. If libraries emit output to
distand services consume that output instead of source, every consumer needs^buildon the targets that read it. - There are generation steps. Code generated from schemas, API definitions or other inputs has to exist before compilation.
dependsOnis how you make Nx run the generator first. - Several teams share one monorepo. A single pipeline in
nx.jsonkeeps ordering consistent across projects owned by different people, and new projects pick it up automatically. - CI runs
nx affectedorrun-manywith parallelism. The more tasks run at once, the more likely a missing edge turns into a race, and the more a precise graph pays off in shorter critical paths.
The people most affected are the platform or build engineers who own CI and the shared nx.json. Application developers mostly need to know one rule: a project-level dependsOn replaces the default, so restate the inherited entries.
When should you avoid adding dependsOn rules?
More edges are not always safer. Avoid or remove them in these cases:
- Tasks that consume source, not build output. If tests or bundlers resolve workspace libraries through path aliases and compile them directly,
^buildon those targets only adds waiting. The illustrative estimate above shows how that cost scales with chain depth. - Small or single-project repositories. With one project, or a handful with no shared compiled output, there is little to order. A default
^buildonbuildis harmless, but a detailed pipeline is overhead to maintain. - Serializing tasks that only conflict over a resource. If two test suites can't run at the same time because they share a database or a port, a
dependsOnedge between them is a false dependency: it encodes "one must finish first" when the real constraint is "not concurrently," and it makes one suite fail when the other does. Isolate the resource, or lower parallelism for that run, instead. - Covering for a broken project graph. If
^buildmisses a dependency because Nx can't see an import or a relationship, a growing list ofprojects: [...]entries hides the problem. Fix the graph, for example withimplicitDependencies, and keep explicit project lists for the rare gaps that can't be expressed there. - Pulling in test runs of dependencies.
testdepending on^testmakes every service wait for every library's suite to pass. That is rarely what you want; keep library tests independent and let the build edge carry the real requirement.
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 dependsOn targetDefaults, 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
.envby 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.