Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

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 months ago · 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 months ago · 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 months ago · Jul 16, 2026 7:57 AM
#3

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