What actually makes monolith build time slow?

In a large Gradle/JVM monolith, faster hardware rarely fixes slow builds. Build time is mostly decided by the dependency graph, meaning how much work one change invalidates, and by cache correctness, meaning whether Gradle can safely skip work it has already done. If a single edit forces hundreds of modules to recompile, a faster CPU only shortens a wait that shouldn't happen at all. This matters most to backend and platform engineers who own the build. Slow builds lengthen the developer feedback loop, lengthen CI queues, and cost real engineering hours.

Illustrative estimate (assumed numbers, not a benchmark). Wasted hours per week = engineers × builds per day × minutes of avoidable wait × 5 ÷ 60. With 40 engineers, 10 builds per day and 3 avoidable minutes per build, that is 40 × 10 × 3 × 5 ÷ 60 = 100 hours per week.

Measure before you change anything. Break each build into phases, because each phase has different causes and different fixes:

Phase What dominates it Typical lever
Configuration Build script logic, plugin count, project count Configuration cache, simpler scripts
Compilation Invalidation across the module graph Module boundaries, incremental compilation
Tests Test count, isolation, forking Caching, parallel forks, test selection
Packaging Archive size, resource processing Avoid repackaging unchanged outputs

To get per-phase and per-task timings, use build scans or the HTML report produced by --profile. Don't trust a single timing, because it mixes warm and cold daemons, cache hits and machine noise. Record wall-clock time over many local and CI runs and watch the median and tail. The trend is what tells you whether a change helped.

#!/usr/bin/env bash
# Record wall-clock Gradle timings over many runs so decisions rest on trends, not one-off numbers.
set -euo pipefail

RUNS="${RUNS:-5}"          # repeat to smooth out daemon warm-up, cache state and machine noise
TASK="${TASK:-assemble}"    # the task developers or CI actually run
OUT="build-timings.csv"     # append-only history; compare medians across days and commits

[ -f "$OUT" ] || echo "timestamp,commit,label,seconds" > "$OUT"
COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo unknown)

time_it() {
  local label="$1"; shift
  local start end
  start=$(date +%s.%N)
  ./gradlew "$@" --quiet > /dev/null
  end=$(date +%s.%N)
  awk -v s="$start" -v e="$end" -v l="$label" -v c="$COMMIT" -v t="$(date -u +%FT%TZ)" \
    'BEGIN { printf "%s,%s,%s,%.2f\n", t, c, l, e - s }' >> "$OUT"
}

for _ in $(seq "$RUNS"); do
  time_it configuration help             # roughly the configuration phase: configures, does little work
  time_it planning "$TASK" --dry-run     # configuration + task graph, no task actions executed
  time_it full "$TASK" --profile         # full run; HTML report lands in build/reports/profile/
done

# Median and slowest run per label across all recorded history.
for label in configuration planning full; do
  awk -F, -v l="$label" '$3 == l { print $4 }' "$OUT" | sort -n | awk -v l="$label" '
    { v[NR] = $1 }
    END {
      if (NR == 0) exit
      m = (NR % 2) ? v[(NR + 1) / 2] : (v[NR / 2] + v[NR / 2 + 1]) / 2
      printf "%-14s runs=%-4d median=%.2fs max=%.2fs\n", l, NR, m, v[NR]
    }'
done

A shell script that times the configuration phase (help), task planning (--dry-run) and a full --profile build over repeated runs, appends each result to a CSV tagged with the commit, and reports the median and slowest run so you can follow trends instead of trusting a single timing.

How does incremental compilation work, and what defeats it?

Incremental compilation narrows a rebuild to the classes a change can affect. In Gradle's Java compilation, the compiler tracks which classes depend on which, so editing a method body recompiles that class and the classes that reference it. Across module boundaries, Gradle compares the ABI of a dependency: its public and protected signatures. If you change only implementation details, downstream modules skip compilation entirely. If you change the ABI, every consumer recompiles.

