LESSON 10 OF 12

10. Solving Stale Data and Cache Stampede Problems

Learn to solve Redis cache problems with stale-while-revalidate, short TTLs, background refresh, distributed locks, and request coalescing.

45 dk 78

Introduction

In the previous lesson, we hardened the cache-aside flow against failures. This lesson focuses on two critical problems that appear when a cached application receives many concurrent requests: stale data and cache stampede.

Stale data means that a cached value is older than the source data. Because every cache entry has a lifetime, stale data cannot always be eliminated; instead, the application must define an acceptable freshness policy. A cache stampede occurs when a popular key expires and many requests execute the same expensive query at the same time. This can exhaust database connections, increase CPU usage, and raise latency.

We will use a product catalog and build a ProductService that reads through IDistributedCache backed by Redis. Under concurrent load, we will compare short TTLs, stale-while-revalidate, background refresh, distributed locks, and request coalescing.

1. Understanding stale data

Managing a cache entry with only one expiration value is often insufficient. If a product list is cached for ten minutes, a request at minute nine may receive data that is almost nine minutes older than the source. If stricter consistency is required, writes should invalidate or update the entry. For catalogs, search results, and recommendation lists, however, a short period of staleness may be acceptable.

Define two time boundaries:

  • Soft TTL: The period during which the value can be returned as fresh.
  • Hard TTL: The maximum lifetime after which the value must not be used.

When the soft TTL expires, the application can use stale-while-revalidate: return the existing value immediately while refreshing it in the background. When the hard TTL expires, the request must treat the entry as a miss and wait for a new value.

Designing a cache envelope

Store timing metadata together with the product list:

public sealed record CacheEnvelope<T>(
    T Value,
    DateTimeOffset CreatedAt,
    DateTimeOffset SoftExpiresAt,
    DateTimeOffset HardExpiresAt);

The application can now determine how old the value is. The physical Redis TTL should be aligned with the hard TTL. This ensures that a stale value is not retained forever if the application stops or refresh attempts continue to fail.

2. Implementing stale-while-revalidate

The following flow returns the value directly while the soft TTL is valid. After the soft TTL, it returns the stale value and schedules a background refresh. After the hard TTL, it performs a synchronous refresh.

public async Task<IReadOnlyList<ProductDto>> GetProductsAsync(
    CancellationToken cancellationToken)
{
    var key = "catalog:products:v1";
    var cached = await _cache.GetStringAsync(key, cancellationToken);

    if (cached is null)
        return await RefreshSynchronouslyAsync(key, cancellationToken);

    var envelope = JsonSerializer.Deserialize<CacheEnvelope<List<ProductDto>>>(cached)
        ?? throw new InvalidOperationException("Cache payload is invalid.");

    var now = _clock.GetUtcNow();

    if (now < envelope.SoftExpiresAt)
        return envelope.Value;

    if (now < envelope.HardExpiresAt)
    {
        await _refreshQueue.EnqueueAsync(key, cancellationToken);
        return envelope.Value;
    }

    return await RefreshSynchronouslyAsync(key, cancellationToken);
}

Queue insertion should be idempotent. If hundreds of requests arrive for the same key, the application should not create hundreds of refresh jobs. The queue can deduplicate keys, or the refresh worker can use a distributed lock so that only one job performs the refresh.

3. Short TTLs and jitter

A short TTL reduces the stale-data window, but an excessively short TTL reduces the hit ratio and increases database access. Select TTL values based on how frequently the data changes, the cost of the query, and the amount of staleness the business can accept.

Another risk occurs when many keys are created at the same time and expire at the same time. This is expiration synchronization. Add a small random offset to spread expirations over time:

private static TimeSpan AddJitter(TimeSpan baseTtl)
{
    var seconds = Random.Shared.Next(0, 30);
    return baseTtl + TimeSpan.FromSeconds(seconds);
}

var options = new DistributedCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = AddJitter(TimeSpan.FromMinutes(5))
};

Jitter does not solve stampede by itself. When one popular key expires, several requests can still execute the source query concurrently. For that reason, jitter is usually combined with a lock or request coalescing.

4. Request coalescing within one server

Request coalescing combines requests waiting for the same key around one producer. For a single application instance, use a ConcurrentDictionary<string, SemaphoreSlim>.

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

private async Task<IReadOnlyList<ProductDto>> RefreshWithLocalGateAsync(
    string key,
    CancellationToken cancellationToken)
{
    var gate = _gates.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));

    await gate.WaitAsync(cancellationToken);
    try
    {
        var secondRead = await _cache.GetStringAsync(key, cancellationToken);
        if (secondRead is not null)
            return Deserialize(secondRead).Value;

        var products = await _repository.LoadProductsAsync(cancellationToken);
        await _cache.SetStringAsync(
            key,
            Serialize(CreateEnvelope(products)),
            BuildCacheOptions(),
            cancellationToken);

        return products;
    }
    finally
    {
        gate.Release();
        if (gate.CurrentCount == 1)
            _gates.TryRemove(key, out _);
    }
}

The second Redis read is essential. Another request may have populated the entry while the current request was waiting for the gate. Without this check, the lock holder would execute the same expensive query unnecessarily.

This method combines requests only inside one process or server. In a multi-server deployment, each server has its own dictionary. Redis-based distributed locking or another cross-instance coordination mechanism is then required.

5. A Redis distributed lock

A simple Redis lock can be created with SET key value NX PX milliseconds and a unique token. NX writes the key only when it does not exist, while PX adds an automatic expiration. The token ensures that only the owner can release the lock.

var lockKey = $"lock:cache:{key}";
var token = Guid.NewGuid().ToString("N");

