skip to content

When a cached exchange rate expires and 200 concurrent requests call IMemoryCache.GetOrCreateAsync for it in ASP.NET Core, how often does the factory run, and why?

level: seniorimportance: should knowfreq 44%

answer

  1. an extension method, not a cache primitive
  2. TryGetValue, CreateEntry, await, dispose
  3. no per-key lock
  4. a thrown factory caches nothing
  5. Task<TItem?> and a cached null

basics

~20 s

Possibly up to 200 times. GetOrCreateAsync is an extension that calls TryGetValue, then awaits the factory and commits the entry, with no lock per key; every caller that misses before the first commit runs its own factory.

solid answer

~40 s

`GetOrCreateAsync` lives in `CacheExtensions`, and its body is short: `TryGetValue`; on a miss, `using var entry = cache.CreateEntry(key)`, apply any `createOptions`, `await factory(entry)`, assign `entry.Value`, and let the dispose commit it. There is **no lock and no in-flight tracking**, so every request that misses before the first commit runs its own factory - here, up to 200 calls to the rate provider - and the later commits replace earlier ones (`EvictionReason.Replaced`). Other edges: if the factory throws, the value was never set, so nothing is cached and the next caller retries; a factory that returns `null` caches the `null`; the return type is `Task<TItem?>`. To let one caller load while the rest wait, use `HybridCache` or add per-key coordination yourself.

code

csharp · 14 lines
csharp
public Task<decimal> GetRateAsync(string pair)
{
    var key = $"fx:{pair}";
    var lazy = cache.GetOrCreate(key, entry =>
    {
        entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(30));
        return new Lazy<Task<decimal>>(() => feed.FetchAsync(pair));
    })!;

    var task = lazy.Value;
    _ = task.ContinueWith(t => cache.Remove(key),
        TaskContinuationOptions.OnlyOnFaulted);
    return task;
}

go deeper

for a junior

Recall that GetOrCreateAsync returns the cached value or runs the factory and caches its result, and that options can be set on the entry inside the factory.

for a middle

Explain the steps inside the extension: TryGetValue, CreateEntry, await the factory, set Value, commit on dispose, and what happens on an exception or a null result.

for a senior

Diagnose duplicate loads on expiry from the missing per-key lock, estimate them from factory latency, and choose between HybridCache and a Lazy<Task<T>> or SemaphoreSlim guard.

for a principal

Weigh the downstream cost of duplicate loads, such as provider quotas, fees and latency spikes, against the complexity of coordination per instance and across instances.

## What GetOrCreateAsync actually is `GetOrCreateAsync` is not part of `IMemoryCache`. It is an extension method on `CacheExtensions`, and in .NET 10 its body is a handful of lines: ```csharp if (!cache.TryGetValue(key, out object? result)) { using ICacheEntry entry = cache.CreateEntry(key); if (createOptions != null) entry.SetOptions(createOptions); result = await factory(entry).ConfigureAwait(false); entry.Value = result; } return (TItem?)result; ``` The entry is committed into the cache when it is **disposed** at the end of the `using` scope; `CreateEntry` alone adds nothing. That shape answers most interview follow-ups directly. ## Why 200 requests can mean 200 factory calls Nothing in that code records that a load for the key is already in flight. When the rate for `fx:USD:MXN` expires: 1. Request 1 calls `TryGetValue`, misses, and starts awaiting the rate provider. 2. Requests 2 to 200 arrive before request 1's entry is committed. Each calls `TryGetValue`, each misses, and each starts its own provider call. 3. As the calls complete, each commits its entry. Every commit after the first replaces the previous entry, which is evicted with `EvictionReason.Replaced`. How many factories run depends on how many requests arrive inside the factory's latency; with a 300 ms provider call and a busy corridor it can be most of them. For a remittance service the cost is concrete: rate-provider quotas, per-call fees, and a latency spike on every expiry. The synchronous `GetOrCreate` has the same gap. ## The other edges of the method | Situation | Behaviour | |---|---| | Factory throws | `entry.Value` is never set, so disposing the entry commits nothing; the exception propagates and the next caller tries again | | Factory returns `null` | `entry.Value = null` counts as set, so `null` is cached and later `TryGetValue` calls return `true` with `null` | | Options | set them on the `ICacheEntry` inside the factory, or pass a `MemoryCacheEntryOptions` as `createOptions` | | Return type | `Task<TItem?>`, so callers must handle `null` even for value-like data | | Size-limited cache | a missing `SetSize` throws when the entry is disposed, after the factory already ran | Caching a `null` is sometimes wanted (remembering that a corridor does not exist) and sometimes a bug (caching "provider unavailable" as "no rate"); decide explicitly. ## Closing the gap in .NET Two .NET-specific ways to let one caller load while the others wait: - **`HybridCache`** (`Microsoft.Extensions.Caching.Hybrid`), whose `GetOrCreateAsync` lets only one concurrent caller per key run the factory inside a process. It is the supported answer and is covered on its own. - **Coordinate yourself**: cache a `Lazy<Task<decimal>>` through `GetOrCreate`; creating a `Lazy` is nearly instant, so almost every caller shares one task, although two exactly simultaneous misses can still each create one. Or guard the miss path with a `SemaphoreSlim` per key and re-check the cache after acquiring it. Remove a faulted task so one failure is not served to everyone. Neither changes what each server does independently: with several instances, each one still loads its own copy. ## Spotting it in production The symptom is easy to miss because every response is correct. Look for: - **Provider call counts that spike at each expiry** instead of one call per key per expiration period. - **Misses that arrive in bursts.** With `MemoryCacheOptions.TrackStatistics = true`, `GetCurrentStatistics().TotalMisses` rises by far more than the number of distinct keys right after an expiry. - **Latency spikes aligned with the expiration interval**, because every request in the burst waits for its own provider call. - **`Replaced` evictions in bursts**, if an eviction callback logs reasons: each duplicate commit evicts the one before it. The synchronous `GetOrCreate` has the same structure; it additionally blocks a request thread for the whole factory call, so a burst of misses on a slow provider also ties up thread-pool threads. ## What not to conclude The gap does not make `IMemoryCache` wrong for rates. For cheap factories, or keys read a few times per expiration period, duplicate loads cost little and the simple extension is the right tool. It becomes a problem when the factory is slow, metered or fragile and the key is hot, which is exactly the profile of a popular currency pair served by a paid rate provider. ## How to answer Say "potentially once per concurrent miss", then justify it from the implementation: check, create, await, commit on dispose, no lock. Add the exception and `null` behaviour, and name `HybridCache` as the built-in alternative when duplicate loads are expensive.

  • If the rate provider throws inside the GetOrCreateAsync factory, what is cached?
    Nothing. The value is assigned only after the awaited factory returns, and a disposed `ICacheEntry` whose value was never set is not committed. The exception propagates to that caller, and the next request misses and runs the factory again.
  • Does making the factory faster solve the duplicate-load problem?
    It narrows it. The number of duplicate loads is roughly the number of requests that miss during the factory's latency, so a faster factory means fewer duplicates, but any concurrent misses before the first commit still each run one. Only per-key coordination, or `HybridCache`, makes it one.

  • GetOrCreateAsync locks the key so only one caller ever runs the factory
  • If the factory throws, the exception is cached and rethrown to later callers
  • CreateEntry adds the entry to the cache immediately, before a value is assigned
  • A factory returning null is treated as a miss and nothing is cached
  • GetOrCreateAsync is a method on the IMemoryCache interface that implementations can make atomic