How to Cache Dependencies Per Matrix Leg in GitHub Actions
Include a matrix value in the cache key so each leg gets an isolated store instead of legs overwriting each other.
Add the matrix dimension (and OS) to the actions/cache key. Distinct keys keep each leg cache separate, avoiding cross-version corruption.
Steps
- Add the matrix value and runner OS to the cache
key. - Add a matching
restore-keysprefix for partial hits. - Restore before install so each leg reuses its own store.
Workflow
.github/workflows/ci.yml
jobs:
test:
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node: [18, 20, 22]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
path: ~/.npm
key: npm-${{ matrix.os }}-node${{ matrix.node }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
npm-${{ matrix.os }}-node${{ matrix.node }}-
- run: npm ci && npm testGotchas
- Omitting the matrix value lets one leg restore another leg store and break the build.
- Caches are scoped per key and branch; a very wide matrix can approach the repository cache limit.
Related guides
How to Run a Matrix Across Node Versions in GitHub ActionsTest one job against several Node versions in parallel in GitHub Actions with a single-dimension strategy.mat…
How to Limit Concurrent Matrix Jobs With max-parallel in GitHub ActionsCap how many GitHub Actions matrix legs run at once with strategy.max-parallel, throttling a wide fan-out to…