Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Discussion

In-Memory Caching: IMemoryCache vs IDistributedCache and Cache Stampede Prevention in C# [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Rep: 57
Datum pridruživanja: Mar 2019
Postovi: 18
Hvala: 40
prije 1 mjeseci · Jul 15, 2026 11:04 PM
#1

How to prevent the Cache Stampede (Thundering Herd) problem when cache keys expire:

When a popular cache key expires, 100 concurrent requests all miss the cache simultaneously and query the database at once, overwhelming the database server.

Solution: Double-Checked Locking with SemaphoreSlim:

CSHARP
public async Task<string> GetCachedDataAsync(string key)
{
    if (_cache.TryGetValue(key, out string val)) return val;
    
    await _semaphore.WaitAsync();
    try
    {
        if (_cache.TryGetValue(key, out val)) return val; // Double check!
        val = await FetchFromDatabaseAsync(key);
        _cache.Set(key, val, TimeSpan.FromMinutes(10));
        return val;
    }
    finally { _semaphore.Release(); }
}
dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rep: 103
Datum pridruživanja: Apr 2018
Postovi: 40
Hvala: 24
prije 1 mjeseci · Jul 16, 2026 1:21 AM
#2

In .NET 9, HybridCache provides built-in multi-tier caching and stampede locking out of the box!

channel_concurrency
Reactive & Pipeline
MEMBER
Rep: 156
Datum pridruživanja: Jan 2022
Postovi: 10
Hvala: 16
prije 1 mjeseci · Jul 16, 2026 7:57 AM
#3

Double-checked locking on cache misses is mandatory for high-traffic API endpoints.