What makes a monolith build slow, and how do you measure it?
Most slow monolith builds are slow because they repeat work, not because the hardware is too weak. A build that recompiles hundreds of unchanged classes, reruns tests whose inputs did not change, or reconfigures every project on each invocation will stay slow on a faster machine. This checklist is for backend and platform engineers who own large builds. Start when a no-op build or a one-line change takes long enough that people switch context while waiting.
Who should use this checklist?
This checklist fits teams with these traits:
- One large codebase built by Gradle. This is usually a JVM monolith with many subprojects, or one that is about to be split into subprojects. The commands and settings here are Gradle-specific. The principles apply to other build systems that track task inputs and outputs.
- Build time is a daily cost. Engineers run no-op or small incremental builds many times a day, and CI runs block merges.
- Someone owns the build. That can be a platform team or one engineer who can change build scripts, plugins and CI configuration across the repository.
It is a poor fit in two cases:
- The project is small and builds quickly. The tuning effort, especially modularization and configuration-cache migration, may never pay back.
- The pipeline is slow somewhere else. If the time goes to deployment, environment provisioning or long end-to-end suites against external systems, fix those stages first. Measure before you assume the compiler is the problem.
How do these speedups work?
Every technique in this checklist relies on one idea: do not repeat work whose inputs have not changed.
- Up-to-date checks. Gradle fingerprints the declared inputs and outputs of each task. If neither changed since the last run, the task is skipped and reported as
UP-TO-DATE. - The build cache. It extends the same idea across clean builds and machines. A task's output is stored under a key computed from its inputs. Any build that produces the same key can reuse the output instead of running the task, and the task is reported as
FROM-CACHE. - Incremental compilation. When a compile task must run, Gradle tracks class-level dependencies and ABI changes. It recompiles only the classes affected by the change instead of the whole source set.
- The configuration cache. It saves the result of the configuration phase, so an unchanged build can skip evaluating build scripts.
- Parallel execution. It cannot reduce the total amount of work. It can reduce wall-clock time by running independent parts of the project graph at the same time, which is why module structure matters.
All of these depend on correct, complete input and output declarations. When a task hides an input, Gradle either reruns it unnecessarily or, worse, reuses an output that is stale. Most items in the checklist are about making those declarations accurate and then letting Gradle skip work safely.
Record a baseline first
Measure three scenarios, both locally and in CI, before you change anything:
| Scenario | What it shows | What "bad" looks like |
|---|---|---|
| Clean build | Total cost of compiling and testing everything | Mostly matters for CI and new checkouts |
| No-op build (run twice, change nothing) | Configuration overhead and up-to-date checking | Any task that executes on the second run |
| Single-file change | How well incremental compilation and task avoidance work | Many downstream modules recompile or retest |
Then use --profile or a build-scan style report to find which tasks dominate wall-clock time and which tasks rerun even though their inputs did not change. Tasks that rerun needlessly are usually cheaper to fix than slow tasks.
Control the conditions
A single timing tells you little. Hardware differences, a cold or warm cache, whether the daemon is fresh or already warmed up, and background load from IDE indexing or antivirus scans can each change results noticeably. Run each scenario several times under the same conditions. Record the median and the spread. Note whether the daemon and caches were warm, so you can compare later runs fairly.
#!/usr/bin/env bash
set -euo pipefail
RUNS=${RUNS:-5}
FILE=${FILE:-app/src/main/java/com/example/OrderService.java} # example path: pick a file many modules depend on
OUT="baseline-$(date +%Y%m%d-%H%M%S).csv"
cp "$FILE" "$FILE.bak"
trap 'mv "$FILE.bak" "$FILE"' EXIT
time_run() {
local s e
s=$(date +%s.%N)
./gradlew "$@" --profile -q > /dev/null
e=$(date +%s.%N)
awk -v s="$s" -v e="$e" 'BEGIN { printf "%.2f\n", e - s }'
}
./gradlew build -q > /dev/null
echo "scenario,run,seconds,daemon=warm" > "$OUT"
for i in $(seq 1 "$RUNS"); do
# Clean: --no-build-cache stops cached outputs from hiding the real compile cost.
echo "clean,$i,$(time_run clean build --no-build-cache)" >> "$OUT"
# No-op: nothing changed since the previous build, so ideally no task executes.
echo "noop,$i,$(time_run build)" >> "$OUT"
# Single-file change: Gradle compares content hashes, so edit the content instead of just touching the file.
echo "// bench $i" >> "$FILE"
echo "single_file,$i,$(time_run build)" >> "$OUT"
done
for sc in clean noop single_file; do
grep "^$sc," "$OUT" | cut -d, -f3 | sort -n | awk -v sc="$sc" '{ a[NR] = $1 }
END { m = (NR % 2) ? a[(NR + 1) / 2] : (a[NR / 2] + a[NR / 2 + 1]) / 2
printf "%-12s median=%.2fs min=%.2fs max=%.2fs\n", sc, m, a[1], a[NR] }'
done
A Bash script that warms the Gradle daemon, then times repeated clean, no-op and single-file-change builds with --profile and reports the median and min/max for each scenario.
How does a build spend its time across configuration and execution?
Gradle runs every build in three phases. Initialization reads the settings file and decides which projects take part. Configuration evaluates every participating build script and builds the task graph. Execution runs only the tasks that are requested and out of date.
Configuration runs on every invocation, including a no-op build where nothing needs to run. Gradle has to evaluate the scripts before it can know that no work is required. Unless the configuration cache is enabled (covered in section 6), that cost repeats on each local build, IDE sync and CI job. In a monolith with many subprojects, small per-project costs add up quickly:
Illustrative estimate (assumed numbers, not a benchmark): configuration time ≈ projects × per-project cost. With 150 projects × 40 ms, that is 6 s before any task runs.
The usual causes:
- Expensive script logic, such as reading files, running
gitor other processes, or making network calls at the top level of a script. - Eager task creation. Every task created with
tasks.createis instantiated and configured even when nobody asks for it. - Configuration-time dependency resolution. Iterating over a configuration's files during configuration forces resolution in every build.
Checklist:
- Measure configuration alone with
gradle help --profilebefore you tune execution. - Replace
tasks.createwithtasks.register, andtasks.all/eachwithconfigureEach. - Move file I/O, process calls and dependency resolution into task actions or providers.
- Re-measure the no-op build after each change.
The example below shows a build script before and after converting to lazy task registration.
// build.gradle.kts -- BEFORE: all of this runs on every invocation, even no-op builds
plugins { java }
// Spawns a git process while the script is evaluated
val gitSha = ProcessBuilder("git", "rev-parse", "HEAD").start()
.inputStream.bufferedReader().readText().trim()
tasks.create("writeBuildInfo") { // eager: always instantiated
val jars = configurations.getByName("runtimeClasspath").files // resolves dependencies now
doLast {
file("build/build-info.txt").writeText("sha=$gitSha\njars=${jars.size}\n")
}
}
tasks.withType<Test>().all { maxHeapSize = "1g" } // configures every Test task eagerly
// build.gradle.kts -- AFTER: the work is deferred until a task actually needs it
plugins { java }
// Provider: git only runs when .get() is called
val gitShaLazy = providers.exec { commandLine("git", "rev-parse", "HEAD") }
.standardOutput.asText.map { it.trim() }
tasks.register("writeBuildInfo") { // lazy: configured only if in the task graph
val runtime = configurations.named("runtimeClasspath") // handle only, no resolution
val out = layout.buildDirectory.file("build-info.txt")
outputs.file(out)
doLast {
// Process call and dependency resolution happen at execution time
out.get().asFile.writeText("sha=${gitShaLazy.get()}\njars=${runtime.get().files.size}\n")
}
}
tasks.withType<Test>().configureEach { maxHeapSize = "1g" } // runs only for tasks that are realized
A Gradle Kotlin DSL build script before and after the fix: the first version spawns a process, creates tasks eagerly and resolves dependencies during configuration, and the second moves that work behind tasks.register, configureEach and providers so it runs only when a task executes.
How do you make incremental compilation actually work?
Gradle's Java compiler recompiles only classes affected by a change, using class-level dependency analysis. Three things defeat it.
Widely depended-on types. If a shared Constants or Utils class sits under hundreds of others, editing it recompiles all of them. Changes to inlined compile-time constants are especially costly, because the compiler copies the value into each caller, so dependency tracking has to be conservative.
Non-incremental annotation processors. Gradle can process annotations incrementally only when a processor declares itself isolating or aggregating. One undeclared processor on the path makes every change a full recompilation of that source set.
Leaky public APIs. When a module exposes a dependency's types in its own public signatures, a change to that dependency's ABI forces recompilation downstream. With api, the dependency also leaks onto every consumer's compile classpath, so the cascade spreads module by module.
Checklist:
- Use the
java-libraryplugin and default toimplementation. Useapionly when a dependency's types appear in your public signatures (parameters, return types, supertypes). The example below shows a module that keeps its JSON library internal while exposing a shared domain module. - Run a one-line change with
--infoand read the compiler output. Gradle states when and why full recompilation is required, including the name of the processor responsible. - Update or replace processors that don't declare incremental support.
- Split catch-all utility and constants classes so each change reaches fewer dependents.
// orders/build.gradle.kts (Gradle Kotlin DSL)
plugins {
// java-library adds the 'api' configuration and separates
// the compile classpath consumers see from the one this module uses
`java-library`
}
dependencies {
// Domain types appear in this module's public signatures, e.g.
// public Order findOrder(OrderId id)
// so consumers must compile against them: use 'api'.
api(project(":domain"))
// Jackson is used only inside method bodies and private fields.
// With 'implementation' it stays off consumers' compile classpath,
// so upgrading or changing it recompiles only this module.
implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")
// Annotation processors go on their own configuration.
// Check --info output to confirm each one runs incrementally.
annotationProcessor(project(":codegen-processor"))
}
// Audit: make a one-line change in this module, then run
// ./gradlew :orders:compileJava --info
// and look for a message explaining why full recompilation was required.
A java-library module that exposes its domain dependency with api, keeps its JSON library internal with implementation, and notes how to check recompilation behavior with --info.
When should you split the monolith into build modules, and when should you avoid it?
Module boundaries matter because Gradle compiles each module as a unit and can only run independent modules in parallel. A change to a module's ABI forces recompilation of everything downstream. That makes the shape of the graph more important than the number of modules.
Linear chain Wide, shallow graph
core -> data -> service core
-> api -> app / | \
billing search users
\ | /
app
In the chain, editing core rebuilds all five modules one after another, and parallelism has nothing to work with. In the wide graph, billing, search and users compile concurrently. A change inside search rebuilds only search and app. One giant module is worse than either: any edit recompiles the whole unit.
- Find cycles before splitting. A package-level cycle cannot become a module boundary until you break it, often by extracting an interface into a small API module.
- Identify hub modules from the project dependency report. A hub is a module that many others depend on and that changes often. Hubs undo the benefit of the graph, so split them, or move their unstable parts out of them.
- Keep
apidependencies narrow. Preferimplementationso ABI changes don't leak transitively.
Limit modularization when the costs exceed the savings:
- Every module adds configuration time.
- Dependency declarations churn as code moves between modules.
- Past a few dozen modules, engineers lose track of where code belongs.
- Splitting is a refactoring project. Budget for it as one, and measure the build before and after.
LINEAR CHAIN WIDE, SHALLOW GRAPH
(edit core: 5 serial rebuilds) (edit search: search + app rebuild)
+---------+ +---------+
| core | | core |
+---------+ +---------+
| / | \
v v v v
+---------+ +---------+ +---------+ +---------+
| data | | billing | | search* | | users |
+---------+ +---------+ +---------+ +---------+
| \ | /
v v v v
+---------+ +---------+
| service | | app* |
+---------+ +---------+
|
v
+---------+
| api | billing, search, users compile
+---------+ in parallel. * = rebuilt after
| an edit inside search.
v
+---------+
| app |
+---------+
In a linear chain, a change to core rebuilds every downstream module in sequence. In a wide, shallow graph, the middle modules compile in parallel, and an edit inside search rebuilds only search and app.
How do you set up and verify the Gradle build cache safely?
- Turn on the local cache first. Set
org.gradle.caching=trueingradle.properties, run a clean build twice, and check the task outcomes. Tasks markedFROM-CACHEare being reused. A task that still runs on the second pass is either not cacheable or has an unstable cache key. - Add a remote cache that only CI writes. In
settings.gradle, configure an HTTP remote cache withpushenabled only when a CI environment variable is set. Developers read from it but never upload. A laptop with uncommitted changes or an unusual toolchain should not publish artifacts that everyone else consumes. - Track the hit rate across machines. Watch for one task type that keeps missing. To compare cache keys between two runs, use
-Dorg.gradle.caching.debug=true. The usual causes are absolute paths, embedded timestamps, environment variables read during execution, and inputs or outputs the task never declares. - Declare inputs and outputs for custom tasks and code generators. Annotate the task with
@CacheableTaskand mark each input with@InputFilesor@Input. Add@PathSensitive(PathSensitivity.RELATIVE)so the checkout location does not change the key. Mark generated sources with@OutputDirectory. An input you forget to declare is the dangerous case. The cache will then return stale output with no warning. - Budget for the cache. The remote cache costs storage and bandwidth. On a slow VPN, downloading a large artifact can take longer than rebuilding it locally.
- Keep an easy bypass. Document
--no-build-cacheand make it the first thing engineers try when they suspect bad output. If a poisoned entry is confirmed, purge the remote cache.
Which built-in build speedups should you enable, and what do they cost?
Gradle ships three speedups that are configured in gradle.properties and need no build-script changes. Turn them on one at a time and re-run the same measured scenarios after each change. If you enable all three together and builds get faster but flaky, you will not know which setting caused the flakiness.
| Setting | Benefit | Resource cost | Main risk |
|---|---|---|---|
org.gradle.parallel=true |
Independent modules build concurrently | More CPU and memory at peak | Exposes undeclared task ordering dependencies |
org.gradle.daemon=true plus org.gradle.jvmargs=-Xmx… |
Skips JVM startup and keeps JIT-warmed code between builds | Resident memory while idle | Too little heap causes GC thrashing. Too much starves IDEs and small runners |
org.gradle.configuration-cache=true |
Skips the configuration phase when inputs are unchanged | Disk for cache entries | Older or third-party plugins may be incompatible |
Parallel execution only helps if the module graph has width. When builds break under it, it is usually because a task reads another task's output without declaring the dependency. Fix the missing dependency declaration rather than disabling parallelism.
Daemon heap should be sized from observed usage, not guessed. Raise -Xmx until GC pauses stop dominating the build. Then check that the setting still fits on your smallest laptop and CI runner, since forked compiler and test JVMs need memory too.
Configuration cache fails fast and reports incompatible plugins. Each incompatible plugin has to be upgraded, replaced, or rewritten. Budget that work before you commit to enabling it.
How do you improve CI build speed and test time beyond bigger runners?
CI starts every run cold unless you persist two things between runs: the dependency cache and the build cache. Keep the checkout and setup steps stable too. A changing absolute path, a timestamp written into a resource, or a file regenerated on every run changes task inputs, and a cache hit becomes a miss.
Treat tests as build time. Put unit and integration tests in separate tasks so that fast feedback does not wait on containers or databases. Sort test reports by duration to find slow classes and tests that run serially. A test that reads the clock, the network or environment variables without declaring them as inputs cannot be cached safely.
| Option | Recurring cost | Helps local builds? | Main risk |
|---|---|---|---|
| Bigger runners | Paid on every run | No | Hides structural growth |
| Caching | Storage and setup effort | Yes, with a shared cache | Undeclared inputs |
| Affected-test selection | Keeping the dependency graph accurate | Partly | Missed tests |
| Sharding | More parallel jobs | No | Uneven shards |
Affected-test selection misses dependencies created by reflection, classpath scanning and shared configuration files. Keep running the full suite on the main branch as a backstop.
Illustrative estimate (assumed numbers, not a benchmark):
Hours saved per week = minutes saved per run × blocking runs per week ÷ 60
With an assumed 8 minutes saved per run and 300 runs per week that block a developer: 8 × 300 ÷ 60 = 40 hours per week.
To prevent regressions:
- Record baselines for configuration time, execution time and cache hit rate.
- Alert when any of them regresses sharply.
- Review new plugins, annotation processors and code generators before merging them. Each one can add configuration cost or break caching.
What are the alternatives to tuning the existing build?
Tuning the current Gradle build is usually the cheapest first step, but it is not the only option. Each alternative below trades build-time savings for a different kind of cost.
- Buy faster hardware and accept the structure. Faster laptops and larger CI runners need no code changes and give immediate relief to CPU-bound clean builds. They do nothing for repeated work. Configuration overhead, needless recompilation and uncached tests scale with the codebase, so the gain erodes as the monolith grows.
- Build less locally. Engineers can run only the tasks for the modules they are working on, such as
./gradlew :orders:testinstead of a fullbuild. Large repositories can also use Gradle composite builds (includeBuild) so that a developer works on a subset of the code. This is cheap to adopt but relies on CI to catch cross-module breakage. - Consume parts of the monolith as prebuilt binaries. Stable, rarely changed parts of the code can move into separately versioned libraries that are published to an artifact repository and consumed as ordinary dependencies. The build no longer compiles them. In exchange, you take on version management, a release process for each library and slower cross-cutting changes.
- Split the system into separately deployed services. This shrinks each build. It is an architectural decision with operational costs, including deployment, networking, observability and data ownership. Build time alone rarely justifies it.
- Migrate to a different build system. Some build systems are designed around hermetic, fine-grained targets with mandatory input declarations, remote caching and remote execution. They can scale further, but migrating a large monolith means rewriting the build definitions and retraining the team, and it often requires dedicated build engineering staff. Consider this only after measurement shows that the current tool, not the build's structure, is the limit.
When you compare these options, use the same baseline scenarios from the first section. An alternative is only better if it improves the scenarios your engineers actually wait on, such as the no-op build, the single-file change and the blocking CI run, at a cost the team can sustain.
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 speed up monolith build time, 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.