Three things commonly defeat this:

  • Edits to widely used public types. Adding a method to a shared base interface or changing a common DTO alters its ABI. Gradle has to recompile every class that references it, and in a monolith that can be most of the codebase. Keep hot shared types small and stable. Put churn behind implementation classes instead.
  • Non-incremental annotation processors. Gradle can only process incrementally if every processor on the path declares itself isolating or aggregating. One processor without that declaration forces a full recompile of the module. Check each processor's documentation for incremental support, and upgrade or replace the ones that lack it.
  • Generated code rewritten on every build. Generators that embed timestamps, use unordered iteration, or always rewrite their output produce files that look changed even when the logic is identical. Make generators deterministic and skip the write when the content is unchanged.

To find these cases, run the build with --info. When Gradle falls back to a full recompile, it logs that a full recompilation is required and states the reason.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public final class ErrorCodeGenerator {

    // Emits the same bytes for the same input, and leaves the file untouched when nothing changed.
    public static void generate(Map<String, Integer> codes, Path out) throws IOException {
        // TreeMap gives a stable, sorted order. HashMap iteration order is not guaranteed.
        Map<String, Integer> sorted = new TreeMap<>(codes);

        StringBuilder src = new StringBuilder();
        // No timestamp or build ID in the header. Those would make every build look like a source change.
        src.append("// Generated by ErrorCodeGenerator. Do not edit.\n");
        src.append("package com.example.errors;\n\n");
        src.append("public final class ErrorCodes {\n");
        for (Map.Entry<String, Integer> e : sorted.entrySet()) {
            src.append("    public static final int ")
               .append(e.getKey()).append(" = ").append(e.getValue()).append(";\n");
        }
        src.append("    private ErrorCodes() {}\n}\n");

        byte[] bytes = src.toString().getBytes(StandardCharsets.UTF_8);

        // Skip the write if the content is identical, so the file's timestamp also stays put.
        if (Files.exists(out) && Arrays.equals(Files.readAllBytes(out), bytes)) {
            return;
        }
        Files.createDirectories(out.getParent());
        Files.write(out, bytes);
    }
}

// To check whether a build still falls back to a full recompile:
//   ./gradlew :app:compileJava --info | grep -i "full recompilation"

A deterministic code generator that sorts its input, leaves out timestamps, and skips the write when the output is unchanged, so incremental compilation is not defeated; the trailing comment shows how to check Gradle's --info output for full recompiles.

How should you structure modules to minimise invalidation?

Module boundaries set the blast radius of a change. A compile task reruns when its own sources change or when the ABI (the public signatures, not the method bodies) of anything on its compile classpath changes. Large modules and widely shared modules make that classpath big and volatile.

Split large modules along change frequency. A module that mixes stable domain types with frequently edited service code makes every edit recompile all of it and re-check everything downstream. Pull the stable parts out so most edits land in leaf modules.

Use api versus implementation deliberately. In the java-library plugin, an implementation dependency is not exposed on consumers' compile classpath. Only api dependencies leak through. Declaring something as api without need means that an ABI change in it recompiles modules that never reference it directly.

Break up common and utils. These modules become hubs. One new public helper changes their ABI, and every module recompiles.

Hub-and-spoke                     Layered API / impl

 orders  billing  search          orders ──► billing-api ◄── billing-impl
    \      |      /                  │                         │
     ▼     ▼     ▼                   ▼                         ▼
       [ utils ]                  strings-util            money-util
  (any ABI change rebuilds all)   (an impl edit rebuilds only billing-impl)

Don't over-split. Each project adds configuration time, a build script to maintain, and another boundary for engineers to keep in mind. Hundreds of tiny modules can make the build slower overall. Split where your change history shows real churn, not by default.

// settings.gradle.kts
include("orders", "billing-api", "billing-impl", "strings-util", "money-util", "app")

// billing-api/build.gradle.kts
// Interfaces and DTOs only. Small, stable, and rarely edited.
plugins { `java-library` }

// billing-impl/build.gradle.kts
plugins { `java-library` }
dependencies {
    // Public classes here implement billing-api types, so consumers need it: api.
    api(project(":billing-api"))
    // money-util is only used inside method bodies. As implementation it stays
    // off consumers' compile classpath, so its ABI changes stop here.
    implementation(project(":money-util"))
}

