How-To Guide

How to Implement a Content-Addressed Cache Store

Build a cache keyed by a hash of its inputs, so identical work is reused and shared across machines, with integrity and safe eviction.

On this page

  1. Introduction
  2. The Key Is a Hash of the Inputs
  3. Storing Entries Immutably
  4. Integrity and Verification
  5. Eviction Without Breaking Correctness
  6. Sharing Across Machines
  7. Edge Cases
  8. Common Pitfalls and Conclusion

Introduction

A cache keyed by a hash of everything that affects the output is the foundation of build caching, HTTP caching and package stores. Because the key is a content hash, the same inputs map to the same key anywhere, so a result computed on one machine is reusable on another, and a result that changes with its inputs can never be served stale. Building such a store means choosing the key, storing the entries immutably, verifying integrity and evicting safely.

The Key Is a Hash of the Inputs

A content-addressed cache key is a hash over everything the output depends on: the input file contents, the command, the environment, and the versions of tools that affect the result. If the key is complete, the same inputs always map to the same key, and a different input produces a different key, so a change never reuses a stale entry.

The key must include the inputs’ contents, not their names or timestamps: a file whose contents are unchanged produces the same key even if its modification time changed, which is what makes the cache stable across checkouts. Hashing names instead of contents causes spurious misses on every checkout.

import { createHash } from 'node:crypto';

export function cacheKey(inputs: string[]): string {
  const h = createHash('sha256');
  // sort so the key does not depend on argument order
  for (const content of [...inputs].sort()) h.update(content);
  return h.digest('hex');       // same inputs => same key, everywhere
}
// hash CONTENTS, not file names or mtimes: stable across checkouts and machines

Storing Entries Immutably

An entry is stored under its key and never modified: writing the same key twice writes the same content, and a changed output has a different key, so the old entry is simply not reused. Immutability means there is no invalidation logic and no stale entry to expire on a content change; correctness is the key, not a TTL.

Store the entry at a path derived from the key, so a lookup is a direct read rather than a scan. Content-addressed stores are often sharded by a prefix of the key to keep directories small. Because the path comes from the content, two identical outputs deduplicate automatically.

# content-addressed layout (sharded by a key prefix)
store/ab/abcdef1234.../output.tar.zst
store/ab/abcdef1234.../meta.json
# same key => same path => same content (dedup); never modified
# sharding by the first 2 hex chars keeps each dir small

Integrity and Verification

Because the key is a hash of the inputs, you can also store a hash of the output and verify it on read: if the stored output does not match its recorded hash, it is corrupt or tampered and must be rejected. This turns the cache into a store you can trust, not one that silently serves wrong bytes.

Sign entries where the cache is shared and untrusted, so a tampered entry cannot inject a wrong output into a build. The signature covers the key and the content hash, so a modified entry fails verification. Combined with the content hash, it detects both corruption and tampering.

export function store(key: string, output: Buffer, sign: (b: Buffer) => Buffer) {
  const contentHash = createHash('sha256').update(output).digest('hex');
  const signature = sign(Buffer.concat([Buffer.from(key), output]));
  writeImmutable(key, { contentHash, signature, blob: output }); // path from key
}
export function read(key: string, verify: (b: Buffer, s: Buffer) => boolean) {
  const entry = readImmutable(key);
  if (!entry) return undefined;
  const h = createHash('sha256').update(entry.blob).digest('hex');
  if (h !== entry.contentHash) return undefined;               // corrupt
  if (!verify(entry.blob, entry.signature)) return undefined;   // tampered
  return entry.blob;
}

Eviction Without Breaking Correctness

An immutable content-addressed store can be evicted freely, because a missing entry only means a miss and a recompute, never a wrong answer. Evict by least-recently-used or by age, and the recompute on a miss is the fallback; there is no risk of serving a stale value, which is the key difference from a mutable cache.

Bound the store so it does not grow without limit, and make eviction robust to concurrent use: if a reader is reading an entry while it is evicted, the reader must handle the missing entry by recomputing rather than crashing. Treat any read failure as a miss.

# eviction is safe because entries are immutable
evict by LRU or age => a missing entry is just a MISS => recompute
# no stale value can be served (the key is the content)
# concurrency: a read that fails (evicted mid-read) is treated as a miss

Sharing Across Machines

Because the key is content-based, a store can be shared across machines: a remote store that a machine publishes to and others read from turns local work into a shared cache. The key is the same everywhere, so a result computed on one machine is found by another that runs the same work.

The remote store adds a network hop on a hit and a transfer on a miss; the trade is that repeated work across many machines is computed once. Scope the store by the environment so a development build is not served to production, and sign entries so an untrusted network cannot inject output.

# local + remote layered
check local store -> hit? use it
                 -> miss? check remote store -> hit? use + backfill local
                                            -> miss? compute, store locally + remotely
# same key everywhere => work computed on one machine is reused on others
# scope by environment; sign entries on an untrusted network

Edge Cases

The hardest part is a complete key: an input the key omits produces a wrong hit, which is worse than a miss. This is why hermetic builds declare every input and why build systems require inputs to be explicit. When you get a wrong hit, the fix is to add the missing input to the key, never to shorten a TTL.

Also handle very large entries (transfer cost) and non-deterministic outputs (a timestamp inside a build artifact changes the output hash even when the inputs did not). Normalise known non-determinism out of the output, or the cache misses on every build even though the inputs are the same.

# edge cases
incomplete key   -> WRONG hit (worse than a miss): add the missing input
large entries    -> transfer cost; keep outputs precise
non-deterministic output -> normalise it out (e.g. fixed timestamps)
# a wrong hit is a key bug, not a TTL problem

Common Pitfalls and Conclusion

Do not key on file names or mtimes instead of contents; you will miss on every checkout. Do not omit an input from the key, which causes a wrong hit. Do not rely on a TTL for correctness; the content key is the correctness. And do not store entries mutably, which reintroduces invalidation and staleness.

A content-addressed cache keys entries by a hash of everything the output depends on, stores them immutably, verifies integrity, evicts safely and shares across machines. Hash contents not names, make the key complete, verify the output hash, treat any read failure as a miss, and reuse results wherever the same inputs appear. It is the mechanism behind build and package caches, and it turns repeated work into a lookup.

Sources: Bazel: Remote caching and content addressing, Nix: Content-addressed store, Git: Content-addressable storage.

FAQ

Why hash file contents instead of names and timestamps?
Because contents are stable across checkouts and machines while names and timestamps change. A key over contents produces the same key wherever the same inputs appear, so the cache is stable and shareable; keying on timestamps causes a miss on every checkout.
Why is a content-addressed cache safe to evict freely?
Because a missing entry is only a miss and a recompute, never a wrong answer; the key is the content, so a stale value cannot be served. That is the difference from a mutable cache, where eviction and TTLs affect correctness.

Related Examples