Coding a HybridCache caching decorator: GetOrCreateAsync with keys and TTLs, stampede protection, invalidation on writes (RemoveAsync, tags), not caching nulls or failures by accident, tenant-aware keys, immutable cached types, registration via factory delegate, keyed services and Scrutor, and tests.
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.
"I'd write
CachedProductRepositoryimplementingIProductRepository, taking the inner repository and aHybridCache. Reads callGetOrCreateAsyncwith a key and a factory that calls the inner repository. HybridCache is the right tool in .NET 9 and later. It has an in-memory L1 and an optional distributed L2 such as Redis, and it has stampede protection, so when 500 requests miss the same key at once, only one of them runs the factory and the rest await that result. The hand-writtenIMemoryCacheversion doesn't give you that.The interesting part is correctness. The key must contain everything that changes the answer: the tenant, maybe the culture, and a version prefix so I can change the cached shape without reading old entries. I'd write
product:v1:{tenantId}:{id}. Writes go through the decorator too. It calls the innerUpdateAsyncfirst and only invalidates the key when that succeeds; if you invalidate first, a concurrent read can repopulate the old value. Errors: if the factory throws, HybridCache doesn't store anything, which is what I want. Nulls are a decision. Caching 'not found' for 30 seconds protects the database from repeated lookups of missing IDs, but a longer TTL hides newly created products. And by default HybridCache hands back a fresh deserialised copy on each call, so callers mutating the result don't corrupt the cache. If the type is sealed and marked[ImmutableObject(true)], it reuses the instance, which is faster but means it really must be immutable.For registration with the built-in container, I register
SqlProductRepositoryas itself and mapIProductRepositoryto a factory that builds the decorator around it. With Scrutor it's one line. The mistake I see is a cache key without the tenant, which serves one customer's data to another. The cache key is part of your security model."
| Decision | Choice | Reason |
|---|---|---|
| Cache | HybridCache |
L1 + L2, stampede protection, serialisation handled |
| Key | product:v1:{tenant}:{id} |
Tenant isolation, schema versioning |
| TTL | 10 min L2, 2 min L1 | Products change rarely; L1 short so instances converge |
| Writes | Inner first, then RemoveAsync |
Avoid repopulating stale data |
| Not found | Cache null for 30 s |
Protect DB from repeated misses |
| Errors | Not cached (default) | Don't pin failures |
| Container | Code |
|---|---|
| Built-in, factory | AddScoped<SqlProductRepository>() + AddScoped<IProductRepository>(sp => new CachedProductRepository(...)) |
| Built-in, keyed | Inner keyed "inner", decorator takes [FromKeyedServices("inner")] |
| Scrutor | AddScoped<IProductRepository, SqlProductRepository>() then Decorate<IProductRepository, CachedProductRepository>() |
A catalogue API serving about 2,000 product reads per second added this decorator. Cache hit rate settled at 94%, p95 read latency dropped from 35 ms to 3 ms, and Azure SQL DTU use fell by about 70%. A load test that cold-started the cache with 1,000 concurrent requests for the same product showed exactly one database query, which confirmed the stampede protection.
Checks the ability to write a correct, production-ready decorator, and understanding of caching correctness and DI registration.
Green flags
HybridCache and explains stampede protection.Red flags
Controller βββΆ IProductRepository
β
CachedProductRepository βββΆ HybridCache (L1 memory βββΆ L2 Redis, optional)
β miss
βΌ
SqlProductRepository βββΆ Azure SQL
Microsoft.Extensions.Caching.Hybrid, registered with AddHybridCache(). If an IDistributedCache (Redis, SQL Server) is registered, it becomes L2 automatically.GetOrCreateAsync(key, factory, options, tags, ct): checks L1, then L2, then runs the factory once per key across concurrent callers on that instance (stampede protection).HybridCacheEntryOptions: Expiration (overall/L2) and LocalCacheExpiration (L1).RemoveAsync(key) and tag-based removal (RemoveByTagAsync) for invalidation.[ImmutableObject(true)], in which case the instance is reused.| Order | Race |
|---|---|
| Invalidate, then write | A read between the two repopulates the old value; stays stale for the TTL |
| Write, then invalidate | A read between the two returns the old value briefly; next read is fresh |
"Write then invalidate" is the standard cache-aside choice. With multiple instances, L1 entries on other instances aren't removed by RemoveAsync on one instance unless you add a backplane; keep LocalCacheExpiration short (for example 1β2 minutes) to bound staleness.
Track hit rate, factory duration and L2 latency with custom metrics (System.Diagnostics.Metrics counters) or the cache's own telemetry, and compare p95 latency and database load before and after. A cache with a 20% hit rate is mostly cost.
AddStackExchangeRedisCache and observe L2 entries with redis-cli MONITOR.The decorator, the registrations and the tests:
namespace Catalogue;
using System.ComponentModel;
using Microsoft.Extensions.Caching.Hybrid;
[ImmutableObject(true)] // sealed + immutable: HybridCache may reuse the instance instead of deserialising per call
public sealed record Product(int Id, string Name, decimal Price);
public interface IProductRepository
{
Task<Product?> GetAsync(int id, CancellationToken ct);
Task UpdateAsync(Product product, CancellationToken ct);
}
public interface ITenantContext { string TenantId { get; } }
public sealed class CachedProductRepository(
IProductRepository inner,
HybridCache cache,
ITenantContext tenant) : IProductRepository
{
private static readonly HybridCacheEntryOptions Found = new()
{
Expiration = TimeSpan.FromMinutes(10), // L2 (and overall)
LocalCacheExpiration = TimeSpan.FromMinutes(2) // L1: short, so other instances converge after writes
};
private string Key(int id) => $"product:v1:{tenant.TenantId}:{id}"; // tenant is part of the key
public async Task<Product?> GetAsync(int id, CancellationToken ct) =>
await cache.GetOrCreateAsync(
Key(id),
(inner, id), // state avoids a closure allocation
static async (state, innerCt) => await state.inner.GetAsync(state.id, innerCt),
Found,
cancellationToken: ct);
// If the factory throws, nothing is cached and the exception propagates.
// null (not found) IS cached here for the same TTL: shorten or skip if new products must appear immediately.
public async Task UpdateAsync(Product product, CancellationToken ct)
{
await inner.UpdateAsync(product, ct); // write first...
await cache.RemoveAsync(Key(product.Id), ct); // ...then invalidate
}
}
// Program.cs: built-in container (no packages)
builder.Services.AddHybridCache();
// builder.Services.AddStackExchangeRedisCache(o => o.Configuration = builder.Configuration.GetConnectionString("Redis")); // optional L2
builder.Services.AddScoped<SqlProductRepository>();
builder.Services.AddScoped<IProductRepository>(sp => new CachedProductRepository(
sp.GetRequiredService<SqlProductRepository>(),
sp.GetRequiredService<HybridCache>(),
sp.GetRequiredService<ITenantContext>()));
// Or with Scrutor: same lifetime as the original registration
// builder.Services.AddScoped<IProductRepository, SqlProductRepository>();
// builder.Services.Decorate<IProductRepository, CachedProductRepository>();
namespace Catalogue.Tests;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
public sealed class CountingRepo : IProductRepository
{
public int Reads;
public Product Current = new(1, "Kettle", 49m);
public async Task<Product?> GetAsync(int id, CancellationToken ct) { Interlocked.Increment(ref Reads); await Task.Delay(20, ct); return Current; }
public Task UpdateAsync(Product p, CancellationToken ct) { Current = p; return Task.CompletedTask; }
}
public sealed record Tenant(string TenantId) : ITenantContext;
public class CachedProductRepositoryTests
{
private static HybridCache NewCache() =>
new ServiceCollection().AddHybridCache().Services.BuildServiceProvider().GetRequiredService<HybridCache>();
[Fact]
public async Task Concurrent_reads_hit_the_inner_once()
{
var inner = new CountingRepo();
var sut = new CachedProductRepository(inner, NewCache(), new Tenant("t1"));
await Parallel.ForAsync(0, 500, async (_, ct) => await sut.GetAsync(1, ct));
Assert.Equal(1, inner.Reads);
}
[Fact]
public async Task Update_invalidates_and_tenants_are_isolated()
{
var cache = NewCache();
var inner = new CountingRepo();
var t1 = new CachedProductRepository(inner, cache, new Tenant("t1"));
var t2 = new CachedProductRepository(inner, cache, new Tenant("t2"));
await t1.GetAsync(1, default);
await t1.UpdateAsync(new Product(1, "Kettle", 39m), default);
Assert.Equal(39m, (await t1.GetAsync(1, default))!.Price); // re-read after invalidation
await t2.GetAsync(1, default);
Assert.Equal(3, inner.Reads); // t2 has its own key
}
}
IMemoryCache.TryGetValue + set. Why it is wrong: No stampede protection: a cold key under load sends hundreds of identical queries to the database. Instead: HybridCache.GetOrCreateAsync (or IMemoryCache.GetOrCreateAsync with a per-key lock).with to change.AddScoped<IProductRepository, CachedProductRepository>() when the decorator needs IProductRepository. Why it is wrong: Circular dependency. Instead: Factory delegate, keyed inner or Scrutor.A caching decorator is one of the highest-value, lowest-risk patterns in a .NET service, if the keys and invalidation are right. The repository stays simple, caching can be switched off by changing one registration, and HybridCache removes the stampede problem that used to make hand-rolled caches dangerous.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| HybridCache decorator | Read-heavy, tolerates secondsβminutes of staleness | Invalidation discipline | Strong consistency required |
IMemoryCache |
Single instance, simple needs | No L2, no stampede protection | Multiple instances |
Output caching (AddOutputCache) |
Whole HTTP responses, anonymous or varied by keys | Coarse | Per-user data without vary-by |
| No cache, better query/index | Cache would hide a slow query | Query work | Load is genuinely beyond the DB |
I decide TTLs with the business ("how stale can a price be?"), keep L1 TTL short when there are several instances, and watch three numbers: hit rate, p95 latency, database load.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
Prefer immutable types for values, messages, configuration, cache entries and anything shared across threads: an object that cannot change is automatically thread-safe, safe to cache and share, safe as a dictionary key, and easier to reason about. C# gives you readonly fields, init and get-only properties, records with with, readonly struct, ImmutableArray<T>/ImmutableList<T> and FrozenDictionary/FrozenSet for read-mostly data. Remember that read-only is not immutable: IReadOnlyList<T> over a List<T> can still change underneath. Keep mutability where it is natural and contained: entities whose state changes through methods that guard invariants, builders, and hot loops where allocating new objects would cost too much.
Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).
.NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.
The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().
The trade-off is that order matters and long chains are harder to debug.
How to tell it (STAR)
**S:** At [company] our catalogue API saw Azure SQL hit [100%] DTU every few minutes, and p95 jumped from [5 ms] to [nearly 2 seconds]. **T:** I needed to find why a cached endpoint was hammering the database. **A:** Query Store showed [~600] identical queries in a single second, right when popular products expired. Our caching decorator checked the cache and, on a miss, every concurrent request went to the database, on each of our [six] instances. I added TTL jitter as a quick fix, then rewrote the decorator on HybridCache, which runs the factory once per key, and added Redis as a shared L2. **R:** Database spikes disappeared, DTU averaged [~25%], p95 settled at [~3 ms], and a cold-start load test in the pipeline now guards against regressions.
Last updated 18 Nov 2026.