Where does Gradle build time actually go in a large Java monolith?

Gradle runs every build in three phases, and each one costs time for a different reason.

  1. Initialization. Gradle evaluates the settings file and decides which projects are part of the build. In a monolith with hundreds of subprojects, this alone has a cost.
  2. Configuration. Gradle evaluates the build scripts and plugins and wires up the task graph. This runs on every invocation, including a no-op build where nothing has changed. Script logic that runs during configuration, such as resolving dependencies, shelling out to git, reading files or eagerly creating tasks, adds to every build.
  3. Execution. Gradle runs only the tasks it selected, and it tries hard to skip them.

For each task, the execution phase checks these in order:

  1. Up-to-date check. If the input and output fingerprints match the last run in this workspace, Gradle skips the task.
  2. Local build cache. Gradle computes a cache key from the inputs and restores the outputs if that key is in the local cache.
  3. Remote build cache. If the local cache misses, Gradle checks the shared cache.
  4. Run the task. If every lookup misses, Gradle executes the task and stores the outputs.

In a large monolith, most lost time comes from work that didn't need to happen: configuration repeated on every invocation, cache misses caused by unstable inputs, and recompiles that ripple through modules after a small change. Slow javac is rarely the main cost. The later sections cover the levers for each problem: the configuration cache, the build cache, incremental compilation and module structure.

Illustrative estimate (assumed numbers, not a benchmark). Use this formula:

daily cost = configuration seconds × invocations per engineer per day × engineers

With 15 s × 40 × 50, that is 30,000 s, or about 8.3 engineer-hours a day spent before any task runs.

+---------------------+   +---------------------+   +---------------------+
| 1. Initialization   |-->| 2. Configuration    |-->| 3. Execution        |
| settings file:      |   | build scripts and   |   | selected tasks only |
| which projects?     |   | plugins, task graph |   +----------+----------+
+---------------------+   | runs on EVERY build,|              |
                          | even no-op builds   |              | per task
                          +---------------------+              |
   +-----------------------------------------------------------+
   v
+-----------------------------+
| Up-to-date check            |
| inputs/outputs unchanged?   |--yes--> skip task (UP-TO-DATE)
+--------------+--------------+
               | no
               v
+-----------------------------+
| Local build cache hit?      |--yes--> restore outputs (FROM-CACHE)
+--------------+--------------+
               | no
               v
+-----------------------------+
| Remote build cache hit?     |--yes--> restore outputs (FROM-CACHE)
+--------------+--------------+
               | no
               v
+-----------------------------+
| Run the task, store outputs |
+-----------------------------+

Gradle runs initialization and configuration on every invocation, including no-op builds. In the execution phase, each selected task goes through the up-to-date check, then the local build cache, then the remote build cache, and runs only if all three miss.

How do you measure a baseline before changing anything?

Before changing any setting, measure the build you have. Run the build with --profile for a local HTML report, or with --scan to publish a build scan. Both separate the configuration phase, where Gradle evaluates build scripts and creates the task graph, from the execution phase, where tasks run. This split matters because each phase has different fixes. A slow configuration phase points to the configuration cache and to script hygiene. A slow execution phase points to caching, compilation and tests.

Measure three scenarios separately, because each one stresses a different part of the build:

Scenario How to produce it What it mostly reveals
Clean build Run clean followed by the build Total compile and test cost, and how much the build cache could save
No-op build Run the same task twice and time the second run Configuration overhead and up-to-date checking cost
Incremental edit Change a method body, or change a public method signature in a widely used module How far one change spreads through recompilation

Keep the two incremental edits as separate measurements. A change to a method body should stay local. A change to a public API can force recompilation across many dependent modules.

Run each scenario several times and discard the first run, because a cold daemon distorts it. Record the median. Repeat the same scenarios on representative machines, such as typical developer laptops and CI agents. A gain on one fast laptop, or on one kind of edit, may not carry over to other machines or edits.

This work pays off most for teams whose developer loops or CI queues are dominated by build time.

#!/usr/bin/env bash
# Baseline: time clean, no-op and two incremental-edit scenarios.
# Each --profile run writes an HTML report under build/reports/profile/
# that splits configuration time from task execution time.
set -euo pipefail
TASK=":app:assemble"   # placeholder: the task developers run most
BODY_FILE="core/src/main/java/com/example/core/PriceCalculator.java"
API_FILE="core/src/main/java/com/example/core/PricingService.java"
RUNS=5                  # the first run is discarded as daemon warm-up

