Skip to content
Back to blog
Tooling5 minute read

A Practical Guide to Content-Hashed Caches

Why task graphs built from explicit inputs beat whole-repo hashes, and how to keep the cache small enough to trust.

ASRaka Mahendra
  • Tooling
  • Caching
  • CI
  • Build Systems
Cover art for “A Practical Guide to Content-Hashed Caches”

A content-hashed cache only works if the hash describes what a task actually consumes. Hash the whole repository and every README edit invalidates every build; hash too little and a stale artifact ships green. The interesting work is choosing the input list.

Declare inputs at the leaf

Leaf packages — validators, types, small utilities — have few inputs and change rarely. Give each task an explicit list: its own sources, the exact dependencies it imports, and the config files that alter its output. Everything outside that list is none of the task’s business.

export function taskHash(files: ReadonlyMap<string, string>, inputs: readonly string[]): string {
  const material = inputs
    .filter((path) => files.has(path))
    .sort()
    .map((path) => `${path}:${files.get(path)}`)
    .join('\n');
  return createHash('sha256').update(material).digest('hex').slice(0, 16);
}

Sort before hashing

Filesystem enumeration order is not stable across machines. Sort the paths before concatenating, or the same tree produces different keys on a laptop and in CI and the cache silently misses every time.

Store outputs, not just keys

A cache entry is a key and the artifact it produced. Restore with the same tool that created it, and verify the restored tree before trusting it. A partially restored dist/ is worse than no cache because tests pass against yesterday’s code.

Prune aggressively

Caches that grow forever become a second build system nobody understands. Keep the most recent N entries per task and drop the rest. If a task needs an older artifact, the build is fast enough to recreate it.

Copied