tech, developers, and the code underneath

issue 248· essay·

Cache invalidation, concretely

The joke is that it is hard. The useful version is that there are four strategies and picking the wrong one is the actual problem.

The quote about cache invalidation being one of the two hard problems gets repeated as though it were an excuse. It is not. There are a small number of strategies, each with a known failure mode, and most cache bugs come from using one while assuming the properties of another.

the four strategies#

1. Expiry (TTL). Store with a lifetime; serve stale until it lapses.

  • Correctness: eventually consistent, bounded by the TTL.
  • Failure mode: users see old data for up to the TTL, and everything expires at once if you wrote it all at once.
  • Use when: staleness is tolerable and you can name the tolerance in seconds.

2. Explicit purge. Delete the key when the underlying data changes.

  • Correctness: strong, if every writer purges.
  • Failure mode: a writer that does not know about the cache. Also a race: read misses, fetches old value, write commits, write purges, read stores the old value it fetched before the write. The cache is now wrong indefinitely.
  • Use when: writes are few, centralised, and you can enumerate them.

3. Versioned keys. Include a version in the key; bump the version instead of deleting.

user:1234:v7 → {...}
  • Correctness: strong, and immune to the purge race, because the new version is simply a different key.
  • Failure mode: old versions linger and consume memory until they expire.
  • Use when: you can derive the version cheaply — an updated_at, a row version, a monotonic counter.

4. Write-through. Update cache and store together on write.

  • Correctness: strong if the two writes are atomic, which they are not.
  • Failure mode: partial failure leaves them disagreeing, silently and permanently.
  • Use when: rarely. It usually looks safer than it is.

the recommendation#

Versioned keys with a TTL as a backstop. The version gives you correctness without a purge race; the TTL bounds the memory of anything you forget.

python
def cache_key(user_id, version):
    return f"user:{user_id}:v{version}"

# version comes from the row itself — no separate bookkeeping
row = db.fetch("SELECT id, updated_at, ... FROM users WHERE id = %s", user_id)
key = cache_key(row.id, int(row.updated_at.timestamp()))

This does mean a read of the version before a read of the cache. If the version lives in the row you were going to read anyway, it is free. If it does not, keep a small, cheap version table — it is still one fast lookup instead of an entire class of consistency bug.

the two operational problems#

Stampede. A hot key expires and a thousand requests miss simultaneously, all recompute, and the database falls over. Two defences, both worth having:

  • Jittered TTLs. ttl = base + random.randint(0, base // 10). One line, removes synchronised expiry.
  • Single-flight. One request recomputes, the rest wait for its result. Most languages have a primitive for this; if not, a lock keyed on the cache key works.

Stale-while-revalidate. Serve the expired value immediately and refresh in the background. Latency stays flat and the stampede disappears, at the cost of a brief window of known-stale data. For read-heavy endpoints this is usually the right trade and it is underused.

the question to ask first#

Before choosing a strategy, answer this: how long may this data be wrong, and what happens if it is?

A product name being stale for a minute is fine. A permission check being stale for a minute is a security incident. The same cache library, the same code, and completely different correct answers.

Most bad caching is a correct strategy applied to data with a different staleness tolerance than the author assumed.

get README in your inbox

One dispatch, no noise. Tech and developer news, plus the occasional long piece on the craft.

subscribe →