Redis is commonly used to reduce database load and improve application response times. Instead of executing the same database query for every request, an application retrieves frequently accessed data from Redis and returns the cached result.

This approach works well until a popular cache entry expires.

Imagine an application where thousands of users request the same product information. The product details are cached in Redis with a time-to-live (TTL) of 10 minutes. When the entry expires, multiple requests may arrive before the cache is refreshed.

Every request sees a cache miss and attempts to retrieve the same information from the database.

Instead of executing one database query, the application may execute hundreds or thousands of identical queries simultaneously.

This situation is known as a cache stampede, also called the thundering herd problem.

A cache stampede can increase database CPU usage, exhaust connection pools, increase API response times, and eventually make an application unavailable.

The important point is that having Redis in an application does not automatically prevent database overload. The application must also control how cache misses are handled.

This article explains how cache stampedes happen, how to identify them, and how to prevent them using practical Redis and C# implementation patterns.

What Is a Redis Cache Stampede?

A cache stampede occurs when multiple requests try to regenerate the same expired or missing cache entry at approximately the same time.

Normally, the caching process looks like this:

  1. The application receives a request.

  2. It checks Redis for the requested data.

  3. If the data exists, Redis returns the cached value.

  4. If the data does not exist, the application queries the database.

  5. The application stores the result in Redis.

  6. The application returns the result to the user.

This process works when requests arrive at different times.

However, when many requests arrive simultaneously after a popular key expires, they can all execute the database query before any request has populated the cache.

Example of a cache stampede

Consider an application that caches product information:

Code
Cache Key: product:1001
TTL: 10 minutes
Database: PostgreSQL
Cache: Redis

Assume 1,000 users request the same product at approximately the same time.

When the cache entry expires, the requests follow this pattern:

Request

Redis result

Application action

Request 1

Cache miss

Queries database

Request 2

Cache miss

Queries database

Request 3

Cache miss

Queries database

Request 4

Cache miss

Queries database

Request 5

Cache miss

Queries database

...

...

...

Request 1,000

Cache miss

Queries database

All these requests may execute the same database query:

SQL
SELECT
    product_id,
    product_name,
    price,
    stock_quantity
FROM products
WHERE product_id = 1001;

The database performs unnecessary duplicate work because all requests need the same result.

If the database was already handling normal application traffic, this additional load can create a serious performance problem.

Why Cache Stampedes Happen

Several application and infrastructure conditions can contribute to cache stampedes.

Some application data is requested much more frequently than other data.

Examples include:

  • Product details on an e-commerce website.

  • User profile information.

  • Dashboard statistics.

  • Application configuration.

  • Frequently accessed reports.

  • Trending content.

When a popular key expires, a large number of requests may attempt to regenerate it.

The problem becomes worse when many cache entries are assigned the same fixed TTL.

For example:

C#
await database.StringSetAsync(
    "product:1001",
    productJson,
    TimeSpan.FromMinutes(10)
);

If several popular keys are populated around the same time with identical expiration durations, their expiration times can become synchronized.

This can create a burst of database queries.

Multiple application instances receive the same request

A distributed application commonly runs multiple application instances behind a load balancer.

For example:

Code
              Load Balancer
                    |
          -----------------------
          |          |          |
       API 1      API 2      API 3
          |          |          |
          -----------------------
                    |
                  Redis
                    |
                Database

Suppose all three application instances receive requests for the same expired cache key.

Each instance checks Redis and receives a cache miss.

Without coordination, all three instances may query the database.

A local lock inside one application instance cannot prevent another instance from executing the same query.

This is why distributed applications need a strategy that coordinates cache regeneration across instances.

Redis becomes unavailable

A cache stampede can also happen when Redis becomes temporarily unavailable.

If the application treats every Redis connection failure as an ordinary cache miss, all incoming requests may bypass Redis and query the database.

For example:

C#
var cachedValue = await redis
    .StringGetAsync(cacheKey);

if (cachedValue.IsNull)
{
    return await LoadFromDatabaseAsync();
}

This example does not distinguish between an actual missing key and a Redis connection failure.

In production, these conditions should be handled separately.

A Redis outage can affect the entire application because many requests may suddenly fall back to the database.

The application needs a fallback strategy that protects the database instead of sending unlimited requests to it.

Cache Stampede vs. Cache Avalanche vs. Cache Penetration

