skip to content

In ASP.NET Core 10, what is HybridCache, how do you register it with AddHybridCache, and what does GetOrCreateAsync do on a miss?

level: juniorimportance: must knowfreq 52%

answer

  1. abstract class HybridCache, a singleton
  2. Microsoft.Extensions.Caching.Hybrid, stable package
  3. L1 IMemoryCache, L2 any IDistributedCache
  4. Func<CancellationToken, ValueTask<T>> factory
  5. default expiration 5 minutes

basics

~10 s

HybridCache is a two-tier cache: an in-process IMemoryCache in front of any registered IDistributedCache. AddHybridCache registers it; GetOrCreateAsync checks memory, then the distributed store, then runs your factory once and writes both tiers.

solid answer

~40 s

`HybridCache` is an abstract class (namespace `Microsoft.Extensions.Caching.Hybrid`) implemented by the `Microsoft.Extensions.Caching.Hybrid` package, a stable package at 10.10.1 even though the .NET 9 notes called it preview. `builder.Services.AddHybridCache()` registers a singleton, calls `AddMemoryCache()` for the local tier (L1), and uses whatever `IDistributedCache` is registered as the second tier (L2); with none, it is in-process only. You inject `HybridCache` and call `GetOrCreateAsync(key, async ct => await LoadAsync(ct))`. On a call it reads L1; on a miss it reads L2 and deserializes; on another miss it runs the factory, with concurrent callers for that key joining one execution, then stores the value in L1 and, in the background, in L2. Values are serialized with System.Text.Json unless you register a serializer, and entries expire after 5 minutes unless `Expiration` says otherwise.

code

csharp · 14 lines
csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(o =>
    o.Configuration = builder.Configuration.GetConnectionString("redis"));
builder.Services.AddHybridCache();
builder.Services.AddScoped<CatalogueDb>();
var app = builder.Build();

app.MapGet("/catalogue/{sku}", async (string sku, HybridCache cache, CatalogueDb db, CancellationToken ct) =>
    TypedResults.Ok(await cache.GetOrCreateAsync(
        $"card:{sku}",
        async token => await db.LoadCardAsync(sku, token),
        cancellationToken: ct)));

app.Run();

go deeper

for a junior

Recall that HybridCache combines a memory tier and an optional distributed tier, that AddHybridCache registers it, and that GetOrCreateAsync returns the cached value or runs your factory.

for a middle

Walk through the miss path: L1, L2, factory, write-back, plus the 5-minute default expiration, the ValueTask return type and the System.Text.Json default serializer.

for a senior

Explain that L2 read and write failures are logged and degrade to misses, that AddDistributedMemoryCache is ignored as L2, and that other instances' L1 copies can lag after a change.

for a principal

Decide when HybridCache replaces hand-written two-tier code in a codebase and how a shared default expiration policy is set and reviewed across teams.

