Build Cache
Want to learn the tips and tricks top engineering teams use to keep builds fast and performant?Register here for our Build Cache Training. |
The build cache feature described here is different from theAndroid plugin build cache. |
Overview
The Gradlebuild cache is a cache mechanism that aims to save time by reusing outputs produced by other builds.The build cache works by storing (locally or remotely) build outputs and allowing builds to fetch these outputs from the cache when it is determined that inputs have not changed, avoiding the expensive work of regenerating them.
A first feature using the build cache istask output caching.Essentially, task output caching leverages the same intelligence asup-to-date checks that Gradle uses to avoid work when a previous local build has already produced a set of task outputs.But instead of being limited to the previous build in the same workspace, task output caching allows Gradle to reuse task outputs from any earlier build in any location on the local machine.When using a shared build cache for task output caching this even works across developer machines and build agents.
Apart from tasks,artifact transforms can also leverage the build cache and re-use their outputs similarly to task output caching.
For a hands-on approach to learning how to use the build cache, start with reading through theuse cases for the build cache and the follow up sections.It covers the different scenarios that caching can improve and has detailed discussions of the different caveats you need to be aware of when enabling caching for a build. |
Enable the Build Cache
By default, the build cache is not enabled. You can enable the build cache in a couple of ways:
- Run with
--build-cache
on the command-line Gradle will use the build cache for this build only.
- Put
org.gradle.caching=true
in yourgradle.properties
Gradle will try to reuse outputs from previous builds for all builds, unless explicitly disabled with
--no-build-cache
.
When the build cache is enabled, it will store build outputs in the Gradle user home.For configuring this directory or different kinds of build caches seeConfigure the Build Cache.
Task Output Caching
Beyond incremental builds described inup-to-date checks, Gradle can save time by reusing outputs from previous executions of a task by matching inputs to the task.Task outputs can be reused between builds on one computer or even between builds running on different computers via a build cache.
We have focused on the use case where users have an organization-wide remote build cache that is populated regularly by continuous integration builds.Developers and other continuous integration agents should load cache entries from the remote build cache.We expect that developers will not be allowed to populate the remote build cache, and all continuous integration builds populate the build cache after running theclean
task.
For your build to play well with task output caching it must work well with theincremental build feature.For example, when running your build twice in a row all tasks with outputs should beUP-TO-DATE
.You cannot expect faster builds or correct builds when enabling task output caching when this prerequisite is not met.
Task output caching is automatically enabled when you enable the build cache, seeEnable the Build Cache.
What does it look like
Let us start with a project using the Java plugin which has a few Java source files. We run the build the first time.
> gradle --build-cache compileJava:compileJava:processResources:classes:jar:assembleBUILD SUCCESSFUL
We see the directory used by the local build cache in the output. Apart from that the build was the same as without the build cache.Let’s clean and run the build again.
> gradle clean:cleanBUILD SUCCESSFUL
> gradle --build-cache assemble:compileJava FROM-CACHE:processResources:classes:jar:assembleBUILD SUCCESSFUL
Now we see that, instead of executing the:compileJava
task, the outputs of the task have been loaded from the build cache.The other tasks have not been loaded from the build cache since they are not cacheable. This is due to:classes
and:assemble
beinglifecycle tasks and:processResources
and:jar
being Copy-like tasks which are not cacheable since it is generally faster to execute them.
Cacheable tasks
Since a task describes all of its inputs and outputs, Gradle can compute abuild cache key that uniquely defines the task’s outputs based on its inputs.That build cache key is used to request previous outputs from a build cache or store new outputs in the build cache.If the previous build outputs have been already stored in the cache by someone else, e.g. your continuous integration server or other developers, you can avoid executing most tasks locally.
The following inputs contribute to the build cache key for a task in the same way that they do forup-to-date checks:
The task type and its classpath
The names of the output properties
The names and values of properties annotated as described inthe section called "Custom task types"
The names and values of properties added by the DSL viaTaskInputs
The classpath of the Gradle distribution, buildSrc and plugins
The content of the build script when it affects execution of the task
Task types need to opt-in to task output caching using the@CacheableTask annotation.Note that@CacheableTask is not inherited by subclasses.Custom task types arenot cacheable by default.
Built-in cacheable tasks
Currently, the following built-in Gradle tasks are cacheable:
Java toolchain:JavaCompile,Javadoc
Groovy toolchain:GroovyCompile,Groovydoc
Scala toolchain:ScalaCompile,PlatformScalaCompile,ScalaDoc
Native toolchain:CppCompile,CCompile,SwiftCompile
Testing:Test
Code quality tasks:Checkstyle,CodeNarc,Pmd
JaCoCo:JacocoMerge,JacocoReport
Other tasks:AntlrTask,ValidatePlugins,WriteProperties
All other built-in tasks are currently not cacheable.
Third party plugins
There are third party plugins that work well with the build cache.The most prominent examples are theAndroid plugin 3.1+ and theKotlin plugin 1.2.21+.For other third party plugins, check their documentation to find out whether they support the build cache.
Declaring task inputs and outputs
It is very important that a cacheable task has a complete picture of its inputs and outputs, so that the results from one build can be safely re-used somewhere else.
Missing task inputs can cause incorrect cache hits, where different results are treated as identical because the same cache key is used by both executions.Missing task outputs can cause build failures if Gradle does not completely capture all outputs for a given task.Wrongly declared task inputs can lead to cache misses especially when containing volatile data or absolute paths.(Seethe section called "Task inputs and outputs" on what should be declared as inputs and outputs.)
The task path isnot an input to the build cache key.This means that tasks with different task paths can re-use each other’s outputs as long as Gradle determines that executing them yields the same result. |
In order to ensure that the inputs and outputs are properly declared use integration tests (for example using TestKit) to check that a task produces the same outputs for identical inputs and captures all output files for the task.We suggest adding tests to ensure that the task inputs are relocatable, i.e. that the task can be loaded from the cache into a different build directory (see@PathSensitive).
In order to handle volatile inputs for your tasks considerconfiguring input normalization.
Marking tasks as non-cacheable by default
There are certain tasks that don’t benefit from using the build cache.One example is a task that only moves data around the file system, like aCopy
task.You can signify that a task is not to be cached by adding the@DisableCachingByDefault
annotation to it.You can also give a human-readable reason for not caching the task by default.The annotation can be used on its own, or together with@CacheableTask
.
This annotation is only for documenting the reason behind not caching the task by default.Build logic can override this decision via the runtime API (see below). |
Enable caching of non-cacheable tasks
As we have seen, built-in tasks, or tasks provided by plugins, are cacheable if their class is annotated with theCacheable
annotation.But what if you want to make cacheable a task whose class is not cacheable?Let’s take a concrete example: your build script uses a genericNpmTask
task to create a JavaScript bundle by delegating to NPM (and runningnpm run bundle
).This process is similar to a complex compilation task, butNpmTask
is too generic to be cacheable by default: it just takes arguments and runs npm with those arguments.
The inputs and outputs of this task are simple to figure out.The inputs are the directory containing the JavaScript files, and the NPM configuration files.The output is the bundle file generated by this task.
Using annotations
We create a subclass of theNpmTask
and useannotations to declare the inputs and outputs.
When possible, it is better to use delegation instead of creating a subclass.That is the case for the built inJavaExec
,Exec
,Copy
andSync
tasks, which have a method onProject
to do the actual work.
If you’re a modern JavaScript developer, you know that bundling can be quite long, and is worth caching.To achieve that, we need to tell Gradle that it’s allowed to cache the output of that task, using the@CacheableTask annotation.
This is sufficient to make the task cacheable on your own machine.However, input files are identified by default by their absolute path.So if the cache needs to be shared between several developers or machines using different paths, that won’t work as expected.So we also need to set thepath sensitivity.In this case, the relative path of the input files can be used to identify them.
Note that it is possible to override property annotations from the base class by overriding the getter of the base class and annotating that method.
@CacheableTask(1)abstract class BundleTask extends NpmTask { @Override @Internal(2) ListProperty<String> getArgs() { super.getArgs() } @InputDirectory @SkipWhenEmpty @PathSensitive(PathSensitivity.RELATIVE)(3) abstract DirectoryProperty getScripts() @InputFiles @PathSensitive(PathSensitivity.RELATIVE)(4) abstract ConfigurableFileCollection getConfigFiles() @OutputFile abstract RegularFileProperty getBundle() BundleTask() { args.addAll("run", "bundle") bundle.set(project.layout.buildDirectory.file("bundle.js")) scripts.set(project.layout.projectDirectory.dir("scripts")) configFiles.from(project.layout.projectDirectory.file("package.json")) configFiles.from(project.layout.projectDirectory.file("package-lock.json")) }}tasks.register('bundle', BundleTask)
@CacheableTask(1)abstract class BundleTask : NpmTask() { @get:Internal(2) override val args get() = super.args @get:InputDirectory @get:SkipWhenEmpty @get:PathSensitive(PathSensitivity.RELATIVE)(3) abstract val scripts: DirectoryProperty @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE)(4) abstract val configFiles: ConfigurableFileCollection @get:OutputFile abstract val bundle: RegularFileProperty init { args.addAll("run", "bundle") bundle.set(project.layout.buildDirectory.file("bundle.js")) scripts.set(project.layout.projectDirectory.dir("scripts")) configFiles.from(project.layout.projectDirectory.file("package.json")) configFiles.from(project.layout.projectDirectory.file("package-lock.json")) }}tasks.register<BundleTask>("bundle")
(1) Add
@CacheableTask
to enable caching for the task.(2) Override the getter of a property of the base class to change the input annotation to
@Internal
.(3) (4) Declare the path sensitivity.
Using the runtime API
If for some reason you cannot create a new custom task class, it is also possible to make a task cacheable using theruntime API to declare the inputs and outputs.
For enabling caching for the task you need to use theTaskOutputs.cacheIf() method.
The declarations via the runtime API have the same effect as the annotations described above.Note that you cannot override file inputs and outputs via the runtime API.Input properties can be overridden by specifying the same property name.
tasks.register('bundle', NpmTask) { args = ['run', 'bundle'] outputs.cacheIf { true } inputs.dir(file("scripts")) .withPropertyName("scripts") .withPathSensitivity(PathSensitivity.RELATIVE) inputs.files("package.json", "package-lock.json") .withPropertyName("configFiles") .withPathSensitivity(PathSensitivity.RELATIVE) outputs.file("$buildDir/bundle.js") .withPropertyName("bundle")}
tasks.register<NpmTask>("bundle") { args.set(listOf("run", "bundle")) outputs.cacheIf { true } inputs.dir(file("scripts")) .withPropertyName("scripts") .withPathSensitivity(PathSensitivity.RELATIVE) inputs.files("package.json", "package-lock.json") .withPropertyName("configFiles") .withPathSensitivity(PathSensitivity.RELATIVE) outputs.file("$buildDir/bundle.js") .withPropertyName("bundle")}
Configure the Build Cache
You can configure the build cache by using theSettings.buildCache(org.gradle.api.Action) block insettings.gradle
.
Gradle supports alocal
and aremote
build cache that can be configured separately.When both build caches are enabled, Gradle tries to load build outputs from the local build cache first, and then tries the remote build cache if no build outputs are found.If outputs are found in the remote cache, they are also stored in the local cache, so next time they will be found locally.Gradle stores ("pushes") build outputs in any build cache that is enabled and hasBuildCache.isPush() set totrue
.
By default, the local build cache has push enabled, and the remote build cache has push disabled.
The local build cache is pre-configured to be aDirectoryBuildCache and enabled by default.The remote build cache can be configured by specifying the type of build cache to connect to (BuildCacheConfiguration.remote(java.lang.Class)).
Built-in local build cache
The built-in local build cache,DirectoryBuildCache, uses a directory to store build cache artifacts.By default, this directory resides in the Gradle user home directory, but its location is configurable.
Gradle will periodically clean-up the local cache directory by removing entries that have not been used recently to conserve disk space.
For more details on the configuration options refer to the DSL documentation ofDirectoryBuildCache.Here is an example of the configuration.
buildCache { local { directory = new File(rootDir, 'build-cache') removeUnusedEntriesAfterDays = 30 }}
buildCache { local { directory = File(rootDir, "build-cache") removeUnusedEntriesAfterDays = 30 }}
Remote HTTP build cache
Gradle has built-in support for connecting to a remote build cache backend via HTTP.For more details on what the protocol looks like seeHttpBuildCache.Note that by using the following configuration the local build cache will be used for storing build outputs while the local and the remote build cache will be used for retrieving build outputs.
buildCache { remote(HttpBuildCache) { url = 'https://example.com:8123/cache/' }}
buildCache { remote<HttpBuildCache> { url = uri("https://example.com:8123/cache/") }}
You can configure the credentials theHttpBuildCache uses to access the build cache server as shown in the following example.
buildCache { remote(HttpBuildCache) { url = 'https://example.com:8123/cache/' credentials { username = 'build-cache-user' password = 'some-complicated-password' } }}
buildCache { remote<HttpBuildCache> { url = uri("https://example.com:8123/cache/") credentials { username = "build-cache-user" password = "some-complicated-password" } }}
You may encounter problems with an untrusted SSL certificate when you try to use a build cache backend with an HTTPS URL.The ideal solution is for someone to add a valid SSL certificate to the build cache backend, but we recognize that you may not be able to do that.In that case, setHttpBuildCache.isAllowUntrustedServer() to This is a convenient workaround, but you shouldn’t use it as a long-term solution. |
buildCache { remote(HttpBuildCache) { url = 'https://example.com:8123/cache/' allowUntrustedServer = true }}
buildCache { remote<HttpBuildCache> { url = uri("https://example.com:8123/cache/") isAllowUntrustedServer = true }}
Configuration use cases
The recommended use case for the remote build cache is that your continuous integration server populates it from clean builds while developers only load from it.The configuration would then look as follows.
boolean isCiServer = System.getenv().containsKey("CI")buildCache { remote(HttpBuildCache) { url = 'https://example.com:8123/cache/' push = isCiServer }}
val isCiServer = System.getenv().containsKey("CI")buildCache { remote<HttpBuildCache> { url = uri("https://example.com:8123/cache/") isPush = isCiServer }}
It is also possible to configure the build cache from aninit script, which can be used from the command line, added to your Gradle user home or be a part of your custom Gradle distribution.
gradle.settingsEvaluated { settings -> settings.buildCache { // vvv Your custom configuration goes here remote(HttpBuildCache) { url = 'https://example.com:8123/cache/' } // ^^^ Your custom configuration goes here }}
gradle.settingsEvaluated { buildCache { // vvv Your custom configuration goes here remote<HttpBuildCache> { url = uri("https://example.com:8123/cache/") } // ^^^ Your custom configuration goes here }}
Build cache, composite builds andbuildSrc
Gradle’scomposite build feature allows including other complete Gradle builds into another.Such included builds will inherit the build cache configuration from the top level build, regardless of whether the included builds define build cache configuration themselves or not.
The build cache configuration present for any included build is effectively ignored, in favour of the top level build’s configuration.This also applies to anybuildSrc
projects of any included builds.
ThebuildSrc
directory is treated as anincluded build, and as such it inherits the build cache configuration from the top-level build.
How to set up an HTTP build cache backend
Gradle provides a Docker image for abuild cache node, which can connect with Gradle Enterprise for centralized management.The cache node can also be used without a Gradle Enterprise installation with restricted functionality.
Implement your own Build Cache
Using a different build cache backend to store build outputs (which is not covered by the built-in support for connecting to an HTTP backend) requires implementingyour own logic for connecting to your custom build cache backend.To this end, custom build cache types can be registered viaBuildCacheConfiguration.registerBuildCacheService(java.lang.Class, java.lang.Class).
Gradle Enterprise includes a high-performance, easy to install and operate, shared build cache backend.