Cache dependencies in GitHub Actions to speed up builds
Caching in GitHub Actions saves files such as downloaded packages under a key, then restores them in later runs so the install step does less work.
- Updated Nov 27, 2026
- Markdown
Cache npm packages and Docker layers in a workflow with correct keys, and know when a cache gives stale or wrong results.
- A working test or build workflow
Every run starts on an empty machine, so every run downloads the same packages again. A cache stores those downloads under a key and brings them back on the next run. Done well, it removes most of the install time. Done badly, it hides changes behind stale files. This lesson shows the three common patterns and when to skip caching. It builds on the workflow from Run tests on every push and pull request.
How it works#
The cache is a key-value store scoped to your repository. At the start of a step, the runner looks up the key. A hit restores the saved files. A miss starts empty, and at the end of the job the files are saved under that key. Caches are separated by branch in general terms: a run on a branch can restore caches made on that branch and on the default branch, but not from unrelated branches. GitHub also evicts old or unused caches on its own, so a cache is a speed-up and never something you depend on. Your workflow must still work with an empty cache.
Step 1: Use the setup-node cache option#
For npm, yarn or pnpm the easiest route is built into actions/setup-node@v4:
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm testcache: npm caches npm’s download cache directory, keyed on a hash of package-lock.json. npm ci still runs and still deletes node_modules, but it fills it from local files instead of the network. This is the right level for most Node projects. It needs a lockfile in the repository.
Step 2: Use actions/cache for anything else#
For other tools, use actions/cache@v4 directly. The key must change when the inputs change:
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-${{ hashFiles('requirements.txt') }}
restore-keys: |
pip-${{ runner.os }}-How the pieces work:
pathis what gets saved and restored.keyis exact.hashFilescomputes a hash of the file, so editingrequirements.txtproduces a new key and a fresh cache.restore-keysare prefixes tried in order when the exact key misses. An older, partly matching cache is better than none. After the job, the new state is saved under the exact key.
Put the OS in the key (runner.os) when cached files are platform-specific.
Step 3: Cache Docker layers#
Image builds spend their time in layers. With Buildx, the Actions cache can hold them:
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v6
with:
context: .
push: false
tags: app:test
cache-from: type=gha
cache-to: type=gha,mode=maxcache-from reads previous layers, cache-to writes them. mode=max stores layers from all stages, which helps multi-stage builds. Layer order in your Dockerfile matters: copy the dependency manifest and install before copying the rest of the source, so editing code does not invalidate the install layer. The same cache settings apply when you push to a registry, as in Build and push a Docker image to GHCR. The build cache glossary entry has the basics.
Step 4: Know when not to cache#
Caching is not free. Skip or limit it when:
- the install is already fast, so restore plus save costs about as much as it saves
- the cache is large and rarely hit, so you pay upload time every run
- the output is generated by the build (compiled output, test results), because stale output can hide a real failure
- the cache would contain anything sensitive, since other jobs in the repository may restore it
If a build behaves oddly, rerun with the cache disabled or change the key prefix to start fresh. A cache problem looks like a code problem.
Step 5: Understand branch scope#
In general terms, a branch can read caches from itself and from the default branch, and pull requests can read caches from their base branch. A cache written on a feature branch is not visible to other feature branches. This protects branches from each other, and it means the first run on a new branch is often warm only if main has a recent cache. Make sure main runs the workflow regularly so it keeps a cache for others to fall back on. Check the repository’s Actions caches page to see what exists and delete a bad one.
Check it worked#
Run the workflow twice with no lockfile change. In the first run, the cache step reports a miss and saves. In the second, it reports a hit, and the install step is shorter. For actions/cache, the log lines Cache restored from key and Cache hit confirm it. Change the lockfile and confirm the next run misses on the exact key but may restore through a restore-keys prefix. Compare step durations before and after, rather than guessing.
Edge cases and gotchas#
- Do not cache
node_modulesfor npm ci. The command deletes the folder first. Cache the npm download directory instead. - Keys must be unique per content. A static key like
depsnever updates, so you keep restoring the first cache forever. - Caches are not for secrets. Files you cache can be restored by other workflows in the repository.
- Caches can be evicted. Treat a miss as normal. Do not write a pipeline that fails when the cache is gone.
- Different OS or architecture. A binary cache from Linux is useless on another OS. Include
runner.osin the key. - Fork pull requests. They can read caches but follow stricter write rules. Do not rely on them saving a cache.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
Always Cache not found | Key changes every run | Hash a stable file, not a timestamp or SHA |
| Build uses old dependencies | Static key, stale cache | Include hashFiles of the lockfile |
Dependencies lock file is not found from setup-node | No lockfile committed | Commit package-lock.json or set cache-dependency-path |
| Restore takes longer than install | Cache too big or too small a win | Cache less, or remove the cache |
| Docker build ignores the cache | Layer order invalidates early layers | Copy manifests and install before source |
| Cache cannot be saved | Eviction or storage pressure | Delete old caches in the Actions caches page |
| Weird failure that passes after a rerun | Corrupt or stale cache | Change the key prefix to start fresh |
Quick reference#
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-${{ hashFiles('requirements.txt') }}
restore-keys: |
pip-${{ runner.os }}-
- uses: docker/build-push-action@v6
with:
context: .
cache-from: type=gha
cache-to: type=gha,mode=maxRelated lessons#
- Run tests on every push and pull request: the workflow you are speeding up.
- Build and push a Docker image to GHCR: where the Docker layer cache applies.
- Multi-stage Docker builds: how stages and layers affect caching.
- Write your first Dockerfile: ordering instructions for good cache use.
- CI/CD pipeline stages explained: why fast feedback matters.
Next#
Continue with Matrix builds and branch protection.
Check what you learned
Frequently asked questions
How do I cache node_modules in GitHub Actions?
The simplest way is actions/setup-node@v4 with cache set to npm, which caches the npm download cache keyed on package-lock.json. Caching node_modules itself is discouraged because npm ci removes it.
What is restore-keys in actions/cache?
It is a list of key prefixes tried when the exact key has no match. A partial match restores an older cache, which the step can then update and save under the new key.
How do I cache Docker layers in GitHub Actions?
Use docker/build-push-action@v6 with cache-from type=gha and cache-to type=gha,mode=max after setting up Buildx. Unchanged layers are then reused across runs.
Can a cache make my build wrong?
Yes, if the key does not change when the inputs change, you restore stale files. Key on a hash of the lockfile and keep generated build output out of the cache.
Sources
Keep going: guides and tutorials
- Deploy a Docker Compose App Self-Hosted: Web, Redis and Rollback Deploy a Docker Compose app on your own server with Levelrail: a web service and Redis, a bad release that does not take traffic, and a compose rollback.
- Zero Downtime Deploy for Docker Apps, With Rollback How a Docker deploy waits for readiness before cutover, holds the previous release for rollback, rolls back on its own, and how to rehearse it.