Gradle build performance

Learn Android Gradle build performance: configuration cache, local and remote build cache, parallel execution, KSP over kapt, Build Scans and Build Analyzer. About 25 minutes.

Why it matters

  • In a large multi-module Android app, slow local builds and long CI pipelines cost every developer time on every change. Build speed is a team-wide productivity problem.
  • Senior engineers are expected to diagnose a slow Gradle build with evidence (Build Scans, Android Studio's Build Analyzer) instead of guessing.
  • Heavy work at configuration time (file IO, network calls, eager task creation) runs on every Gradle invocation, even ./gradlew help.
  • Interviewers test the Gradle build lifecycle, the difference between the build cache and the configuration cache, and why KSP beats kapt.

The simple explanation

  • A professional kitchen preparing a banquet.
  • Configuration is the chef reading every recipe and planning which dishes to cook.
  • The build cache is pre-cooked sauces in the fridge: if the ingredients are identical, reuse the sauce instead of cooking it again.
  • Parallel execution is several chefs cooking independent dishes at the same time.
  • The configuration cache is keeping the finished plan, so the next identical order skips reading the recipes again.

How do you speed up an Android Gradle build? Measure first, then attack the phase that is slow. A Gradle build has three phases: initialization (find the projects in settings.gradle.kts), configuration (run the build scripts and build the task graph) and execution (run the tasks that are needed).

Configuration phase. Build scripts and plugins run on every invocation. Avoid file IO, network calls or reading environment variables directly in a build script. Use the lazy task APIs (task configuration avoidance): tasks.register instead of tasks.create, and tasks.named(...) or configureEach instead of eagerly looking tasks up. A registered task is only created and configured when something needs it, for example when it is in the task graph. The configuration cache goes further: it stores the result of the configuration phase (the task graph) and, when nothing that affects configuration has changed, Gradle skips configuration entirely and goes straight to execution. Your build logic and plugins must be compatible with it.

Execution phase. Gradle skips a task that is up-to-date (same inputs and outputs as its last run in this workspace). The build cache goes further: it stores task outputs keyed by their inputs and reuses them across builds, branches and machines. Only cacheable tasks (with declared inputs and outputs) can use it.

FeatureLocal build cacheRemote build cache
Where outputs liveA directory on your machineA shared HTTP cache server (for example a Develocity build cache node)
Helps withSwitching branches, clean builds on the same machineReusing outputs that CI or teammates already built
Typical setupOn with org.gradle.caching=trueCI writes to it; developer machines usually only read

Parallel execution (org.gradle.parallel=true) lets Gradle run tasks from independent modules at the same time, so it pays off when the module graph is wide rather than one long chain.

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

Android-specific levers. Prefer KSP over kapt: kapt has to generate Java stubs from Kotlin sources before Java annotation processors can run, while KSP processors read Kotlin symbols directly. Non-transitive R classes (android.nonTransitiveRClass=true, the default since AGP 8.0) give each module an R class with only its own resources, which keeps R classes small and lets more resource changes avoid recompiling other modules. Use implementation instead of api where you can: it does not change the APK, but it means fewer modules recompile when a dependency changes.

Notes

  • Measure before optimizing. Run with --scan to publish a Gradle Build Scan, or open the Build Analyzer in Android Studio after a build to see which tasks and plugins dominate build time.
  • Task configuration avoidance: use tasks.register, tasks.named and configureEach. Avoid tasks.create, tasks.getByName and tasks.all, which create or configure tasks eagerly.
  • The configuration cache stores the task graph and skips the configuration phase when its inputs (build scripts, gradle.properties, environment variables and files read at configuration time) have not changed.
  • The build cache stores task outputs keyed by a hash of their inputs. The local cache helps on one machine; a remote cache shares outputs from CI with the team.
  • A custom task is only cacheable if it declares inputs (@Input, @InputFiles) and outputs (@OutputFile, @OutputDirectory) and is marked @CacheableTask.
  • A task with no declared outputs is never up-to-date, so it runs every time. A task with a missing input is worse: Gradle may wrongly reuse stale outputs.
  • Use @PathSensitive(PathSensitivity.RELATIVE) on file inputs so absolute paths do not end up in cache keys and CI outputs can be reused on developer machines.
  • Avoid volatile inputs such as System.currentTimeMillis() or the current Git commit in a version name for debug builds: they change every build and defeat both up-to-date checks and the build cache.
  • KSP is faster than kapt because it skips Java stub generation. Room, Hilt and Moshi all support KSP.
  • Non-transitive R classes are the default since AGP 8.0: each module's R contains only its own resources.
  • api vs implementation does not change APK size. It changes which modules can compile against a dependency and how many recompile when it changes.
  • Parallel execution helps most with a wide module graph. A long chain of modules that each depend on the previous one cannot be built in parallel.

Code example

This custom task is lazy, cacheable and configuration-cache friendly: it uses Property types, declares inputs and outputs, and is registered with tasks.register.

// build.gradle.kts of a module
@CacheableTask
abstract class GenerateBuildInfoTask : DefaultTask() {
    @get:Input
    abstract val versionName: Property<String>
 
    @get:OutputFile
    abstract val outputFile: RegularFileProperty
 
    @TaskAction
    fun generate() {
        outputFile.get().asFile.writeText("version=" + versionName.get())
    }
}
 
// BAD: eager. The task is created and configured on every build, even `./gradlew help`.
// tasks.create<GenerateBuildInfoTask>("generateBuildInfo") { ... }
 
// GOOD: lazy. The task is only created when something needs it.
tasks.register<GenerateBuildInfoTask>("generateBuildInfo") {
    versionName.set("1.4.0")
    outputFile.set(layout.buildDirectory.file("buildinfo/info.properties"))
}
  • tasks.register returns a TaskProvider; the configuration block only runs if the task is realized, for example because you ran ./gradlew generateBuildInfo.
  • @Input and @OutputFile let Gradle skip the task when it is up-to-date, and @CacheableTask lets it pull the output from the build cache.
  • Property<String> and RegularFileProperty are lazy values, which keeps the task compatible with the configuration cache.
  • layout.buildDirectory is used instead of a hard-coded absolute path, so the output location stays relative to the project.

Run the idea in plain Kotlin

class Task(val name: String) {
  fun run() {
      println("Running task: " + name)
  }
}

class TaskRegistry {
  private val factories = mutableMapOf<String, () -> Task>()
  private val created = mutableMapOf<String, Task>()

  fun register(name: String, factory: () -> Task) {
      println("Registered (not created): " + name)
      factories[name] = factory
  }

  private fun realize(name: String): Task? {
      val existing = created[name]
      if (existing != null) return existing
      val factory = factories[name] ?: return null
      println("Creating task: " + name)
      val task = factory()
      created[name] = task
      return task
  }

  fun run(name: String) {
      val task = realize(name)
      if (task == null) println("Task " + name + " not found") else task.run()
  }

  fun createdCount(): Int = created.size
}

fun main() {
  val registry = TaskRegistry()

  // Configuration phase: register three tasks lazily
  registry.register("compileKotlin") { Task("compileKotlin") }
  registry.register("lint") { Task("lint") }
  registry.register("generateBuildInfo") { Task("generateBuildInfo") }

  // Execution phase: only one task is requested
  println("--- Execution ---")
  registry.run("compileKotlin")
  println("Tasks created: " + registry.createdCount() + " of 3")
}

Expected output:

Registered (not created): compileKotlin
Registered (not created): lint
Registered (not created): generateBuildInfo
--- Execution ---
Creating task: compileKotlin
Running task: compileKotlin
Tasks created: 1 of 3

In production

Every Gradle command got slower
  • After a change to the root build script, even ./gradlew help took noticeably longer, on every machine and on CI.
  • A Build Scan showed the time in the configuration phase: the script called an internal HTTP endpoint at configuration time to fetch a version number, on every invocation.
The fix
  • Moved the network call into a task with a declared output file, so it only runs when the task is needed and its result can be cached.
  • Turned on the configuration cache so that, once the build logic was compatible, unchanged builds skip the configuration phase entirely.
  • Added a CI job that runs a no-op build with --configuration-cache and fails if the cache entry cannot be stored.
The build cache never hit
  • CI and local builds kept re-running a code generation task and everything downstream, even with the remote build cache enabled.
  • The Build Scan's build cache view showed the task's cache key changing on every build: it had an @Input set to System.currentTimeMillis().
The fix
  • Removed the timestamp input and derived the value from stable inputs (the version from the version catalog).
  • Compared two Build Scans with the scan comparison view to confirm the task's inputs were now identical between builds.

Common mistakes

  • Using tasks.create instead of tasks.register. Eager creation configures the task on every invocation, even when it never runs. Use the lazy APIs.
  • Doing IO in the configuration phase. Network calls and file reads in build scripts slow down every command and become configuration cache inputs. Move the work into tasks.
  • Keeping kapt for processors that support KSP. kapt generates Java stubs for Kotlin sources, which is extra work on every compile. Migrate Room, Hilt and Moshi to KSP.
  • Not declaring task inputs and outputs. A task with no outputs runs every time and is never cached; a task with a missing input can reuse stale outputs.
  • Absolute paths in task inputs. They put machine-specific paths into cache keys, so a cache entry produced on CI never matches a developer machine. Use relative path sensitivity.
  • Optimizing without measuring. Turning flags on blindly hides the real bottleneck. Compare Build Scans or Build Analyzer reports before and after each change.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between the build cache and the configuration cache?”

“How do you optimize a slow Android build?”

“What is task configuration avoidance?”

“Why is kapt slower than KSP?”

Quiz

Which Gradle API registers a task so it is only created when something needs it?

A custom task declares inputs but no outputs. What happens?

What does the configuration cache store?

Which build script code is incompatible with the configuration cache?

0 of 4 answered

Mini task

Task: find a configuration bottleneck

  1. Open a multi-module Android project.
  2. Run ./gradlew help --scan (help runs no real tasks, so almost all of its time is initialization and configuration).
  3. Accept the terms when asked, then open the Build Scan link.
  4. Open the Performance section and its Configuration tab, and sort scripts and plugins by configuration time.
  5. Run ./gradlew help --configuration-cache twice and compare the two runs: the second should report that the configuration cache entry was reused.
  6. In Android Studio, run a build and open Build Analyzer to see which tasks and plugins dominate execution time.
  7. Done condition: you can name the plugin or script that costs the most configuration time, and you have confirmed whether the configuration cache is reused on the second run.
Next: Convention plugins and version catalogs