Caching dependencies
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every GitHub Actions run starts on a brand-new machine, so Maven downloads ShopLite's dependencies again and the same push takes minutes longer than on your laptop. How do you stop paying that cost on every run?
Why every run downloads the internet
The local repository is the folder ~/.m2/repository where Maven keeps every jar it has downloaded. On your laptop it fills once; on a hosted runner it starts empty every time.
This is what a run's log looks like with no cache: hundreds of download lines before the build even starts.
Run ./mvnw -B verify[INFO] Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/4.1.1/spring-boot-starter-parent-4.1.1.pom[INFO] Downloaded from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/4.1.1/spring-boot-starter-parent-4.1.1.pom (13 kB at 412 kB/s)... (about 700 more Downloading/Downloaded pairs) ...A hosted runner is thrown away after each job, so the next run downloads Spring Boot, Hibernate, Flyway, Testcontainers, the Maven plugins and their dependencies again: a few hundred MB and often two to four minutes.
Nothing about your code changed; the time is pure waiting.
setup-java's cache: maven
A cache key is the name a saved cache is stored under. If a saved cache has the same key, it is restored. setup-java builds the key from the operating system and a hash of every pom.xml.
cache: maven is one extra line on the setup-java step. It saves Maven's local repository after a run and restores it at the start of the next.
- uses: actions/setup-java@v5 with: distribution: temurin java-version: '25' cache: maven # restore ~/.m2/repository, save it after the jobExample 1 · When does the cache key change?
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.HexFormat;
public class CacheKeyDemo { static String key(String pomXml) throws NoSuchAlgorithmException { byte[] hash = MessageDigest.getInstance("SHA-256").digest(pomXml.getBytes(StandardCharsets.UTF_8)); return "Linux-maven-" + HexFormat.of().formatHex(hash).substring(0, 12); }
public static void main(String[] args) throws NoSuchAlgorithmException { String pom = "<artifactId>shoplite-api</artifactId><version>4.1.1</version>"; String samePom = "<artifactId>shoplite-api</artifactId><version>4.1.1</version>"; String newDependency = pom + "<dependency>testcontainers-mysql</dependency>";
System.out.println("monday push : " + key(pom)); System.out.println("tuesday, only src/ : " + key(samePom)); System.out.println("added a dependency : " + key(newDependency)); }}monday push : Linux-maven-917a64aa7481 tuesday, only src/ : Linux-maven-917a64aa7481 added a dependency : Linux-maven-13d544533c09
What this code does
- The key is a hash of
pom.xmlonly, so Tuesday's code changes give the same key and an exact cache hit. Adding a dependency changespom.xml, so the key changes and the cache is rebuilt once. - This is a model: GitHub's
hashFiles('**/pom.xml')hashes all pom files together, and setup-java adds its own prefix, but the rule is the same.
At the start of the job the cache is restored if one exists; after the job succeeds, a "Post" step saves it.
A hash is a short fingerprint of a file's content: the same content always gives the same hash, and any change gives a different one. So the key stays the same while your dependencies stay the same, however much code you change, and a new key appears as soon as you edit pom.xml.
Find the bug
Which key is wrong?
Tap the line with the bad cache key.
Runs are never faster. Which line is the problem?
Round 1 of 2actions/cache: key, restore-keys, hit and miss
restore-keys is a list of key prefixes. When no cache has the exact key, GitHub restores the newest cache whose key starts with one of the prefixes, which is called a partial hit.
These two examples use actions/cache by hand, then model the lookup that decides between an exact hit, a partial hit and a miss.
Example 2 · actions/cache by hand, and what the log says
Runs in: a GitHub repository with the shoplite-api project
- uses: actions/setup-java@v5 with: distribution: temurin java-version: '25'- name: Cache Maven repository id: m2 uses: actions/cache@v4 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven-- run: echo "exact cache hit? ${{ steps.m2.outputs.cache-hit }}"- run: ./mvnw -B verify(run 1: empty cache) Cache not found for input keys: Linux-maven-6f1c0d2e..., Linux-maven- ... Post Cache Maven repository Cache saved with key: Linux-maven-6f1c0d2e... (run 2: same pom.xml) Cache restored from key: Linux-maven-6f1c0d2e... exact cache hit? true Post Cache Maven repository Cache hit occurred on the primary key Linux-maven-6f1c0d2e..., not saving cache. (run 3: pom.xml changed) Cache restored from key: Linux-maven-6f1c0d2e... exact cache hit? false [INFO] Downloading from central: .../testcontainers-mysql-2.0.5.pom Cache saved with key: Linux-maven-b81e4a90...
What this code does
- Run 1 misses and saves; run 2 is an exact hit and saves nothing; run 3 has a new key, so
restore-keysfinds the newest cache starting withLinux-maven-(a partial hit,cache-hitisfalse), Maven downloads only the new jars, and a new cache is saved. - Use
cache: mavenon setup-java unless you need this extra control; do not use both for the same folder.
Example 3 · Exact hit, partial hit or miss: a model of the lookup
import java.util.List;
public class CacheLookupDemo { // Saved caches, newest first static List<String> saved = List.of("Linux-maven-b81e4a90", "Linux-maven-6f1c0d2e");
static String lookup(String key, String restorePrefix) { if (saved.contains(key)) { return "exact hit (" + key + "), nothing new to save"; } for (String s : saved) { if (s.startsWith(restorePrefix)) { return "partial hit (" + s + "), save new cache " + key; } } return "miss, download everything, save " + key; }
public static void main(String[] args) { System.out.println(lookup("Linux-maven-6f1c0d2e", "Linux-maven-")); System.out.println(lookup("Linux-maven-c0ffee12", "Linux-maven-")); System.out.println(lookup("macOS-maven-6f1c0d2e", "macOS-maven-")); }}exact hit (Linux-maven-6f1c0d2e), nothing new to save partial hit (Linux-maven-b81e4a90), save new cache Linux-maven-c0ffee12 miss, download everything, save macOS-maven-6f1c0d2e
What this code does
- A partial hit takes the newest cache with the prefix, here
b81e4a90, because the list is newest first. Most of its jars are still right, so only the difference is downloaded. - The macOS key starts differently, so Linux caches never match it: jars are the same, but some caches hold OS-specific files, which is why
runner.osis part of the key.
What each lookup result means:
- Exact hit: a cache with exactly
keyexists. It is restored,cache-hitistrue, and nothing is saved at the end. - Partial hit: the newest cache starting with a
restore-keysprefix is restored,cache-hitisfalse, and a fresh cache is saved under the newkey. - Miss: nothing matches. Everything is downloaded, and the cache is saved at the end.
Caches belong to a branch; a pull request can also read the caches of main. A repository keeps up to 10 GB of caches by default, and a cache unused for 7 days is deleted.
Predict the output
Hit, partial hit or miss?
Saved caches: Linux-maven-b81e (newest), Linux-maven-6f1c.
Round 1 of 3
The run asks for the key below. What happens?
Docker layer cache in CI: type=gha
type=gha is a Buildx cache backend that stores Docker image layers in the GitHub Actions cache, so a fresh runner can reuse layers built in an earlier run.
Here is the image build step with the layer cache switched on. The next lesson also pushes the image.
Example 4 · Image build with the GitHub Actions layer cache
Runs in: a GitHub repository with the shoplite-api project and its Dockerfile
- uses: docker/setup-buildx-action@v3 # BuildKit builder that can use type=gha- uses: docker/build-push-action@v6 with: context: . push: false # the next lesson pushes it tags: shoplite-api:ci cache-from: type=gha cache-to: type=gha,mode=max # also cache the Maven build stage(first build) #8 [build 4/6] RUN --mount=type=cache,target=/root/.m2 ./mvnw -B dependency:go-offline #8 DONE 96.4s #14 exporting cache to GitHub Actions Cache #14 DONE 11.2s (next build, only src/ changed) #5 importing cache manifest from gha:9154872460212345678 #8 [build 4/6] RUN --mount=type=cache,target=/root/.m2 ./mvnw -B dependency:go-offline #8 CACHED #10 [build 6/6] RUN ./mvnw -B package -DskipTests #10 DONE 31.7s
What this code does
- The second build reuses the dependency layer (
CACHED) and rebuilds only from the step where the source changed, exactly like layer caching on your laptop from the Dockerising module. mode=maxis what saves thebuildstage's layers; with the defaultmode=minonly the final image's layers would be cached and the slow Maven stage would run again.
A fresh runner has no Docker layer cache, so without this the dependency layer of ShopLite's multi-stage build is rebuilt every time. The action needs Buildx, set up first with docker/setup-buildx-action.
cache-from: type=gha reads the saved layers and cache-to: type=gha,mode=max writes them. mode=max also saves the layers of the build stage (the Maven stage), not only the final image's layers, which is what makes the next build fast.
Measuring the gain
Runner minutes are the time a hosted runner spends on your jobs. On private repositories they count against your plan, so a faster job saves money as well as waiting time.
Do not guess, measure. This program turns two run times from the Actions tab into the time saved per run and per month.
Example 5 · Run time before and after caching
public class CacheGainDemo { static int seconds(int min, int sec) { return min * 60 + sec; }
public static void main(String[] args) { int before = seconds(7, 48); // run with an empty cache int after = seconds(4, 12); // next run, exact cache hit int runsPerMonth = 300; // pushes and PR updates
int savedPerRun = before - after; System.out.printf("before: %d:%02d after: %d:%02d%n", before / 60, before % 60, after / 60, after % 60); System.out.printf("saved per run: %d s (%.0f%%)%n", savedPerRun, 100.0 * savedPerRun / before); System.out.printf("saved per month: %d runner minutes%n", savedPerRun * runsPerMonth / 60); }}before: 7:48 after: 4:12 saved per run: 216 s (46%) saved per month: 1080 runner minutes
What this code does
- The times are sample numbers for a Spring Boot project like ShopLite; read your own from the Actions tab. The rest of the 4:12 is compiling and the tests, which caching does not change.
- On private repositories runner minutes count against your plan, so caching saves money as well as waiting time.
Every run in the Actions tab shows its total time, and every step its own time. Compare one run with an empty cache (or a changed pom.xml) with the next run on the same code.
Only the download part shrinks; compile and test time stay. If a run is still slow with a cache hit, look at the tests next, for example how many Testcontainers start.
Next step
Check your understanding
12 quick questions