الانتقال إلى المحتوى
.NETPerformance· 6 دقائق للقراءة

IMemoryCache Won't Stop a Cache Stampede: What HybridCache Adds

GetOrCreateAsync isn't atomic, so every request that misses runs your factory. What HybridCache coordinates, what it shares between servers, and where its protection stops.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A product page gets its prices from an internal pricing API that takes about 200 ms per call, so the team caches each price for five minutes with 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

The belief: 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.

The name does most of the convincing: "get or create" sounds like a single step. The docs say 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.

But thread-safe means the cache's own data structure won't be corrupted. It says nothing about the code you pass in.

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

That burst isn't a one-time startup cost. Each time a popular entry expires, every request that arrives before the new value is stored runs the factory. That's a . Every deploy, restart and scale-out starts with an empty cache and repeats it. And 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

The same service, before and after:

C# PriceService.cs
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!;    }}

Register it with 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.GetOrCreateAsyncHybridCache.GetOrCreateAsync
Concurrent misses on one serverEvery caller runs the factoryOne runs, the others wait for it
Several serversSeparate caches, separate missesOne call per server; later servers can read the shared level
What callers get backThe same object for everyoneA fresh copy by default
Removing an entryRemove on this serverRemoveAsync or RemoveByTagAsync: this server and the shared level
Where it comes fromBuilt into ASP.NET CoreThe Microsoft.Extensions.Caching.Hybrid package

How to apply it in your project

  1. Find the expensive GetOrCreate callsSearch for GetOrCreate and GetOrCreateAsync on IMemoryCache, and focus on factories that call a database or an HTTP API for popular keys.
  2. Switch to HybridCacheAdd the Microsoft.Extensions.Caching.Hybrid package, call AddHybridCache(), inject HybridCache and keep the same keys. Set Expiration and a shorter LocalCacheExpiration per entry or as defaults.
  3. Add a shared level if you run several instancesRegister an out-of-process IDistributedCache, such as Redis. The docs note that AddDistributedMemoryCache isn't used as the second level, because it lives in the same process.
  4. Remove entries when the data changesCall RemoveAsync with the key, or give related entries tags and call RemoveByTagAsync, from the code that updates the data.

Key takeaways

  • IMemoryCache.GetOrCreateAsync isn'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.
  • HybridCache runs 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.
  • HybridCache returns copies by default; sealed plus [ImmutableObject(true)] lets it reuse instances.

📚 المصادر

  1. HybridCache library in ASP.NET Core — Microsoft Learn
  2. Cache in-memory in ASP.NET Core — Microsoft Learn
  3. Distributed caching in ASP.NET Core — Microsoft Learn
  4. Overview of caching in ASP.NET Core: HybridCache — Microsoft Learn

التعليقات (0)