
IMemoryCache Won't Stop a Cache Stampede: What HybridCache Adds
- كاتب موثّق
- .NET 10
محتويات المقال
IMemoryCache.GetOrCreateAsync. The hit rate looks excellent. Yet the pricing team keeps reporting the same pattern: every few minutes, a wall of identical requests for the most popular products, and after each deploy, enough of them to hit the API's rate limit. The cache is working. It just isn't doing the one thing everyone assumed it does.
The common misconception
GetOrCreateAsync runs the factory once per key. Concurrent requests for a missing key wait for the first one to fill it, and the cache takes care of the rest, even across several server instances.
MemoryCache is thread-safe, which is true and easy to over-read. And in development, with one request at a time, the factory really does run once per expiration.
What actually happens
GetOrCreateAsync is check, then act
GetOrCreateAsync is an extension method that looks up the key and, on a miss, runs your factory and stores the result. Nothing stops other callers between the lookup and the store. The memory cache docs say it directly: these methods aren't atomic, each request that misses runs the factory, and the last value written is the one that stays. Tested on .NET 10: 100 concurrent callers on a cold key with a 200 ms factory produced 100 factory calls.
Every expiry opens the window again
IMemoryCache lives inside one process, so five servers mean five separate caches, five separate stampedes, and possibly five different values for the same key.
What HybridCache coordinates
HybridCache, from the Microsoft.Extensions.Caching.Hybrid package, changes the first part. Within one HybridCache instance, only one concurrent caller per key runs the factory; the others wait for its result. In the same test, 100 concurrent callers produced one factory call. When the factory threw, all 20 waiting callers received the exception, nothing was cached, and the next call ran the factory again.
What it shares between servers
HybridCache keeps entries in process memory first. If the app registers an out-of-process , such as Redis, it becomes the second level: values found there skip the factory, and new values are written to both. In a test with two instances sharing a second level, a cold key called the factory twice, once per instance. A third instance started later read the value from the shared level and didn't call it at all.
The fix: let one caller do the work
using Microsoft.Extensions.Caching.Memory;public sealed class PriceService(IMemoryCache cache, PricingClient pricing){ public async Task<Price> GetAsync(int productId, CancellationToken ct) { // Not atomic: every concurrent miss calls the pricing API var price = await cache.GetOrCreateAsync($"price:{productId}", entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); return pricing.GetPriceAsync(productId, ct); }); return price!; }}using Microsoft.Extensions.Caching.Hybrid;public sealed class PriceService(HybridCache cache, PricingClient pricing){ private static readonly HybridCacheEntryOptions Options = new() { Expiration = TimeSpan.FromMinutes(5), // shared level LocalCacheExpiration = TimeSpan.FromMinutes(1) // this server's memory }; // One factory call per key on this server, however many callers wait public ValueTask<Price> GetAsync(int productId, CancellationToken ct) => cache.GetOrCreateAsync($"price:{productId}", async token => await pricing.GetPriceAsync(productId, token), Options, cancellationToken: ct);}builder.Services.AddHybridCache(). Without a distributed cache, it still gives you the per-key coordination in memory. To share values between servers, also register an IDistributedCache such as AddStackExchangeRedisCache from the Microsoft.Extensions.Caching.StackExchangeRedis package.
IMemoryCache.GetOrCreateAsync | HybridCache.GetOrCreateAsync | |
|---|---|---|
Remove on this server | RemoveAsync or RemoveByTagAsync: this server and the shared level | |
Microsoft.Extensions.Caching.Hybrid package |
How to apply it in your project
Find the expensive GetOrCreate calls Search for GetOrCreateandGetOrCreateAsynconIMemoryCache, and focus on factories that call a database or an HTTP API for popular keys.Switch to HybridCache Add the Microsoft.Extensions.Caching.Hybridpackage, callAddHybridCache(), injectHybridCacheand keep the same keys. SetExpirationand a shorterLocalCacheExpirationper entry or as defaults.Add a shared level if you run several instances Register an out-of-process IDistributedCache, such as Redis. The docs note thatAddDistributedMemoryCacheisn't used as the second level, because it lives in the same process.Remove entries when the data changes Call RemoveAsyncwith the key, or give related entries tags and callRemoveByTagAsync, from the code that updates the data.
Key takeaways
IMemoryCache.GetOrCreateAsyncisn't atomic: concurrent misses each run the factory, and the last write wins.Every expiry, deploy and scale-out reopens that window, once per server. HybridCacheruns one factory call per key per instance, makes the other callers wait, and doesn't cache failures.With a distributed cache as its second level, servers share values, but coordination and in-memory removal stay per server. HybridCachereturns copies by default;sealedplus[ImmutableObject(true)]lets it reuse instances.
التعليقات (0)