← Concepts

阅读中文版本

Build Cache

A build cache stores outputs keyed by inputs so repeated builds reuse compiled artifacts, downloaded dependencies, and layers, cutting CI time without changing results.

delivery

Definition

A build cache persists the outputs of build steps, keyed by a hash of their inputs, so a later build with identical inputs can reuse the stored result instead of recomputing it, provided the cache key and artifacts are trustworthy.

Context and scope

It matters in CI pipelines, monorepos, and container builds where the same work runs many times a day and feedback latency directly affects developer throughput.

Common misconceptions

  • Caches always make builds faster — restoring a large, low-hit cache can cost more than rebuilding.
  • A cache hit is always correct — keys that ignore tool versions or environment variables can return stale outputs.
  • Clearing the cache is harmless — cold builds expose flaky dependencies and can take hours.

Anti-patterns

  • Keying the cache on a branch name so every branch starts cold
  • Caching node_modules across operating systems or Node versions
  • Sharing a mutable cache between untrusted pull requests

Related concepts

Related examples

Authoritative source

https://docs.docker.com/build/cache/

Reuse work keyed by inputs

A build cache works like a memoized function. Each step declares its inputs: source files, dependency lockfiles, compiler flags, environment. The cache hashes those inputs into a key and stores the output under that key. On the next build, a matching key means the output is restored instead of recomputed. Container builds apply the same idea per layer; monorepo tools apply it per package.

- uses: actions/cache@v4
  with:
    path: ~/.pnpm-store
    key: pnpm-${{ hashFiles('pnpm-lock.yaml') }}

When to use it

Use a build cache when builds repeat the same steps: CI runs on every push, a monorepo builds many packages, or container images change one layer at a time. The benefit grows with dependency install time and test suite size. For a small project that builds in seconds, cache configuration may cost more than it saves.

Trade-offs

Correctness is the price. A cache that ignores the compiler version or an environment variable can serve outputs that do not match the source. Remote caches need access control, because poisoned artifacts can execute in later builds. Storage and network transfer also cost money, and low hit rates produce the worst of both worlds.

Example and misconceptions

A monorepo with forty packages caches each package build keyed by its source and lockfile. A change to one package rebuilds that package and its dependents, not the other thirty-eight. The common misconception is that caching is always a win; measuring hit rate and restore time is part of the design. Related concepts: CI/CD, monorepo, and dependency pinning.