timed() {  # print wall-clock milliseconds for one Gradle invocation
  local start=$(date +%s%N)
  ./gradlew "$@" --profile --quiet
  echo $(( ($(date +%s%N) - start) / 1000000 ))
}

scenario() {  # $1 = label, $2 = setup command run before each timed build
  local label=$1 setup=$2 times=()
  for i in $(seq 1 "$RUNS"); do
    eval "$setup"
    t=$(timed "$TASK")
    [ "$i" -gt 1 ] && times+=("$t")
    git checkout -- "$BODY_FILE" "$API_FILE"  # undo any edit
    ./gradlew "$TASK" --quiet                  # return to an up-to-date state
  done
  # median of the kept runs (RUNS-1 = 4 values; take the lower middle)
  median=$(printf '%s\n' "${times[@]}" | sort -n | sed -n "$(( ${#times[@]} / 2 ))p")
  echo "$label: runs=${times[*]} ms, median=${median} ms"
}

# Clean build: full compile and test cost (separate clean so it is not timed).
scenario "clean"      "./gradlew clean --quiet"
# No-op build: nothing changed, so this is configuration + up-to-date checks.
scenario "no-op"      "true"
# Method-body edit: the class ABI is unchanged, recompilation should stay local.
scenario "body-edit"  "sed -i 's/int retries = 3;/int retries = 4;/' $BODY_FILE"
# Public API edit: adding a public method changes the ABI of a widely used class.
scenario "api-edit"   "sed -i 's|^}\$|  public int baselineProbe() { return 0; }\n}|' $API_FILE"

A bash script that times clean, no-op, method-body and public-API-edit builds with --profile, discards the warm-up run and reports the median, so the same scenarios can be rerun on developer laptops and CI agents.

How do you enable the configuration cache and the build cache safely?

Start with the configuration cache, because it removes a cost every build pays. Set org.gradle.configuration-cache=true in gradle.properties. Gradle then serializes the task graph produced by the configuration phase. On the next run with the same build logic and inputs, it skips evaluating build scripts and plugins entirely. In a monolith with hundreds of tasks, that phase can take several seconds on every invocation.

When something is incompatible, Gradle writes an HTML problem report under build/reports/configuration-cache and prints its path. Group the entries by plugin or script location. Common causes in older or in-house build logic include:

  • Accessing project inside a task action
  • Reading environment variables or system properties directly instead of through providers
  • Relying on build listeners

Third-party plugins may need upgrades or replacements. Rewriting custom logic is real engineering work, so schedule it rather than treating it as a flag flip.

Next, set org.gradle.caching=true to enable the local build cache. Then add a remote HTTP cache in settings.gradle. Set push to true only when the build runs on CI, so developer machines read from the cache but never write to it. A developer's dirty working tree or unusual local environment could otherwise upload wrong outputs under a valid key, which poisons the cache for everyone.

To check hit rates, read the end-of-build summary, which counts tasks executed, up-to-date and from cache. Look for compileJava and test tasks that are marked FROM-CACHE. A remote cache is also a service: someone must handle its storage, eviction, access credentials and network security.

# --- gradle.properties ---
org.gradle.configuration-cache=true
org.gradle.caching=true

// --- settings.gradle ---
// CI sets CI=true; developer machines usually do not.
def isCi = System.getenv('CI') != null

buildCache {
    local {
        enabled = true
    }
    remote(HttpBuildCache) {
        url = ''
        // Only CI writes. Developers read, so a dirty local tree
        // cannot upload bad outputs under a valid cache key.
        push = isCi
        credentials {
            // Injected by CI or a developer's shell. Never commit them.
            username = System.getenv('GRADLE_CACHE_USER')
            password = System.getenv('GRADLE_CACHE_PASSWORD')
        }
    }
}

# --- checking hit rates from a shell ---
# Plain console prints one outcome per task, such as FROM-CACHE or UP-TO-DATE.
./gradlew clean compileJava test --console=plain | grep -E 'compileJava|:test'
# The last lines show the totals, for example:
#   N actionable tasks: X executed, Y from cache, Z up-to-date

This example enables the configuration cache and build cache in gradle.properties, sets up a remote HTTP cache in settings.gradle that only CI can write to, and runs a command that shows which compileJava and test tasks were loaded from the cache.

Why do cached builds still miss? Making task inputs and outputs deterministic

