Video in progress

Senior 🌱 Spring

When you use a cache, how do you deal with inconsistency with the database data and with cache stampedes?

For each cache I decide how stale the data is allowed to get and pick the strategy accordingly: TTL, evict after commit, versioned keys. Against a stampede: a single loader (request coalescing), refreshing in the background before expiry, and adding a random part to the TTL.

📖 Answer

Where inconsistency comes from:

  • the update committed to the database, but evicting the cache failed;
  • the cache was evicted before the commit, and another request still read the old data and put it back in the cache;
  • local caches on several instances.

The practical approach (cache-aside): on read, if it's not in the cache, load it from the database and put it in the cache with a TTL; on write, commit first, then evict the cache (AFTER_COMMIT). The TTL is there so the system heals itself after any mistake.

A cache stampede is when a popular key expires and 2000 requests rush to the database in a single second. What you can do:

  • A single loader. Caffeine's LoadingCache/AsyncCache loads a given key only once while the others wait for the result. In Spring @Cacheable(sync = true) works this way, but only within a single instance.
  • refreshAfterWrite refreshes in the background before expiry, and users get the old value in the meantime.
  • Jitter. If you give every key the same 10 minutes, after a deploy they all expire together. Make it 10 ± 2 minutes.
  • A distributed lock (Redis), if you need a single loader across many instances, but that's more complexity.

Think hard before caching data that has to be exact, like prices or stock levels. Often the right index turns out to be a simpler solution than a cache.