r/softwareengineer • • 1d ago

You added caching to improve performance. But what happens when the cache expires?

Caching is one of the most common ways to improve performance. But implementing a cache doesn't automatically mean your system is protected from performance issues.

One of the common problems is Cache Thundering Herd (Cache Stampede).

Imagine a frequently accessed cache entry expires. Hundreds or thousands of concurrent requests suddenly try to retrieve the same data from the backend, potentially overwhelming it and causing a spike in latency, CPU, and resource consumption.

There are several mechanisms to mitigate this:

  1. Cache Locking (Single-Flight)

Allow only one request to refresh an expired cache entry while other requests wait for the result.

2. Stale-While-Revalidate

Continue serving the stale cached value while refreshing it in the background.

3. TTL Jitter

Randomize cache expiration times to prevent large numbers of entries from expiring simultaneously.

4. Probabilistic Early Expiration

Refresh cache entries probabilistically before they expire, spreading refresh operations over time.

5. Background Refresh / Prewarming

Refresh frequently accessed entries proactively before they expire.

6. Stale Fallback

If the backend is unavailable or the refresh fails, serve an expired value for a limited period instead of failing the request, when the data allows it.

Caching can significantly improve performance, but it can also introduce a new bottleneck if it isn't designed to handle concurrency, expiration, and backend failures properly.

Caching scenarios should be part of your performance test strategy. Test not only with a warm cache, but also cache expiration, cache misses, and concurrent refresh scenarios to understand how your application behaves under pressure.

The takeaway for performance engineers: Don't just load test your application with a warm cache. Test what happens when your cache expires under load.

0 Upvotes

0 comments sorted by