A task can be marked cacheable, hit the cache locally, and still miss on every CI agent. Gradle computes a cache key from the task's declared inputs, so anything that varies between machines or runs, such as a timestamp, a hostname, an absolute path, or file ordering, produces a new key. Nothing fails. The task just reruns, so the cache looks correctly configured while saving very little.

The damage spreads downstream. If a code generator writes // Generated at 2024-… into a source file, that file is a new input to compileJava, which then misses too, along with every task that consumes its output.

Declare inputs and outputs precisely

Custom tasks are not cached by default. Annotate the task class with @CacheableTask, mark properties with @Input, @InputFiles, @OutputDirectory and related annotations, and add @PathSensitive(PathSensitivity.RELATIVE) to file inputs. Without that, absolute paths can become part of the key, and a checkout in /home/alice will never match one in /builds/agent-7. Use @Classpath or @CompileClasspath for classpaths so Gradle applies normalization suited to them.

For generated files, drop the timestamps, sort collections before writing them, and write relative paths instead of absolute ones. If a file such as a build-info.properties has to change on every build, keep it out of the classpath hash with runtime classpath input normalization rules.

Audit checklist

  • Is the task annotated @CacheableTask, or explicitly marked cacheable?
  • Is every file the task reads declared as an input, and every file it writes declared as an output?
  • Do file inputs use relative path sensitivity?
  • Run the task twice from clean output directories. Are the outputs byte-identical?
  • Does --info explain why the task executed?
  • Are environment variables or system properties read without being declared as inputs?
import org.gradle.api.DefaultTask;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;

@CacheableTask // custom tasks are not cached unless you opt in
public abstract class GenerateSchemaRegistry extends DefaultTask {
    @Input // plain value, part of the cache key
    public abstract Property<String> getPackageName();

    @InputFiles
    @PathSensitive(PathSensitivity.RELATIVE) // ignore where the checkout lives
    public abstract ConfigurableFileCollection getSchemas();

    @OutputDirectory // everything written here is stored in and restored from the cache
    public abstract DirectoryProperty getOutputDir();

    @TaskAction
    public void generate() throws IOException {
        // Sort so file-system iteration order never changes the output bytes.
        List<String> names = new ArrayList<>();
        for (File f : getSchemas().getFiles()) names.add(f.getName()); // names only, no absolute paths
        Collections.sort(names);

        StringBuilder src = new StringBuilder();
        src.append("// Generated by GenerateSchemaRegistry. Do not edit.\n"); // no timestamp, no hostname
        src.append("package ").append(getPackageName().get()).append(";\n\n");
        src.append("public final class SchemaRegistry {\n    public static final String[] SCHEMAS = {\n");
        for (String n : names) src.append("        \"").append(n).append("\",\n");
        src.append("    };\n}\n");

        Path out = getOutputDir().get().file("SchemaRegistry.java").getAsFile().toPath();
        Files.createDirectories(out.getParent());
        Files.writeString(out, src.toString(), StandardCharsets.UTF_8); // fixed charset for identical bytes
    }
}

A cacheable custom code-generation task that declares its inputs and outputs, uses relative path sensitivity, and writes sorted, timestamp-free source so the same inputs produce byte-identical output on every machine.

How does incremental compilation work, and why do API changes cascade?

Gradle's Java compile task records which classes depend on which. When a source file changes, it recompiles that class plus the classes that reference it, not the whole source set. Across project boundaries, Gradle uses compile avoidance. A downstream module's compile task looks only at the ABI of its classpath: public and protected signatures, superclasses, and annotations. Method bodies and private members are not part of that ABI. If you change only the body of a method in core-domain, every module that depends on it stays up to date. If you rename a public method, add a parameter, or change a return type, every consumer's compile task becomes out of date. In a monolith where a shared module has dozens of dependents, one signature tweak can turn a 10-second rebuild into a multi-minute one.

Annotation processors that break incrementality

A processor must declare itself incremental (isolating or aggregating) for Gradle to keep compilation incremental. One undeclared processor on the annotation processor path forces a full recompile of that module on every change. Run a compile with --info and look for a message saying full recompilation is required because a processor is not incremental. That message names the culprit, so you can upgrade it, replace it, or move it into a smaller module.

Habits that keep edits non-ABI

  • Declare dependencies with implementation instead of api unless consumers truly need the type. This stops your module's dependencies from leaking into its consumers' ABI.
  • Keep shared modules' public surface small. Hide helpers behind private methods or internal classes.
  • Batch signature changes rather than editing them iteratively.

