How to Split Cache Restore and Save in GitHub Actions
The restore and save sub-actions let you read a cache early and write it only after a step succeeds.
actions/cache/restore reads a cache without registering a save, and actions/cache/save writes one on demand. Splitting them lets you restore at the top, run a build, and save only when the build passes, or save under a fresh immutable key.
Steps
- Restore near the start with
actions/cache/restore. - Run the build or install.
- Save with
actions/cache/save, optionally only on success.
Workflow
.github/workflows/ci.yml
steps:
- id: restore
uses: actions/cache/restore@v4
with:
path: ~/.npm
key: npm-${{ hashFiles('package-lock.json') }}
- run: npm ci && npm run build
- if: always() && steps.restore.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: ~/.npm
key: npm-${{ hashFiles('package-lock.json') }}Gotchas
- A cache key is immutable once written; saving under an existing key is a no-op.
- Use a fresh key (or a run suffix) when you intend to overwrite content.
Related guides
How to Use the cache-hit Output to Skip Work in GitHub ActionsRead the cache-hit output of actions/cache in GitHub Actions to conditionally skip a rebuild or reinstall ste…
How to Save a Cache Only on the Default Branch in GitHub ActionsWrite caches only from default-branch runs in GitHub Actions using the save sub-action with an if on github.r…