These terms describe different caching problems, although their symptoms can overlap.

Problem

What happens

Typical example

Cache stampede

Many requests regenerate the same expired key

Thousands of requests query one product

Cache avalanche

Many cache entries expire or become unavailable around the same time

A large group of keys expires together

Cache penetration

Requests repeatedly ask for data that does not exist in the cache or database

Invalid product IDs generate repeated database queries

Understanding the difference helps select the correct solution.

For example, request coalescing is useful for a cache stampede involving one key. TTL jitter helps distribute expiration times across many keys. Negative caching can reduce repeated database queries for nonexistent records.

These techniques solve related but different problems.

Preventing Cache Stampedes With Request Coalescing

Request coalescing ensures that only one request loads a particular missing value while other requests wait for the same result.

This pattern is also known as single-flight request handling.

Instead of allowing every request to query the database, the application coordinates requests using the cache key.

The process looks like this:

  1. Multiple requests check Redis.

  2. All requests receive a cache miss.

  3. One request becomes responsible for loading the data.

  4. Other requests wait for the same operation.

  5. The responsible request queries the database.

  6. The result is stored in Redis.

  7. Waiting requests receive the same result.

<escape>### </escape>Implementing request coalescing in C#

For an application running on a single process, SemaphoreSlim can help coordinate requests for the same cache key.

The following example uses StackExchange.Redis:

C#
using StackExchange.Redis;
using System.Collections.Concurrent;
using System.Text.Json;

public class ProductCacheService
{
    private readonly IDatabase _redis;

    private readonly ConcurrentDictionary<
        string,
        SemaphoreSlim> _locks = new();

    public ProductCacheService(IConnectionMultiplexer connection)
    {
        _redis = connection.GetDatabase();
    }

    public async Task<Product?> GetProductAsync(
        int productId)
    {
        var cacheKey = $"product:{productId}";

        var cachedValue = await _redis.StringGetAsync(
            cacheKey);

        if (!cachedValue.IsNull)
        {
            return JsonSerializer.Deserialize<Product>(
                cachedValue.ToString());
        }

        var semaphore = _locks.GetOrAdd(
            cacheKey,
            _ => new SemaphoreSlim(1, 1));

        await semaphore.WaitAsync();

        try
        {
            // Check Redis again because another request
            // may have populated the cache while waiting.
            cachedValue = await _redis.StringGetAsync(
                cacheKey);

            if (!cachedValue.IsNull)
            {
                return JsonSerializer.Deserialize<Product>(
                    cachedValue.ToString());
            }

            var product = await LoadProductFromDatabaseAsync(
                productId);

            if (product is null)
            {
                return null;
            }

            var json = JsonSerializer.Serialize(product);

            await _redis.StringSetAsync(
                cacheKey,
                json,
                TimeSpan.FromMinutes(10));

            return product;
        }
        finally
        {
            semaphore.Release();
        }
    }

    private Task<Product?> LoadProductFromDatabaseAsync(
        int productId)
    {
        // Replace with the actual database query.
        throw new NotImplementedException();
    }
}

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; } = string.Empty;
    public decimal Price { get; set; }
}

The important part is the second Redis check after acquiring the semaphore.

Without this check, requests that were waiting could still execute unnecessary database queries even after the first request populated the cache.

Important production considerations

This implementation provides request coalescing only within one application process.

It does not coordinate requests across multiple application instances.

For example, if an application has five instances, each instance can have its own SemaphoreSlim for the same cache key.

That means up to five database queries may still execute during a simultaneous cache miss.

Also, the dictionary of locks needs a lifecycle strategy. A long-running application that creates locks for an unlimited number of unique keys can retain unnecessary objects in memory.

For a small, controlled set of cache keys, this may be manageable. For high-cardinality workloads, use a lock manager with safe cleanup or a bounded single-flight implementation.

Using Redis Distributed Locks

When an application runs across multiple instances, a distributed lock can coordinate cache regeneration across the entire application.

Redis supports atomic operations that allow an application to acquire a lock only when the lock key does not already exist.

The SET command supports the NX and PX options:

  • NX creates the key only if it does not already exist.

  • PX assigns an expiration time in milliseconds.

For example:

Code
SET lock:product:1001 unique-token NX PX 10000

If the command succeeds, the application owns the lock for the specified period.

If another application instance attempts to acquire the same lock, it receives a result indicating that the lock is already held.