Illustrative estimate: assume 20 edit-compile cycles a day, with ABI changes in a shared module costing 3 minutes and body-only changes costing 15 seconds. Moving half of those edits to body-only saves roughly 25 minutes per engineer per day.

When should you split the monolith into more modules, and when should you avoid it?

Module boundaries determine how far an ABI change spreads, so they are the next lever after keeping edits body-only.

api versus implementation

In the java-library plugin, an api dependency is exposed on the compile classpath of every consumer. An implementation dependency is not. This matters because Gradle recompiles a consumer when the ABI of anything on its compile classpath changes. A module that declares its libraries as api therefore widens the rebuild set for every bump or edit. Prefer implementation unless the type actually appears in your public signatures.

Expect breakage when you switch. Downstream modules that compiled only because a class leaked through will fail. Fix each failure by having that module declare its own direct dependency rather than restoring api.

Breaking up god modules

A large common or core module that everything depends on turns every edit into a full rebuild. To shrink it:

  • Split it by rate of change: stable interfaces and value types in one module, volatile implementations in another.
  • Keep dependency edges pointing one way.
  • Resolve cycles by extracting the shared contract into its own module. Cycles between projects either fail the build or force workarounds that defeat isolation.

When not to split

Every module adds a build script, configuration work and dependency declarations to keep aligned. Split only where measured rebuild cost justifies that overhead.

Aspect Few large modules Many small modules
Rebuild blast radius Wide Narrow
Configuration overhead Low Higher
Dependency maintenance Simple More declarations to align
Parallelism opportunity Limited Greater
Refactoring across boundaries Easy Requires API changes

How should you tune parallelism, the daemon and tests without overloading machines?

Parallelism and memory are a single budget. Set org.gradle.parallel=true in gradle.properties so independent modules build concurrently. Gradle caps concurrent work with org.gradle.workers.max, which defaults to the number of CPU cores. That default is reasonable on a dedicated machine but too aggressive on a shared CI runner, where the visible core count may exceed the CPU quota the job actually gets.

Size the daemon heap through org.gradle.jvmargs (for example, -Xmx). Too small and the daemon spends time in garbage collection or fails with out-of-memory errors. Too large and it competes with everything else on the machine. The daemon heap is not the whole bill. Each test fork is a separate JVM with its own maxHeapSize, and forked compiler or worker processes add more. Total memory is roughly the daemon heap plus forks × fork heap plus process overhead. On a 16 GB laptop running an IDE, exceeding that total causes swapping, which is slower than running fewer forks.

For tests, a common starting point is maxParallelForks set to half of Runtime.getRuntime().availableProcessors(), with a floor of 1. Raise it only if CPU stays idle and memory has headroom.

Separate slow integration tests

Move database-backed and container-backed tests into their own source set with a dedicated integrationTest task. Do not wire that task into test, so local builds stay fast. Then make CI run it on every pull request as a required check. If the suite only runs nightly or gets skipped when it fails intermittently, regressions will reach main without anyone noticing.

What are the alternatives to tuning Gradle, and how do you prioritize the work?

Tuning Gradle is not the only option. Compare each alternative on what it costs and which part of the build it actually shortens.

Option Cost Effort Expected impact
Bigger machines or CI runners Ongoing spend Low Helps CPU-bound compile and test phases; does nothing for configuration time or unnecessary recompilation
Remote or distributed execution Infrastructure plus operations High Large gains only when task inputs are already deterministic, otherwise remote workers just rerun everything
Migrating to another build tool Months of engineering time Very high Uncertain; you rewrite build logic and plugins and inherit new failure modes
Accepting the status quo Developer wait time None Gets worse as the codebase grows

Better hardware hides waste instead of removing it. Remote execution and migration also depend on the hygiene work described earlier, so do that work first.

Prioritized order

  1. Configuration cache. It removes fixed overhead from every invocation, which is what the no-op baseline exposes.
  2. Deterministic inputs and the build cache. These turn clean CI builds into mostly cache hits.
  3. Narrower module APIs. This is the fix when the one-line implementation change still recompiles downstream modules.
  4. Parallelism and test tuning.
  5. Hardware. Buy it only for the CPU-bound work that remains after steps 1 to 4.

After each step, rerun the same baseline scenarios on the same machine type, using warm and cold runs. To estimate engineering time saved, multiply the change in median duration by how often each scenario happens per developer per day. For example, a 40-second drop on a scenario that runs 30 times a day saves about 20 minutes per developer per day (illustrative estimate). If the median does not move, revert the change or revisit it before starting the next step.

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 gradle build speed large project, 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.