Sub topic 5
Falling back with restore-keys
This chapter assumes you can read a workflow file and have used actions/cache with a key built from hashFiles. It covers what happens when that exact key does not exist yet. A fallback list called restore-keys lets the job start from an older cache instead of from nothing.
The problem with exact keys
A key such as ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }} changes whenever the lock file changes. That is intended, because a new lock file means new dependencies. But adding one package to a project with 800 dependencies produces a new key. The key has no match, so the job downloads all 800 packages again.
That wastes work. Most of the old cache is still valid. restore-keys lets the job restore the closest older cache. The package manager then fetches only what is missing.
How restore-keys works
restore-keys is an optional input of actions/cache. It is a list of key prefixes, written one per line in a multi-line string.
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- id: cache
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
- run: npm ci
- run: npm testThe action looks for a cache in this order:
- It looks for an exact match on
key. - If there is none, it tries each entry in
restore-keysfrom top to bottom. An entry matches any cache whose key starts with that text. - If several caches match one prefix, it picks the most recently created one.
- If nothing matches, the step is a miss, and the job continues without a cache.
The first prefix that matches wins, even if a later prefix would match a newer cache. Order the list from most specific to least specific.
What happens after a partial match
A partial match does not replace the cache. Caches are immutable, so an existing key cannot be overwritten. The sequence is:
- The step restores the older cache, for example the one saved for the previous lock file.
npm ciruns and downloads only the packages that are not in the restored cache.- At the end of the job, a post step saves the
pathcontents under the new exactkey.
The next run with the same lock file gets an exact hit. The post step skips saving after an exact hit, because that key already exists.
This is why the fallback improves speed without extra effort. Each new lock file gets one slower run that starts from the previous state. Later runs are fast.
Writing good prefixes
The prefix is plain text matching from the start of the key. Two habits prevent most mistakes.
Keep the trailing separator. With the key linux-npm-<hash>, the prefix linux-npm- is clear. A prefix of linux-npm would also match a key like linux-npm2-<hash> from a different setup.
Put the parts that must not be mixed before the part that varies. The hash goes last. Anything that makes caches incompatible, such as the operating system or the language version, goes in the shared prefix.
You can list several fallbacks, from narrow to broad:
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
${{ runner.os }}-The second entry is rarely a good idea here. It would match any cache for that operating system, including caches for other tools. Use a broad prefix only when every cache under it is safe to reuse.
Which caches the lookup can see
The lookup searches caches in the scope of the current branch first. If it finds nothing, it searches the default branch. For pull requests, it also searches the base branch. A branch cannot read caches from sibling branches.
The same rule applies to partial matches. A feature branch with no caches of its own can restore the most recent matching cache from the default branch. Its first run is then fast. Its post step saves the new cache under the feature branch's scope. Chapter 11 covers scope and eviction in full.
Checking what was restored
cache-hit is 'true' only for an exact match on key. After a partial match it is 'false', and it can be empty when nothing was restored. A step that checks cache-hit therefore cannot tell a partial match from a miss.
To see which key was restored, read the cache-matched-key output. It holds the key of the cache that was restored, whether the match was exact or partial.
steps:
- uses: actions/checkout@v4
- id: cache
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
- name: Report cache result
run: |
echo "exact hit: '${{ steps.cache.outputs.cache-hit }}'"
echo "restored key: '${{ steps.cache.outputs.cache-matched-key }}'"
- run: npm ciRead the output this way:
| `cache-hit` | `cache-matched-key` | Meaning |
|---|---|---|
| `true` | Same as `key` | Exact hit. Nothing is saved at job end. |
| `false` | A key starting with a prefix | Partial hit. A new cache is saved under `key`. |
| empty | empty | Miss. A new cache is saved under `key`. |
When a partial match is risky
A partial match gives you the most recent cache with that prefix, not the best one. Whether that is safe depends on what you cache.
Package manager download caches are safe. npm, pip, and Cargo's registry cache are content-addressed or verified, so extra or outdated entries do no harm. They only cost disk space.
Build outputs are riskier. A cached node_modules directory or a target directory restored from an older state can contain files that do not match the current sources. If the build tool does not detect stale files, you can get a green build that tests the wrong thing. For those paths, either omit restore-keys or make sure your tool invalidates stale output.
Caches also grow. Each partial restore starts from the old contents, and the new cache adds to them. Entries that nothing uses anymore are never removed. If the cache size keeps rising, tighten the prefix, or add a version tag to it and change the tag to start fresh.
key: v2-${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
v2-${{ runner.os }}-npm-Changing v2 to v3 makes every old cache unreachable. The old entries then age out through eviction.
Common mistakes
- Writing a prefix that never matches. A prefix such as
npm-fails if every key begins withLinux-npm-. Compare the prefix with a real key from a previous run. - Putting the hash in the prefix. A prefix with
hashFiles(...)in it is just a second exact key. It cannot match older caches. - Expecting a newer cache from a later prefix. The first matching prefix wins, regardless of age.
- Reading
cache-hitas "something was restored". It is only true for an exact match. - Expecting the broad cache to update. The old cache stays as it is. Only the new key is added.
Exercise
Your key is Linux-pip-<hash of requirements.txt>, and restore-keys is Linux-pip-. You change one line in requirements.txt and push to a branch. The default branch has a cache from the old requirements file. (1) What does cache-hit print? (2) Is a cache saved at the end of the job? (3) What happens on the next push with the same requirements file?
Show answer
(1) false, because there is no exact match for the new hash. The step restores the default branch's cache through the Linux-pip- prefix, and cache-matched-key shows its key. (2) Yes. The post step saves the new contents under the new key, in the branch's scope, because that key did not exist. (3) The lookup finds an exact match. cache-hit is true and no save happens.
Exercise
A workflow lists these restore-keys: Linux-node- first, then Linux-node-20-. A cache named Linux-node-20-abc was created today, and Linux-node-18-xyz was created yesterday. Which cache is restored on a miss of the exact key, and how would you change the list to prefer the Node 20 cache?
Show answer
The first prefix, Linux-node-, matches both caches, and the action picks the newest one with that prefix, which is Linux-node-20-abc here. Had the Node 18 cache been newer, it would have been chosen, because the first matching prefix wins. To prefer Node 20, put the narrower prefix Linux-node-20- first, or remove the broad prefix entirely so a Node 18 cache can never be restored.