Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
Discussion

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

csharp_async_master
Async & Task Expert
MEMBER
Reputasi: 57
Tanggal Bergabung: Mar 2019
Postingan: 18
Terima kasih: 40
1 bulan yang lalu ยท 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
Reputasi: 103
Tanggal Bergabung: Apr 2018
Postingan: 40
Terima kasih: 24
1 bulan yang lalu ยท 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
Reputasi: 156
Tanggal Bergabung: Jan 2022
Postingan: 10
Terima kasih: 16
1 bulan yang lalu ยท Jul 16, 2026 7:57 AM
#3

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