Cache by content, not by guess
How to make a build fast without making it wrong
A cache that is keyed on the wrong thing is either useless or dangerous. Key it on what the result depends on, and order the work so the stable parts come first.
The fastest build step is the one you skip. A cache lets you skip work when the inputs have not changed, and the whole craft is in deciding what "not changed" means.
The two ways a cache fails
If the key is too broad, the cache is hit when it should not be, and you ship a stale result that looks fine. If the key is too narrow, it almost never hits and you pay for storing it. The first is a correctness bug, the second only a wasted effort, so err towards narrow and then widen with evidence.
Key on what the result depends on
A dependency install depends on the lock file, the tool version and the platform. Hash those. A key of "latest" or a date depends on nothing and means nothing. A content hash changes exactly when the inputs change, with no human judgement involved.
Order the work by how often it changes
In a layered build, each step reuses the cache only if every step above it is unchanged. Put the slow, rarely changing steps first, such as installing dependencies, and the fast, frequently changing steps last, such as copying source. One edit to a source file then rebuilds one layer instead of all of them.
Measure the hit rate
Print whether each cache hit or missed, and how long the step took. A cache that misses every time is invisible without this, and a cache that restores slowly can cost more than the work it saves.
Keep a way to start clean
Sometimes you need to know the build works from nothing. Keep a clean build on a schedule or on demand, so a poisoned cache cannot hide a real failure for months.