A field guide to caching
Every cache is a bet that an answer you computed earlier is still right. Here is how to place that bet, and how to find out when you lost.
A cache stores an answer so you don't have to work it out again. That is the whole idea, and it is also the whole problem: the stored answer was right when you saved it, and nothing guarantees it still is.
Most caching bugs are not about storage. They are about the moment a stored answer stops being true and nobody tells the cache.
Decide what "stale" costs
Before choosing a strategy, work out what happens when a reader gets an old answer.
- A stale avatar is harmless for an hour.
- A stale price loses money or trust.
- A stale permission check is a security incident.
That cost sets the budget. Cheap staleness can ride on a timer. Expensive staleness needs an explicit signal the moment the data changes.
Three ways to expire an entry
Time to live
Give every entry a lifetime and drop it when the lifetime ends. It is simple and it always converges, but for the whole lifetime you may be serving something wrong.
const cache = new Map<string, { value: unknown; expires: number }>();
export function remember<T>(key: string, ttlMs: number, load: () => T): T {
const hit = cache.get(key);
if (hit && hit.expires > Date.now()) return hit.value as T;
const value = load();
cache.set(key, { value, expires: Date.now() + ttlMs });
return value;
}Invalidate on write
Delete the entry whenever the underlying data changes. Readers never see stale data, provided every write path remembers to invalidate. The one that forgets is the bug you will be chasing in six months.
Versioned keys
Put a version in the key itself, such as user:42:v17. A write bumps the version, so old entries are never read again and simply age out. Nothing needs deleting, which also means nothing can be deleted too late.
Watch the miss, not the hit
A cache that looks healthy on a dashboard can still take a service down. When a popular entry expires, every request that arrives before it is refilled does the expensive work at once.
# 400 requests arrive in the second after the entry expires
$ grep "cache=miss key=home:feed" app.log | wc -l
400The fix is to let one request rebuild the entry while the rest wait for it, or keep serving the old value until the new one is ready.
When not to cache
If the uncached path is already fast enough, leave it alone. A cache adds a second copy of the truth, and every second copy is one more thing that can be wrong. Measure first, and add the cache only where the measurement says it pays.