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.