Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
прадстаўнік: 57
Дата далучэння: Mar 2019
Паведамленні: 18
Дзякуй: 40
1 месяцаў таму · 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
прадстаўнік: 103
Дата далучэння: Apr 2018
Паведамленні: 40
Дзякуй: 24
1 месяцаў таму · 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
прадстаўнік: 156
Дата далучэння: Jan 2022
Паведамленні: 10
Дзякуй: 16
1 месяцаў таму · Jul 16, 2026 7:57 AM
#3

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