DEV Community

Cover image for Your Gradle Build Is Redoing Work It Already Did
Android Expert
Android Expert

Posted on Originally published at Medium

Your Gradle Build Is Redoing Work It Already Did

A measured walk through the configuration cache, the build cache, and the module structure that keeps both honest.

Most slow Android builds are not slow because Gradle is slow. They are slow because Gradle is asked, again and again, to re-derive answers it already computed: the same task graph, the same compiled classes, the same generated sources. Three features exist to stop that waste: the configuration cache, the build cache, and a well-shaped module graph. Turning on the two caches takes one line each; the module graph is design work. Keeping all three working is the actual job.

1. Profile with Build Analyzer

profiling-loop

The profiling loop: baseline, open analyzer, read the report, change one thing, re-measure

Get a baseline you can trust

A single stopwatch run on a warm laptop is noise. Use gradle-profiler so every scenario gets warm-ups, repeated iterations and a median. A scenario file for the three situations that matter day to day:

# perf.scenarios
clean_assemble {
    tasks = [":app:assembleDebug"]
    cleanup-tasks = ["clean"]
    warm-ups = 2
    iterations = 5
}

leaf_edit {
    tasks = [":app:assembleDebug"]
    apply-non-abi-change-to = "feature/cart/src/main/kotlin/com/acme/shop/cart/CartViewModel.kt"
    warm-ups = 2
    iterations = 5
}

api_edit {
    tasks = [":app:assembleDebug"]
    apply-abi-change-to = "core/model/src/main/kotlin/com/acme/shop/model/Order.kt"
    warm-ups = 2
    iterations = 5
}
Enter fullscreen mode Exit fullscreen mode
gradle-profiler --benchmark --scenario-file perf.scenarios clean_assemble leaf_edit api_edit
Enter fullscreen mode Exit fullscreen mode

Record the medians somewhere permanent. They are the “before” column you will be glad to have.

Read the report like a build engineer

Run a normal build in Android Studio, then open the Build tool window and select the Build Analyzer tab. Three views carry most of the value:

  • Tasks determining build duration. This is the critical path: the chain of tasks that sets the wall-clock time. Making a task off the critical path faster changes nothing. Always start here.
  • Plugins. The cumulative cost per plugin, which quickly exposes the one that adds seconds to every module.
  • Warnings. Always-run tasks, non-incremental annotation processors, configuration cache problems, and heavy garbage collection (the usual sign that org.gradle.jvmargs needs a larger heap).

What the sample app’s report said, in order of pain:

  1. Configuration took about 14 seconds on a no-op build. Nothing had changed, yet Gradle re-ran every build.gradle.kts.
  2. kaptGenerateStubs and kapt tasks sat on the critical path of six modules.
  3. generateDebugBuildConfig re-ran on every build in three modules, with no source change to justify it.

Each finding maps to a section below. For a deeper, shareable view (including CI), add --scan and publish a build scan; --profile writes a lightweight HTML report to build/reports/profile if you can't publish anything.

Failure mode: profiling the wrong build. A report from a cold daemon includes JIT warm-up, dependency resolution and file-system cache fill. Profile the second or third build, and profile the scenario developers actually hit, not the one that makes the chart look best.

2. Fix cache misses

Two different caches, two different questions:

  • The configuration cache asks: can I skip configuring the project, because nothing that configuration depends on has changed?
  • The build cache asks: can I skip executing this task, because someone already ran it with identical inputs?

Start with the cheap one.

Configuration cache: turn it on, then make it stay on

# gradle.properties
org.gradle.configuration-cache=true
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.jvmargs=-Xmx4g -XX:+UseParallelGC

# While migrating, report problems instead of failing the build.
# Remove this line once the report is clean.
org.gradle.configuration-cache.problems=warn
Enter fullscreen mode Exit fullscreen mode

configuration-cache-lifecycle

Configuration cache lifecycle: a cache hit replaces the configuration phase with a quick load

Gradle prints a link to an HTML problem report at the end of any build that violated the rules. The two offenders you will meet most often:

