Tune CI Cache Hit Rate
A cache that never hits is pure overhead: upload time, storage cost, and no speedup. Key on inputs, measure the hit rate, and evict what the cache cannot reuse.
Procedure
- Measure before changing anything. From the last 50 runs, count hits:
gh run list --limit 50 --json conclusion,displayTitleplus each job's log lineCache restored from key/Cache not found. - Key the cache on the lockfile hash, not the branch:
key: npm-${{ runner.os }}-${{ hashFiles('**/package-lock.json') }} - Add a
restore-keysfallback so a near-miss still seeds the cache:restore-keys: npm-${{ runner.os }}- - Cache the right directory. Node:
~/.npm(download cache) notnode_modules(platform-specific). Python:~/.cache/pip. Cargo:~/.cargo/registryand~/.cargo/git, nottarget/. Go:~/go/pkg/mod. - Split immutable from mutable: cache the registry/download layer permanently, and the build output with a per-target key that includes the compiler version.
- For monorepos, use the tool's own content-addressed remote cache (
nx,turbo, Bazel) so a target hits across branches and machines, not just per-workflow. - Invalidate deliberately: bump a
CACHE_VERSIONin the key string when the cache format changes, or poisoned entries persist. - Watch the size cap — GitHub evicts the least-recently-used cache over 10 GB per repo, silently turning hits into misses.
Pitfalls
- Caching
node_modulesacross OSes or Node versions serves binaries built for the wrong architecture. - A key that includes
github.run_idor the commit SHA of every run never hits; the SHA changes each push. - Secrets written into a restored cache directory can leak across fork PRs; never cache anything containing credentials.
actions/cacheandactions/setup-node's built-in cache can both run and fight; pick one.- A cache hit that restores a
node_modulesnewer than the lockfile hides a missingnpm ci, so the build diverges from a clean checkout — always run an install step even on hit.
Verification
gh run view <id> --log | grep -E 'Cache (restored|not found|saved)' | sort | uniq -c
Inspect the ratio across the last 50 runs; a healthy dependency cache restores on >90% of runs and saves only when the lockfile changed.
Report: "Cache key <key> hits / recent runs; job time dropped from to while npm ci --prefer-offline still runs on every job."