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 }}/4Gotchas
- All shards run concurrently, so most start before any of them has written the cache.
- Cache the download store (
~/.npm) notnode_modules, which varies per platform.
Related guides
How to Weigh the Cost vs Time Tradeoff of More ShardsUnderstand why adding more test shards cuts wall-clock time but raises total CI minutes, since each shard rep…
How to Shard Tests With a Matrix in GitHub ActionsSplit a slow test suite into parallel shards in GitHub Actions with strategy.matrix, passing a shard index an…