var acquired = await _redis.StringSetAsync(
    lockKey,
    token,
    expiry: TimeSpan.FromSeconds(10),
    when: When.NotExists);

if (acquired)
{
    try
    {
        await RefreshCacheAsync(key, cancellationToken);
    }
    finally
    {
        const string releaseScript = """
            if redis.call('get', KEYS[1]) == ARGV[1] then
                return redis.call('del', KEYS[1])
            else
                return 0
            end
            """;

        await _redis.ScriptEvaluateAsync(
            releaseScript,
            new RedisKey[] { lockKey },
            new RedisValue[] { token });
    }
}
else
{
    await Task.Delay(TimeSpan.FromMilliseconds(50), cancellationToken);
    return await ReadAfterAnotherRequestAsync(key, cancellationToken);
}

Releasing the lock with only DEL lockKey is unsafe. The lock may expire and another process may acquire it before the first process finishes. If the first process then deletes the key, it deletes the second process's lock. The Lua script deletes the key only when the stored token is still the same.

The lock lifetime should exceed the expected refresh duration, but an excessively long lifetime makes failures block other requests for too long. If refreshes can exceed the lease, consider lease renewal, bounded waiting, and timeout behavior. Distributed locks should be introduced deliberately; for many workloads, short TTLs, stale-while-revalidate, and request coalescing are simpler and safer.

6. Designing background refresh

When stale data is returned, the refresh should not block the request thread. An ASP.NET Core hosted service and a bounded channel can process refresh requests in the background. A hosted service must create a scope before resolving scoped dependencies.

public sealed record RefreshRequest(string Key);

public sealed class CacheRefreshWorker(
    Channel<RefreshRequest> channel,
    IServiceScopeFactory scopeFactory,
    ILogger<CacheRefreshWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var request in channel.Reader.ReadAllAsync(stoppingToken))
        {
            try
            {
                await using var scope = scopeFactory.CreateAsyncScope();
                var refresher = scope.ServiceProvider
                    .GetRequiredService<IProductCacheRefresher>();

                await refresher.RefreshIfNeededAsync(request.Key, stoppingToken);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Cache refresh failed for {Key}", request.Key);
            }
        }
    }
}

The queue should be bounded. If Redis or the database becomes slow, an unbounded queue can consume application memory. If refresh fails, stale data may remain available until the hard TTL, but that behavior must be documented according to the business and data-sensitivity requirements.

7. Testing a cache stampede

Do not add a protection mechanism without measuring its effect. Add an artificial delay to the repository, clear the cache key, and send concurrent requests for the same key.

var repositoryCalls = 0;

var tasks = Enumerable.Range(0, 100)
    .Select(_ => service.GetProductsAsync(CancellationToken.None));

var stopwatch = Stopwatch.StartNew();
var results = await Task.WhenAll(tasks);
stopwatch.Stop();

Console.WriteLine($"Requests: {results.Length}");
Console.WriteLine($"Repository calls: {repositoryCalls}");
Console.WriteLine($"Elapsed: {stopwatch.ElapsedMilliseconds} ms");

Compare at least these scenarios:

  1. Unprotected cache-aside: every request reaches the repository after expiration.
  2. Short TTL with jitter: expirations are spread, but concurrent misses for one key can remain.
  3. Local request coalescing: repository calls collapse to one on a single server.
  4. Redis distributed lock: a multi-server test coordinates refreshes across instances.
  5. Stale-while-revalidate: requests return quickly while refresh runs in the background.

Measure more than total duration. Track p50, p95, and p99 latency; cache hit and miss rates; repository call count; Redis command count; CPU and memory usage; and database connection-pool utilization. Stale-while-revalidate often reduces user-visible latency, but it adds background work and a temporary stale-data cost.

8. Common mistakes

  • Relying on one TTL: TTL is not the complete freshness policy. Separate soft and hard boundaries.
  • Waiting indefinitely for a lock: Define lock timeouts and fallback behavior to avoid cascading latency.
  • Creating a lock without expiration: A crashed process could leave the key locked forever.
  • Deleting a lock without validating the token: You may delete a lock owned by another process.
  • Injecting scoped services directly into a background worker: Hosted services are singletons, so scope lifetime must be managed explicitly.
  • Serving stale data forever: Use a hard TTL or maximum stale period.
  • Looking only at average latency: Stampede effects are often visible in p95 and p99 latency.

Practice exercise

Modify the product-list endpoint to support three modes: unprotected cache-aside, local request coalescing, and stale-while-revalidate. Send 200 concurrent requests for each mode. Record repository calls, p95 latency, and cache hit ratio. Then run the application as two separate processes or containers and observe why a local semaphore is not equivalent to a distributed lock.

Evaluate the results with this table:

ApproachExpected source callsUser latencyStale-data possibility
Unprotected cache-asideHighCan be highLow
Request coalescingLow on one serverModerate for the first requestLow
Stale-while-revalidateControlledUsually lowPossible during soft TTL window
Distributed lockControlled across serversDepends on lock waitLow or policy-controlled

Conclusion

Stale data and cache stampede are different problems. Stale data requires an explicit freshness and acceptable-age policy. Cache stampede requires limiting concurrent regeneration. Short TTLs and jitter distribute load; request coalescing combines duplicate work on one server; distributed locks coordinate multiple servers; and stale-while-revalidate reduces user-visible latency through controlled background refresh.

Do not apply one technique to every cache entry. For critical, frequently changing data, use invalidation and a small stale tolerance. For expensive queries that can be briefly outdated, stale-while-revalidate may be appropriate. In multi-instance deployments, use distributed coordination only when measurements show that local techniques are insufficient.

Sources