Failure mode 1: reaching for project inside a task action.

// Rejected by the configuration cache: Task.project is unavailable at execution time.
tasks.register("printVersion") {
    doLast { println("Building ${project.version}") }
}
Enter fullscreen mode Exit fullscreen mode

The task must carry everything it needs as serializable state. Capture the value during configuration:

tasks.register("printVersion") {
    val version = project.version.toString()
    doLast { println("Building $version") }
}
Enter fullscreen mode Exit fullscreen mode

For anything beyond a throwaway task, declare a typed Property input (the cacheable task later in this section does exactly that).

Failure mode 2: a volatile value read during configuration. This one is quiet. The build works, but every CI run misses the cache.

// app/build.gradle.kts
// Changes on every pipeline run, so the configuration cache can never be reused.
android.defaultConfig {
    versionCode = System.getenv("CI_BUILD_NUMBER")?.toInt() ?: 1
}
Enter fullscreen mode Exit fullscreen mode

Gradle tracks environment variables read this way as inputs to the cache entry. A value that changes every build invalidates it every build. Keep pull-request and local builds on a constant, and inject the volatile value only on the pipeline that actually ships:

// app/build.gradle.kts (versionCode exists only on application modules)
val isReleasePipeline = providers.gradleProperty("releasePipeline").isPresent

android.defaultConfig {
    versionCode = if (isReleasePipeline) {
        // Fail loudly with a useful message instead of a bare NumberFormatException
        // when the variable is missing or empty.
        providers.environmentVariable("CI_BUILD_NUMBER").orNull?.toIntOrNull()
            ?: error("releasePipeline requires a numeric CI_BUILD_NUMBER")
    } else {
        1
    }
}
Enter fullscreen mode Exit fullscreen mode

Also expect problems from older third-party plugins. Check each plugin’s release notes for configuration cache support before blaming your own scripts.

Build cache: understand the key, then protect it

A cache hit requires an identical cache key, which is a hash over every declared input of the task.

cache-key-anatomy

Anatomy of a build cache key: stable inputs produce a hit, unstable inputs force a re-execute

Verify it works with a clean build run twice:

./gradlew clean :app:assembleDebug
./gradlew clean :app:assembleDebug --console=plain | grep FROM-CACHE
Enter fullscreen mode Exit fullscreen mode

The second run should show FROM-CACHE on the expensive cacheable tasks, such as Kotlin and Java compilation. Not everything will: the Android Gradle Plugin deliberately leaves some cheap or I/O-bound steps (certain merge and packaging tasks) uncacheable, so judge the result by the slow tasks on your critical path, not by a 100% hit rate. Slow cacheable tasks that still re-execute are your investigation list. To see why, run the task with --info and compare the cache keys between two runs or two machines, or open a build scan comparison. -Dorg.gradle.caching.debug=true prints the individual input hashes when the key alone doesn't tell you enough.

Failure mode 3: a timestamp baked into BuildConfig.

android.defaultConfig {
    buildConfigField("long", "BUILT_AT", "${System.currentTimeMillis()}L")
}
Enter fullscreen mode Exit fullscreen mode

This is a double bug. The generated class changes on every configuration, so generateDebugBuildConfig and everything compiled against it misses the cache. Worse, with the configuration cache on, the script doesn't even re-run, so the timestamp is frozen at whatever it was when the cache entry was stored, and the value in your app is silently wrong. Delete the constant and ask the platform at runtime:

fun Context.installedAtMillis(): Long {
    val info = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
    } else {
        @Suppress("DEPRECATION")
        packageManager.getPackageInfo(packageName, 0)
    }
    return info.lastUpdateTime
}
Enter fullscreen mode Exit fullscreen mode

(The two-argument getPackageInfo(String, Int) is deprecated from API 33, hence the guard.)

Failure mode 4: a custom task that isn’t cacheable, or is cacheable but sloppy. Here is a small task that generates a feature flag object from a properties file, written so that it caches correctly everywhere:

