IC Improve Code Recipes

Recipe 3.4 · C#

Preventing Cache Stampedes

Problem

A dashboard summary takes eight seconds to compute and is cached for five minutes. Every five minutes the entry expires, and every request that arrives in the next eight seconds misses, so instead of one query the database gets fifty copies of its most expensive one. This is a cache stampede, and it tends to happen at the busiest time of day, because that is when the most requests arrive during the gap.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: a global lock around every cache read.
private static readonly object Sync = new object();

public DashboardSummary GetSummary()
{
    lock (Sync)
    {
        var s = (DashboardSummary)HttpRuntime.Cache["Dashboard"];
        if (s == null)
        {
            s = BuildSummary();   // 8 seconds, holding the lock
            HttpRuntime.Cache.Insert("Dashboard", s, null,
                DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
        }
        return s;
    }
}

This prevents the stampede, but every reader of every cache entry behind that lock now queues behind the eight-second build. And you cannot await inside a lock, so it cannot become async.

The improved recipe

C#
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;

namespace ImproveCode.Caching;

public sealed class SingleFlightCache(IMemoryCache cache)
{
    private readonly ConcurrentDictionary<string, Lazy<Task<object?>>>
        _inFlight = new();

    public async Task<T> GetOrCreateAsync<T>(
        string key,
        Func<CancellationToken, Task<T>> factory,
        TimeSpan timeToLive,
        CancellationToken ct = default)
    {
        if (cache.TryGetValue(key, out T? cached))
        {
            return cached!;
        }

        Lazy<Task<object?>> load = _inFlight.GetOrAdd(
            key,
            k => new Lazy<Task<object?>>(
                () => LoadAsync(k, factory, timeToLive)));

        object? value = await load.Value.WaitAsync(ct);
        return (T)value!;
    }

    public void Remove(string key) => cache.Remove(key);

    private async Task<object?> LoadAsync<T>(
        string key,
        Func<CancellationToken, Task<T>> factory,
        TimeSpan timeToLive)
    {
        try
        {
            T value = await factory(CancellationToken.None);
            cache.Set(key, value, timeToLive);
            return value;
        }
        finally
        {
            _inFlight.TryRemove(key, out _);
        }
    }
}

How it works

The first request that misses adds a Lazy<Task> for the key to the in-flight dictionary and starts the load. Every request that misses while that load is running gets the same Lazy from GetOrAdd and awaits the same task. The database sees one query, and fifty requests share its result. Requests for other keys are not affected at all.

Lazy<T> matters here. ConcurrentDictionary.GetOrAdd may call its value factory more than once when two threads race, keeping only one result. Wrapping the load in Lazy means the losing factory call only creates an unused Lazy object, and the expensive load still starts exactly once.

When the load finishes, its result goes into the cache and the in-flight entry is removed in the finally block. If the load throws, the exception reaches every waiting caller, nothing is cached, and the next request starts a fresh attempt. Failures are not cached.

The shared load runs with CancellationToken.None, because it belongs to every waiting request, not just the one that started it. Each caller instead waits with WaitAsync(ct) (.NET 6 and later), so a cancelled request stops waiting without cancelling the load for the others.

Register it as a singleton: services.AddSingleton<SingleFlightCache>();.

Variations and pitfalls

  • This protects one process. With ten web servers you can still get ten loads. That is usually fine. If it is not, use a distributed lock or let one background job refresh the value.
  • Refresh ahead. For values that are expensive and read constantly, have a BackgroundService (Chapter 14) rebuild the entry on a timer before it expires, so readers never miss.
  • Jitter. When many entries are created at the same moment, such as at startup, add a few random seconds to each lifetime so they do not all expire together.
  • HybridCache. Starting with .NET 9, the Microsoft.Extensions.Caching.Hybrid package provides HybridCache, which has this stampede protection built in and adds an optional distributed second level. If you are on .NET 9 or later, prefer it over writing your own:
C#
// Usage snippet: services.AddHybridCache(); at startup.
DashboardSummary summary = await hybridCache.GetOrCreateAsync(
    "dashboard:summary",
    async cancel => await builder.BuildAsync(cancel),
    new HybridCacheEntryOptions
    {
        Expiration = TimeSpan.FromMinutes(5)
    },
    cancellationToken: ct);