Right after a deploy, thousands of concurrent requests call HybridCache.GetOrCreateAsync for one catalogue key; how many times does the factory run, and what limits that?
answer
- one execution per key per process
- late callers join the in-flight load
- L2 read is shared too
- a thrown factory fails every joined caller
- shared work stops when the last caller cancels
basics
~20 sOnce per key per instance at a time: the first caller starts the load and concurrent callers for that key join it. Across N instances it can still run N times, fewer when the distributed tier holds the value.
solid answer
~50 s`DefaultHybridCache` keeps a table of in-flight loads keyed by cache key. The first caller that misses L1 creates the entry and runs the L2 read and, if that misses, the factory; every concurrent caller for the same key on that instance joins the same task, so after a deploy empties L1 one request per instance reads Redis and at most one runs the database query. The coordination is per process: four instances that all miss L2 run the factory up to four times. If the factory throws, the exception goes to every caller that joined, nothing is cached, and the next call starts a new load. If a caller's token is cancelled, it stops waiting, but the shared load keeps running until the last caller has cancelled, so one impatient client cannot fail the others. This differs from `IMemoryCache.GetOrCreateAsync`, which lets every concurrent miss run its own factory.
go deeper
Recall that HybridCache lets only one caller per key run the factory while the others wait for its result.
Explain the path from L1 miss to joining an in-flight load, the single L2 read, and why IMemoryCache's extension of the same name does not coordinate.
Bound the remaining load as one per key per instance, explain exception and cancellation behaviour, and use L2 so fresh instances warm without the database.
Decide whether per-instance coordination is enough for a fragile backend or whether the backend needs its own protection, such as capacity, queuing or a distributed lock.
## The scenario A sports retailer deploys its storefront API to four instances. The deploy restarts each process, so every in-memory L1 is empty. The first minute after traffic returns, thousands of requests ask for the same popular catalogue card, `card:boot-123`. With hand-written cache code, every one of those requests could miss and query the catalogue database. `HybridCache.GetOrCreateAsync` is designed to stop that. ## How the coordination works Inside `DefaultHybridCache`, a miss does not go straight to the factory: 1. **L1 check.** The caller looks in `IMemoryCache`. After the deploy it misses. 2. **Find or create the in-flight load.** The cache keeps a dictionary of pending loads, keyed by cache key and the effective flags. The first caller adds an entry and becomes responsible for the work; every later caller for the same key finds that entry and joins it. 3. **L2 read, once.** The responsible load reads the distributed store. If the previous deployment had already cached the card in Redis, this read succeeds and no factory runs at all. 4. **Factory, once.** Only if L2 also misses does the factory run, with a shared cancellation token. 5. **Release.** The value is put in L1 and every joined caller receives it; the L2 write then happens in the background. So on one instance, thousands of concurrent requests for `card:boot-123` produce **one** Redis read and **at most one** database query. ## What it does not coordinate | Situation | Factory executions | |---|---| | One instance, value in L2 | 0 | | One instance, L1 and L2 empty | 1 | | Four instances, L2 empty | up to 4, one per instance | | Requests for 500 different keys | up to 500 per instance, one per key | The coordination lives in each process's memory. There is no distributed lock, so instances that miss L2 at the same moment each load. For most catalogue data that is acceptable; one load per instance instead of one per request is the large win. ## Failure and cancellation - **The factory throws.** The pending load completes with that exception, every joined caller sees it, the load is removed from the table and nothing is cached. The next request starts a fresh load. Errors are not cached. - **The distributed store fails.** A Redis read error is logged as "Cache backend read failure." and treated as a miss, so the factory runs and the request succeeds; a failed L2 write is logged and ignored. - **A caller cancels.** When callers pass cancellable tokens, the load runs on its own with a shared `CancellationTokenSource`. A caller whose request is aborted stops waiting; the shared token is cancelled only when the **last** caller has cancelled. One client disconnecting does not fail everyone else's request. ## Compared with IMemoryCache.GetOrCreateAsync `IMemoryCache.GetOrCreateAsync` is an extension method that checks, awaits the factory and stores, with no record of loads in flight, so concurrent misses each run the factory. The `HybridCache` method with the same name is a different contract: concurrent callers on one instance share one load. That difference, not the second tier, is often the main reason teams adopt it. ## Making the most of it - **Keep keys stable.** Coordination is per exact key; `card:BOOT-123` and `card:boot-123` are two loads. - **Pass the request's token.** It lets an abandoned request stop waiting without cancelling the shared load. - **Keep an L2 for deploys.** With Redis behind HybridCache, a fresh instance warms from Redis instead of the database. - **Watch for per-instance multiplication.** If even one load per instance is too many for a backend, that is a capacity question for the backend, not something HybridCache solves. ## Observing it `HybridCache` publishes an `EventSource` whose events make the coordination visible: local hits and misses, distributed hits, misses and failures, factory starts, completions and failures, and a "stampede join" each time a caller attaches to a load already in flight. After a deploy you expect a burst of local misses, a burst of joins, and only a handful of factory starts per instance. Many factory starts with few joins means requests are using keys that differ, often through inconsistent casing or formatting, so the coordination never gets a chance to work.
- Does HybridCache cache the exception when the factory throws?No. The in-flight load completes with the exception, every caller that joined it receives the exception, and the load is removed so nothing is stored in L1 or L2. The next request for that key starts a new load and calls the factory again.
- Two callers request the same key, one passing HybridCacheEntryFlags.DisableDistributedCache; do they share one load?Not necessarily. The table of in-flight loads is keyed by the cache key together with the effective flags, so calls with different flags can run separate loads for the same key.
Each shop in a chain sends one runner to the warehouse when a popular item sells out, and customers at that shop wait for the runner instead of all driving to the warehouse. Every shop still sends its own runner, so a chain of four shops can make four trips.
- HybridCache takes a distributed lock so only one instance in the farm runs the factory
- HybridCache caches a factory exception and rethrows it until the entry expires
- Cancelling one waiting request cancels the factory for every caller
- HybridCache's GetOrCreateAsync behaves like IMemoryCache.GetOrCreateAsync under concurrent misses
- Every joined caller performs its own distributed-cache read before waiting