Distributed lock workflow

Consider three application instances receiving requests for the same product.

Code
API 1 --------\
API 2 --------- Redis
API 3 --------/

API 1 acquires lock:product:1001
API 2 waits for the cache
API 3 waits for the cache

API 1 queries database
API 1 updates Redis
API 1 releases the lock

API 2 and API 3 read the cached result

Only one instance performs the expensive database operation.

Implementing a Redis lock

The following example demonstrates the basic lock acquisition and safe release pattern.

C#
using StackExchange.Redis;

public class RedisLockService
{
    private readonly IDatabase _database;

    public RedisLockService(
        IConnectionMultiplexer connection)
    {
        _database = connection.GetDatabase();
    }

    public async Task<bool> TryAcquireLockAsync(
        string lockKey,
        string lockToken,
        TimeSpan expiration)
    {
        return await _database.StringSetAsync(
            lockKey,
            lockToken,
            expiration,
            When.NotExists);
    }

    public async Task ReleaseLockAsync(
        string lockKey,
        string lockToken)
    {
        const string script = """
            if redis.call('GET', KEYS[1]) == ARGV[1] then
                return redis.call('DEL', KEYS[1])
            else
                return 0
            end
            """;

        await _database.ScriptEvaluateAsync(
            script,
            new RedisKey[] { lockKey },
            new RedisValue[] { lockToken });
    }
}

The release operation uses a Lua script to ensure that an application deletes the lock only when the stored token matches its own token.

This is important because a lock may expire and another application instance may acquire it before the original owner attempts to release it.

A simple DEL operation could accidentally delete the newer owner's lock.

What happens if the lock owner crashes?

Distributed locks must also account for application failures.

Suppose an application acquires a lock and crashes before completing the database query.

Without an expiration time, the lock could remain indefinitely.

An expiration time allows another request to attempt the operation after the lock expires.

However, the lock duration must be selected carefully.

If the database query takes longer than the lock expiration, another instance may acquire the lock while the original operation is still running.

Both instances could then query the database.

For longer operations, use lock renewal with appropriate ownership checks, or a coordination mechanism with fencing tokens where stronger protection is required.

A Redis lock reduces duplicate work, but it should not be treated as a guarantee that the protected operation can never execute twice.

When should you use distributed locks?

Distributed locking is useful when:

  • The application runs across multiple instances.

  • The same cache keys are accessed frequently.

  • Database queries are expensive.

  • Duplicate cache regeneration creates significant load.

  • A shared cache coordinates multiple services.

For less expensive queries, local request coalescing may be sufficient. Distributed locking introduces additional Redis operations and failure-handling complexity.

Choose the approach based on the actual cost of duplicate database work.

Preventing Simultaneous Expiration With TTL Jitter

TTL jitter introduces a small random variation into cache expiration times.

Instead of assigning every cache entry exactly 10 minutes, the application adds or subtracts a random amount of time.

For example:

Cache entry

Base TTL

Actual TTL

product:1001

10 minutes

9 minutes

product:1002

10 minutes

11 minutes

product:1003

10 minutes

10 minutes 30 seconds

product:1004

10 minutes

9 minutes 40 seconds

This distributes expiration times and reduces the likelihood that many entries expire together.

Implementing TTL jitter in C#

C#
private static TimeSpan GetCacheExpiration()
{
    var random = Random.Shared.Next(
        540,
        661);

    return TimeSpan.FromSeconds(random);
}

The returned expiration time varies between 9 minutes and 11 minutes.

You can use it when storing a cache entry:

C#
await redis.StringSetAsync(
    cacheKey,
    productJson,
    GetCacheExpiration());

TTL jitter is particularly useful when:

  • Many cache entries are created during application startup.

  • A batch process populates large numbers of cache keys.

  • Popular records have similar expiration durations.

  • A cache refresh operation updates many entries together.

However, TTL jitter alone does not prevent multiple requests from regenerating the same popular key.

It reduces synchronized expiration across keys. Request coalescing handles concurrent requests for an individual key.

For better protection, combine both techniques.

Using Stale-While-Revalidate

Some applications do not need every response to contain the latest database value.

For example, a product description or dashboard summary may remain acceptable for a short period after its nominal cache expiration.

In these cases, stale-while-revalidate can improve availability and reduce database pressure.

The idea is to keep a cached value available after its normal freshness period while a background operation refreshes it.

