Skip to content
Latchkey

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

Run this faster and cheaper on Latchkey managed runners. Start free →