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

📚 Interview question

Show me how you would use HybridCache in .NET 10 to replace hand-written cache-aside code. Explain the two cache levels, how it protects against stampedes, how tags and invalidation work, and how you would prove the change helped.

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.

Mid-Level Coding Intermediate aspnet-core cache-stampede caching hybridcache performance redis

🎯 Key points

  • AddHybridCache; GetOrCreateAsync(key, state, factory, options, tags, ct) replaces get/check/set code
  • Library GA March 2025, runs on .NET 8+; the recommended cache abstraction in .NET 9 and 10
  • L1 = in-process MemoryCache; L2 = any registered IDistributedCache (e.g. Redis)
  • Stampede protection: concurrent callers for one key in one process share a single factory call
  • Limits: no cluster-wide coordination or distributed lock; N instances can run N factories
  • RemoveAsync removes the key from this process's L1 and from L2; RemoveByTagAsync invalidates a tag group logically
  • Other instances' L1 copies stay until LocalCacheExpiration, so keep it short for mutable data
  • Prove it with k6 or BenchmarkDotNet: source call count, p95 and allocations before and after

⏱ 30-second answer

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

  • Two levels: an in-process L1 (MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).
  • Stampede protection: concurrent misses for the same key in one process share a single factory call.
  • Tags: entries can carry tags, and 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 whatever IDistributedCache you'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, and RemoveByTagAsync invalidates 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 LocalCacheExpiration short."


Hand-written cache-aside vs HybridCache

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

Entry options that matter

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

Production example

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.

🔍 What the interviewer is checking

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

  • Uses GetOrCreateAsync with the state overload and entry options
  • States that stampede protection is per process
  • Explains that other pods' L1 copies remain until LocalCacheExpiration
  • Proves the improvement with source-call counts and p95

Red flags

  • Thinks HybridCache gives distributed locking or instant cluster-wide invalidation
  • Caches per-user data without the user in the key
  • No measurement plan

📚 Learn in depth

1. The lookup path

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

2. Stampede protection internals

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.

3. Tags and invalidation

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.

4. Serialisation and object reuse

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.

5. What it doesn't do

  • Distributed locking or cluster-wide stampede protection.
  • Stale-while-revalidate (serve stale while refreshing in the background) out of the box; libraries such as FusionCache add that and a backplane.
  • Replace the need to put the user or tenant into keys for personal data.

Try it yourself

  1. Write a factory that increments a counter and sleeps 200 ms; fire 100 concurrent GetOrCreateAsync calls and assert the counter is 1.
  2. Run two instances against one Redis, expire the key and count factory calls (expect up to 2).
  3. Tag entries with product:{id}, call RemoveByTagAsync, and verify the next read calls the factory.
  4. Run k6 at a steady rate against the old cache-aside endpoint and the HybridCache endpoint; compare p95 and database calls in Application Insights.
  5. Benchmark L1 hits with a mutable class versus a sealed [ImmutableObject(true)] record using [MemoryDiagnoser].

💻 Code

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

⚠ Common mistakes

  • Mistake: Switching to HybridCache without measuring before and after. Why it is wrong: You can't show it helped, or spot that the hit ratio is poor. Instead: Record source call counts, p95 and Redis traffic under the same k6 load before and after.
  • Mistake: Micro-optimising cold paths, such as wrapping rarely called admin queries. Why it is wrong: Adds staleness with no measurable gain. Instead: Apply it to hot, read-heavy paths first.
  • Mistake: Assuming stampede protection is cluster-wide. Why it is wrong: It coordinates callers inside one process only; N pods can still run N factories. Instead: Accept N, or add jittered expiry or early refresh for very expensive keys.
  • Mistake: Long 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.
  • Mistake: Capturing variables in the factory lambda on a hot path. Why it is wrong: Allocates a closure per call. Instead: Use the state overload with a static lambda.
  • Mistake: Caching user-specific data with a key that lacks the user or tenant. Why it is wrong: Users can see each other's data. Instead: Include user or tenant ids in the key and tags.
  • Mistake: Caching nulls or errors unintentionally. Why it is wrong: A transient failure or missing row can be served for the full expiration. Instead: Throw on errors (nothing is cached) and decide deliberately whether to cache "not found" with a short lifetime.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions wrapping a repository Why: Checks they can apply HybridCache as a decorator with DI
    How to 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.

  2. When: Candidate mentions ConcurrentDictionary.GetOrAdd for de-duplication Why: Checks they know GetOrAdd can run the factory more than once
    How to answer

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

  3. When: Candidate mentions tags or invalidating across instances Why: Checks they can invalidate output cache entries across instances too
    How to answer

    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.

🛠 Real-world problems: how you handle them

Hot product keys expire and every request hits SQL at once
Situation
A catalogue API running on [6] pods cached product details in Redis with hand-written cache-aside code and a fixed 5-minute expiry. Peak traffic was [500] requests per second, mostly for [200] popular products.
Signals
Azure SQL DTU spiked to [90%] every 5 minutes; Application Insights showed bursts of identical product queries; p95 jumped from [40 ms] to [600 ms] for a few seconds after each expiry.
Investigation
Application Insights dependency telemetry grouped by query showed [30-50] identical calls per product within one second of expiry. Query Store confirmed the same query plan was fine; the problem was call volume. A k6 test reproduced the spike locally with two instances.
Resolution
Immediate: added a random jitter of up to 60 seconds to expirations to spread the misses. Real fix: replaced the cache-aside blocks with HybridCache (L1 30 s, L2 10 min) and tag-based invalidation on product updates.
Prevention
A custom OpenTelemetry counter for factory calls per key with an alert on spikes; a k6 load test in the pipeline that checks database calls per expiry; a team guideline that new caching uses HybridCache.

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.

↩ Usually asked after

More in Caching

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me