Video in progress

Strong Middle 🧩 Microservices

The moment a popular cache key expires, hundreds of requests hit the downstream service at once (a cache stampede). How do you prevent it?

At the moment the key is gone, every request goes to the downstream at the same time because it's "not in the cache". To prevent it, only one request reloads the value (coalescing or a lock) while the rest wait or get the stale value; you add jitter to TTLs and refresh hot keys before they expire.

📖 Answer

The classic case: the "home page categories" are stored in Redis for 5 minutes, at 2,000 requests per second. The key expires, and within the next 300 ms 600 requests go to catalog-service. It runs a heavy query for each, slows down, and the following requests can't fill the cache either. Instead of helping, the cache created a wave of load.

Protection techniques (usually several together):

  1. A single load within one instance. Caffeine's cache.get(key, loader) calls the loader once per key, and the other threads wait for the result. In Spring @Cacheable(sync = true) does the same:
@Cacheable(cacheNames = "categories", sync = true)
public List<Category> categories() { return catalogClient.categories(); }
  1. Refreshing before expiry. In Caffeine, refreshAfterWrite(4, MINUTES) + expireAfterWrite(10, MINUTES): after 4 minutes the first request gets the old value immediately while the refresh runs in the background. The user doesn't wait, and the downstream gets one request.

  2. Across instances. With 20 pods, the first technique leaves one request per pod, 20 in total. Often that's enough. If it isn't, use a short lock in Redis (SET key:lock 1 NX PX 5000) so only one pod loads, and the others serve the old value.

  3. Jitter on the TTL. If a thousand keys were written at the same time (during a deploy, say), they expire at the same time. ttl = 300s + random(0..60s) spreads that out.

  4. Stale-on-error. If the downstream returns an error, returning the expired value is better than an error; for that, separate a "soft TTL" from a "hard TTL".

You can see this easily in metrics: in the cache hit ratio and the downstream RPS graph, spikes appear matching the TTL period.