Chapter 12 · Lesson 7 of 10
CI/CD and automation

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.

By the end you will

Cache npm packages and Docker layers in a workflow with correct keys, and know when a cache gives stale or wrong results.

Time
15 min
Level
Intermediate
Check
4 questions
You need
  • 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:

yaml
steps:
  - uses: actions/checkout@v4
  - uses: actions/setup-node@v4
    with:
      node-version: 20
      cache: npm
  - run: npm ci
  - run: npm test

cache: 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:

yaml
- uses: actions/cache@v4
  with:
    path: ~/.cache/pip
    key: pip-${{ runner.os }}-${{ hashFiles('requirements.txt') }}
    restore-keys: |
      pip-${{ runner.os }}-

How the pieces work:

  • path is what gets saved and restored.
  • key is exact. hashFiles computes a hash of the file, so editing requirements.txt produces a new key and a fresh cache.
  • restore-keys are 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:

yaml
- 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=max

cache-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_modules for npm ci. The command deletes the folder first. Cache the npm download directory instead.
  • Keys must be unique per content. A static key like deps never 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.os in the key.
  • Fork pull requests. They can read caches but follow stricter write rules. Do not rely on them saving a cache.

Troubleshooting#

SymptomLikely causeFix
Always Cache not foundKey changes every runHash a stable file, not a timestamp or SHA
Build uses old dependenciesStatic key, stale cacheInclude hashFiles of the lockfile
Dependencies lock file is not found from setup-nodeNo lockfile committedCommit package-lock.json or set cache-dependency-path
Restore takes longer than installCache too big or too small a winCache less, or remove the cache
Docker build ignores the cacheLayer order invalidates early layersCopy manifests and install before source
Cache cannot be savedEviction or storage pressureDelete old caches in the Actions caches page
Weird failure that passes after a rerunCorrupt or stale cacheChange the key prefix to start fresh

Quick reference#

yaml
- 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=max

Next#

Continue with Matrix builds and branch protection.

Check what you learned4 questions
1What should the cache key for npm packages be based on?
2What does restore-keys provide?
3Which settings enable the GitHub Actions cache for Docker builds?
4When can caching hurt?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios