What is the Nx Gradle plugin and how does it work?
The Nx Gradle plugin lets Nx treat a Gradle build as part of its project graph without asking you to rewrite anything. Nx asks Gradle to describe itself, then maps each Gradle project (the root and every subproject in settings.gradle) to an Nx project and each Gradle task to an Nx target. Dependencies between subprojects, such as implementation project(':shared-model'), become edges in the Nx graph. Your build.gradle or build.gradle.kts files remain the source of truth. If you add a subproject or register a task, Nx picks it up on the next graph computation, and there is no parallel project.json to keep in sync.
The tools sit at two levels. Nx decides which projects and targets run, in what order, and whether a whole target result can be restored from its cache. When Nx does run a target, it invokes Gradle, and Gradle still builds its own task graph. Inside that run, Gradle applies its up-to-date checks and its build cache to individual tasks such as compileJava or test.
Each layer keeps its caches in a different place:
- Nx local cache: in the workspace (by default under
.nx/cache). - Nx remote cache: a shared Nx cache that you configure for the workspace.
- Gradle up-to-date state: in each project's
build/outputs and the.gradle/directory. - Gradle local build cache: under the Gradle user home.
- Gradle remote build cache: an HTTP build cache that you configure in
settings.gradle.
This setup suits backend and platform teams that keep Spring or Ktor services in the same repository as TypeScript frontends, Python tooling, or infrastructure code. They get one affected graph and one CI entry point while Gradle keeps doing the JVM-specific work.
# Register the plugin in nx.json. Nothing in the Gradle build changes.
npx nx add @nx/gradle
# Gradle's view of the build: root project plus subprojects from settings.gradle
./gradlew projects
# Nx's view after asking Gradle to describe itself: one Nx project per Gradle project
npx nx show projects
# Targets Nx inferred from the Gradle tasks of one subproject
# (placeholder name; use a name from the list above)
npx nx show project orders-service
# Dependencies such as implementation project(':shared-model') appear as graph edges
npx nx graph
# Outer layer: Nx decides which projects run and in what order.
# Inside each target, Gradle builds its own task graph and applies its
# up-to-date checks and build cache to tasks like compileJava and test.
npx nx run orders-service:build
# Run the same target again with no changes. Nx can restore the whole
# target result from .nx/cache, so Gradle is not invoked at all.
npx nx run orders-service:build
# Run Gradle directly to see only the inner layer at work.
# --build-cache turns on the Gradle build cache for this invocation.
./gradlew :orders-service:build --build-cache
# CI entry point for a mixed repo: one affected graph that covers
# JVM services alongside the other projects in the workspace
npx nx affected -t test
Shell session that adds the Nx Gradle plugin, compares the Nx projects and targets it infers with Gradle's own project list, and shows where an Nx cache restore skips Gradle entirely and where Gradle's up-to-date checks and build cache take over.
How do Nx caching and Gradle caching differ?
…compilation, dependency resolution, and test execution underneath. That split matters because both tools ship a build cache, and they work at different levels.
Gradle caches per task. Its cache key is computed from what the task declares: input properties, input files, the task implementation's classpath, and normalized classpaths for compile tasks. Outputs must be declared too, and only tasks marked cacheable are stored. The local cache sits in the Gradle user home. A remote cache is an HTTP backend that CI populates and developers read from.
Nx caches per target. It hashes the files matched by the target's inputs, the hashes of dependent projects, and any configured environment or runtime inputs. On a hit it restores the files listed in outputs and replays the terminal log. Nx never sees Gradle's task graph, only the command it invoked and the files that command produced. Nx also has a local cache in the workspace and an optional shared remote cache.
| Aspect | Gradle build cache | Nx cache |
|---|---|---|
| Unit | Single Gradle task | Nx target (one or more Gradle tasks) |
| Key source | Inputs declared by the task | Inputs configured in Nx |
| Restores | Declared task outputs | Configured output paths and logs |
| Remote mode | HTTP cache backend | Shared remote cache |
If you cache the same task in both layers, you store and transfer the same JARs and class files twice. Each layer has its own key, so a stale artifact can come from either one. The worst problem is masking. Suppose a Gradle task reads a file it never declared. An Nx hit means Gradle never runs, so the stale output keeps getting replayed. Nobody notices until someone clears the Nx cache or changes an Nx input, and then the bug shows up long after the change that caused it.
Which tool should own caching for each kind of task?
The rule that prevents that failure is simple: each cache should own a distinct layer, and no task's result should depend on both caches agreeing.
| Task type | Cache owner | Why |
|---|---|---|
compileJava, test, jar |
Gradle | Gradle tracks classpath, compiler args and file fingerprints at task level. Nx only sees the project boundary. |
| Affected-project selection, cross-language ordering | Nx | Nx holds the project graph across JVM and non-JVM code. Gradle does not. |
Coarse aggregates (e.g. a ci target that runs check and publishes reports) |
Nx, optionally | A hit skips Gradle daemon startup and configuration entirely. This only works if inputs are declared fully. |
| Integration tests against databases, containers or network | Neither | The result depends on state outside the file inputs, so a hit asserts nothing. |
| Known-flaky tests | Neither | Caching a lucky pass hides the flake. Caching a failure blocks retries. |
To mark a task non-cacheable, set cache: false on the Nx target, either in the project configuration or in target defaults. On the Gradle side, disable output caching for that task with outputs.cacheIf { false }, or with doNotCacheIf and a stated reason. You need both settings, because disabling only one leaves the other layer free to replay a stale result.
For debuggability, adopt two conventions:
- Run Gradle in CI with plain console output, so per-task outcomes such as
FROM-CACHEandUP-TO-DATEappear in the logs. - Keep Nx's own cache-hit notices visible rather than suppressed.
Name aggregate targets distinctly, such as ci-check instead of test. When a result looks wrong, an engineer can then read the log and tell whether Nx replayed it or Gradle produced it.
// build.gradle.kts (Gradle Kotlin DSL) for one JVM service.
// The matching Nx target for integrationTest must also set "cache": false
// in project.json, so neither layer can replay a result.
plugins {
java
}
// Unit tests: pure file inputs, so Gradle owns caching here.
tasks.named<Test>("test") {
useJUnitPlatform {
excludeTags("integration", "flaky")
}
}
// Integration tests hit a real database or container. File fingerprints
// do not describe that state, so a cache hit would assert nothing.
val integrationTest by tasks.registering(Test::class) {
description = "Runs tests tagged 'integration' against external services"
group = "verification"
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
useJUnitPlatform {
includeTags("integration")
}
// Keep it out of the build cache, with a reason Gradle can report.
outputs.doNotCacheIf("Result depends on external DB/container state") { true }
// Also skip local up-to-date checks, so it always executes.
outputs.upToDateWhen { false }
}
// In CI, run with plain output so FROM-CACHE / UP-TO-DATE lines are logged:
// ./gradlew integrationTest --console=plain
A Gradle Kotlin DSL build script keeps unit tests cacheable and marks an integration test task as never cached and never up-to-date. The comments note the matching Nx cache: false setting and the plain-console CI invocation.
How do you declare inputs and outputs so cache hits can be trusted?
A cache key is only as honest as its input list, and the two tools fail in opposite directions. In Gradle, a task that reads something it never declared, such as a file loaded by path inside a custom task or a system property read with System.getProperty, still produces a key that ignores it. When that value changes, Gradle reuses the old output. That is a stale hit, and nothing in the log flags it. In Nx, the usual mistake is the reverse. Inputs like "every file in the workspace" are safe, but they invalidate every project on any edit, so the cache rarely hits at all.
For each project, both tools should agree on the same inputs:
- source and resource directories
- build scripts and convention plugins
- the version catalog and dependency lock files
- the JDK identity
- any environment variables or system properties that affect output
In Nx, list environment variables explicitly as env inputs instead of letting them leak in.
Reproducibility across machines needs three habits:
- Pin the JDK with a Gradle toolchain. Without one, the result depends on whichever JDK each machine has installed. A CI runner and a laptop can then produce different bytecode under the same key.
- Keep outputs byte-stable. Disable file timestamps in archives, use a fixed file order, and keep absolute paths out of generated manifests and resources. A build that embeds the current time can never match another machine's build.
- Keep generated sources inside declared outputs. Annotation processors and code generators should write under
build/. If generated files land in the source tree, they become inputs and outputs at the same time, which breaks restore.
// build.gradle.kts (service module, Gradle Kotlin DSL)
plugins {
java
}
java {
// Pin the JDK so CI and laptops compile with the same version under the same key.
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
// Byte-stable archives: no file timestamps and a deterministic entry order.
tasks.withType<AbstractArchiveTask>().configureEach {
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
}
// A custom task whose output depends on a system property.
val generateBuildInfo by tasks.registering {
// Read through providers instead of System.getProperty, then declare it,
// so a changed value changes the cache key instead of causing a stale hit.
val region = providers.systemProperty("deploy.region").orElse("eu-west-1")
val outDir = layout.buildDirectory.dir("generated/build-info")
inputs.property("deployRegion", region)
outputs.dir(outDir)
outputs.cacheIf { true }
doLast {
// No timestamps or absolute paths: same inputs always give the same bytes.
outDir.get().file("build-info.properties").asFile
.writeText("region=${region.get()}\n")
}
}
sourceSets.main {
// Generated files stay under build/, inside the task's declared output.
resources.srcDir(generateBuildInfo)
}
A Gradle Kotlin DSL build script that pins the JDK with a toolchain, makes archives byte-stable, declares a system property as a task input, and keeps generated resources inside a declared output under build/.
When is affected-only CI safe for a JVM monorepo?
nx affected compares the current branch against a base commit, maps changed files to projects, and walks the project graph to find every dependent. For a Gradle workspace that graph comes from the plugin's reading of project(...) dependencies. If orders-service depends on :libs:pricing, a change to pricing reruns both. If the edge is missing, Nx skips the service and CI passes without testing it. Affected-only CI is only as safe as that graph is complete.
Gradle project dependencies miss several common kinds of coupling:
- Shared resources. A root-level
config/directory, logback templates, or test fixtures read by path are not project dependencies. Add those paths to the consuming projects' inputs so changes to them invalidate the cache and mark the projects as affected. - Schema-driven code generation. If services generate clients from an OpenAPI, Avro, or protobuf file in another directory, the schema change affects every generator, even though no
.javafile changed yet. Model the schema as its own project and add it as animplicitDependenciesentry, or declare the schema file as an input. - Runtime-only coupling. Services that talk over HTTP or a message topic share contracts but have no build edge. Use implicit dependencies for the contract tests, and keep a scheduled full run as a backstop for whatever the graph still misses.
Remote cache trust is a separate concern. A developer machine with a different JDK, local edits outside declared inputs, or a dirty environment can produce artifacts that the next build accepts as valid. Give developers read-only cache credentials and let only CI agents, with pinned toolchains, write entries.
{
"name": "orders-service",
"implicitDependencies": [
"orders-api-schema",
"inventory-events-contract"
],
"namedInputs": {
"sharedResources": [
"{workspaceRoot}/config/**/*",
"{workspaceRoot}/test-fixtures/orders/**/*"
]
},
"targets": {
"build": {
"inputs": ["default", "^default", "sharedResources"]
},
"test": {
"inputs": ["default", "^default", "sharedResources"]
}
}
}
A project.json for orders-service declares edges that Gradle project dependencies miss: implicit dependencies on a schema project and an event-contract project, plus root-level config and fixture paths added to build and test inputs.
How much CI time and engineering cost does this save?
Illustrative estimate (assumed numbers, not a benchmark). The figures below are assumptions. Replace them with your own.
- N = 40 services
- t = 6 agent-minutes to compile and test one service
- a = 0.15, the fraction of services affected by a typical change
- h = 0.4, the cache hit rate among affected tasks (unchanged hashes, reruns)
- o = 20 seconds of Gradle startup and configuration per invocation, with 2 invocations per affected service
CI time ≈ N × t × a × (1 − h) + (N × a × 2 × o)
| Strategy | Formula | Agent-minutes |
|---|---|---|
| Full Gradle build | N × t | 240 |
| Affected only | N × t × a + overhead | 36 + 4 = 40 |
| Affected + cache | N × t × a × (1 − h) + overhead | 21.6 + 4 ≈ 26 |
The result depends most on a, the affected fraction. A change to a widely shared library can push a toward 0.8, which leaves little to save. The hit rate h only discounts work that affected-only already shrank, so it matters less. Keeping a low is an architecture task: use narrow shared modules and stable APIs.
The overhead term grows with the number of invocations. Every separate Gradle call pays for daemon handshake and project configuration. It also runs alone, so Gradle cannot schedule tasks across projects in parallel.
Two settings reduce this overhead:
- Batch invocations. Pass many tasks to one Gradle call so Gradle builds a single task graph.
- Enable the configuration cache. Gradle can then skip the configuration phase on later runs.
The estimate leaves out an ongoing cost: two tools and two configuration surfaces. Every new plugin, source set, or code-generation step needs matching Nx inputs and outputs. If the two drift apart, the cache can return wrong results without any error. Budget review time for both configurations.
How do you verify the setup and when should you avoid Nx for Java?
Verify before you trust it
Run three checks on a clean checkout, preferably on a CI agent rather than a laptop, so local state cannot mask problems.
- Same commit, twice. Run the full build, then run it again with no changes. Every cacheable target should report a hit. A miss on the second run means some input is not stable. Common causes are a generated file with a timestamp, an environment variable, or an absolute path. Fix that first, because nothing else in this procedure means anything until it passes.
- One input, one change. Edit a single source file in one library. Only that project and the projects that depend on it should miss. If unrelated services rebuild, your inputs are too broad. If a dependent service hits, your inputs are too narrow, and that is the dangerous case.
- Cached versus uncached output. Rebuild with the cache bypassed and diff the artifacts. Make the comparison possible by turning on reproducible archives in Gradle: disable
preserveFileTimestampsand enablereproducibleFileOrder. Without those settings, JARs differ on every build and the diff tells you nothing.
Repeat the checks after upgrading Nx or its Gradle plugin. The way the plugin infers targets can change between releases.
When to skip Nx
| Situation | Better choice |
|---|---|
| JVM-only repo, one build tool | Gradle build cache plus configuration cache |
| Mixed JVM and JS/TS services | Nx with the Gradle plugin |
| CI cost driven by running every service's tests | Nx affected selection, if dependency edges are accurate |
| Small team, no platform owner | Gradle alone |
Most JVM-only teams get the bulk of the savings from Gradle's own caching. Add Nx when cross-language orchestration or affected selection pays for the second tool you must maintain.
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 gradle plugin, 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.