TExcelTAD
Home › Build Fundamentals: From Source to Binary › Content-Addressed Caches

Content-Addressed Caches

An incremental build reuses outputs from your own previous build. A build cache goes further: it reuses outputs from any previous build with the same inputs, yours from last week, a colleague's, or CI's. The idea, used by ccache, sccache, Bazel, Gradle, Turborepo and Nx, fits in one sentence:

Hash everything that can affect a step's output into a cache key. If the key has been seen before, fetch the stored output instead of running the step.

Two stores: action cache and CAS

Real caches split storage in two:

  • The content-addressable store (CAS) stores blobs (files) under the hash of their own content. The same file is stored once, however many builds produce it, and a blob can't be corrupted silently: its name is its checksum.
  • The action cache maps a cache key (the hash of an action's inputs) to the hashes of its outputs in the CAS.

Bazel's remote cache protocol (REAPI) uses exactly these two stores, and ccache does something similar on local disk.

Model: cache keys

The key must cover everything that influences the output: the command, the tool version, every input file's content, and relevant environment variables. Whatever is left out becomes a source of wrong cache hits; whatever is included needlessly (an absolute path, a timestamp) becomes a source of misses.

python · try it yourself
import hashlib, json

def sha(data):
    return hashlib.sha256(data.encode()).hexdigest()

cas = {}            # content hash -> bytes
action_cache = {}   # action key  -> output content hash

def compile_step(sources, flags, compiler="gcc 13.3.0", env=None):
    inputs = {name: sha(text) for name, text in sorted(sources.items())}
    key = sha(json.dumps({"tool": compiler, "flags": flags, "inputs": inputs, "env": env or {}}, sort_keys=True))
    if key in action_cache:
        return f"HIT  key {key[:10]} -> output {action_cache[key][:10]}"
    output = f"object code for {sorted(inputs.values())} {flags} {compiler}"   # pretend to compile
    out_hash = sha(output)
    cas[out_hash] = output
    action_cache[key] = out_hash
    return f"MISS key {key[:10]} -> stored  {out_hash[:10]}"

src = {"f.c": "int twice(int x) { return x * 2; }", "f.h": "int twice(int);"}
print("first build      ", compile_step(src, ["-O2"]))
print("rebuild          ", compile_step(src, ["-O2"]))
print("other machine    ", compile_step(dict(src), ["-O2"]))           # same content, same key
print("flag change      ", compile_step(src, ["-O2", "-DNDEBUG"]))
print("header edit      ", compile_step({**src, "f.h": "int twice(int x);"}, ["-O2"]))
print("compiler upgrade ", compile_step(src, ["-O2"], compiler="gcc 14.2.0"))
print("blobs in CAS:", len(cas), "| actions cached:", len(action_cache))
first build       MISS key ccd252c28c -> stored  6e6de1f7fd
rebuild           HIT  key ccd252c28c -> output 6e6de1f7fd
other machine     HIT  key ccd252c28c -> output 6e6de1f7fd
flag change       MISS key 623f1a1d5e -> stored  5ecaee2508
header edit       MISS key ee8d773de0 -> stored  5a411a72fc
compiler upgrade  MISS key 4580329657 -> stored  928f997f77
blobs in CAS: 4 | actions cached: 4

Note that the key used the content of the inputs, not their names or timestamps: a fresh checkout on another machine produces the same key. That is what makes a cache shareable.

ccache: a real compiler cache

ccache wraps the compiler (ccache gcc …, or CMAKE_C_COMPILER_LAUNCHER=ccache). It has two ways of computing a key:

  • direct mode hashes the source file, the headers it included last time, the compiler and the command line, without running the preprocessor (fast);
  • preprocessed mode runs the preprocessor and hashes its output, which catches cases where the source text changed but the preprocessed result didn't.

The helper step below runs one compile through ccache and compares ccache's counters before and after to say what happened:

bash · try it yourself
mkdir -p cache/a cache/b && cd cache
step() {   # compile through ccache, then report hit/miss from its counters
  local before after
  before=$(ccache --print-stats | awk '$1 ~ /^(cache_miss|direct_cache_hit)$/ {printf "%s ", $2}')
  ccache gcc "$@"
  after=$(ccache --print-stats | awk '$1 ~ /^(cache_miss|direct_cache_hit)$/ {printf "%s ", $2}')
  set -- $before; local miss0=$1 direct0=$2; set -- $after
  if [ "$1" != "$miss0" ]; then echo "miss: compiled"
  elif [ "$2" != "$direct0" ]; then echo "hit (direct mode)"
  else echo "hit (preprocessed mode)"; fi
}
ccache --version | head -1
printf 'int twice(int x) { return x * 2; }\n' > a/f.c
cd a
printf '%-38s' "first compile:";                  step -c f.c -o f.o
printf '%-38s' "again, after rm f.o:";            rm f.o; step -c f.c -o f.o
printf 'int twice(int x) { return x * 2; } /* doubled */\n' > f.c
printf '%-38s' "comment added on the same line:"; step -c f.c -o f.o
printf '%-38s' "same source, -O2:";               step -c -O2 f.c -o f.o
cp f.c ../b/ && cd ../b
printf '%-38s' "same source and flags, other folder:"; step -c -O2 f.c -o f.o
cd ../a
printf '%-38s' "with -g:";                        step -c -g f.c -o f.o
cd ../b
printf '%-38s' "with -g, other folder:";          step -c -g f.c -o f.o
ccache version 4.14.2
first compile:                        miss: compiled
again, after rm f.o:                  hit (direct mode)
comment added on the same line:       hit (preprocessed mode)
same source, -O2:                     miss: compiled
same source and flags, other folder:  hit (direct mode)
with -g:                              miss: compiled
with -g, other folder:                miss: compiled

Read the results as cache-key decisions:

  • A comment changes the source text, so direct mode misses, but the preprocessed output is identical (the comment is removed and the line count is unchanged), so preprocessed mode hits.
  • -O2 is part of the key: miss.
  • The same file in another folder hits, because the key uses content and the relative command line, not the folder.
  • With -g, the object's debug information records the compilation directory, so ccache includes the current directory in the key (its hash_dir setting, on by default): the other folder misses. This is the most common reason caches don't share well across machines and checkouts; -fdebug-prefix-map (see Reproducible Builds) and ccache's base_dir setting fix it.

Caching beyond C

Tool What it caches Key includes
ccache / sccache compiler outputs (sccache also Rust, and remote storage in S3, GCS, Redis…) compiler, flags, preprocessed or direct source hash
Gradle build cache task outputs task inputs declared by the task (files, properties, classpath)
Bazel / Buck2 every action's outputs, locally and remotely the full action: command, all input digests, environment, platform
Turborepo / Nx script outputs in JS monorepos input file hashes, env vars, dependency task hashes
Docker image layers the instruction plus the previous layer (and copied files' contents)

The common pitfall is the same everywhere: an input that affects the output but is not in the key. The next lesson is about making sure there are none.

Test yourself

What does a content-addressable store use as the name of a stored blob?

  1. Its file name
  2. The hash of its own content
  3. The time it was stored
  4. A sequence number

Why did ccache miss with -g in another folder, but hit without -g?

  1. -g disables ccache
  2. Debug info records the compilation directory, so ccache adds the current directory to the key
  3. The other folder was empty
  4. -g is slower

What happens if an input that affects the output is left out of the cache key?

  1. More cache misses
  2. Wrong cache hits: a stale output is reused when that input changes
  3. Nothing
  4. The cache gets smaller