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

Every Gradle invocation runs three phases. Initialization evaluates the settings file, decides which projects take part in the build, and sets up included builds. Configuration runs the build scripts of the participating projects, applies plugins, and builds the task graph for the tasks you requested. Execution runs those tasks: compilation, annotation processing, tests, packaging.

The phases fail in different ways. Execution cost grows with the amount of code that actually changed. Configuration cost grows with the number of projects, plugins, and build-script logic, and it is paid again on every invocation, even when nothing needs to run. In a large monolith, configuration can take several seconds before the first task starts. Engineers feel that delay on every edit-compile-test cycle.

To find out which phase dominates, use a build scan (--scan) or the --profile HTML report. Both show time per phase and per task. A single run tells you little because daemon warm-up and caches distort it. Instead, compare two kinds of repeated builds:

  • No-op build: run the same task twice. On the second run almost nothing should execute, so the remaining time is mostly initialization and configuration.
  • Small-change build: edit one class, rebuild, and repeat several times. This shows how far a local change spreads through compilation and tests.

The rest of the article follows that order. Measure first, make configuration cacheable next, and modularize last. Teams that gain the most have large monoliths, slow configuration, and developers who run frequent local edit-compile-test loops.

#!/usr/bin/env bash
# Repeated no-op and small-change builds, so one-off timing noise does not mislead you.
# Each --profile run writes an HTML report to build/reports/profile/
# with time per phase and per task. Add --scan for a build scan instead.
set -euo pipefail

TASK=":app:compileJava"   # placeholder: the task developers run most often
FILE="app/src/main/java/com/example/orders/OrderService.java"  # placeholder class
RUNS=5

# Warm-up: start the daemon and fill local caches. Do not count this run.
./gradlew "$TASK" --quiet

echo "== No-op builds: remaining time is mostly initialization + configuration =="
for i in $(seq 1 "$RUNS"); do
  time ./gradlew "$TASK" --profile --quiet
done

echo "== Small-change builds: how far one edit spreads =="
cp "$FILE" "$FILE.bak"
trap 'mv "$FILE.bak" "$FILE"' EXIT   # always restore the original source
for i in $(seq 1 "$RUNS"); do
  # Change the file contents, not just the timestamp:
  # Gradle detects changes by content, so 'touch' alone would be a no-op.
  echo "// measurement edit $i" >> "$FILE"
  time ./gradlew "$TASK" --profile --quiet
done

# Compare runs: if no-op builds are slow, configuration dominates.
# If small-change builds are slow, look at which compile and test tasks rerun.
ls -t build/reports/profile/ | head -n $((RUNS * 2))

A bash script that warms up the Gradle daemon, then times repeated no-op builds and small-change builds with --profile so you can tell whether configuration or execution dominates.

What is the Gradle configuration cache and when does it help?

…builds of the same few tasks.

The configuration cache stores the result of the configuration phase: the task graph Gradle computed for the tasks you requested, along with each task's configured state and inputs. On the next invocation with the same requested tasks, Gradle checks whether anything that fed configuration has changed. That includes build scripts, gradle.properties, files read during configuration, and environment variables or system properties the build accessed. If nothing has changed, Gradle loads the stored graph and skips configuration entirely, including evaluating every project's build script.

This pays off when configuration is slow and requests repeat. A developer running the same test task dozens of times a day pays configuration once instead of on every run. A clean CI agent starts with no stored entry, so it pays full configuration anyway. The configuration cache also does not skip task execution, so clean CI builds gain little unless a shared build cache supplies task outputs.

Technique What it saves When it works
Configuration cache The entire configuration phase Repeat invocations with unchanged inputs
Configuration avoidance Creating and configuring tasks that won't run Every build, including the first

Configuration avoidance is a separate technique. Declaring tasks with tasks.register instead of tasks.create, and avoiding eager calls like tasks.all or getByName, keeps unused tasks unrealized. That cuts configuration time before the cache ever hits.

Wait before enabling the cache if your build logic reads timestamps, git state, or environment variables at configuration time. Each changing value is a tracked input, so the cache invalidates on every run until you move those reads into task execution or make them stable.

// build.gradle.kts (Kotlin DSL)

// Eager: tasks.create("printBuildId") { ... } builds and configures the task
// on every invocation, even when it is not requested.

// Lazy: register() defers creation until the task is actually needed.
tasks.register("printBuildId") {
    // Avoid: val id = System.getenv("BUILD_ID") at this point.
    // Reading it during configuration makes BUILD_ID a cache input,
    // so every new CI build ID would invalidate the stored entry.
    val buildId = providers.environmentVariable("BUILD_ID").orElse("local")

    doLast {
        // Resolved at execution time, outside the configuration phase.
        println("Build ID: ${buildId.get()}")
    }
}

// Avoid: tasks.all { } and tasks.getByName("test") realize tasks eagerly.
// configureEach applies only to tasks that end up being realized.
tasks.withType<Test>().configureEach {
    maxParallelForks = 2
}

