GitHub Actions cache never hits: why our CI rebuilt from scratch
Every pull request build spent nine minutes reinstalling dependencies because actions/cache reported a miss. The key hashed a file that changed every run, PR caches could not be shared between branches, and the repo was over its cache budget. Three small changes cut builds to under three minutes.
Our pull request workflow for a TypeScript monorepo had drifted from three minutes to almost twelve. The job timeline showed where the time went: the pnpm install step took nine minutes on every run, including reruns of the same commit. The cache step said why:
Run actions/cache@v4
Cache not found for input keys: Linux-pnpm-4e1c0b5a9f6d3e8a2b7c1d0f5e4a3b2c1d0e9f8a7b6c5d4e3f2a1b0c9d8e7f6a5, Linux-pnpm-
The post-job step then saved a new cache, about 1.4 GB, which the next run also failed to find.
Reproducing it
Rerunning the same workflow on the same commit was enough. Each run computed a different key hash, so each run missed. Opening a second pull request from a different branch also missed, even when the first PR had just saved a cache with an identical lock file.
What we ruled out
Cache service outage. The GitHub status page was green, and other repositories in the organisation got hits.
Wrong path. The
path:pointed at the pnpm store directory reported bypnpm store path, and the save step uploaded a large archive, so the content was right.Lock file churn.
git log -- pnpm-lock.yamlshowed no change for a week, yet the hash kept changing.
Root cause
Three separate problems stacked on each other:
The key used
hashFiles('**/package.json', '**/pnpm-lock.yaml'). A build script earlier in the job rewroteversionfields in workspacepackage.jsonfiles to include the run number, so the hash was different on every run.Even with a stable key, caches created in a pull request are scoped to that PR's merge ref. A new PR cannot restore them; it can only restore caches from its own ref and from the base branch. Nothing ran on
mainto create a base-branch cache, so every new PR started cold.The repository was over its cache size budget. Every run saved a fresh 1.4 GB entry, older entries were evicted, and the few useful ones disappeared within hours.
What is happening under the hood
actions/cache works in two phases. At the start of the job it asks the cache service for an entry whose key matches key exactly. If none exists, it tries each restore-keys prefix in order and returns the most recently created match. At the end of the job, if there was no exact hit, it saves a new entry under key. Entries are immutable; a key that already exists is never overwritten.
Access is restricted by ref. A workflow run can restore caches created:
on its own branch or ref;
on the default branch;
for pull requests, on the base branch of the PR.
It cannot restore caches created on sibling branches or by other pull requests. That rule exists so an untrusted branch cannot poison caches used by others.
Each repository has a cache storage budget, 10 GB by default. When usage goes over it, the service evicts entries, least recently used first. Entries not accessed for 7 days are also removed. A workflow that saves a new large entry on every run churns the budget and evicts its own useful caches.
Environment
Component | Version / value |
|---|---|
Runner | GitHub-hosted |
Cache action |
|
Package manager | pnpm 10, Node.js 22 |
Repository | 38 workspace packages, lock file about 22k lines |
Cache entry size | about 1.4 GB per save |
Trigger |
|
Minimal reproduction
on: pull_request
jobs:
test:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- run: node scripts/stamp-versions.js "$GITHUB_RUN_NUMBER" # edits package.json files
- uses: actions/cache@v4
with:
path: ~/.local/share/pnpm/store
key: ${{ runner.os }}-pnpm-${{ hashFiles('**/package.json', '**/pnpm-lock.yaml') }}
restore-keys: ${{ runner.os }}-pnpm-
- run: pnpm install --frozen-lockfile
Two details make it worse: the stamp step runs before the cache step, so the hash changes; and the restore-keys fallback can only match caches in scope, of which there were none.
Who is affected
Any workflow using actions/cache or the built-in caching in setup-node, setup-python, setup-go and similar actions, where the key includes generated or frequently changing files, where only pull_request events create caches, or where cache entries are large and saved on every run.
The fix
1. Hash only the lock file, and do it before anything edits the tree. The lock file is the true description of what gets installed.
- uses: actions/checkout@v4
- - run: node scripts/stamp-versions.js "$GITHUB_RUN_NUMBER"
- uses: actions/cache@v4
with:
path: ~/.local/share/pnpm/store
- key: ${{ runner.os }}-pnpm-${{ hashFiles('**/package.json', '**/pnpm-lock.yaml') }}
+ key: ${{ runner.os }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: ${{ runner.os }}-pnpm-
- run: pnpm install --frozen-lockfile
+ - run: node scripts/stamp-versions.js "$GITHUB_RUN_NUMBER"
In the end we replaced the manual step with the built-in cache of setup-node, which keys on the lock file for us:
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
2. Seed the cache on the default branch. We added push: branches: [main] to the workflow. After every merge, main saves a cache that every PR can restore.
on:
pull_request:
push:
branches: [main]
3. Stop saving on every PR. Pull requests only restore; main saves. With the split restore/save actions this is explicit:
- uses: actions/cache/restore@v4
id: pnpm-cache
with:
path: ~/.local/share/pnpm/store
key: ${{ runner.os }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
restore-keys: ${{ runner.os }}-pnpm-
- run: pnpm install --frozen-lockfile
- uses: actions/cache/save@v4
if: github.ref == 'refs/heads/main' && steps.pnpm-cache.outputs.cache-hit != 'true'
with:
path: ~/.local/share/pnpm/store
key: ${{ runner.os }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
4. Clean the budget once. We deleted the stale PR caches so the useful entries had room:
gh cache list --limit 200 --sort size_in_bytes --order desc
gh cache list --ref refs/pull/1234/merge --json id --jq '.[].id' | xargs -n1 gh cache delete
Alternatives and trade-offs
Cache
node_modulesinstead of the store. Faster restore, but tied to the exact Node and OS version and easy to break with native modules. The store is safer.Larger cache budget. Admins can raise the limit on some plans, but a bigger budget only delays eviction if every run still saves a fresh entry.
Self-hosted runners with a warm disk. Removes the network transfer but brings back state between jobs, which is the problem post 37 describes for stale dependencies.
Remote build cache (Turborepo, Nx). Complements dependency caching by skipping unchanged tasks, not installs.
How to test the fix
Merge to
main; confirm the run saves a cache.Open a PR without lock file changes; the log should show:
Cache restored from key: Linux-pnpm-9b2f6e1a...
Rerun the PR job; it must hit again with the same key.
Change a dependency in a PR; expect a prefix restore from
restore-keysand an install that only fetches the new packages.
Confirming in production
Median PR build time over the next two weeks dropped from 11 min 40 s to 2 min 50 s; the install step went from nine minutes to 25 seconds on a hit. gh cache list showed a handful of entries from main and none from pull requests, and total usage stayed around 3 GB instead of hovering at the limit.
Regression guard
A step prints the cache hit status into the job summary so slow builds are explained at a glance:
echo "pnpm cache hit: ${{ steps.pnpm-cache.outputs.cache-hit }}" >> "$GITHUB_STEP_SUMMARY"
A weekly scheduled workflow fails if the repository's cache usage passes 8 GB, using
gh api repos/{owner}/{repo}/actions/cache/usage.Code review rule: cache keys hash lock files only, never generated files.
Security implications
The branch scope rule we tripped over is a security feature: it prevents a pull request from writing a cache that main or another branch later restores. Do not work around it by running cache-saving jobs on pull_request_target with untrusted code, which would let a fork poison caches used by trusted builds. Saving only from main keeps the cache trustworthy. Never put credentials or build secrets inside a cached path.
Prevention checklist
Key dependency caches on the lock file only.
Create caches on the default branch; let pull requests restore.
Avoid saving a new large cache on every run.
Watch cache usage against the repository budget.
Prefer the built-in
cache:option of setup actions where it fits.
References
GitHub Docs, Dependency caching reference: https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching
actions/cache README: https://github.com/actions/cache
actions/setup-node, caching packages: https://github.com/actions/setup-node
GitHub CLI manual, gh cache: https://cli.github.com/manual/gh_cache
Add a label
Embed this post
<iframe src="https://hibug.me/github-actions-cache-miss-slow-builds" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I started as a Linux administrator in a hosting company and never really left the command line. Today I look after fleets of Linux servers, edge networking and CDN setups for web platforms, and I still do on-call shifts. My posts are the notes I wish I had found at three in the morning: the symptom, the commands that narrowed it down, the actual cause and the change that fixed it. I try to explain what each number in vmstat, iostat or ss output means, so you can reason about your own system instead of copying commands.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.