HybridCache (Microsoft.Extensions.Caching.Hybrid, GA since March 2025): GetOrCreateAsync, L1/L2 behaviour, per-process stampede protection, tags and RemoveByTagAsync, serialisation, entry options, and measuring the improvement.
HybridCache (Microsoft.Extensions.Caching.Hybrid, GA March 2025, works on .NET 8+) replaces hand-written cache-aside code with one call: GetOrCreateAsync(key, factory, options, tags, ct).
MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).RemoveByTagAsync invalidates them as a group.I prove it by counting source calls and measuring p95 under a k6 load test before and after. The trade-off: protection and L1 invalidation are per process, so I keep L1 lifetimes short when data changes.
"Most codebases I've seen have the same hand-written cache-aside block copied around: read Redis, deserialise, on a miss call the database, serialise, write back. It has three problems: every concurrent miss calls the database, there's no in-memory layer so each hit is a network hop, and the serialisation and key code is duplicated. HybridCache, which went GA in March 2025 and is the recommended choice for .NET 9 and 10, replaces all of that with
GetOrCreateAsync.It has two levels. L1 is an in-process
MemoryCache, so a hit costs nanoseconds. L2 is whateverIDistributedCacheyou've registered, typically Redis, so instances share results and survive restarts. On a miss it checks L1, then L2, then runs your factory once, and stores the result in both. If fifty requests in the same process miss the same key at once, they all await the same factory call; that's the stampede protection. Tags let me group entries, for example everything for one product, andRemoveByTagAsyncinvalidates the whole group.For example, on [a catalogue service] I replaced [about 15] hand-written cache-aside blocks with HybridCache. I measured with a k6 test at [500] requests per second: database calls for the hot endpoint dropped from [about 40] per key expiry to [one per pod], and p95 went from [85 ms] to [22 ms], because most hits never left the process. The mistake I see is assuming the stampede protection is cluster-wide. It isn't: with twelve pods you can still get twelve factory calls, and removing a key doesn't clear the other pods' L1 copies, so for data that changes I keep
LocalCacheExpirationshort."
| Concern | Hand-written | HybridCache |
|---|---|---|
| L1 (in-memory) | Usually missing | Built in |
| L2 (Redis) | Manual serialise/deserialise | Automatic via registered IDistributedCache |
| Concurrent misses | Every request hits the source | One factory call per key per process |
| Group invalidation | KEYS scans or version counters |
Tags and RemoveByTagAsync |
| Serialisation | Copied around | System.Text.Json by default; pluggable per type |
| Payload/key limits | None | MaximumPayloadBytes, MaximumKeyLength guard rails |
| Option | Purpose |
|---|---|
Expiration |
Overall lifetime (L2) |
LocalCacheExpiration |
L1 lifetime; keep it shorter for data that changes |
Flags |
e.g. disable L1 or L2 for specific entries, or skip compression |
tags parameter |
Group entries for RemoveByTagAsync |
After the change, Redis traffic for the catalogue fell by about 70% because L1 served most hits, and database CPU at the top of each 5-minute expiry no longer spiked. The source call count per key expiry, read from a custom counter, matched the number of pods, which confirmed the per-process protection was working.
Checks that the candidate can use HybridCache correctly, understands L1 and L2, and knows exactly what its stampede protection and invalidation do and don't guarantee.
Green flags
GetOrCreateAsync with the state overload and entry optionsLocalCacheExpirationRed flags
GetOrCreateAsync(key)
|-> L1 MemoryCache hit? ---------------------------------> return (ns)
|-> join in-flight call for key in this process? --------> await shared task
|-> L2 IDistributedCache hit? --> deserialise, fill L1 --> return (~1 ms)
\-> run factory once --> serialise --> write L2 + L1 --> return to all waiters
HybridCache keeps a per-key record of in-flight work. The first caller creates it and runs the L2 read and factory; later callers for the same key await the same result. Cancellation is handled so one caller cancelling doesn't cancel the shared work for the others while any are still waiting. Across processes there is no coordination, so a cold start of N pods can produce N factory calls.
RemoveAsync(key) removes the key from the local L1 and from L2. RemoveByTagAsync(tag) is logical: HybridCache records that entries with that tag created before now are invalid, and checks that on read, rather than scanning Redis. Other instances' L1 entries are not actively purged, which is why a short LocalCacheExpiration (or your own broadcast) matters when correctness depends on fast invalidation.
By default values are serialised with System.Text.Json (strings and byte[] are handled specially), and you can add serialisers per type or a factory (for example protobuf). Because L1 may hold serialised data and deserialise per call, mutating a returned object doesn't corrupt the cache; marking a type [ImmutableObject(true)] and sealing it lets HybridCache reuse the instance and skip deserialisation.
GetOrCreateAsync calls and assert the counter is 1.product:{id}, call RemoveByTagAsync, and verify the next read calls the factory.[ImmutableObject(true)] record using [MemoryDiagnoser].Before: hand-written cache-aside. After: HybridCache with tags and a short local lifetime.
// BEFORE: every concurrent miss calls the database; no L1; serialisation duplicated.
public async Task<ProductDto?> GetProductAsync(int id, CancellationToken ct)
{
var key = $"product:{id}";
var cached = await _distributedCache.GetStringAsync(key, ct);
if (cached is not null) return JsonSerializer.Deserialize<ProductDto>(cached);
var product = await _repository.GetAsync(id, ct); // 50 callers -> 50 queries
if (product is not null)
await _distributedCache.SetStringAsync(key, JsonSerializer.Serialize(product), ct);
return product;
}
using System.ComponentModel;
using Microsoft.Extensions.Caching.Hybrid;
namespace Catalogue.Products;
// Sealed + immutable lets HybridCache reuse the L1 instance instead of deserialising per hit.
[ImmutableObject(true)]
public sealed record ProductDto(int Id, string Name, decimal Price, int CategoryId);
public interface IProductRepository
{
Task<ProductDto?> GetAsync(int id, CancellationToken ct);
Task UpdatePriceAsync(int id, decimal price, CancellationToken ct);
}
public sealed class ProductService(HybridCache cache, IProductRepository repository)
{
private static readonly HybridCacheEntryOptions EntryOptions = new()
{
Expiration = TimeSpan.FromMinutes(10), // L2 lifetime
LocalCacheExpiration = TimeSpan.FromSeconds(30) // L1: bounds staleness on other pods
};
public async Task<ProductDto?> GetAsync(int id, CancellationToken ct) =>
await cache.GetOrCreateAsync(
$"product:v1:{id}",
(repository, id), // state avoids a closure allocation
static async (state, token) => await state.repository.GetAsync(state.id, token),
EntryOptions,
tags: [$"product:{id}", "products"],
cancellationToken: ct);
public async Task UpdatePriceAsync(int id, decimal price, CancellationToken ct)
{
await repository.UpdatePriceAsync(id, price, ct);
await cache.RemoveByTagAsync($"product:{id}", ct); // write, then invalidate
}
}
// Program.cs: L2 is whatever IDistributedCache is registered.
builder.Services.AddStackExchangeRedisCache(o =>
o.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddHybridCache(options =>
{
options.MaximumPayloadBytes = 1024 * 1024; // refuse to cache oversized values
options.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5),
LocalCacheExpiration = TimeSpan.FromMinutes(1)
};
});
builder.Services.AddScoped<ProductService>();
LocalCacheExpiration for data that changes. Why it is wrong: RemoveAsync/RemoveByTagAsync on one pod doesn't purge other pods' L1 copies immediately. Instead: Keep L1 short (seconds) for mutable data.state overload with a static lambda.HybridCache is the default I reach for in .NET 9 and 10 because it removes a whole class of copy-paste bugs and gives L1, L2 and stampede protection in one API. The senior part is knowing its edges: per-process coordination, logical tag invalidation, and no built-in backplane for L1, so you choose L1 lifetimes from how stale data may be on other instances.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| HybridCache | Most application caching in .NET 9/10 | Package and config; per-process guarantees | You need raw Redis data structures |
| FusionCache | You need backplane L1 invalidation, fail-safe, stale-while-revalidate | Third-party dependency | Simple cases HybridCache covers |
Hand-written IMemoryCache + IDistributedCache |
Legacy code you can't change yet | Duplication, stampedes | New code |
Measure with a factory-call counter (OpenTelemetry metric), the Redis dependency rate in Application Insights, and endpoint p95 under a repeatable load test.
The decorator implements IProductRepository and reads through HybridCache.GetOrCreateAsync, sending misses to the inner repository. HybridCache gives an in-memory L1 cache, an optional distributed L2, and stampede protection: 500 concurrent misses for a key make one database call.
product:v1:{tenant}:{id}.null is a deliberate choice with a short TTL.Register it with a factory delegate or a keyed inner service, or use Scrutor's Decorate<,>(). The trade-off is staleness: choose the TTL from how stale the business can tolerate.
System.Collections.Concurrent types are safe for many threads at once. ConcurrentDictionary uses lock-free reads and fine-grained (striped) locks for writes. Each single method is atomic, but check-then-act across two calls is not, so use GetOrAdd, AddOrUpdate, TryUpdate or TryRemove. Caveat: the value factory in GetOrAdd/AddOrUpdate can run more than once under contention (only one result is stored), so wrap expensive or side-effecting work in Lazy<T>. Count, IsEmpty and ToArray take every lock, so avoid them in hot paths. ConcurrentQueue/ConcurrentStack are lock-free FIFO/LIFO. ConcurrentBag is unordered, optimised for the same thread adding and taking. BlockingCollection adds bounding and blocking Take but blocks threads; for async producer/consumer use Channel<T>.
Tag entries in the policy (.Tag("products")) and call IOutputCacheStore.EvictByTagAsync("products", ct) after a write. With the default in-memory store, eviction only affects the instance that handled the write, so other instances keep serving stale entries until they expire.
For several instances, use the Redis output cache store (AddStackExchangeRedisOutputCache from Microsoft.AspNetCore.OutputCaching.StackExchangeRedis, available since .NET 8 and current in .NET 10). Output caching uses its own IOutputCacheStore abstraction, not IDistributedCache, because it needs tag-based eviction.
Alternatives: short expiries where a little staleness is fine, versioned keys (vary by a data version so a write naturally misses), or publishing an invalidation event (Redis pub/sub, Service Bus) that each instance handles by evicting locally. The trade-off is freshness versus the cost of a shared store.
How to tell it (STAR)
**S:** At [company] our catalogue API saw database spikes every five minutes, and p95 briefly hit [600 ms] at peak. **T:** I was asked to find why and stop it. **A:** I lined up Application Insights dependency telemetry with cache expiry and saw [up to 50] identical queries per product per expiry, because our hand-written cache-aside let every concurrent miss through. I added jitter as a quick fix, then moved the service to HybridCache with a short local cache and tag invalidation, and proved it with a k6 run before and after. **R:** Database calls per expiry fell to [one per pod], DTU peaks dropped from [90%] to [35%], and p95 stayed under [45 ms] at peak.
Last updated 23 Nov 2026.