Skip to content
Latchkey

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-keys prefix 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 test

Gotchas

  • 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

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