Instead of removing the value immediately, store two expiration boundaries:

  • Soft expiration: The point at which the value should be refreshed.

  • Hard expiration: The point after which the value must no longer be served.

For example:

Code
Product Cache
-----------------------------
Fresh for:       10 minutes
Serve stale for:  5 minutes
Hard expiration: 15 minutes

The application behaves as follows:

Cache state

Application behavior

Fresh

Return cached value

Soft expired

Return stale value and trigger one refresh

Hard expired

Wait for refresh or use a controlled fallback

This avoids forcing every user to wait for a database query when a cached value becomes slightly outdated.

Example implementation

A cache entry can contain the data and its refresh metadata:

C#
public class CachedProduct
{
    public Product Product { get; set; } = new();

    public DateTimeOffset RefreshAfter { get; set; }

    public DateTimeOffset ExpiresAt { get; set; }
}

The application can inspect the cached value:

C#
var cachedJson = await redis.StringGetAsync(cacheKey);

if (!cachedJson.IsNull)
{
    var cached = JsonSerializer.Deserialize<CachedProduct>(
        cachedJson.ToString());

    if (cached is not null)
    {
        var now = DateTimeOffset.UtcNow;

        if (now < cached.RefreshAfter)
        {
            return cached.Product;
        }

        if (now < cached.ExpiresAt)
        {
            // Return the stale value immediately.
            // Trigger a coordinated background refresh.
            await TryScheduleRefreshAsync(productId);

            return cached.Product;
        }
    }
}

The refresh operation should use a distributed coordination mechanism so that multiple application instances do not all start refreshing the same key.

The background refresh must also have a failure strategy.

If the database is temporarily unavailable, the application may continue serving the stale value until the hard expiration is reached, provided the data is safe to serve.

For payment balances, account permissions, inventory reservations, or other sensitive data, stale responses may be unacceptable.

Stale-while-revalidate should therefore be applied according to the consistency requirements of the data.

Using Probabilistic Early Refresh

Another approach is to refresh popular cache entries before they actually expire.

Instead of waiting until the TTL reaches zero, the application decides whether to refresh the entry based on its remaining lifetime and a probability calculation.

This approach is useful for frequently accessed cache entries where expiration would otherwise produce a large number of simultaneous requests.

One established technique is known as XFetch.

The algorithm uses factors such as the previous regeneration time, a tuning parameter, a random value, and the remaining cache lifetime to decide when to refresh.

The goal is to spread refresh activity over time without requiring every cache key to use the same fixed refresh interval.

For example:

  • A popular key may be refreshed before expiration.

  • A less frequently accessed key may remain cached until its normal expiration.

  • Only selected requests initiate early refreshes.

Probabilistic early refresh is more sophisticated than ordinary TTL jitter.

It can be useful for high-traffic systems with predictable hot keys, but it requires careful implementation and testing.

For most applications, request coalescing and TTL jitter are simpler starting points.

Handling Redis Failures Without Overloading the Database

A robust caching strategy must also account for Redis connection failures.

Consider this implementation:

C#
try
{
    return await LoadFromCacheAsync();
}
catch
{
    return await LoadFromDatabaseAsync();
}

This approach appears convenient because the application can continue working when Redis is unavailable.

However, if thousands of requests execute this fallback simultaneously, the database may become overloaded.

A better approach is to control database fallback traffic.

Possible protections include:

  • Local in-memory caching for frequently accessed data.

  • Request coalescing before querying the database.

  • Database concurrency limits.

  • Circuit breakers.

  • Request timeouts.

  • Controlled retries with jitter.

  • Serving previously cached values when their age is acceptable.

Use a circuit breaker

A circuit breaker can stop repeated attempts to access an unhealthy dependency.

For example, when Redis is experiencing a connection problem, the application can temporarily avoid sending repeated requests that are unlikely to succeed.

A circuit breaker does not solve cache stampedes by itself. It helps control repeated failures and prevents unnecessary dependency calls.

The database also needs its own protection because bypassing Redis should never mean allowing unlimited database queries.

Monitoring Cache Stampedes

Preventing cache stampedes requires monitoring both Redis and the database.

A cache may appear healthy while the database experiences sudden spikes caused by simultaneous cache misses.

Monitor the following metrics:

Metric

Why it matters

Cache hit ratio

Indicates how frequently requests are served from Redis

Cache miss rate

