Sub topic 3
Caching with actions/cache
This chapter covers how the actions/cache action works: its inputs, its outputs, and when it saves. It assumes you can read a workflow file, know how jobs, steps, and runners relate, and have used a package manager such as npm or pip in CI. Key design, restore keys, and eviction get their own chapters. Here the focus is the action's mechanics and the mistakes people make when first adding it.
What the action does
actions/cache stores files from a runner in GitHub's cache storage and restores them in later runs. Runners are fresh virtual machines, so without a cache every run downloads every dependency again. The action fixes this with two phases from a single uses: line:
- Restore. When the step runs, the action looks up the cache entry named by
key. If it finds one, it unpacks the files to the paths you listed. - Save. After all other steps in the job finish, a hidden post step runs. If the restore was not an exact hit and the job succeeded, it packs the paths and uploads them under
key.
You do not write the save step. It is part of the action. This is why the cache step is usually placed before the install command and never after it.
A first workflow
This workflow caches npm's download cache. The key contains a hash of the lock file, so the cache changes whenever dependencies change.
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- 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 testOn the first run there is no entry, so the step reports a miss and npm ci downloads everything. When the job succeeds, the post step uploads ~/.npm. On the next run with the same lock file, the key matches exactly and the packages come from the cache.
Notice that the path is ~/.npm, not node_modules. npm ci deletes node_modules before it installs, so caching that folder would gain nothing. Cache the directory your package manager downloads into, and let the install command rebuild the project folder from it.
Inputs
| Input | Required | Purpose |
|---|---|---|
| `path` | Yes | One or more files or directories to save and restore. Accepts `~`, globs, and `!` exclusions, one per line. |
| `key` | Yes | The exact name of the cache entry to restore and later save. |
| `restore-keys` | No | Ordered prefixes to try if the exact key is missing. |
| `fail-on-cache-miss` | No | Fail the step if no entry is found. Useful when an earlier job was supposed to create it. |
| `lookup-only` | No | Check whether an entry exists without downloading it. |
| `enableCrossOsArchive` | No | Allow Windows and Linux or macOS runners to share an entry. |
Several paths go on separate lines:
path: |
~/.cache/pip
~/.cache/pre-commit
!~/.cache/pip/logEach cache entry holds one archive containing all the listed paths. Two unrelated tools can share one entry, but then a change to either tool's inputs invalidates both. Give each tool its own cache step when they change at different rates.
The cache-hit output
The step sets an output named cache-hit. It is the string 'true' only when the restored entry matched key exactly. It is 'false' when the entry came from a restore-keys prefix, and it is empty when nothing was found. Compare it as a string, and give the step an id so later steps can read it.
name: Python tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- id: pip-cache
uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
- name: Report cache result
run: echo "Exact hit: ${{ steps.pip-cache.outputs.cache-hit }}"
- run: pip install -r requirements.txt
- run: python -m pytestDo not skip the install command when cache-hit is 'true'. The cache holds downloaded packages, and the install step is still what puts them in place. Skipping the install is only safe if you cache the installed environment itself, which is more fragile because it ties the cache to a specific interpreter and operating system.
Rules that surprise people
Saves happen only on success. If any step fails, the post step does not upload. A job that fails every time before the tests, for example during a lint step, never populates the cache. Fix the failure first, or use the separate restore and save actions covered later in this tutorial.
Entries are immutable. Once a key exists, you cannot overwrite it. If you cache ~/.npm under a fixed key such as npm-cache, the first run saves and every later run restores the same stale content. The post step sees the existing key and does nothing. A key must change whenever the content should change, which is why the hash of the lock file belongs in it.
A hit on a prefix still saves. If the restore came from restore-keys, the exact key was not found. The job then saves a new entry under the full key, so the next run gets an exact hit.
Restore happens at the step's position. Files written by earlier steps are visible to the cache step, and the restore can overwrite them. Put the cache step after checkout and after any setup action that installs the language runtime, but before the install command.
Forks and pull requests have limits. A workflow can restore caches from its own branch and from the default branch, but not from sibling branches. Scope rules are covered in a later chapter. For now, expect the first run on a new branch to find the cache created on the default branch and not one from another feature branch.
Paths must exist at save time. If a listed path does not exist, the action prints a warning and may save an empty or partial archive. Check the path against your package manager's documentation. Common locations are ~/.npm for npm, ~/.cache/pip for pip, and ~/.cargo/registry plus ~/.cargo/git for Cargo.
Reading the log
A cold run typically shows a message that the cache was not found for the input key, and the post step later reports saving the cache. A warm run shows the cache restored from the key, and the post step reports that a cache hit occurred on the primary key and that it is not saving. If the post step keeps saving on every run, your key is changing every time. A frequent cause is hashFiles matching a file that changes during the job, or an expression that includes a timestamp or the commit SHA.
Choosing what to cache
Cache things that are expensive to fetch and cheap to store. Downloaded packages are the standard case. Compiled build output can also be cached, but it only helps if the key reflects every input to the build. Caching too much slows the job, since the archive must be downloaded and unpacked on each run. Measure the restore time in the log, and compare it with the time the install takes without a cache. If restoring takes longer than reinstalling, the cache is hurting.
Exercise
A workflow caches ~/.npm with the fixed key npm-cache. You add a new dependency and push. The install still downloads the new package on every run, and the cache never updates. Why, and how do you fix it?
Show answer
Cache entries are immutable. The key npm-cache already exists from the first successful run, so the post step finds it and skips the save. Later runs restore the old content, which lacks the new package. Fix it by putting a hash of the lock file in the key, for example ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}. The key then changes with the dependencies, and a new entry is saved.
Exercise
In the pip example, steps.pip-cache.outputs.cache-hit is an empty string. What does that tell you about the restore?
Show answer
Nothing was found, neither an exact match for the key nor any entry under a restore-keys prefix. The value 'true' means an exact match, and 'false' means the restore came from a prefix. After this run succeeds, the post step will save a new entry under the full key.