// Try it from the shell:
//   ./gradlew printBuildId --configuration-cache   # stores the entry
//   ./gradlew printBuildId --configuration-cache   # "Reusing configuration cache."
//   BUILD_ID=ci-1234 ./gradlew printBuildId --configuration-cache
//     # still reuses the entry: BUILD_ID is read only at execution time

A Kotlin DSL build script that uses tasks.register and configureEach for configuration avoidance and defers an environment variable read to execution time, so a changing BUILD_ID does not invalidate the configuration cache.

How do you enable the configuration cache and fix incompatibilities?

Run ./gradlew build --configuration-cache once to see where you stand. Then make it the default by setting org.gradle.configuration-cache=true in gradle.properties, so every developer and CI agent uses the same behaviour. When Gradle finds state it cannot serialize, or a read that would make a cached result wrong, it writes an HTML problems report under build/reports/configuration-cache. Treat each entry as a fix item. Entries name the problem and the script or plugin that caused it. Many of them trace back to one plugin or one shared script, so group them by source before you start.

Cause Before After
Project used at execution time project.copy {} or project.file() inside doLast Inject FileSystemOperations or ProjectLayout, or capture values during configuration
Undeclared system property, environment variable or file read System.getenv("X") at configuration time providers.environmentVariable("X") wired into a task input
Shared mutable state A static map or a rootProject.ext field written by tasks A shared build service registered with gradle.sharedServices
Eager task creation tasks.create tasks.register, with inputs declared as Property/Provider
Outdated plugin A plugin that reads Project internally An upgraded, patched or replaced plugin

These fixes have costs. Provider-style code is more verbose, and application developers often find lazy wiring unfamiliar, so review turnaround slows at first. An incompatible third-party plugin may keep you on org.gradle.configuration-cache.problems=warn for a while. The way out is to upgrade it, fork and patch it, or replace it, and a forked plugin has to be maintained for as long as you keep it.

// Before: doLast { project.copy { into(System.getenv("RELEASE_CHANNEL")) } }
// That reads Project at execution time and makes an undeclared env read.
// After: lazy inputs, an injected service, and a registered (not created) task.
public abstract class StageArtifacts extends DefaultTask {
    @Input // declared, so changing the variable invalidates the cache entry
    public abstract Property<String> getReleaseChannel();

    @InputDirectory
    public abstract DirectoryProperty getSourceDir();

    @OutputDirectory
    public abstract DirectoryProperty getStagingDir();

    @Inject // replaces project.copy {} inside the action
    protected abstract FileSystemOperations getFs();

    @TaskAction
    void stage() {
        String channel = getReleaseChannel().get();
        getFs().copy(spec -> {
            spec.from(getSourceDir());
            spec.into(getStagingDir().get().dir(channel));
        });
    }
}

public class StagingPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {
        // register() defers configuration until the task is needed
        project.getTasks().register("stageArtifacts", StageArtifacts.class, t -> {
            t.getReleaseChannel().set(project.getProviders()
                .environmentVariable("RELEASE_CHANNEL").orElse("dev"));
            t.getSourceDir().set(project.getLayout().getBuildDirectory().dir("libs"));
            t.getStagingDir().set(project.getLayout().getBuildDirectory().dir("staging"));
        });
    }
}

A task that is compatible with the configuration cache: it uses an injected FileSystemOperations instead of project.copy, declares the environment variable as a Provider-backed input, and is created lazily with tasks.register (imports from org.gradle.api. and javax.inject are omitted).*

Why does a multi-module Gradle layout speed up a large Java build?

A single-project build treats the whole codebase as one compilation unit. Changing one private method recompiles everything and reruns every test, because Gradle can't tell which parts of the output depend on that change. Splitting the code into modules gives Gradle that information.

Each module's compile task has its own inputs. When module A depends on module B, Gradle compares only B's ABI: public signatures, constants and annotations. Changes to method bodies or private members leave that ABI unchanged, so A's compileJava stays up to date. This is compile avoidance. Modules that don't depend on each other can also compile and test at the same time when org.gradle.parallel=true is set. A change also invalidates only the cache entries of the affected module and its real consumers, so more tasks hit the cache.

In the java-library plugin, api and implementation decide what a module exposes to its consumers:

Configuration On consumers' compile classpath Effect of a change in that dependency
api Yes Consumers recompile
implementation No (runtime only) Consumers usually stay up to date

Declaring everything as api is easy but leaks dependencies. Consumers start compiling against libraries they never declared, and every upgrade of those libraries spreads recompilation through the build. Being too strict has its own cost. Consumers must declare dependencies they use directly. When a type from an implementation dependency appears in a public signature, you have to promote it to api, which means frequent small build-file edits. A practical default is implementation, using api only for types that appear in your public signatures.

// settings.gradle.kts: one root, several small compilation units
rootProject.name = "shop"
include(":orders-model", ":orders-core", ":app")

// gradle.properties: build independent modules concurrently and reuse task outputs
// org.gradle.parallel=true
// org.gradle.caching=true