// orders/build.gradle.kts
plugins { `java-library` }
dependencies {
    // Compile against the contract, not the implementation. Edits to
    // billing-impl (bodies or signatures) never recompile orders.
    implementation(project(":billing-api"))
    implementation(project(":strings-util"))
}

// app/build.gradle.kts
plugins { application }
dependencies {
    implementation(project(":orders"))
    // The implementation is wired in at runtime only. No module compiles
    // against it, so it is a leaf for compile invalidation.
    runtimeOnly(project(":billing-impl"))
}
application { mainClass.set("com.example.app.Main") }

Gradle Kotlin DSL build scripts for the layered split in the diagram: orders compiles only against billing-api, billing-impl keeps money-util as an implementation detail, and the app pulls billing-impl in with runtimeOnly so implementation edits do not recompile its consumers.

How does the Gradle build cache work, and when does it return wrong results?

The build cache stores task outputs under a key computed from the task's inputs: hashed file contents, input property values, and the task implementation's classpath. If the key matches, Gradle restores the outputs instead of running the task. The local cache lives on the machine. A remote cache shares results across developers and CI. Only cacheable tasks take part, such as those annotated @CacheableTask. Those tasks must declare every input and output, because Gradle hashes only what you declare.

Diagnosing misses

When two machines produce different keys for the same commit, the inputs differ. Run both builds with -Dorg.gradle.caching.debug=true and compare the input hashes each task logs. Common causes:

  • Absolute paths. A file input without @PathSensitive(RELATIVE) hashes the checkout location.
  • Timestamps. Build dates embedded in manifests or generated sources change on every run.
  • Environment. JDK vendor, locale, or environment variables read inside a task action.

When to limit it

Situation Remote cache?
Expensive compile on a fast network Yes
Cheap task, large output, slow link No, because downloading costs more than rebuilding
Undeclared inputs No. Fix the declarations first

An undeclared input is the dangerous case. The cache can then return stale outputs, and a wrong build is worse than a slow one.

Ownership

Give trusted CI builds on protected branches sole write access. Developers and fork pull requests should be read-only, so that untrusted code cannot poison entries. Set storage limits and an eviction policy, and assign an owner who is responsible for both.

// settings.gradle.kts (Kotlin DSL)
// Enable caching itself with org.gradle.caching=true in gradle.properties or --build-cache.

// Only the protected-branch CI job sets this variable. Developer machines
// and fork pull requests never have it, so they stay read-only.
val isTrustedCiWriter = System.getenv("GRADLE_CACHE_PUSH") == "true"

buildCache {
    local {
        // Per-machine cache; always useful, never shared.
        isEnabled = true
    }
    remote<HttpBuildCache> {
        url = uri("")
        // Everyone may read. Only trusted CI may write, which prevents
        // untrusted code from poisoning entries.
        isPush = isTrustedCiWriter
        credentials {
            // Injected as CI secrets. Fork PR jobs should not receive them.
            username = System.getenv("GRADLE_CACHE_USER") ?: ""
            password = System.getenv("GRADLE_CACHE_PASSWORD") ?: ""
        }
    }
}

// To diagnose a miss, run the same commit on two machines and diff the logged input hashes:
//   ./gradlew build --build-cache -Dorg.gradle.caching.debug=true
// Fix inputs before relying on the remote cache, for example:
//   @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE)
// This stops a task from hashing the absolute checkout path.

A settings.gradle.kts that uses a local cache everywhere and a remote HTTP cache. Only trusted protected-branch CI jobs can push to the remote cache, while developers and fork pull requests can only read, and the comments show how to debug cache misses.

Keeping the build warm and parallel: daemon, parallelism and configuration cache

Every Gradle invocation pays fixed costs before any task runs. It starts a JVM, loads and JIT-compiles the build logic, evaluates every project's build script and builds the task graph. In a monolith with hundreds of modules, that overhead can be a large share of a small incremental build.

