Using Gradle Build Cache Server

Fastest way to work is to avoid doing work that doesn’t need to be done

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.

Since Gradle comes with built-in support for HTTP cache backend, this is really good for sharing results between CI builds. The build cache will end up bridging physical distance between computers, allowing results generated on one machine to be re-used by another. Using a shared HTTP build cache backend can significantly reduce the work CI agents need to do. This translates into faster builds, faster feedback for developers, and less money spent on the CI resources.

Preparations server side

Since gradle has a built-in support for HTTP cache backend, we’ll need an HTTP server that is capable of storing files uploaded via PUT requests. There’s a ready-to-use build cache node Docker container that you can fire up without hassle. It operates as an HTTP Gradle build cache, and it can be run via:

$ docker run --detach --publish 8885:80 gradle/build-cache-node

Now go to http://ip-of-the-server:8885/

Tap settings so you can set your username/password and disable the default user.

Enabling the Build Cache on the client side

By default, the build cache is disabled. You can enable the build cache in a couple of ways:

Run with --build-cache on the command-line

Or by adding this to your gradle.properties

org.gradle.caching=true

When the build cache is enabled, it will store build outputs in the Gradle user home.

Linking your app to the server

The recommended use case from the Gradle team for the build cache is that your continuous integration server populates the remote build cache with clean builds while developers pull from it and push to a local build cache. The configuration would then look as follows.

This should be added to your settings.gradle file

Results

Without server build cache:

❯ ./gradlew clean app:assembleDebug



BUILD SUCCESSFUL in 18s

31 actionable tasks: 30 executed, 1 up-to-date

With build cache server enabled:

❯ ./gradlew clean app:assembleDebug



BUILD SUCCESSFUL in 7s

31 actionable tasks: 11 executed, 19 from cache, 1 up-to-date

As you can see, using this project we went from 18 seconds for a clean build to 7 seconds, that’s a 250% gain in speed!

Thanks

… for getting this far! I would love to know what do you think and if you do something in a different way. Also it would be awesome if you click the little clap icon and share the article so more people would benefit from it.

If you are interested in more tech related topics, please check my other articles, follow me on Twitter or check my GitHub projects.

Sources