Skip to content
Latchkey

How to Cache Dependencies Across Test Shards in CI

A lockfile-keyed cache lets every shard restore the same dependency store instead of reinstalling from scratch.

Key the cache on the lockfile hash so all shards share one entry. The first shard to finish install populates it and the rest hit it.

Workflow

.github/workflows/ci.yml
jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        shard: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/cache@v4
        with:
          path: ~/.npm
          key: npm-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            npm-
      - run: npm ci
      - run: npx jest --shard=${{ matrix.shard }}/4

Gotchas

  • All shards run concurrently, so most start before any of them has written the cache.
  • Cache the download store (~/.npm) not node_modules, which varies per platform.

Related guides

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