// build-logic/convention/src/main/kotlin/GenerateFeatureFlags.kt
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import java.util.Properties

@CacheableTask
abstract class GenerateFeatureFlags : DefaultTask() {

    // RELATIVE: the same file at /Users/ana/... and /home/ci/... hashes identically.
    @get:InputFile
    @get:PathSensitive(PathSensitivity.RELATIVE)
    abstract val flagsFile: RegularFileProperty

    @get:Input
    abstract val packageName: Property<String>

    @get:OutputDirectory
    abstract val outputDir: DirectoryProperty

    @TaskAction
    fun generate() {
        val flags = Properties().apply {
            flagsFile.get().asFile.inputStream().use(::load)
        }
        // sorted(): Properties iteration order is not guaranteed, and unstable output
        // would change the inputs of every compile task downstream.
        // uppercase() is locale-invariant, so a Turkish-locale machine generates the same names.
        val body = flags.stringPropertyNames().sorted().joinToString("\n") { name ->
            "    const val ${name.uppercase()} = ${flags.getProperty(name).toBoolean()}"
        }
        val pkg = packageName.get()
        val dir = outputDir.get().asFile.resolve(pkg.replace('.', '/')).also { it.mkdirs() }
        dir.resolve("FeatureFlags.kt").writeText(
            "package $pkg\n\nobject FeatureFlags {\n$body\n}\n"
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

The three habits worth copying: declare every input with a type, use PathSensitivity.RELATIVE for files, and make output deterministic. Wire it into the variant's sources with the lazy API so it never runs unless something needs it:

// feature-flags/build.gradle.kts
val generateFlags = tasks.register<GenerateFeatureFlags>("generateFeatureFlags") {
    flagsFile.set(layout.projectDirectory.file("flags.properties"))
    packageName.set("com.acme.shop.flags")
    outputDir.set(layout.buildDirectory.dir("generated/flags"))
}

androidComponents {
    onVariants { variant ->
        variant.sources.kotlin?.addGeneratedSourceDirectory(
            generateFlags,
            GenerateFeatureFlags::outputDir,
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

Failure mode 5: the cache works on your laptop and nowhere else. Cross-machine hits die for boring reasons: a different JDK, a different absolute path baked into an input, a different locale. Pin the JDK with a toolchain (shown in the next section) so the compiler is the same everywhere, and treat any task showing absolute paths in its --info inputs as a bug.

Failure mode 6: a poisoned remote cache. A remote cache shared by everyone is only as trustworthy as its least careful writer. Let CI populate it and give developers read-only access:

// settings.gradle.kts
buildCache {
    local { isEnabled = true }
    remote<HttpBuildCache> {
        url = uri("https://build-cache.example.com/cache/")
        isPush = providers.environmentVariable("CI").isPresent
        credentials {
            username = providers.environmentVariable("CACHE_USER").orNull
            password = providers.environmentVariable("CACHE_PASSWORD").orNull
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Finally, take the annotation-processor warning seriously. If Build Analyzer flags kapt on the critical path, migrating Room, Hilt or Moshi to KSP typically removes a stub-generation step per module and gives you processors designed for incremental builds.

3. Convention plugins

Every fix above is a build logic fix: a toolchain, a flag, a compiler option. If each of 38 modules carries its own copy, the fixes drift. One module keeps an old jvmTarget, another sets a different compileSdk, and the cache hit rate quietly erodes because inputs no longer match.

convention-plugins-layout

Convention plugins: shared build logic in one included build instead of repeated in every module

The layout

The files involved, relative to the repository root:

  • settings.gradle.kts registers the included build.
  • gradle/libs.versions.toml is the shared version catalog.
  • build-logic/settings.gradle.kts points the included build at that catalog.
  • build-logic/convention/build.gradle.kts declares the plugins.
  • build-logic/convention/src/main/kotlin/ holds AndroidLibraryConventionPlugin.kt, AndroidFeatureConventionPlugin.kt and GenerateFeatureFlags.kt.

Register the included build as a source of plugins:

// settings.gradle.kts
pluginManagement {
    includeBuild("build-logic")
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}
Enter fullscreen mode Exit fullscreen mode

Let build-logic read the same version catalog as the rest of the build:

// build-logic/settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
    versionCatalogs {
        create("libs") { from(files("../gradle/libs.versions.toml")) }
    }
}
rootProject.name = "build-logic"
include(":convention")
Enter fullscreen mode Exit fullscreen mode
# gradle/libs.versions.toml (excerpt)
[versions]
agp = "<your AGP version>"
kotlin = "<your Kotlin version>"
compileSdk = "35"
minSdk = "26"

[libraries]
android-gradlePlugin = { module = "com.android.tools.build:gradle", version.ref = "agp" }
kotlin-gradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
Enter fullscreen mode Exit fullscreen mode
// build-logic/convention/build.gradle.kts
plugins {
    `kotlin-dsl`
}

kotlin { jvmToolchain(17) }

dependencies {
    compileOnly(libs.android.gradlePlugin)
    compileOnly(libs.kotlin.gradlePlugin)
}

gradlePlugin {
    plugins {
        register("androidLibrary") {
            id = "acme.android.library"
            implementationClass = "AndroidLibraryConventionPlugin"
        }
        register("androidFeature") {
            id = "acme.android.feature"
            implementationClass = "AndroidFeatureConventionPlugin"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The plugins

// build-logic/convention/src/main/kotlin/AndroidLibraryConventionPlugin.kt
import com.android.build.api.dsl.LibraryExtension
import org.gradle.api.JavaVersion
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalog
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.getByType
import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension

internal val Project.libs: VersionCatalog
    get() = extensions.getByType<VersionCatalogsExtension>().named("libs")

internal fun VersionCatalog.intVersion(alias: String): Int =
    findVersion(alias).get().requiredVersion.toInt()

class AndroidLibraryConventionPlugin : Plugin<Project> {
    override fun apply(target: Project): Unit = with(target) {
        pluginManager.apply("com.android.library")
        pluginManager.apply("org.jetbrains.kotlin.android")

        extensions.configure<LibraryExtension> {
            compileSdk = libs.intVersion("compileSdk")
            defaultConfig.minSdk = libs.intVersion("minSdk")
            compileOptions {
                sourceCompatibility = JavaVersion.VERSION_17
                targetCompatibility = JavaVersion.VERSION_17
            }
        }

        extensions.configure<KotlinAndroidProjectExtension> {
            jvmToolchain(17) // one JDK everywhere keeps cache keys portable
            compilerOptions {
                allWarningsAsErrors.set(
                    providers.gradleProperty("warningsAsErrors").map(String::toBoolean).orElse(false)
                )
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

If your Android Gradle Plugin version bundles Kotlin support itself, remove only the pluginManager.apply("org.jetbrains.kotlin.android") line. Keep the Kotlin compiler settings (toolchain, compilerOptions), and check your AGP release notes for which kotlin extension type they now configure. Convention plugins turn this kind of migration into a one-file change instead of 38.

A feature plugin builds on the library plugin and encodes the architectural rule: features depend on core modules, never on each other.

// build-logic/convention/src/main/kotlin/AndroidFeatureConventionPlugin.kt
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.dependencies

class AndroidFeatureConventionPlugin : Plugin<Project> {
    override fun apply(target: Project): Unit = with(target) {
        pluginManager.apply("acme.android.library")

        dependencies {
            add("implementation", project(":core:model"))
            add("implementation", project(":core:ui"))
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

And a consuming module shrinks to what is actually unique about it:

// feature/cart/build.gradle.kts
plugins {
    id("acme.android.feature")
}

android {
    namespace = "com.acme.shop.feature.cart"
}
Enter fullscreen mode Exit fullscreen mode

Why this belongs in a build speed post

Convention plugins are not just tidiness. They are what keeps cache inputs identical across modules, and they give you one place to apply a speed fix to the whole build. Two more things make the module graph itself fast:

  • Keep the graph wide and shallow. Gradle parallelizes across modules, so a few deep chains serialize the build. A rule like “features never depend on features” gives you dozens of independent compile tasks that can run side by side.
  • Keep the public surface of core modules small. A change to a public signature recompiles every dependent module. Turning on explicit API mode for core libraries makes every public declaration a conscious decision, and implementation instead of api stops dependencies from leaking into consumers' compile classpaths.
// in a core-only convention plugin
extensions.configure<KotlinAndroidProjectExtension> { explicitApi() }
Enter fullscreen mode Exit fullscreen mode

Failure mode 7: the god module. If :core:common holds "everything shared", every edit in it invalidates everything. The tell in Build Analyzer is that a one-line change to a rarely touched file lights up compile tasks in nearly every module. Split it by reason to change: models, networking, UI components.

Failure mode 8: buildSrc as a dumping ground. A change inside buildSrc tends to invalidate far more of the build than a change inside an included build, because the whole build-script classpath is affected. An included build-logic keeps invalidation closer to the plugins that actually changed.

Failure mode 9: version conflicts on the plugin classpath. If build-logic declares AGP with implementation, you can get errors about the plugin being loaded more than once at different versions. Declare AGP and the Kotlin plugin as compileOnly, as above, so the version is supplied by the build that applies them.

4. Before/after times

before-after-times

Before and after times across five scenarios, on a log scale

Every row below was measured with the gradle-profiler scenarios from section 1: two warm-ups, five iterations, median reported, machine plugged in, other heavy apps closed.

  • Configuration phase, no-op build: 14.2s to 1.3s (10.9x). Pure configuration cache. This is the cheapest win in the post and the one every developer feels hundreds of times a day.
  • Clean assemble with a warm local cache: 9m 20s to 1m 40s (5.6x). The build cache restoring compile and other cacheable outputs, after the misses from section 2 were removed. The timestamp in BuildConfig alone had been dragging three modules and their dependents back into recompilation.
  • Edit one feature file: 1m 35s to 22s (4.3x). Configuration cache hit, KSP instead of kapt in the affected modules, and a wide module graph so unrelated modules stay UP-TO-DATE.
  • Edit a public API in :core:model: 3m 10s to 1m 05s (2.9x). The smallest gain, and the most honest one. An ABI change legitimately forces dependents to recompile. The improvement came from shrinking what :core:model exposes and who depends on it, not from a flag.
  • CI pull-request build: 16m 30s to 6m 10s (2.7x). Main-branch builds populate the remote cache, and pull requests read from it. Gains here depend heavily on how much of a PR is untouched code.

Notice the spread. Flags gave the largest multipliers; structure gave the most durable ones. The 2.9x on API edits is a reminder that no cache removes work that truly has to happen.

A checklist to take back to your own project

  1. Capture a gradle-profiler baseline for a clean build, a leaf edit and an API edit.
  2. Open Build Analyzer; write down the critical path and every warning.
  3. Enable the configuration cache with problems=warn; fix the report until it is clean, then remove warn.
  4. Enable the build cache; run a clean build twice and chase every task that is not FROM-CACHE.
  5. Remove volatile inputs: timestamps, absolute paths, unsorted output, per-build environment values.
  6. Pin the JDK with a toolchain; let CI be the only writer to the remote cache.
  7. Move shared build logic into build-logic convention plugins.
  8. Re-measure. Keep what moved the number; revert what didn’t.

Builds don’t get slow in one commit. They get slow one unstable input at a time. Measure them the same way: one change, one number.

📱 New to Jetpack Compose? Start Here

If you’re coming from the classic Android View system — XML layouts, findViewById, RecyclerView adapters — and want a clear, no-jargon path into Jetpack Compose, I recommend "Learning Jetpack Compose: Your Practical Guide from the Android View System to Modern Declarative UI." Every chapter starts from something you already know and shows its Compose equivalent side by side, building up to a full capstone: a real Notes app. Once you're comfortable and want to go deeper — the Composition tree, recomposition internals, the runtime itself — "Mastering Jetpack Compose Internals" is the natural next step.

Top comments (0)