📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Write a caching decorator for IProductRepository using HybridCache in .NET 10. Register it with the built-in container, then with Scrutor, and explain how you handle invalidation, cache keys, stampedes and the risk of caching errors or other users' data.

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.

Mid-Level Coding Intermediate caching decorator dependency-injection design-patterns hybridcache scrutor

🎯 Key points

  • The decorator implements IProductRepository, reads through HybridCache.GetOrCreateAsync and delegates misses to the inner repository
  • HybridCache (.NET 9+) gives L1 in-memory (nanoseconds) + optional L2 distributed cache (a network hop, ~1 ms) and stampede protection: concurrent misses for one key share a single factory call
  • Keys must include every input that changes the result (product:v1:{tenant}:{id}); a key without the tenant serves one customer's data to another
  • UpdateAsync calls the inner write first, then cache.RemoveAsync(key) (or RemoveByTagAsync); invalidating first lets a concurrent read repopulate stale data
  • Exceptions in the factory are not cached; decide explicitly whether to cache null (negative caching with a short TTL); a deserialisation failure after a schema change is avoided with a version prefix in the key
  • HybridCache deserialises a fresh copy per call unless the type is sealed and marked [ImmutableObject(true)]; cached objects must not be mutated
  • Built-in DI: register inner concretely or keyed, decorator via factory or [FromKeyedServices] (never AddScoped<IRepo, Decorator> alone, which is circular); Scrutor: Decorate<IProductRepository, CachedProductRepository>() keeps the inner lifetime
  • Test: fake inner counts calls; assert one call for 500 parallel reads, re-read after update, and per-tenant isolation

⏱ 30-second answer

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.

  • Keys include everything that changes the result: product:v1:{tenant}:{id}.
  • Writes go through the decorator and invalidate after the inner write succeeds.
  • Exceptions aren't cached. Caching 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"I'd write CachedProductRepository implementing IProductRepository, taking the inner repository and a HybridCache. Reads call GetOrCreateAsync with 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-written IMemoryCache version 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 inner UpdateAsync first 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 SqlProductRepository as itself and map IProductRepository to 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."


Design decisions

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

Registration

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>()

Production example

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.

πŸ” What the interviewer is checking

Checks the ability to write a correct, production-ready decorator, and understanding of caching correctness and DI registration.

Green flags

  • Uses HybridCache and explains stampede protection.
  • Tenant-aware, versioned keys.
  • Write-then-invalidate, and a deliberate stance on caching nulls and errors.
  • Working registration without circular dependencies; knows Scrutor.
  • Tests that prove single-flight, invalidation and isolation.

Red flags

  • Keys without tenant or user.
  • Mutable cached objects.
  • No invalidation strategy, or circular registration.

πŸ“š Learn in depth

1. Where the decorator sits

Controller ──▢ IProductRepository
                  β”‚
          CachedProductRepository ──▢ HybridCache (L1 memory ──▢ L2 Redis, optional)
                  β”‚ miss
                  β–Ό
          SqlProductRepository ──▢ Azure SQL

2. HybridCache in one page

  • Package 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.
  • Values are serialised (System.Text.Json by default) for L2. L1 stores serialised bytes too, and a fresh object is deserialised per call unless the type is sealed and [ImmutableObject(true)], in which case the instance is reused.

3. Invalidation order

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.

4. Key design

  • Include every input that changes the result (tenant, user if per-user, culture, query parameters).
  • Prefix with a version to change the cached shape safely.
  • Keep keys short and free of personal data: keys can appear in Redis monitoring tools.

5. What not to cache

  • Results that depend on the current user's permissions, unless the key includes the user or a permission set hash.
  • Large, rarely reused objects (memory with no hit rate).
  • Anything where staleness is unacceptable (balances, stock at checkout): read through to the source.

6. Measuring

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.

Try it yourself

  1. Implement the decorator and a fake inner that counts calls; prove 1,000 parallel reads cause one call.
  2. Make the inner throw once; check that the next read calls the inner again (not cached).
  3. Remove the tenant from the key and write a test that fails because tenant B sees tenant A's product.
  4. Add Redis via AddStackExchangeRedisCache and observe L2 entries with redis-cli MONITOR.

πŸ’» Code

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
    }
}

⚠ Common mistakes

  • Mistake: Leaving the tenant or user out of the cache key. Why it is wrong: One customer's cached data is served to another, which is a privacy breach. Instead: Include every input that changes the result in the key, and test isolation.
  • Mistake: Invalidating before the write. Why it is wrong: A concurrent read repopulates the old value, which then stays for the full TTL. Instead: Write first, then invalidate.
  • Mistake: Hand-rolling 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).
  • Mistake: Mutating an object returned from the cache. Why it is wrong: With a reused instance you corrupt every future read; with copies the change silently disappears. Instead: Cache immutable records; copy with with to change.
  • Mistake: Caching "not found" with a long TTL. Why it is wrong: Newly created products stay invisible for minutes. Instead: Short TTL for nulls, or don't cache them, or invalidate on create.
  • Mistake: Registering AddScoped<IProductRepository, CachedProductRepository>() when the decorator needs IProductRepository. Why it is wrong: Circular dependency. Instead: Factory delegate, keyed inner or Scrutor.
  • Mistake: Caching per-user, permission-filtered results under a shared key. Why it is wrong: Users see items they're not authorised for. Instead: Cache the unfiltered data and filter per request, or key by permission set.
  • Mistake: Adding a cache without measuring hit rate. Why it is wrong: A low hit rate costs memory and complexity for little gain. Instead: Emit hit/miss metrics and review them.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate registers the decorator or cache with a different lifetime than the repository Why: Checks lifetime mismatches when wiring a cache decorator
    How to answer

    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.

  2. When: Candidate mentions ImmutableObject or not mutating cached results Why: Checks why cached values should be immutable
    How to answer

    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.

  3. When: Candidate wires the decorator chain Why: Checks the general Decorator pattern and ordering
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Cache stampede on a cold key took Azure SQL to 100% DTU
Situation
A catalogue API on .NET [10] with [6] instances in Azure Australia East, [~2,000] product reads per second. A hand-written `IMemoryCache` decorator cached products for 5 minutes.
Signals
Every few minutes, Azure SQL DTU spiked to [100%] and p95 latency jumped from [5 ms] to [1.8 s]. Application Insights showed bursts of [hundreds] of identical `SELECT ... WHERE Id = @id` queries within one second, aligned with cache expiry of popular products.
Investigation
Query Store showed the same query executed [~600] times in a second. The decorator did `TryGetValue`, and on a miss every concurrent request called the database before any of them set the cache: a stampede on each expiry, multiplied by [6] instances with separate memory caches.
Resolution
Immediate: raised the TTL and added jitter to spread expiries. Real fix: replaced the decorator with `HybridCache.GetOrCreateAsync` (single flight per key per instance) and added Redis as L2 so instances shared results; short L1 TTL to keep instances consistent after writes.
Prevention
A load test that cold-starts the cache with 1,000 concurrent requests for one key and asserts one database query per instance; hit-rate and factory-duration metrics with an alert; guideline to use HybridCache for read-through caches.

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.

↩ Usually asked after

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me