Caching is one of the most effective ways to improve application performance. By storing frequently requested data in Redis, .NET applications can reduce database queries, improve response times, and handle more concurrent users.
However, caching introduces another problem that developers often overlook: cache stampedes.
A cache stampede occurs when a popular cache entry expires or becomes unavailable and many requests attempt to retrieve the same data from the database at the same time. Instead of reducing database load, the cache temporarily increases it. Under heavy traffic, this can overload the database, increase API response times, and even cause application failures.
This problem is particularly common in applications that use Redis as a distributed cache and serve thousands of concurrent requests.
In this article, we will explore what causes Redis cache stampedes, how to identify them, and how to prevent them in .NET applications using expiration jitter, request coalescing, HybridCache, and Redis-based distributed locking.
What Is a Redis Cache Stampede?
A Redis cache stampede happens when multiple application requests encounter the same cache miss and independently try to load the same data from the original data source.
Consider an e-commerce application that stores product details in Redis.
var product = await cache.GetStringAsync("product:101");
if (product == null)
{
product = await database.GetProductAsync(101);
await cache.SetStringAsync(
"product:101",
product,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(10)
});
}
This implementation works when requests arrive at different times. However, it has a problem when many requests access the same key immediately after it expires.
Imagine that 500 users request the same popular product at almost the same moment.
The following sequence can occur:
Redis contains the product information.
The cache entry expires after ten minutes.
All 500 requests check Redis.
Redis returns a cache miss to every request.
All requests independently query the database.
The database receives 500 identical queries.
Every request attempts to write the same product information back to Redis.
This situation creates unnecessary database traffic.
<escape> </escape>
Why Cache Stampedes Are Dangerous
Cache stampedes are not limited to one database query. They can affect the entire application infrastructure.
For example, if a product API normally receives 2,000 requests per second and has a cache hit ratio of 95%, the database may receive only a small portion of those requests.
If a popular cache entry expires and hundreds of requests miss simultaneously, the database can suddenly receive a large number of queries for the same record.
The consequences include:
Increased database CPU and memory usage.
Higher database connection-pool consumption.
Increased API response times.
Request timeouts and failed requests.
Increased Redis and network traffic.
Cascading failures in dependent services.
Higher infrastructure costs.
A cache stampede can also trigger a feedback loop. As database response times increase, requests remain active for longer. More requests accumulate, consume application resources, and create additional pressure on the database.
The problem becomes more serious when several application instances share the same Redis cache.
Common Causes of Redis Cache Stampedes
Understanding the causes helps developers choose the right prevention strategy.
Simultaneous Cache Expiration
The most common cause is a popular cache entry expiring at a time when many users request it.
For example, if every product cache entry is configured with a fixed ten-minute expiration, frequently accessed entries may expire together.
This is especially problematic when applications warm up large groups of cache entries at the same time.
High Traffic on Popular Keys
Some cache keys receive significantly more traffic than others.
Examples include:
Homepage data.
Product details.
User configuration.
Frequently accessed reports.
Dashboard statistics.
Public API responses.
When one of these keys expires, many requests can compete to reload the same data.
Slow Database Queries
A slow database query increases the time during which the cache remains empty.
If retrieving a product takes 500 milliseconds, hundreds of requests may reach the database before the first request completes and writes the result to Redis.
Multiple Application Instances
In a distributed environment, several ASP.NET Core instances may access the same Redis server.
A local lock in one application instance cannot coordinate requests arriving at other instances.
For example, five application instances may each allow one request to load the same missing product. The database still receives five queries instead of one.
Use Expiration Jitter to Prevent Simultaneous Expiration
One of the simplest ways to reduce cache stampedes is to introduce random variation into cache expiration times.
This technique is commonly called expiration jitter.
Instead of assigning every cache entry the same expiration time, add a random duration to the configured time-to-live.
For example, rather than expiring every product entry after exactly ten minutes, assign a random expiration between eight and twelve minutes.
This spreads cache expiration across time and reduces the possibility of many entries expiring simultaneously.
Implement Expiration Jitter in C#
using Microsoft.Extensions.Caching.Distributed;
using System.Security.Cryptography;
public static class CacheExpiration
{
public static TimeSpan AddJitter(
TimeSpan baseExpiration,
int maximumJitterSeconds = 120)
{
var jitterSeconds =
RandomNumberGenerator.GetInt32(
0,
maximumJitterSeconds + 1);
return baseExpiration +
TimeSpan.FromSeconds(jitterSeconds);
}
}
Use this helper when storing data in Redis:
var expiration = CacheExpiration.AddJitter(
TimeSpan.FromMinutes(10));
await cache.SetStringAsync(
"product:101",
productJson,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = expiration
});
Each cache entry receives a slightly different expiration time.
Expiration jitter is useful when applications cache many records or populate several entries together.
However, it does not guarantee that only one request will load a particular missing key. If a highly popular key expires, multiple requests can still reach the database. Combine jitter with request coalescing or another coordination mechanism when the workload requires stronger protection.
Use Request Coalescing to Avoid Duplicate Database Queries
Request coalescing ensures that concurrent requests for the same missing cache key share one data-loading operation.
For example, if 100 requests need product 101 and the value is missing from Redis, one request loads the product from the database. The other requests wait for that operation and use its result.
This pattern is also called single-flight request processing.
Implement Request Coalescing With SemaphoreSlim
For a single application instance, SemaphoreSlim provides a straightforward way to coordinate concurrent requests.
using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Distributed;
public class ProductCacheService
{
private readonly IDistributedCache _cache;
private readonly ConcurrentDictionary<
string,
SemaphoreSlim> _locks = new();
public ProductCacheService(
IDistributedCache cache)
{
_cache = cache;
}
public async Task<string?> GetProductAsync(
string key,
CancellationToken cancellationToken)
{
var cached = await _cache.GetStringAsync(
key,
cancellationToken);
if (cached != null)
return cached;
var semaphore = _locks.GetOrAdd(
key,
_ => new SemaphoreSlim(1, 1));
await semaphore.WaitAsync(cancellationToken);
try
{
// Check Redis again after acquiring the lock.
cached = await _cache.GetStringAsync(
key,
cancellationToken);
if (cached != null)
return cached;
var product = await LoadProductFromDatabaseAsync(
key,
cancellationToken);
if (product == null)
return null;
await _cache.SetStringAsync(
key,
product,
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(10)
},
cancellationToken);
return product;
}
finally
{
semaphore.Release();
}
}
private Task<string?> LoadProductFromDatabaseAsync(
string key,
CancellationToken cancellationToken)
{
// Replace this with the actual database query.
return Task.FromResult<string?>(
"""{"id":101,"name":"Laptop"}""");
}
}
The second cache lookup is important.
While one request is waiting for the semaphore, another request may already have loaded the data and stored it in Redis. Checking Redis again avoids an unnecessary database query.
This implementation provides request coalescing only inside one application process. It does not coordinate requests across multiple ASP.NET Core instances.
There is also a lifecycle consideration: the dictionary retains semaphore entries for every distinct key used. Applications with unbounded or highly variable cache keys should use a bounded coordination mechanism or a cache implementation that manages this state internally.
Use HybridCache for Built-In Stampede Protection
Modern .NET applications can use HybridCache to simplify caching and reduce duplicate data-loading operations.
HybridCache combines local in-memory caching with a distributed cache such as Redis.
It provides several useful features:
Two-level caching.
Configurable serialization.
Tag-based invalidation.
Built-in stampede protection.
A unified API for cache access.
HybridCache was introduced in .NET 9 and is available through the Microsoft.Extensions.Caching.Hybrid package.
Install the package:
dotnet add package Microsoft.Extensions.Caching.Hybrid
Configure Redis and HybridCache
Register Redis as the distributed cache and configure HybridCache in Program.cs.
using Microsoft.Extensions.Caching.Hybrid;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration =
builder.Configuration.GetConnectionString("Redis");
});
builder.Services.AddHybridCache(options =>
{
options.DefaultEntryOptions =
new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(30),
LocalCacheExpiration =
TimeSpan.FromMinutes(5)
};
});
var app = builder.Build();
app.Run();
The Redis connection string can be configured in appsettings.json:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
For production, use an appropriate secure connection configuration and store credentials outside source control.
Retrieve Data With GetOrCreateAsync
Instead of manually checking Redis, loading the database, and writing the result back, use GetOrCreateAsync.
public class ProductService
{
private readonly HybridCache _cache;
private readonly IProductRepository _repository;
public ProductService(
HybridCache cache,
IProductRepository repository)
{
_cache = cache;
_repository = repository;
}
public async Task<Product?> GetProductAsync(
int productId,
CancellationToken cancellationToken)
{
return await _cache.GetOrCreateAsync(
$"product:{productId}",
async token =>
{
return await _repository.GetByIdAsync(
productId,
token);
},
cancellationToken: cancellationToken);
}
}
When multiple concurrent requests use the same key through the same HybridCache instance, HybridCache coordinates the operation so that only one request performs the underlying factory operation while the others wait for the result.
This is a useful way to prevent duplicate database queries without implementing custom locks.
However, an important limitation must be understood: HybridCache's stampede protection coordinates requests within the same HybridCache instance. It does not provide a distributed lock shared by separate application processes.
If an application runs five instances, each instance may independently execute its factory operation for the same missing key.
Join the conversation! Your thoughts help the community grow.