CI guide
GitHub Actions cache: how it works and how to keep it warm
How a cache key is matched, which branches can read which caches, why pull-request caches never warm the next pull request, and what to check when the cache stops hitting.
The GitHub Actions cache keeps files from one workflow run so a later run can restore them instead of rebuilding them: downloaded packages, compiler caches, build outputs. Restoring a warm cache is usually faster than reinstalling from the network, but only when the cache actually hits. Most cache problems are not about the YAML at all. They come from how keys are matched, which branch a cache belongs to, and how quickly GitHub evicts it.
This guide covers the cache as GitHub documents it today. Every limit quoted here is from GitHub's own documentation (linked under Sources); limits and prices change, so check the dependency caching reference before you plan around a number.
Cache or artifact?
Both store files outside the runner, and they are easy to confuse:
- Cache: files you want to reuse across runs to save time, such as
~/.npm,~/.cache/pipor a Gradle cache. A cache can be missing at any time and the job must still work without it. - Artifact: files a run produces that you want to keep or hand to another job, such as a test report, a coverage file or a built binary.
If a job breaks when the files are absent, they belong in an artifact (or in the job itself), not in the cache.
The quickest setup: let a setup-* action do it
For the common package managers, the official setup-* actions create and restore the dependency cache for you, keyed on a hash of the lockfile:
| Package managers | Action |
|---|---|
| npm, Yarn, pnpm | actions/setup-node |
| pip, pipenv, Poetry | actions/setup-python |
| Gradle, Maven | actions/setup-java |
| RubyGems | ruby/setup-ruby |
Go (go.sum) |
actions/setup-go |
| .NET NuGet | actions/setup-dotnet |
For a Node.js project:
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm test
Two details from the setup-node README are worth knowing. It caches npm's global package data, not node_modules, so npm ci still runs; it just downloads less. And since v6 it turns npm caching on by itself when package.json names npm in packageManager or devEngines.packageManager; set package-manager-cache: false in a privileged workflow that should not restore a cache. In a monorepo, point cache-dependency-path at the lockfile (or lockfiles) the key should hash.
Writing your own key with actions/cache
When no setup action covers what you want to keep (a build tool's cache, a downloaded toolchain, generated files), use actions/cache directly. It takes a path to cache, a key to save it under, and optional restore-keys to fall back on:
- name: Cache npm downloads
id: cache-npm
uses: actions/cache@v6
with:
path: ~/.npm
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
- name: Install
run: npm ci
The key changes whenever the lockfile does, so a dependency change gets a fresh cache. The restore key means a run with a new lockfile still starts from the most recent npm cache on that OS rather than from nothing.
A few rules shape every key you write:
- A cache can't be updated. Once a key exists, its contents are fixed. To store new contents you need a new key, which is why keys usually include a hash of the files that decide what is cached.
- Keys are at most 512 characters. A longer key fails the step.
- The
pathis part of the match. GitHub stamps each cache with a version made from its paths and the compression tool, which depends on the runner OS. The same key saved from a differentpath, or from Windows instead of Linux, is a different cache. - v5 and later need a recent runner. The README notes that
actions/cache@v5runs on Node.js 24 and needs Actions Runner 2.327.1 or newer, which matters on self-hosted runners.
How a key is matched
On restore, actions/cache looks in this order:
- An exact match for
keyin the current branch. - A prefix match for
keyin the current branch. - Each line of
restore-keys, in order, as an exact then a prefix match in the current branch. Where several caches share a prefix, the most recently created one wins. - The same search again in the default branch (and, for a pull request, in its base branch).
Only an exact match on key is a cache hit. The cache-hit output is 'true' then, and the action does not save at the end of the job, because that key already exists. A restore through restore-keys is a miss: cache-hit is not 'true', and if the job succeeds, a new cache is saved under key.
That is why you should not skip an install step just because something was restored. Gate it on the exact hit:
- name: Install
if: steps.cache-npm.outputs.cache-hit != 'true'
run: npm ci
Use this only when the cached path is the installed result itself (a vendor or virtualenv directory, say). When the cache holds downloads, as ~/.npm does, always run the install.
Restore and save as separate steps
actions/cache saves only when the job succeeds. The actions/cache/restore and actions/cache/save actions split the two halves so you choose when each happens:
- name: Restore build cache
id: restore
uses: actions/cache/restore@v6
with:
path: .build-cache
key: build-${{ runner.os }}-${{ github.sha }}
restore-keys: |
build-${{ runner.os }}-
- run: make build test
- name: Save build cache
if: always() && github.ref == 'refs/heads/main'
uses: actions/cache/save@v6
with:
path: .build-cache
key: ${{ steps.restore.outputs.cache-primary-key }}
This keeps a build cache from a failed run (so the next attempt starts warm) and saves only from main, so feature branches read the cache without each writing their own copy. Two more inputs help in the same spirit: lookup-only: true checks whether a cache exists without downloading it, and fail-on-cache-miss: true fails the job when a cache that must exist is missing.
Which runs can read which caches
Caches are scoped to a branch, and this is where most "the cache never hits" reports come from:
- A run can restore caches from its own branch and from the default branch.
- A pull-request run can also restore caches from its base branch.
- A run cannot restore caches from child or sibling branches, or from a different tag.
- A cache saved by a
pull_requestrun belongs to the merge ref,refs/pull/<number>/merge. Only re-runs of that same pull request can restore it. It never warmsmainor any other pull request.
So the cache every pull request depends on is the one on the default branch, and the only way to keep it current is a workflow that runs on push to that branch and saves. If your CI runs only on pull_request, every new pull request starts cold against a default-branch cache that may have been evicted days ago.
This matters more when coding agents open the pull requests. Many short-lived branches each save their own copies under merge refs, which nothing else can use, while all of them compete for the same repository storage as the default-branch cache they actually read from.
Limits and eviction
From GitHub's documentation at the time of writing:
- Caches not accessed in over 7 days are removed.
- A repository's caches share 10 GB by default. Repository administrators and organization or enterprise owners can raise the limit; storage above 10 GB is billed, and budgets set for Actions cache storage can put the cache into read-only mode when they run out. See GitHub's usage limits and eviction policy for current prices and settings.
- When the limit is reached, GitHub still saves the new cache, then evicts the least recently accessed caches until the total fits.
- Uploads are limited to 200 per minute and downloads to 1,500 per minute per repository.
When pull-request caches fill the quota, the default branch's caches can be evicted and recreated over and over ("cache thrashing"). GitHub's suggested remedy is to delete a pull request's caches when it closes:
name: Delete caches of closed pull requests
on:
pull_request:
types: [closed]
jobs:
cleanup:
runs-on: ubuntu-latest
permissions:
actions: write
steps:
- name: Delete caches
run: |
for id in $(gh cache list --ref "$BRANCH" --limit 100 --json id --jq '.[].id'); do
gh cache delete "$id" || true
done
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
BRANCH: refs/pull/${{ github.event.pull_request.number }}/merge
Clearing a cache
There are three ways to get rid of a cache that holds bad contents:
- In the browser: the repository's Actions tab, then Caches under "Management" in the sidebar. You can filter by branch or with
key: <name>, and delete an entry with its trash icon (this needs write access). - From the command line:
gh cache listandgh cache delete <id>, or the REST API's cache endpoints. - From the workflow: change the key, for example by adding a version prefix such as
v2-${{ runner.os }}-npm-…. Old entries stop matching and age out after seven days unused.
Cache poisoning and who may write
Cache contents are not signed or verified, and a restored cache can overwrite files a later step executes. GitHub's guidance:
- Never put secrets in a cached path. Anyone who can open a pull request can read the caches on its base branch, and forks can read the caches of the branch they target.
- Only trusted triggers write to the default branch's caches. Runs triggered by
push,workflow_dispatch,repository_dispatch,delete,registry_package,page_buildandschedulecan save there. Others that resolve to the default branch, includingpull_request_target,issue_commentandworkflow_run, get read-only access: their save is skipped with a warning and the job carries on. - Use
cache-modeto grant the least access a job needs. The workflow or job key takesread,write,write-onlyornone. Declaringwriteon a low-trust trigger switches the protection off, so do it only for jobs that never process untrusted input. In low-trust workflows,actions/cache/restoremakes a read-only intent explicit.
Docker layer caching
Docker Buildx can keep its layer cache in the same GitHub Actions cache with the gha backend. With docker/build-push-action the URL and token are filled in for you:
- uses: docker/setup-buildx-action@v4
- uses: docker/build-push-action@v7
with:
context: .
push: true
tags: <registry>/<image>:latest
cache-from: type=gha
cache-to: type=gha,mode=max
mode=max exports the layers of every stage rather than only the final image's. If one workflow builds several images, give each its own scope (for example type=gha,scope=api): the default scope is shared, so each build would otherwise overwrite the last one's cache. Layer caches are large, so they count heavily against the repository's limit; branch scope and the trigger rules above apply to them as well.
When the cache doesn't hit
| Symptom | Likely cause |
|---|---|
| Every pull request starts cold | No workflow saves on push to the default branch, or its cache was evicted after 7 days unused |
| A fallback restore every run, never an exact hit | The key includes something that changes every run (github.sha, a timestamp), so every run misses and saves another full copy; fine when intended, but it fills the quota fast |
| Same key, but no match | A different path or runner OS gives the cache a different version; the list-caches API shows each cache's version |
| Save step warns that writing was denied | The run has read-only cache access (a low-trust trigger or cache-mode: read) |
| Caches appear and vanish within hours | The repository is over its storage limit and evicting; check the Caches page and delete pull-request caches |
| Restore takes about as long as installing | The cache is too big or holds things that are quick to rebuild; cache less |
Measure before and after
A cache is worth what it saves on the runs that matter, and a hit rate alone doesn't tell you that. Compare the install and build step durations of runs that hit, runs that restored through a fallback, and runs that started cold, and look at the time from push to verdict rather than one step. Our piece on measuring commit-to-verdict time walks through separating queue wait from run time so you can tell which fix actually helped.