## What HybridCache is ASP.NET Core has long had two caching abstractions: `IMemoryCache`, which holds objects in one process, and `IDistributedCache`, which stores bytes in Redis, SQL Server or another shared store. Real applications often wanted both, plus serialization and protection against duplicate loads, and wrote that glue by hand. `HybridCache` packages it: - **L1**: the process's `IMemoryCache`, for fast reads with no network hop. - **L2**: any `IDistributedCache` already registered, so instances share values and survive restarts. - **One API**: `GetOrCreateAsync`, `SetAsync`, `RemoveAsync` and `RemoveByTagAsync`. The abstract `HybridCache` type lives in `Microsoft.Extensions.Caching.Abstractions`; the implementation ships in the `Microsoft.Extensions.Caching.Hybrid` NuGet package from the dotnet/extensions repository, on its own version line (10.10.1 at the time of writing). The ASP.NET Core 9 release notes still say it is preview; the package has since shipped as a normal, stable release. The ASP.NET Core docs page says L1 uses `System.Runtime.Caching.MemoryCache`; the implementation actually resolves `IMemoryCache` from DI. ## Registering it ```csharp builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration.GetConnectionString("redis")); builder.Services.AddHybridCache(o => { o.DefaultEntryOptions = new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(10), LocalCacheExpiration = TimeSpan.FromMinutes(1) }; }); ``` `AddHybridCache` does three things worth knowing: 1. Registers `HybridCache` as a **singleton** with `TryAddSingleton`, implemented by an internal `DefaultHybridCache`. 2. Calls `AddMemoryCache()`, so L1 is the same shared `IMemoryCache` the rest of the app uses. 3. Resolves `IDistributedCache` if one exists. If none is registered, every entry is local only. If the registered one is just `AddDistributedMemoryCache`'s in-process store, it is ignored, since it would duplicate L1. It returns an `IHybridCacheBuilder` for adding serializers, and `AddKeyedHybridCache` registers additional named instances. ## What GetOrCreateAsync does For a sports retailer's catalogue lookup: ```csharp public sealed class Catalogue(HybridCache cache, CatalogueDb db) { public ValueTask<ProductCard> GetCardAsync(string sku, CancellationToken ct) => cache.GetOrCreateAsync( $"card:{sku}", async token => await db.LoadCardAsync(sku, token), cancellationToken: ct); } ``` 1. **L1 lookup.** A hit returns immediately, with no serialization for immutable types. 2. **Join or start.** On a miss, the call either joins an in-flight load for the same key on this instance or starts one. 3. **L2 lookup.** The loader reads the distributed store. A failure there is logged and treated as a miss rather than thrown. 4. **Factory.** On an L2 miss it runs your factory, passing a cancellation token shared by all waiting callers. 5. **Write back.** The value is serialized, put in L1, handed to every waiting caller, and then written to L2 in the background; an L2 write failure is logged, not thrown. The method returns `ValueTask<T>`, and the factory is a `Func<CancellationToken, ValueTask<T>>`. An overload takes a `TState` argument so a static lambda can avoid capturing variables. There is no plain "get" method: reading without creating means passing flags such as `HybridCacheEntryFlags.DisableUnderlyingData`. ## Defaults worth quoting | Setting | Default | |---|---| | `Expiration` | 5 minutes when nothing sets it | | `LocalCacheExpiration` | same as `Expiration` | | `MaximumPayloadBytes` | 1 MiB | | `MaximumKeyLength` | 1024 characters | | Serializer | built-in for `string` and `byte[]`, System.Text.Json for everything else | ## Why interviewers ask about it HybridCache replaces three pieces of hand-written code at once: the memory-then-distributed lookup, the serialization round trip and the lock that stops concurrent misses from all hitting the database. A good answer names the two tiers, the registration and what happens on a miss, and adds the cost: L1 copies on other instances can lag behind a change, which is what `LocalCacheExpiration` bounds. ## Compared with the two older abstractions | | `IMemoryCache` | `IDistributedCache` | `HybridCache` | |---|---|---|---| | Values | object references | byte arrays | typed `T`, serialized for you | | Shared across instances | no | yes | yes, through L2 | | Concurrent misses | each runs its loader | each runs its loader | one load per key per instance | | Store failure | not applicable | throws | logged, treated as a miss | | Group invalidation | tokens | none | tags | Neither older abstraction is deprecated. `IMemoryCache` remains the right tool for process-local objects with eviction callbacks or size accounting, and `IDistributedCache` for code that needs direct control over the stored bytes; `HybridCache` is the default choice for new data caching in an ASP.NET Core 10 app.

  • What happens if you call AddHybridCache without registering any IDistributedCache?
    It still works, as an in-process cache only. `DefaultHybridCache` finds no `IDistributedCache`, marks the distributed tier disabled, and keeps entries in `IMemoryCache` with the same miss coordination and serialization. Each instance then has its own copy, and a restart starts empty.
  • Why does GetOrCreateAsync return ValueTask<T> rather than Task<T>?
    Most calls are L1 hits that complete synchronously, and a `ValueTask<T>` lets those return without allocating a `Task`. The usual rule follows: await it once, and do not store it and await it again.
  • Is HybridCache still a preview API in .NET 10?
    No. The ASP.NET Core 9 release notes describe it as preview, to ship later in a .NET Extensions release, and that is what happened: `Microsoft.Extensions.Caching.Hybrid` is a normal, stable package, 10.10.1 alongside ASP.NET Core 10.

  • HybridCache requires Redis and fails to start without an IDistributedCache
  • AddHybridCache registers HybridCache as a scoped service
  • HybridCache is still a preview-only API in .NET 10
  • Entries added with GetOrCreateAsync never expire unless an expiration is set
  • A distributed-store read failure inside GetOrCreateAsync is thrown to the caller

Assumes Microsoft.Extensions.Caching.Hybrid 10.10.1 with ASP.NET Core 10; the ASP.NET Core 9 release notes still describe HybridCache as preview, but the package is now a stable release.