Sub topic 9
Giving each matrix job its own cache key
This chapter assumes you can read a workflow file and know how actions/cache builds keys with hashFiles. It also assumes you know how strategy.matrix expands into jobs. Here you combine the two so that each matrix job saves and restores the right cache.
The problem with one shared key
Take the cache step from a single-job workflow and put it in a matrix job without changing it:
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}The key does not mention the Node.js version. Three jobs that run on Ubuntu with Node 18, 20, and 22 all compute the same string. Three things go wrong:
- Only one job saves. Cache entries are immutable. When several jobs miss the same key, the first to finish saves it. The others log a warning such as "Unable to reserve cache with key ..., another job may be creating this cache" and save nothing.
- Jobs restore content built for another configuration. Whatever the winning job saved is what every later run restores. That is harmless for a download cache that holds only tarballs. It breaks
node_modulesdirectories, compiled native addons, and build output, which depend on the Node version. - You can't tell what is happening. The cache looks healthy because there are hits. The failures show up later as errors that are hard to trace.
The fix is to put every matrix value that changes the cached content into the key.
Add matrix values to the key
Inside a job, ${{ matrix.<name> }} holds the value for that job. You can use it in a key the same way you use runner.os. This is the spine's example in a complete workflow:
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node${{ matrix.node }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node${{ matrix.node }}-npm-
- run: npm ci
- run: npm testThis produces six jobs and six cache entries. One of the keys is Linux-node20-npm-3f2a..., where the trailing part is the lock file hash. Each entry is saved by exactly one job, and each job restores only its own.
Which values belong in the key
Include a value when it changes what ends up in the cached directory. Leave it out when it does not, because every extra value multiplies the number of entries.
| Matrix value | In the key? | Reason |
|---|---|---|
| Operating system | Yes | Paths, line endings, and native binaries differ. |
| Language version | Yes, for compiled or installed artifacts | Native addons and `node_modules` can depend on the runtime. |
| CPU architecture | Yes, if you mix x64 and ARM runners | Use `runner.arch`. |
| Lint-only flag or test shard number | Usually no | The dependencies are identical, so shards can share one entry. |
| `experimental: true` set through `include` | No | The flag changes which tests run, not what is installed. |
Sharing an entry across shards has a catch. Several shards will miss the same key at the same moment and race to save it. That is fine, because one wins and the content is identical. If you want to avoid the "unable to reserve" warnings, install dependencies in one earlier job. You can also restore the cache in the matrix jobs and save it only from a single job, as described in the chapter on splitting restore and save.
Use runner.os, not matrix.os
The matrix in the example has os: [ubuntu-latest, windows-latest]. The key uses runner.os, which is Linux or Windows. Either works, but runner.os is shorter and does not change when you rename a runner label.
A label like ubuntu-latest also moves to a new image over time. When it does, matrix.os stays the same string while the toolchain underneath changes. That is a reason to be careful with native build output. If you cache compiled artifacts, add a manual version prefix such as v1- to the key and bump it when you want to discard old entries.
Restore keys must carry the same prefix
restore-keys is a list of prefixes tried in order after an exact miss. The most recently created entry that matches a prefix is restored. If the prefix leaves out the matrix values, a miss on Node 22 can restore an entry that Node 18 saved:
# Too broad: any Linux npm cache can match
restore-keys: |
${{ runner.os }}-npm-
# Correct: only the same OS and Node version match
restore-keys: |
${{ runner.os }}-node${{ matrix.node }}-npm-A good rule is that each restore key is the main key with the trailing hash removed. A partial hit is then a cache from the same configuration with an older lock file. Only the changed packages need to be downloaded.
Handle include and exclude correctly
The key follows the matrix, so include and exclude need no extra work. Excluded combinations never run, so they never create entries. An include entry that adds a new variable only makes that variable available. It matters to the cache only if you put it in the key.
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
node: [18, 20, 22]
exclude:
- os: windows-latest
node: 18
include:
- os: ubuntu-latest
node: 22
experimental: trueThis produces five jobs, since six combinations minus one excluded gives five. The include entry matches the existing Ubuntu and Node 22 job, so it adds experimental to it instead of creating a sixth job. The key from the earlier workflow works unchanged.
Gotchas
Quote versions. YAML reads 3.10 as the number 3.1. A Python matrix of python: [3.9, 3.10] produces the key fragment python3.1, and setup-python installs the wrong version. Write ["3.9", "3.10"].
Key limits. A key can be at most 512 characters and cannot contain commas. Matrix values like ubuntu-latest are safe. A value you build from user input is not.
Windows paths. ~/.npm is the npm cache location on Linux and macOS. On Windows npm uses a directory under %LocalAppData%. A matrix that includes Windows may therefore save an empty or irrelevant path. Either use the cache: npm option of actions/setup-node, which asks npm for the right directory, or set the path from npm config get cache in an earlier step.
Cancelled jobs do not save. The save step runs after the job succeeds. With the default fail-fast: true, one failure cancels the other jobs, and those cancelled jobs never save their caches. Use fail-fast: false while you are warming new caches.
Storage use grows. A repository has a total cache limit of 10 GB by default, and old entries are evicted. A matrix with 12 jobs and a 500 MB cache each uses 6 GB per lock file version. Each lock file change adds a fresh set, so eviction can start discarding entries that are still useful. Keep the cached path small, and cache only what is expensive to rebuild.
Check that each job gets its own entry
Make the hit status visible in the job log. Give the cache step an id and read its cache-hit output, which is true only on an exact key match:
- id: npm-cache
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node${{ matrix.node }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node${{ matrix.node }}-npm-
- run: echo "exact hit = ${{ steps.npm-cache.outputs.cache-hit }}"On the first run every job prints an empty or false value, because nothing exists yet. Re-run the workflow and each of the six jobs should report true. If only some do, compare the keys in the "Post Run" step logs of the jobs that missed. Also look at the repository's Actions cache list, which shows one entry per key. You should see one entry per combination.
Exercise
A matrix has os: [ubuntu-latest, macos-latest] and python: ["3.11", "3.12"]. The cache step uses key: pip-${{ hashFiles('requirements.txt') }} and restore-keys: pip-. Name two problems this causes and write a corrected key and restore key.
Show answer
All four jobs compute the same key, so only the first to finish saves an entry and the others get a reserve warning. The jobs also restore content from other operating systems and Python versions, and the restore key pip- matches any of them. A corrected version is key: ${{ runner.os }}-py${{ matrix.python }}-pip-${{ hashFiles('requirements.txt') }} with restore-keys: ${{ runner.os }}-py${{ matrix.python }}-pip-. This creates four entries, one per job.
Exercise
Your workflow uses fail-fast: true (the default) with a matrix of six jobs. One job fails early and you notice that caches for the other jobs are never saved. Why, and what should you change?
Show answer
The cache save is a post step that runs only when the job succeeds. When fail-fast cancels the other jobs, they never reach it. Set fail-fast: false so the remaining jobs finish and save their entries.