The daemon removes most JVM startup and warm-up cost by keeping a long-lived process with loaded classes and in-memory caches. It is on by default locally. Give it enough heap through org.gradle.jvmargs so it is not slowed by garbage collection. org.gradle.parallel=true runs tasks from independent projects at the same time, which only helps if your module graph is wide rather than a long chain.

Configuration time grows with the number of projects, so keep it cheap. Build scripts should not run shell commands, read large files or resolve dependencies eagerly. That work belongs inside tasks, where it is skipped when the task is not requested. org.gradle.configuration-cache=true goes further: it serialises the task graph and reuses it when build inputs have not changed, skipping configuration entirely.

Both features have costs. Parallel execution exposes hidden shared state. Tests in different modules may bind the same port, write to a shared temp directory or use one database schema, and these failures look like flakiness. The configuration cache forbids build logic from accessing the Project object at execution time and reports undeclared inputs. Older plugins and custom build logic often violate these rules. In a large build, migrating can take weeks, so enable it with warnings first and fix the violations incrementally.

How can you improve CI speed for a monolith?

The highest-leverage CI change is making CI the only writer to the remote cache. CI agents start from clean, consistent environments, so the entries they produce are trustworthy. Developers then configure their builds to read from the cache but never push to it. This keeps one engineer's odd local JDK or stale generated file from poisoning everyone else's results.

Next, stop building everything on every commit. Diff the change set against the target branch, map changed files to modules, and walk the dependency graph upward to find every module that consumes them. Build and test only that set. When a selected suite still runs long, shard its test classes across several agents. Shard by historical duration rather than by class count, because one slow class can otherwise dominate a shard.

Tests are usually the real bottleneck, not compilation. Split them as follows:

  • Fast unit tests should run on every change. Keep these tasks cacheable by avoiding timestamps, random ports written to outputs, and undeclared environment reads.
  • Slow integration tests belong in a separate task that runs less often or in parallel.
  • Flaky or pathologically slow suites should be quarantined so they report results without blocking merges, then fixed or deleted.

Do not trust change-based selection on its own. It cannot see dependencies that run through reflection, classpath resources, or shared config files, so a change can break a module the graph says is unaffected. Run a full, uncached build on a schedule to catch those cases.

Faster CI may not improve the local edit-compile-test loop at all. Developers rarely hit cache entries for the code they are actively changing, so measure local build times separately from CI times.

What are the alternatives, and is the engineering cost worth it?

Treat local and CI build times as two separate targets when you compare the options below.

Approach What it reduces Main cost
Bigger CI hardware Wall-clock time for work that runs in parallel Ongoing spend; no help with serial chains
Build cache and incrementality Repeated work across builds Keeping tasks cacheable and correct
Module restructuring Fan-out of a typical change Refactoring time; risk of churn
Test selection and sharding Test time Dependency tracking; possible missed tests
Split repos or services Build scope per team Versioning, cross-repo changes, release coordination

Illustrative estimate (assumed numbers, not a benchmark). These figures assume serial execution, so divide by parallel workers for your own setup.

Expected build time = fan-out × [hit rate × download time + (1 − hit rate) × build time]

The assumed inputs are 40 s per module build and 3 s per cache download.

  • Fan-out 30, hit rate 60%: 30 × (1.8 + 16) = 534 s, about 9 minutes.
  • Fan-out 30, hit rate 90%: 30 × (2.7 + 4) = 201 s, about 3.4 minutes.
  • Fan-out 10, hit rate 60%: 10 × 17.8 = 178 s, about 3 minutes.

In this example, cutting fan-out from 30 to 10 saves about as much as raising the hit rate from 60% to 90%. Misses dominate the cost, so either lever helps. Plug in your own numbers before deciding which one is cheaper to move.

To prioritise, estimate the minutes saved per build and multiply by builds per week. Compare that against the engineering time needed to migrate and then maintain the change. Hardware and caching are usually cheapest to try first. Restructuring modules pays off when fan-out is high. Splitting the repository is the most expensive and the hardest to reverse, so treat it as an organisational decision, not a build-speed fix.

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 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.
  • 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.