Redis is often placed in front of a database to reduce database load and improve application response times. In a normal cache-aside implementation, the application checks Redis first and queries the database only when the requested value is not available in the cache.
That sounds simple, but there is a production problem that can appear when a popular cache entry expires or gets evicted.
If hundreds or thousands of requests miss the same key at almost the same time, those requests can all query the database. Redis is doing exactly what it was asked to do, but the database suddenly receives a request volume that the cache was supposed to prevent.
This situation is commonly called a cache stampede or thundering herd.
The problem is not that cache misses are bad. Cache misses are expected. The problem is allowing many requests to perform the same expensive cache rebuild at the same time.
This article explains how the problem happens and how to protect a C# application from it using techniques such as request coalescing, distributed locking, stale-while-revalidate, TTL jitter, and refresh-ahead caching.
Understanding the Problem
A typical cache-aside flow looks like this:
Client
|
v
ASP.NET Core Application
|
v
Redis
|
| Cache hit
v
Return cached value
|
| Cache miss
v
Database
|
v
Store result in Redis
|
v
Return resultFor an ordinary request, this works well.
For example:
Request 1 -> Redis hit -> Return value
Request 2 -> Redis hit -> Return value
Request 3 -> Redis hit -> Return valueNow consider what happens when the cached value expires.
Request 1 -> Redis miss -> Database
Request 2 -> Redis miss -> Database
Request 3 -> Redis miss -> Database
Request 4 -> Redis miss -> Database
Request 5 -> Redis miss -> DatabaseAll five requests are asking the database for the same information.
If the application has many instances, the situation can become much worse.
Instance A -> Redis miss -> Database
Instance B -> Redis miss -> Database
Instance C -> Redis miss -> Database
Instance D -> Redis miss -> DatabaseThe database may suddenly receive hundreds of identical queries.
Cache Miss, Cache Stampede, and Cache Penetration Are Different
These terms are sometimes mixed together, but they describe different problems.
Problem | What happens | Typical cause |
|---|---|---|
Cache miss | Requested key is not in Redis | Expiration, eviction, cold cache |
Cache stampede | Many requests miss the same key and hit the database together | Popular key expiration |
Cache penetration | Requests repeatedly ask for data that does not exist | Invalid IDs or uncached negative results |
Cache avalanche | Large numbers of cache entries expire together | Same TTL or mass cache expiration |
A normal cache miss is not necessarily a problem.
A cache stampede is a concurrency problem caused by many requests rebuilding the same cache entry simultaneously.
The Naive Cache-Aside Implementation
A simple C# implementation might look like this:
public async Task<Product?> GetProductAsync(
int productId,
CancellationToken cancellationToken)
{
var cacheKey = $"product:{productId}";
var cached = await _redis.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cached))
{
return JsonSerializer.Deserialize<Product>(cached);
}
var product = await _db.Products
.AsNoTracking()
.FirstOrDefaultAsync(
x => x.Id == productId,
cancellationToken);
if (product is not null)
{
var json = JsonSerializer.Serialize(product);
await _redis.StringSetAsync(
cacheKey,
json,
TimeSpan.FromMinutes(10));
}
return product;
}The code is valid for a basic cache-aside implementation.
The problem appears under concurrency.
Suppose a product is extremely popular and its Redis entry expires.
Ten requests can execute this sequence:
Request 1: GET product:100 -> MISS
Request 2: GET product:100 -> MISS
Request 3: GET product:100 -> MISS
Request 4: GET product:100 -> MISS
Request 1 -> Database
Request 2 -> Database
Request 3 -> Database
Request 4 -> DatabaseEach request performs the same database operation.
The database work is duplicated even though only one request actually needed to rebuild the cache.
Why Popular Keys Are More Dangerous
Not every cache key creates the same amount of risk.
Consider two keys:
product:918273and:
homepage:featured-productsThe first might receive a few requests per minute.
The second could receive thousands of requests per second.
If the second key expires, the application can generate a sudden database spike.
This is why cache protection should focus on hot keys rather than treating every cache entry exactly the same way.
Solution One: Request Coalescing
One of the simplest solutions is to make requests for the same key share the same refresh operation.
This is sometimes called single-flight or request coalescing.
The idea is:
Redis MISS
|
+---------+---------+
| | |
Request Request Request
\ | /
\ | /
+-------+-------+
|
One DB operation
|
Cache result
|
All requests receive
the resultIn a single application instance, a keyed ConcurrentDictionary can coordinate requests.
For example:
private readonly ConcurrentDictionary<string, Lazy<Task<Product?>>> _refreshes = new();
public async Task<Product?> GetProductAsync(
int productId,
CancellationToken cancellationToken)
{
var cacheKey = $"product:{productId}";
var cached = await _redis.GetStringAsync(cacheKey);
if (!string.IsNullOrEmpty(cached))
{
return JsonSerializer.Deserialize<Product>(cached);
}
var refresh = _refreshes.GetOrAdd(
cacheKey,
_ => new Lazy<Task<Product?>>(
() => LoadProductAndCacheAsync(
productId,
cacheKey,
cancellationToken)));
try
{
return await refresh.Value;
}
finally
{
_refreshes.TryRemove(cacheKey, out _);
}
}The actual database and Redis refresh can be placed in a separate method:
private async Task<Product?> LoadProductAndCacheAsync(
int productId,
string cacheKey,
CancellationToken cancellationToken)
{
var product = await _db.Products
.AsNoTracking()
.FirstOrDefaultAsync(
x => x.Id == productId,
cancellationToken);
if (product is not null)
{
var json = JsonSerializer.Serialize(product);
await _redis.StringSetAsync(
cacheKey,
json,
TimeSpan.FromMinutes(10));
}
return product;
}Now concurrent requests for the same key can share the same refresh task.
There is an important limitation.
This dictionary exists only inside one application process.
If the application has five instances, each instance has its own dictionary.
Instance A -> local lock
Instance B -> local lock
Instance C -> local lock
Instance D -> local lockRedis can still receive multiple refresh operations from different instances.
For a distributed application, another strategy is needed.
Solution Two: Distributed Locking With Redis
A Redis-based distributed lock can allow one application instance to rebuild a cache entry while other instances wait or use another response strategy.
The basic concept is:
Instance A -> Acquires lock
Instance B -> Cannot acquire lock
Instance C -> Cannot acquire lock
Instance A -> Database
Instance A -> Redis
Instance A -> Releases lock
Instance B -> Reads Redis
Instance C -> Reads RedisA Redis lock can be created with SET using the NX and PX options.
With StackExchange.Redis, the operation can look like this:
var lockKey = $"lock:{cacheKey}";
var lockToken = Guid.NewGuid().ToString("N");
var acquired = await _redis.StringSetAsync(
lockKey,
lockToken,
TimeSpan.FromSeconds(10),
When.NotExists);When.NotExists ensures that the lock is created only when another process does not already hold it.
The lock should always have an expiration.
Without an expiration, a crashed application could leave a permanent lock behind.
Releasing the lock also needs care.
An application should not simply delete the lock key.
Imagine this sequence:
Instance A -> Acquires lock
Instance A -> Processing takes too long
Lock expires
Instance B -> Acquires new lock
Instance A -> Finishes
Instance A -> Deletes lockInstance A has now deleted a lock owned by Instance B.
The safer approach is to release the lock only if the stored token still belongs to the current process.
A Lua script can perform the check and delete atomically:
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
endThe token acts as ownership information.
Distributed locks are useful, but they should not automatically become the default solution for every cache miss.
A lock that is held while a slow database query runs can create another bottleneck.
For many applications, stale-while-revalidate is a better approach for high-traffic data.
Solution Three: Stale-While-Revalidate
With stale-while-revalidate, the application can continue serving an older value while one request refreshes the cache.
Instead of treating expiration as:
Expired -> Delete -> Database -> Cachethe application can use:
Fresh -> Serve normally
Stale -> Serve old value
+
Start refreshThis avoids making every user wait for the database.
A cache object can contain metadata about when the value should be refreshed:
public sealed record CachedProduct(
Product Value,
DateTimeOffset ExpiresAt,
DateTimeOffset StaleUntil);The application can decide whether the cached value is fresh or stale.
if (cached.ExpiresAt > DateTimeOffset.UtcNow)
{
return cached.Value;
}
if (cached.StaleUntil > DateTimeOffset.UtcNow)
{
_ = RefreshProductAsync(productId);
return cached.Value;
}
return await LoadProductAndCacheAsync(
productId,
cacheKey,
cancellationToken);The exact implementation depends on whether background processing is available and how important the data is.
The key idea is that a slightly old value is sometimes much better than forcing thousands of requests to wait for the database.
This approach is particularly useful for:
Product catalogs
Configuration data
Dashboard summaries
Public content
Frequently viewed reference data
Recommendations
Aggregated statistics
It is less appropriate when every response must reflect the latest database state.
Solution Four: Add TTL Jitter
Another useful technique is avoiding identical expiration times.
Suppose an application stores 100,000 keys with exactly the same TTL:
SET key-1 ... EX 600
SET key-2 ... EX 600
SET key-3 ... EX 600If those keys were inserted around the same time, many can expire around the same time.
Instead, introduce a small random variation.
var baseTtl = TimeSpan.FromMinutes(10);
var jitterSeconds = Random.Shared.Next(0, 60);
var ttl = baseTtl.Add(
TimeSpan.FromSeconds(jitterSeconds));
await _redis.StringSetAsync(
cacheKey,
json,
ttl);Now the expiration times are spread across a wider window.
TTL jitter does not solve a hot-key stampede by itself.
It reduces synchronized expiration and works particularly well as part of a broader cache strategy.
Solution Five: Refresh Popular Keys Before They Expire
Some applications know which cache entries are important.
For example:
homepage:products
homepage:offers
category:electronics
category:laptopsInstead of waiting for these keys to expire, a background process can refresh them before expiration.
This is called refresh-ahead caching.
The application can periodically:
Identify important keys.
Check their remaining TTL.
Refresh keys that are close to expiration.
Keep the value available for normal requests.
This works well when the set of hot keys is reasonably predictable.
It also removes cache rebuilding from the request path.
Solution Six: Cache Negative Results
Cache stampedes are not limited to existing records.
Consider an endpoint such as:
GET /api/products/999999If the product does not exist, every request may perform the same database query.
Without negative caching:
Request -> Redis MISS
-> Database
-> No productThe next request repeats the same work.
A short-lived negative cache entry can prevent this:
product:999999 -> NOT_FOUNDThe TTL should generally be much shorter than the TTL for valid objects.
For example:
await _redis.StringSetAsync(
cacheKey,
"NOT_FOUND",
TimeSpan.FromSeconds(30));This also helps protect against cache penetration caused by repeated invalid requests.
A Better Cache-Aside Flow
A production cache layer can combine several of these techniques.
A practical flow looks like this:
Request
|
v
Redis GET
|
+---- Hit and fresh ----> Return value
|
+---- Hit but stale ----> Return stale value
| |
| +--> Background refresh
|
+---- Miss --------------> Request coalescing
|
+--> One refresh operation
|
v
Database
|
v
Redis SET
|
v
Return valueFor multiple application instances, distributed coordination can be added around the refresh operation.
Protect the Database Even Further
Cache protection should not stop at Redis.
The database should also have safeguards.
A sudden cache failure can turn a healthy application into a database overload scenario.
Useful protections include:
Connection pool limits
Query timeouts
Cancellation tokens
Rate limiting
Bulkheads
Circuit breakers
Read replicas where appropriate
Expensive query monitoring
Request timeouts
For example, do not allow a cache refresh to wait indefinitely:
using var timeoutCts =
CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken);
timeoutCts.CancelAfter(TimeSpan.FromSeconds(2));
var product = await _db.Products
.AsNoTracking()
.FirstOrDefaultAsync(
x => x.Id == productId,
timeoutCts.Token);The exact timeout should be based on the application's normal database latency rather than an arbitrary value.
Comparing the Main Strategies
Strategy | Works Across Instances | Reduces Duplicate DB Calls | Best Use |
|---|---|---|---|
Local single-flight | No | Yes | One application instance |
Redis distributed lock | Yes | Yes | Controlled cache rebuild |
Stale-while-revalidate | Yes | Yes | High-traffic readable data |
TTL jitter | Yes | Partially | Avoiding synchronized expiration |
Refresh-ahead | Yes | Yes | Known hot keys |
Negative caching | Yes | Yes | Missing or invalid records |
These strategies are not mutually exclusive.
A production application may use several at the same time.
For example:
TTL jitter
+
Stale-while-revalidate
+
Request coalescing
+
Database timeoutThis combination is often more resilient than relying on one mechanism.
Common Mistakes
Using one global lock
A lock such as:
cache-refresh-lockcan serialize unrelated cache refreshes.
If one product is slow to load, another product may unnecessarily wait.
Prefer key-specific coordination:
lock:product:100
lock:product:200
lock:product:300Using only an in-memory lock in a distributed application
A SemaphoreSlim or ConcurrentDictionary can coordinate requests inside one process, but it cannot coordinate different application instances.
If five instances can process the same key, each instance can still perform a database refresh.
Creating a distributed lock without expiration
A lock should have a bounded lifetime.
A crashed process should not be able to permanently block cache rebuilding.
Deleting a lock without checking ownership
Always ensure that the process releasing the lock still owns it.
Blindly calling DEL can remove another process's lock.
Giving every key the same TTL
Fixed TTL values can cause groups of keys to expire together.
Adding jitter helps spread expiration.
Holding a lock during an unlimited database operation
A slow or unavailable database can keep the lock occupied for too long.
Use appropriate timeouts and cancellation.
Treating stale data as always acceptable
Stale-while-revalidate is not appropriate for every type of data.
Balance freshness requirements against availability and database load.
Monitoring for a Cache Stampede
A cache stampede usually becomes visible through metrics before it becomes obvious from application errors.
Useful metrics include:
Cache hit ratio
Cache miss rate
Redis latency
Database query rate
Database CPU
Database connection pool usage
Cache refresh duration
Cache refresh failures
Lock acquisition failures
Lock wait duration
Hot-key access frequencyOne useful diagnostic pattern is to compare cache misses with database traffic.
For example:
09:00
Cache misses: 500
DB requests: 2,000
09:10
Cache misses: 5,500
DB requests: 5,700If database traffic suddenly follows cache misses for a popular key, the cache layer may not be protecting the database effectively.
Application logs should also include the cache key or a safe identifier for the resource being refreshed.
Do not log sensitive cache contents.
A Practical Production Checklist
Before deploying a Redis-backed cache for a high-traffic application, check the following:
Identify which cache keys are actually hot.
Decide what should happen when a key expires.
Prevent multiple requests from rebuilding the same key simultaneously.
Use distributed coordination if multiple application instances can refresh the same key.
Add expiration jitter where synchronized TTLs are possible.
Consider stale-while-revalidate for data that can tolerate short periods of staleness.
Cache negative results for repeated missing records.
Put timeouts around database refresh operations.
Monitor Redis misses and database traffic together.
Test the behavior when Redis is unavailable.
Test the behavior when the database is slow.
Load-test hot keys rather than only testing average traffic.
The most important part is to test expiration under concurrency.
A cache implementation can look perfectly healthy during normal testing because requests are spread out.
The real test is what happens when a popular key expires and hundreds of requests arrive at nearly the same time.
Advantages and Disadvantages
Advantages
Reduces duplicate database queries.
Protects the database from sudden cache-related traffic spikes.
Improves response times for hot data.
Makes cache expiration more predictable.
Allows the application to handle traffic bursts more gracefully.
Provides better control over database load.
Disadvantages
Adds concurrency and cache-management complexity.
Distributed locks require careful ownership and expiration handling.
Stale-while-revalidate can return older data.
TTL jitter makes expiration timing less predictable.
Background refresh introduces additional application work.
Poorly designed locking can become a bottleneck.
The goal is not to eliminate every cache miss.
The goal is to make a cache miss an inexpensive event instead of allowing it to become a database incident.
Conclusion
Redis is effective at reducing database load, but simply adding a cache does not automatically protect the database from traffic spikes.
The dangerous case is not one request missing the cache. It is many requests missing the same cache entry at the same time and independently rebuilding it.
For low-traffic applications, a basic cache-aside pattern may be enough. As traffic grows, the cache layer needs to account for concurrency and failure scenarios.
Request coalescing can prevent duplicate work inside one application instance. Distributed locks can coordinate refreshes across instances when used carefully. Stale-while-revalidate can keep users from waiting during cache rebuilds. TTL jitter can reduce synchronized expiration, while refresh-ahead can remove cache rebuilding from the request path entirely.
A good Redis caching strategy therefore looks beyond cache hit ratio. It considers what happens during expiration, eviction, Redis failures, database slowdowns, and sudden bursts of requests.
The database should remain protected even when the cache is empty.
That is the real purpose of cache stampede protection.


Join the conversation! Your thoughts help the community grow.