Home DevOpsGitHub Actions Caching: Faster CI Builds in Minutes

GitHub Actions Caching: Faster CI Builds in Minutes

by Knowledge Base Linux
GitHub Actions caching workflow speeding up CI builds

GitHub Actions caching is the fastest way to cut minutes off a CI pipeline without changing your build itself. Every fresh runner starts empty, so without a cache each job reinstalls dependencies, recompiles toolchains, and downloads the same packages it downloaded on the previous run. A cache stores those reusable artifacts between runs and restores them in seconds, which turns a five minute dependency installation step into a ten second restore. This guide shows how actions/cache works, how to write cache keys that are precise without being brittle, and how to apply caching to Node, Python, and Docker builds. It also covers the limits that catch people by surprise, including the per-repository storage cap and the seven day eviction rule.

The mental model is straightforward. A cache entry is identified by a key, which is a string you construct, usually from the operating system, a tool version, and a hash of your lockfile. When a job runs, the cache action looks up the key: on an exact match it restores the saved paths and reports a cache hit, and on a miss it runs your build normally and then saves the paths under that key for next time. Restore keys are fallback prefixes used when no exact match exists, so a job can reuse the most recent compatible cache instead of starting from nothing. Understanding that exact matches restore and prefix matches fall back is enough to reason about nearly every caching behaviour in this guide. If you are building your first pipeline alongside this article, our guide on how to build a CI/CD pipeline with GitHub Actions and Docker covers the surrounding workflow structure.

GitHub Actions caching key and restore-keys example

Prerequisites

You need a GitHub repository with an existing Actions workflow, plus a project that has a lockfile: package-lock.json for Node, requirements.txt or a similar pinned file for Python, or a Dockerfile for the Docker section. You should be able to read workflow YAML and to inspect workflow run logs, because the troubleshooting section relies on the cache step output. No marketplace subscription or self-hosted runner is required: caching works on GitHub-hosted runners, and the examples use ubuntu-latest. One thing to decide before you start is which directories are worth caching: dependency directories such as node_modules or the pip cache are ideal, while build outputs that change on every commit are usually not, because saving and restoring them costs almost as much as rebuilding them.

GitHub Actions Caching Basics with actions/cache

The actions/cache action takes three main inputs: path, key, and restore-keys. Path is the directory or file to cache, and it supports multiple paths on separate lines. Key is the unique identifier for the cache entry. Restore-keys is an ordered list of prefixes to try when the exact key misses. The action exposes a cache-hit output that later steps can test, which lets you skip an installation step entirely when the cache restored successfully. The example below caches npm dependencies on a Linux runner, using a key built from the runner operating system and a hash of the lockfile.

steps:
  - uses: actions/checkout@v4
  - name: Cache npm dependencies
    uses: actions/cache@v4
    with:
      path: ~/.npm
      key: npm-Linux-x64-node20-${{ hashFiles('**/package-lock.json') }}
      restore-keys: |
        npm-Linux-x64-node20-
  - name: Install dependencies
    run: npm ci

Two details in this example are worth noting. First, the key includes the operating system and the Node major version, because a cache built on one platform or runtime version is not safe to reuse on another. Second, caching the npm cache directory rather than node_modules is the recommended approach for npm ci, because npm ci deletes node_modules and reinstalls from the cache, which is both fast and reproducible. If you use npm install instead, caching node_modules directly can work, but it risks stale or partially updated trees, so prefer the npm cache directory unless you have a measured reason to do otherwise. The official documentation on dependency caching in GitHub Actions documents the same recommendation and the full input reference.

GitHub Actions Caching Keys: Precise but Not Brittle

A cache key that is too broad restores stale dependencies, while a key that is too narrow never hits and wastes storage on entries that are saved once and never reused. The standard pattern balances the two: include everything that determines the contents of the cached directory, and nothing else. For Node, that means the operating system, the runtime version, and the lockfile hash. For Python, it means the operating system, the Python version, and the hash of requirements.txt. Including the lockfile hash is essential, because it guarantees that a dependency upgrade produces a new cache entry rather than silently restoring the old one.

- name: Cache pip packages
  uses: actions/cache@v4
  with:
    path: ~/.cache/pip
    key: pip-Linux-python3.12-${{ hashFiles('**/requirements.txt') }}
    restore-keys: |
      pip-Linux-python3.12-

Restore keys provide the graceful degradation. When requirements.txt changes, the exact key misses, but the restore key prefix matches the previous entry, so pip starts from the old package set and only downloads what changed. That is dramatically faster than a cold install and is the main reason to always include a restore key. One subtlety: restore keys are prefix matches, and the action picks the most recently created matching entry, not necessarily the closest one, so keep your prefixes specific enough that the most recent match is a sensible base. Avoid including the commit SHA or the branch name in the key itself, because that makes every run miss; branch scoping is handled by the cache system separately, as explained below.