Helps identify sudden increases in database fallback

Key expiration rate

Reveals expiration patterns

Database query rate

Shows whether cache misses are increasing database activity

Database connection usage

Helps identify connection pool exhaustion

API response time

Shows the impact on application requests

Redis latency

Helps identify cache infrastructure problems

Lock acquisition failures

Indicates contention around popular cache keys

Background refresh failures

Helps identify cache regeneration problems

Check Redis statistics

Redis provides the INFO command for inspecting server statistics.

For example:

Code
INFO stats

Important counters include:

Code
keyspace_hits
keyspace_misses
expired_keys
evicted_keys

These counters help understand cache activity.

You can calculate a basic cache hit ratio using the hit and miss counters:

Code
Cache Hit Ratio =
    keyspace_hits /
    (keyspace_hits + keyspace_misses)
    * 100

For meaningful monitoring, calculate the ratio over a consistent observation period rather than interpreting lifetime counters without context.

Also remember that cache misses do not automatically indicate a stampede. Correlate Redis metrics with application-level database query counts and request traces.

Identify repeated database queries

Application monitoring should capture:

  • The cache key involved in the miss.

  • The number of concurrent requests for that key.

  • The number of database queries generated.

  • The duration of cache regeneration.

  • The time taken to populate Redis.

  • Whether requests waited for another refresh operation.

Avoid logging sensitive cache values or customer information.

A useful metric is the number of database regeneration operations per cache key over a defined period.

If one popular key repeatedly causes many database queries during expiration, request coalescing or refresh-ahead strategies may be needed.

Common Mistakes When Preventing Cache Stampedes

Mistake

Why it creates problems

Better approach

Using only a fixed TTL

Popular keys can expire together

Add TTL jitter

Using SemaphoreSlim across multiple instances

Locks are local to each process

Use distributed coordination when necessary

Releasing a Redis lock with a simple DEL

May delete another owner's lock

Compare the ownership token before deletion

Setting a very short lock expiration

Another instance may acquire the lock too early

Select and manage lock lifetime carefully

Retrying database queries immediately

Retries can amplify the load

Use bounded retries with exponential backoff and jitter

Treating Redis failures as ordinary misses

Every request may hit the database

Add controlled fallback and concurrency limits

Serving stale data for every type of record

Some information must remain accurate

Define freshness requirements per data type

Ignoring failed background refreshes

Cache entries may remain stale or expire

Monitor refresh failures and define recovery behavior

Assuming a high cache hit ratio guarantees safety

A single hot key can still create a stampede

Monitor per-key concurrency and regeneration

No single technique prevents every type of cache stampede.

A practical approach combines several protections based on the application's workload.

For a typical distributed application using Redis and a relational database, consider this strategy:

Layer

Recommended technique

Purpose

Cache expiration

TTL jitter

Distribute expiration times

Application instance

Request coalescing

Prevent duplicate queries within one process

Distributed application

Redis distributed lock or another coordination mechanism

Coordinate refreshes across instances

Cache freshness

Stale-while-revalidate

Continue serving acceptable cached values during refresh

Database access

Concurrency limits and timeouts

Protect database capacity

Failure handling

Circuit breaker and bounded retries

Prevent cascading failures

Monitoring

Redis and database metrics

Detect stampedes before they become outages

For an application with a small number of hot keys, start with request coalescing and TTL jitter.

For applications running multiple instances, add distributed coordination where duplicate database work is expensive.

For data that can tolerate a short freshness delay, consider stale-while-revalidate.

Finally, make sure the database has a defined maximum amount of concurrent work it can safely handle.

Conclusion

A Redis cache stampede occurs when multiple requests attempt to regenerate the same missing or expired cache entry at the same time.

Although Redis reduces database traffic during normal operation, an uncontrolled cache miss can send a large number of duplicate queries directly to the database.

Preventing this problem requires more than setting an expiration time.

Use request coalescing to ensure that concurrent requests share the same database result. Introduce TTL jitter to distribute expiration times. Use distributed locks when multiple application instances must coordinate cache regeneration. Consider stale-while-revalidate when slightly outdated data can be served safely.

Also, protect the database from sudden traffic increases with concurrency limits, timeouts, and controlled fallback behavior.

A well-designed caching system should not only serve data quickly when cache entries exist. It should also handle cache expiration, Redis failures, and sudden traffic spikes without overwhelming the database.