// orders-core/build.gradle.kts
plugins {
    `java-library`
}

dependencies {
    // Order and OrderId from :orders-model appear in OrderService's public
    // method signatures, so consumers need them on their compile classpath.
    api(project(":orders-model"))

    // Jackson is used only inside method bodies. It stays off consumers'
    // compile classpath, so upgrading it recompiles orders-core but not :app.
    implementation(libs.jackson.databind)
}

// app/build.gradle.kts
plugins {
    application
}

dependencies {
    // :app gets orders-model transitively through api. If :app used Jackson
    // directly, it would have to declare that dependency itself.
    implementation(project(":orders-core"))
}

// Editing a private method in orders-core leaves its ABI unchanged,
// so :app:compileJava stays UP-TO-DATE and only orders-core recompiles.

A three-module Kotlin DSL layout where orders-core uses api only for types that appear in its public signatures and implementation for internal libraries, so changes to implementation details don't trigger recompilation in :app.

How should you choose module boundaries in a Java monolith?

Start from the dependencies your packages already have. Run a package-level dependency analysis, or just grep imports, and look for clusters that depend on each other heavily but on the rest of the codebase only lightly. Those clusters are your candidate modules. Boundaries that match the existing structure only need build-file changes. Boundaries that cut through tightly coupled code turn into a refactoring project.

Extract stable, low-level code first: domain value types, serialization helpers, persistence abstractions. Many modules depend on these and they change rarely, so their outputs stay up to date and cached for most builds. Avoid a catch-all common module. Everything ends up depending on it, so any edit there invalidates almost the whole build and you lose the compile avoidance you split for.

Then look at the shape of the graph, not just the number of modules. If module A feeds B, B feeds C, and so on, the build has to run them one after another, and parallel execution cannot help. A wide, shallow graph lets independent modules compile at the same time.

When not to split, or to split less

Each project adds configuration work and its own task graph. Very fine-grained modules can cost more in configuration than they save in compilation. That overhead matters most when the configuration cache is missed. Granularity that is too fine also makes small changes span many build files.

If packages depend on each other in cycles, Gradle will reject any module split that keeps those cycles. You have to break them in code first. That work carries real risk, so plan it as its own project and do not mix it into a build-tooling change.

How do the build cache and convention plugins fit in?

The configuration cache removes the cost of configuring the build. It does nothing for tasks that still have to run. That part belongs to the build cache. When a task's inputs hash to a key Gradle has seen before, it restores the stored outputs and skips the task. The two caches have the same weak point: tasks must declare every input and output. If a task reads an undeclared file, it produces stale cache hits. If it embeds a timestamp or an absolute path, it produces constant misses.

A local build cache lives on one machine. It helps when you switch branches or run a clean build. A shared remote cache extends reuse across the team. The usual setup has CI populate the remote cache and developers only read from it. This keeps unverified local outputs out of the shared store. Because the key depends on inputs, a remote cache also exposes non-reproducible tasks quickly.

Keep build logic in convention plugins, either in buildSrc or in an included build. Avoid copied script blocks and allprojects/subprojects. Cross-project configuration lets one project change another's model. That coupling works against the configuration cache and blocks project isolation. Each module should apply the plugin it needs and nothing more.

Technique What it skips Depends on
Configuration cache Configuration phase Cacheable task graph, no build-time side effects
Build cache (local/remote) Task execution Accurate, reproducible task inputs and outputs
Multi-module layout Unaffected modules Acyclic, well-chosen boundaries
Convention plugins Duplicated, coupled build logic Project-local configuration only

How do you roll this out and know it saves engineering time?

Before changing anything, record three baselines on the same machine type and in CI. Run each several times and keep the median, because a single run is skewed by JIT warm-up and daemon state.

Baseline How to run it What it shows
Clean Fresh checkout, --no-build-cache, no daemon Worst case and CI cold-start cost
No-op Repeat the same task with nothing changed Configuration overhead, which the configuration cache targets
Small change Edit one method body in a leaf module The loop developers repeat all day

Change one thing at a time: the configuration cache, then module splits, then the build cache. If you change several at once and a build gets slower or breaks, you cannot tell which change caused it.

Trust the cache only after verifying it. A slow build wastes minutes. A stale cached result can ship a class that does not match its source. Schedule a periodic CI job that builds from clean with caching disabled and compares its outputs, such as class files, test results and generated resources, against a cached build of the same commit. Any difference points to an undeclared input and is a bug to fix before relying on the cache.

Illustrative estimate (assumed numbers, not a benchmark)

Annual hours saved = developers × small-change builds per day × seconds saved per build × working days ÷ 3600

Assume 60 developers, 25 builds a day, 40 seconds saved and 220 working days: 60 × 25 × 40 × 220 ÷ 3600 ≈ 3,670 hours a year.

Assumed cost: two engineers for eight weeks (640 hours) plus about 200 hours a year of upkeep, roughly 840 hours. On these assumptions the migration pays for itself in about three months. Replace each input with your measured baselines.

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 configuration cache, 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.