Node, Python, and Docker Layer Caching

For Node projects, the setup-node action offers a built-in cache option that wraps actions/cache for you. Setting cache to npm with a cache-dependency-path pointing at your lockfile is less code and less room for error than writing the cache step by hand, and it is the right default for most Node workflows. Use the explicit actions/cache step only when you need to cache additional paths, such as a build tool directory or a Cypress binary cache, alongside the package manager cache. The same pattern exists for Python through setup-python with cache set to pip, and for other ecosystems through their respective setup actions.

- uses: actions/setup-node@v4
  with:
    node-version: 20
    cache: npm
    cache-dependency-path: package-lock.json

Docker layer caching is a different mechanism and a common source of confusion. The actions/cache action is not the right tool for large image layers, because layer data is large, changes frequently, and is better handled by the build tool itself. Instead, use the docker/build-push-action with cache-from and cache-to pointing at a registry or a GitHub Actions cache backend, which lets BuildKit reuse unchanged layers across runs. The registry backend is the most reliable choice for teams, because it is not subject to the same eviction rules as the actions cache and it works identically on self-hosted runners. If your pipeline builds Docker images, pair that approach with the matrix strategy in our guide to GitHub Actions matrix builds to test across versions without multiplying build time.

Cache Limits, Scopes, and Eviction Rules

GitHub enforces a cache storage limit of 10 GB per repository, and when usage exceeds that limit, older entries are evicted until usage falls back under it. There is also a time-based rule: any cache entry that has not been accessed for seven days is removed automatically, which means caches for inactive branches or rarely run workflows simply disappear. These limits have practical consequences. A repository with many branches, many jobs, and broad keys can churn through its quota quickly, evicting the very entries that active branches need. Keep the number of distinct cache entries low by sharing keys across jobs where the contents are identical, and avoid caching huge directories such as full build outputs or virtual machine images.

Cache scope is the other rule that surprises people. A cache created on a branch is only visible to that branch and to pull requests based on it, except that the default branch cache is visible everywhere as a fallback. In practice this means a feature branch first run restores from the default branch cache, then saves its own entry, and subsequent runs on that branch use their own entry. Pull request workflows can read caches from the base branch but cannot write to them, which is a security measure against cache poisoning from untrusted forks. If your pull request builds seem slower than your main branch builds, this scoping, rather than a misconfigured key, is usually the explanation.

Troubleshooting

Cache misses are the most reported problem, and the debugging sequence is always the same. First, read the cache step output in the workflow log: it prints the exact key it looked up and whether it found a hit or a miss, along with the restore key it fell back to. Compare that key with the key from the run that saved the cache. If the lockfile changed, a miss is correct behaviour, and the restore key should have softened the blow. If the lockfile did not change but the key still missed, check for inputs that vary between runs, such as a runner image version embedded in the key, a hashFiles pattern that matches different files on different jobs, or a key that includes a branch name.

A key that is too broad shows the opposite symptom: the cache always hits, but builds behave as if dependencies never update. This happens when the key omits the lockfile hash, so a dependency upgrade reuses the old package set. The fix is to add the hash back and, if necessary, to delete the stale entry so the next run saves a fresh one. Conversely, a key that is too narrow, for example one that includes a timestamp or a run number, never hits at all and fills the quota with single-use entries; remove the varying component and rely on the lockfile hash alone. When a cache entry seems corrupted, the cleanest recovery is to change the key prefix, which abandons the old entries and lets them expire, rather than trying to delete entries individually through the API.

Finally, if the cache step itself fails, check the size of the paths being cached and the available quota. A single cache entry larger than the practical limits will fail to save, and the job will continue without a cache rather than failing outright, which can look like a silent performance regression. Enable step debug logging for one run to see the detailed save and restore messages, and trim the cached paths to dependency directories only. Remember that the cache-hit output lets you skip installation steps conditionally, but only test it in a step that runs after the cache step, and only when the cached directory is genuinely complete without installation.

Conclusion

GitHub Actions caching rewards a small amount of care with a large and permanent reduction in build time. Write keys from the operating system, the tool version, and the lockfile hash; always include a restore key; prefer the setup action cache options for Node and Python; handle Docker layers through BuildKit rather than actions/cache; and respect the 10 GB quota and seven day eviction rule by keeping entries few and focused. When a build gets slower, read the cache step output before changing anything else, because it almost always tells you whether the problem is a miss, a stale hit, or a scope surprise. Done well, caching is invisible: the pipeline just gets faster, and stays faster.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.