GitHub Actions cache keys, restore-keys and scope explained
Build a cache key with hashFiles, fall back with restore-keys, and learn cache immutability, branch scope, who can write the cache and the 10 GB limit.
In this series26 guides, you're on Cache keys and scopes
Caching dependencies covers the basics of actions/cache, the built-in caching of the setup-* actions, and why caching matters. This article is the deep-dive companion: it explains how cache keys are actually constructed, how restore-keys fallback works, why caches are immutable, and the branch-scope and eviction rules that decide whether you get a hit or a miss. Get these right and your cache stops being a coin flip.
All examples use actions/cache@v6 and ubuntu-latest. (Inputs and outputs haven’t changed since v4: v5 moved to the Node.js 24 runtime, which needs Actions Runner 2.327.1 or later on self-hosted runners, and v6 moved to ESM. Upgrading is a version bump.)
Anatomy of a good cache key#
A cache key is just a string, but the way you build that string determines how often you hit, how often you miss, and whether you ever restore the wrong cache. A good key is composed of three parts:
- name: Cache npm uses: actions/cache@v6 with: path: ~/.npm key: ${{ runner.os }}-node24-${{ hashFiles('**/package-lock.json') }}Read the key left to right:
${{ runner.os }}— the runner’s operating system:Linux,WindowsormacOS. A cache built onLinuxis useless to aWindowsormacOSjob.runner.ossays nothing about the CPU, though, so an x64 job and an arm64 job compute the same key and restore each other’s caches. If you run on more than one architecture (for exampleubuntu-24.04andubuntu-24.04-arm), add${{ runner.arch }}too, since native modules compiled on x64 will not work on arm64.node24— the language/toolchain version. Dependencies resolved or compiled against Node 24 are not guaranteed to be valid for Node 22. Bake the version into the key so an upgrade naturally creates a fresh cache instead of restoring a stale, incompatible one.${{ hashFiles('**/package-lock.json') }}— a hash of the lockfile.hashFilesreturns a single SHA-256 derived from the contents of every matching file. When the lockfile changes (you added, removed, or bumped a dependency), the hash changes, so the key changes, so you get a new cache entry. When the lockfile is identical, the hash is identical and you get an exact hit.hashFilesonly sees files insideGITHUB_WORKSPACE, and when nothing matches (a typo in the pattern, a repository that usesyarn.lock, or a cache step that runs beforeactions/checkout), it returns an empty string. The key then silently becomes the constantLinux-node24-, which pins every later run to the first cache saved under it.
Each component answers a different question: which platform, which toolchain, which exact set of dependencies. Drop any one of them and you open the door to restoring a cache that does not match the job actually running. Whatever goes into it, a key can be at most 512 characters long and can’t contain a comma.
Cache immutability: keys are write-once#
This is the single most important mental model for caching, and the one people most often get wrong.
Once a cache is written under a given key, it is never overwritten. If a later run tries to save under a key that already exists, GitHub keeps the original entry and the step carries on without saving. After an exact hit, actions/cache doesn’t even try: it logs Cache hit occurred on the primary key …, not saving cache. A save that collides with an existing entry logs Failed to save: Unable to reserve cache with key …, another job may be creating this cache. There is no “update in place”. Keys are write-once per branch scope: the same key can exist once on your branch and once on main.
That is by design, and it works hand in hand with hashFiles:
- You bump a dependency, so
package-lock.jsonchanges. - The hash changes, so the key changes — say from
Linux-node24-abc123toLinux-node24-def456. - No cache exists for
def456yet, so the job builds fresh and saves a brand-new entry.
The old abc123 entry is untouched and still serves any run that still has the old lockfile. You are not “updating the cache”, you are accumulating immutable snapshots keyed by content. This is exactly what you want — but it also means your key must change whenever the cached contents should change. A key that never changes will pin you to the very first cache forever, even as your dependencies drift. To start over with a fresh cache, bump a version prefix you control (v2-${{ runner.os }}-node24-…) in the key and in its restore-keys, or delete the entry with gh cache delete <key>.
restore-keys: ordered prefix fallback#
If the exact key is not found, a fresh feature branch or a lockfile bump would normally mean a complete cache miss and a from-scratch install. restore-keys softens that by letting you fall back to an older but related cache and build incrementally on top of it.
- name: Cache npm uses: actions/cache@v6 with: path: ~/.npm key: ${{ runner.os }}-node24-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node24- ${{ runner.os }}-Here is what happens on a run:
- Exact-key lookup. The action first looks for a cache whose key matches
keyexactly. If found, that is a cache hit — it restores and is done. Because the contents match the lockfile hash, this is the ideal path. - Prefix fallback. If there is no exact match, the action looks for a cache key that starts with
key, then walksrestore-keystop to bottom and, for each one, looks for any cache key that starts with that prefix. The first match wins. If multiple caches share a prefix, the most recently created one is chosen. This is a partial restore: the step restores a cache, but not one saved under the exactkey. - Other scopes. Steps 1 and 2 search the run’s own branch first (for a pull request, its merge ref). Only if nothing matched there does the action repeat them on the other branches the run can read, such as the default branch.
- Total miss. If nothing matches anywhere, the step restores nothing and the path stays empty.
Every match also needs the same cache version, which records the path input and the compression tool: a restore whose path differs from the one the cache was saved with misses even when the key is identical.
Two things about partial restores trip people up:
- Ordering matters: most specific first. Put
${{ runner.os }}-node24-before${{ runner.os }}-so you prefer a cache built for the same Node version before falling back to “any cache for this OS”. The action stops at the first matching prefix, so a too-broad key listed first will shadow a better one below it. Scope comes before specificity, though: an oldLinux-node24-…entry on your branch wins over an exact match onmain. - A partial restore still re-saves under the new exact key. When the job ends successfully and the exact
keywas not the one that got restored,actions/cachesaves a new entry under the exactkey. So a lockfile bump restores last run’s~/.npmvia a restore-key,npm cionly downloads the few packages that changed, and a fresh, fully-up-to-date cache is written under the new hash. Next run gets a clean exact hit. (Thanks to immutability, the restored-from entry is left intact.)
Always set both key and restore-keys for dependency caches. key gives you precise invalidation; restore-keys gives you a warm start when the key inevitably changes.
Single-step vs. split restore/save#
actions/cache@v6 is the one-step form: it restores at the start of the job and automatically saves at the end (when the exact key was not already present). That is the right default for the common case.
Sometimes you want finer control over when the save happens. For that, actions/cache ships two sub-actions you can use separately:
actions/cache/restore@v6— restore only.actions/cache/save@v6— save only.
A classic use case: only write the cache from the default branch, so pull requests read the warm cache but never spend storage budget polluting it with short-lived, branch-specific entries.
jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7
- name: Restore npm cache id: cache uses: actions/cache/restore@v6 with: path: ~/.npm key: ${{ runner.os }}-node24-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node24-
- run: npm ci - run: npm test
- name: Save npm cache # Only save from the default branch, and only when there was no exact hit. if: github.ref == 'refs/heads/main' && steps.cache.outputs.cache-hit != 'true' uses: actions/cache/save@v6 with: path: ~/.npm key: ${{ steps.cache.outputs.cache-primary-key }}Another common pattern is saving even when the job fails — useful for expensive build caches you do not want to rebuild from zero just because tests went red. Wrap the save in if: ${{ !cancelled() }} rather than always(): it saves after a test failure but not after a cancel, when the upload would only delay the cancellation. A build cache keyed on the commit SHA never matches exactly on the next commit, so the restore step needs a restore-keys prefix to pick up the newest entry:
- name: Restore build cache id: build-cache uses: actions/cache/restore@v6 with: path: .build-cache key: ${{ runner.os }}-build-${{ github.sha }} restore-keys: | ${{ runner.os }}-build-
# ... build and test steps ...
- name: Save build cache # On main, even after a failed test, but not after a cancel or an exact hit. if: ${{ !cancelled() && github.ref == 'refs/heads/main' && steps.build-cache.outputs.cache-hit != 'true' }} uses: actions/cache/save@v6 with: path: .build-cache key: ${{ steps.build-cache.outputs.cache-primary-key }}The github.ref check keeps the saves on main: a per-commit key writes a new entry for every commit, and if every branch saved them, they would quickly fill the repository’s cache. The cache-hit check skips the save on a re-run of the same commit, whose key already exists.
Restore outputs#
actions/cache/restore sets three outputs, which later steps read through the step’s id (steps.cache.outputs.cache-hit):
cache-hit:'true'when an entry matchedkeyexactly,'false'on a partial restore, and empty on a miss. Test it with!= 'true'to run a step, such as an install or a save, whenever the cache wasn’t an exact match.cache-primary-key: the evaluatedkey. Pass it toactions/cache/save, as both examples above do, so the save uses the key the restore looked up even if a step rewrote a file thathashFilesreads.cache-matched-key: the key of the entry actually restored, which differs fromkeyon a partial restore and is empty on a miss.
The one-step actions/cache sets only cache-hit.
Cache scope: which branches can read which caches#
A cache miss on a brand-new feature branch is almost always a scope issue, not a key issue. GitHub deliberately isolates caches between branches for security, so a run can only read a limited set of caches:
- caches created on its own branch,
- caches created on the repository’s default branch (usually
main), and - for pull requests, caches created on the base branch (the branch the PR targets, including base branches in forks).
A run cannot restore caches from arbitrary sibling branches, child branches, or a different tag. Only a pull request run reads its base branch: a PR from feature-b into feature-a reads caches from main, feature-a and feature-b. A push to feature-b reads only feature-b and main, even if feature-b was created from feature-a: the branch you started from plays no part, only the PR’s target does. Two unrelated feature branches never see each other’s caches.
This is exactly why a fresh feature branch gets cold-cache misses until the default branch’s cache is warm: until main has run and populated its cache, there is nothing in scope for your new branch to fall back to. The practical fix is to make sure your caching workflow runs on main (on push or on a schedule) so every new branch inherits a warm baseline.
One sharp edge worth knowing for pull requests: a cache created during a PR-triggered run is written for the merge ref (refs/pull/.../merge), so it has a narrow scope — only later runs of the same pull request (re-runs and new pushes) can restore it. It is not visible to the base branch or to other PRs targeting the same base. So PRs happily read the base/default cache, but caches they write mostly benefit only themselves. This reinforces the “save on the default branch” pattern from earlier. If PR caches crowd out main’s, delete them when the PR closes: GitHub’s cleanup workflow ↗ lists them with gh cache list --ref refs/pull/<number>/merge and removes each one with gh cache delete.
Scope doesn’t keep a cache private, though: anyone who can open a pull request can read the base branch’s caches, so never cache tokens or credentials.
Who can write the cache#
Since June 2026, GitHub also decides who may write to the default branch’s cache, to stop cache poisoning: a low-trust run writes a malicious entry, and a later privileged run on main restores and executes it.
Only runs triggered by push, workflow_dispatch, repository_dispatch, schedule, delete, registry_package and page_build can create or overwrite caches in the default branch’s scope. Runs triggered by anything else that resolves to the default branch, such as pull_request_target, issue_comment, workflow_run and a merged pull request’s closed run, get read-only access: they can restore, and their saves fail with a warning while the job carries on. pull_request runs are unaffected, since they already write to their own merge-ref scope.
Since September 2026, you can also set the access yourself with the cache-mode key, at the workflow or job level:
cache-mode: read # read | write | write-only | none
jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/cache@v6 # restores, never saves under cache-mode: read with: path: ~/.npm key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}cache-mode | Restore | Save |
|---|---|---|
read | Yes | No |
write | Yes | Yes |
write-only | No | Yes |
none | No | No |
Leave it out and you get write on trusted triggers and read on low-trust ones. The runner exposes the effective value as ACTIONS_CACHE_MODE, and a cache step that the mode blocks doesn’t fail the job. As of November 2026, though, the actions/cache@v6 release doesn’t read the variable: it still attempts a save it isn’t allowed to make and logs the refusal as a warning (Failed to save: ... cache write denied: ...). The skip with an info line that GitHub’s docs describe isn’t released yet.
Declaring cache-mode: write (or write-only) on a pull_request_target or workflow_run workflow brings back exactly the cache-poisoning risk the default closes, so keep cache writes in a push workflow on main and use actions/cache/restore in low-trust workflows. cache-mode also caps reusable workflows, but only when the caller sets it: if the calling job neither sets nor inherits a cache-mode, a called workflow can ask for write even from a pull_request_target caller. Set cache-mode: read on jobs that call reusable workflows from low-trust triggers.
Limits and eviction#
GitHub gives each repository 10 GB of cache for free. Admins can raise the limit (up to 10 TB for a repository owned by a user; organizations and enterprises set their own maximum), and storage above 10 GB is billed. Raising the limit needs a payment method on file. Two things reclaim space:
- Over-limit eviction is LRU by last access. When total cache size exceeds the limit, GitHub deletes caches “in order of last access date, from oldest to most recent” until the total is back under the limit. The key word is access, not creation: a frequently-restored old cache survives, while a large cache nobody has touched in a while is the first to go. Writing a huge new cache can therefore silently evict useful older ones.
- Idle entries expire after 7 days by default. Since November 2025, admins can set a different retention, in days, next to the size limit. An entry not accessed within that window is removed, whatever the total size.
The combination is fine for small dependency caches but quietly hostile to busy monorepos: a few large Docker-layer or build caches across many branches blow past 10 GB fast, and you end up thrashing — evicting the very caches you were about to reuse, which produces cache misses, which produce slow builds. You can audit what is taking up space from the repository’s Actions → Caches page or via the gh cache list CLI.
Raising the limit is not free either: if the owner caps cache storage with a budget, going over that budget makes the cache read-only ↗ until billing is resolved or usage drops back under 10 GB. Restores keep working, but every save fails with Cache reservation failed: You have reached your configured budget, your cache is now read only to prevent additional charges.
As of November 2026, GitHub also limits each repository to 200 cache uploads, 1,500 cache downloads and 400 cache deletes a minute (each delete request, by key or by ID, counts). Above that, saves, restores and deletes fail until the limit resets.
Conclusion#
Effective caching comes down to two ideas: build keys that change exactly when the cached contents should change (OS/arch + toolchain version + lockfile hash), and understand the rules around them — immutability means keys are write-once, restore-keys give you warm partial restores that re-save under the fresh key, branch scope decides what is even visible, and the size limit and idle expiry (10 GB and 7 days by default) decide what survives. Get those right and your cache becomes a reliable speed-up instead of a mystery. For Docker images, see Docker layer caching; to hand files to later jobs, use artifacts.
On RunsOn#
RunsOn’s Magic Cache stores the entries of actions/cache and the setup-* actions in an S3 bucket in your AWS account. Keys, restore-keys and branch scope work as described above, but three rules change:
- There is no 10 GB cap and no budget lockout.
- Each entry expires after the stack’s retention window, 10 days by default, counted from its save: restores don’t extend it.
- Saving under a key that already exists replaces the entry instead of being skipped: the last save wins.
Magic Cache is opt-in: on Flex, add extras=s3-cache to the job label and run runs-on/action@v2 before the cache step; on Fleet, the platform team enables the s3-cache extra in the runner definition.
jobs: build: runs-on: runs-on=${{ github.run_id }}/runner=2cpu-linux-x64/extras=s3-cache steps: - uses: runs-on/action@v2 - uses: actions/checkout@v7