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

📚 Interview question

How do you design cache invalidation and TTLs for a .NET service? Explain explicit invalidation, tag-based invalidation, versioned keys and stale-while-revalidate, and how you choose a TTL for a given piece of data.

Cache invalidation strategies (explicit delete, tags, versioned or generational keys, event-driven invalidation) and TTL design (absolute vs sliding, soft and hard expiry, stale-while-revalidate, jitter), with how to choose a TTL from business tolerance.

Mid-Level Theory Intermediate cache-invalidation caching hybridcache performance stale-while-revalidate ttl

🎯 Key points

  • TTL is the staleness bound and safety net; explicit invalidation shortens it for writes you control
  • Classify data first: reference (hours), entity/content (minutes), user/permission (seconds), real-time (don't cache)
  • Explicit invalidation: delete the key after the DB commit; works for single, well-known keys
  • Tags (HybridCache RemoveByTagAsync) invalidate groups; namespace tags (e.g. 'catalogue:product:42') to avoid accidental collisions
  • Versioned/generational keys: bump a version so old keys are never read again and expire naturally
  • Stale-while-revalidate: soft expiry triggers a background refresh while serving stale; hard expiry bounds it
  • Add jitter; avoid sliding-only expiration; monitor hit ratio and staleness and adjust TTLs over time

⏱ 30-second answer

I treat the TTL as the upper bound on staleness and explicit invalidation as a way to do better for changes I control.

  • Explicit delete after the database commit for single, known keys.
  • Tags (HybridCache RemoveByTagAsync) to invalidate groups, such as every cached view of product 42, without tracking keys.
  • Versioned keys (catalogue:v{n}:...): bump n and old entries are simply never read again.
  • Stale-while-revalidate: after a soft expiry, serve the old value and refresh in the background, with a hard expiry as the limit.

I choose a TTL from how stale the business can accept, how often the data changes and how expensive it is to rebuild, then add jitter. The trade-off is freshness versus load and latency.

🗣 Full answer (senior)

How I would answer this in an interview

"I start from a business question: how wrong can this value be, and for how long? A product description can be an hour old; a price shown at checkout probably needs to be right within seconds; stock levels for the last item in a flash sale shouldn't be cached at all. That answer gives me the TTL, and the TTL is my guarantee, because explicit invalidation can fail: a process can crash between the database commit and the cache delete.

On top of the TTL, I invalidate explicitly when my own code changes the data. For one known key, that's just deleting it after the commit. When one change affects many cached entries, like a product appearing in search results, category pages and a recommendations block, I use tags: in HybridCache every entry carries tags such as product:42, and RemoveByTagAsync("product:42") invalidates all of them logically, without me knowing every key. Another technique is versioned keys: the key includes a version, say catalogue:v17, and publishing a new catalogue bumps it to 18. Nothing is deleted; old entries just stop being read and age out. That's ideal for bulk changes.

For expensive data I use stale-while-revalidate: a soft expiry after which the next read returns the cached value immediately and triggers a refresh, and a hard expiry beyond which I won't serve it. Users never wait for a rebuild, and the hard expiry keeps staleness bounded. The mistake I see is sliding expiration on its own, so a popular entry never refreshes, and identical TTLs on keys written together, so they all expire in the same second."


Invalidation strategies

Strategy How Best for Weakness
TTL only Entry expires Data where staleness is fine Stale for up to the TTL
Explicit delete RemoveAsync(key) after commit One known key per change Dual-write; misses related keys
Tags RemoveByTagAsync(tag) One change affects many entries L1 on other pods stays until local expiry
Versioned keys Bump version in key Bulk refreshes, deploys Old entries use memory until they expire
Event-driven Publish change event; subscribers delete Many services caching the same data Needs messaging; at-least-once

Choosing a TTL

Data Tolerable staleness Example TTL
Reference data (countries, categories) Hours 1-24 h + explicit invalidation on admin change
Product descriptions Minutes to an hour 30-60 min, tags on edit
Prices Seconds to minutes 1-5 min + write-through or tag invalidation
User permissions Seconds 30-60 s, or invalidate on change
Stock for checkout, balances None Don't cache, or cache only for display with a clear label

Production example

A catalogue site cached category pages for 10 minutes with no invalidation, so merchandisers waited up to 10 minutes to see edits. Adding product:{id} and category:{id} tags with RemoveByTagAsync on save, and raising the TTL to 60 minutes, made edits visible within the 30-second L1 window and raised the hit ratio from 82% to 96%, cutting SQL reads for those pages by about 75%.

🔍 What the interviewer is checking

Checks that the candidate can turn business freshness requirements into a concrete TTL and invalidation design, and knows the tools in .NET.

Green flags

  • Starts from business tolerance for staleness
  • Uses TTL as a safety net with explicit invalidation on top
  • Knows tags and versioned keys, and HybridCache's L1 caveat
  • Mentions jitter and soft/hard expiry

Red flags

  • "Just set 5 minutes everywhere"
  • Pattern deletes with KEYS
  • No TTL because invalidation is explicit

📚 Learn in depth

1. The two clocks

Every cached entry has a freshness clock (when it stops being trustworthy) and an availability clock (when serving it is worse than waiting). A single TTL merges them. Splitting them gives you stale-while-revalidate:

set ---- fresh ---- softExpiry ---- serve stale + refresh ---- hardExpiry ---- must reload

2. How HybridCache tags work

RemoveByTagAsync("catalogue:product:42") doesn't scan Redis for matching keys. HybridCache records an invalidation timestamp for the tag; when it later reads an entry carrying that tag that was created before the timestamp, it treats it as a miss. That makes invalidation cheap regardless of how many entries carry the tag. The instance that called it drops its own L1 copies; other instances may keep serving their L1 copy until LocalCacheExpiration, so keep that short for data whose edits must show quickly. RemoveByTagAsync("*") invalidates everything.

Namespacing tags. Tags are plain strings shared by everything using the same L2. If two services or two features both use product:42 for different things, one service's edit invalidates the other's entries (harmless but wasteful), or a broad tag like products wipes far more than intended. Prefix tags with the owning bounded context (catalogue:product:42, pricing:product:42), keep a small documented list of tag shapes, and avoid very broad tags except for deliberate flushes.

3. Versioned (generational) keys

catalogue:version -> 17
catalogue:v17:product:42 -> {...}

Readers fetch the current version (itself cached briefly) and build keys from it. A publish increments the version atomically (INCR). Old generations are unreachable and expire by TTL. This is the cleanest way to invalidate millions of keys without KEYS/SCAN deletes.

4. Event-driven invalidation across services

When service B caches data owned by service A, A publishes ProductChanged (ideally through an outbox) to Azure Service Bus; B's handler removes its tags or keys. Deletes are idempotent, so at-least-once delivery is fine. Order doesn't matter for deletes, which is another reason to delete rather than push new values.

5. Choosing the number

Classify the data first:

Class Examples Starting TTL
Reference Countries, categories, config Hours, plus invalidation on admin change
Entity/content Product descriptions, articles Minutes to an hour, with tags
User/permission Roles, entitlements, profile Seconds to a minute, or invalidate on change
Real-time Stock at checkout, balances Don't cache

A useful heuristic: TTL ≈ min(business tolerance, a few multiples of the typical time between changes), then check that the expected hit ratio justifies caching at all. Add 10-20% jitter. Prefer absolute expiration; sliding is only for session-like data and should be capped.

6. Revisit with data

TTLs are a hypothesis. Track hit ratio, sampled staleness (cached version vs database version) and time-to-visible after edits per data class, and adjust quarterly or after incidents.

Try it yourself

  1. Tag cached category and product views in HybridCache, call RemoveByTagAsync on save, and measure time-to-visible on a second instance with different LocalCacheExpiration values.
  2. Implement versioned keys with Redis INCR and show a bulk publish invalidates everything in one operation.
  3. Build soft and hard expiry into a cached value (store RefreshAfter) and serve stale while a background task refreshes.
  4. Log hit ratio and a sampled staleness metric (cached version vs DB version) before and after changing TTLs.

💻 Code

Tags, versioned keys and a simple stale-while-revalidate wrapper on top of HybridCache.

using Microsoft.Extensions.Caching.Hybrid;
using StackExchange.Redis;

namespace Catalogue.Caching;

public sealed record ProductView(int Id, string Name, decimal Price, int CategoryId);

public interface ICatalogueReader
{
    Task<ProductView?> GetProductAsync(int id, CancellationToken ct);
}

public sealed class ProductCache(HybridCache cache, ICatalogueReader reader, IConnectionMultiplexer redis)
{
    private static readonly HybridCacheEntryOptions Options = new()
    {
        Expiration = TimeSpan.FromMinutes(60),          // business tolerance for descriptions
        LocalCacheExpiration = TimeSpan.FromSeconds(30) // bounds staleness on other pods after a tag removal
    };

    public async Task<ProductView?> GetAsync(int id, CancellationToken ct)
    {
        var version = await GetCatalogueVersionAsync();
        return await cache.GetOrCreateAsync(
            $"catalogue:v{version}:product:{id}",      // versioned key: bulk publish = bump version
            (reader, id),
            static async (s, token) => await s.reader.GetProductAsync(s.id, token),
            Options,
            tags: [$"catalogue:product:{id}"],           // namespaced tag: can't collide with another service's 'product:42'
            cancellationToken: ct);
    }

    // Single product edited: invalidate everything tagged with it.
    public ValueTask OnProductEditedAsync(int id, CancellationToken ct) =>
        cache.RemoveByTagAsync($"catalogue:product:{id}", ct);

    // Whole catalogue republished: one INCR; old keys are never read again and age out.
    public async Task OnCataloguePublishedAsync() =>
        await redis.GetDatabase().StringIncrementAsync("catalogue:version");

    private async Task<long> GetCatalogueVersionAsync() =>
        (long?)await redis.GetDatabase().StringGetAsync("catalogue:version") ?? 0;
}
// Stale-while-revalidate: store a soft expiry inside the value; the hard expiry is the cache TTL.
public sealed record Swr<T>(T Value, DateTimeOffset RefreshAfter);

public static class SwrExtensions
{
    public static async Task<T> GetSwrAsync<T>(this HybridCache cache, string key,
        Func<CancellationToken, Task<T>> load, TimeSpan soft, TimeSpan hard, CancellationToken ct)
    {
        var options = new HybridCacheEntryOptions { Expiration = hard };

        // State overload: (key, state, factory, options, tags, ct). State is a tuple, so the lambda can be static.
        var entry = await cache.GetOrCreateAsync(key, (load, soft),
            static async (state, token) => new Swr<T>(await state.load(token), DateTimeOffset.UtcNow + state.soft),
            options, cancellationToken: ct);

        if (DateTimeOffset.UtcNow > entry.RefreshAfter)
        {
            // Serve stale now; refresh in the background. Don't capture the request token or scoped services.
            _ = Task.Run(async () =>
            {
                var fresh = new Swr<T>(await load(CancellationToken.None), DateTimeOffset.UtcNow + soft);
                await cache.SetAsync(key, fresh, options);
            });
        }
        return entry.Value;
    }
}

⚠ Common mistakes

  • Mistake: Picking TTLs without measuring change frequency or hit ratio. Why it is wrong: You either serve stale data needlessly or get no benefit. Instead: Measure how often data changes and how often it's read, then set the TTL and verify hit ratio and staleness.
  • Mistake: Micro-optimising cold paths with elaborate invalidation. Why it is wrong: Tags and events on rarely read data add complexity for nothing. Instead: A short TTL is enough for cold data.
  • Mistake: Setting TTLs once and never revisiting them. Why it is wrong: Change rates and traffic shift; a TTL that was right at launch can become too stale or too short. Instead: Dashboard hit ratio, staleness and time-to-visible per data class and adjust.
  • Mistake: No TTL because "we invalidate explicitly". Why it is wrong: A missed delete leaves data stale forever. Instead: Always keep a TTL as the safety net.
  • Mistake: Sliding-only expiration on shared data. Why it is wrong: Hot entries never refresh. Instead: Absolute expiration, optionally capped sliding.
  • Mistake: Deleting by pattern with KEYS prefix*. Why it is wrong: O(n) and blocks Redis. Instead: Tags or versioned keys.
  • Mistake: Generic, un-namespaced tags such as product:42 or all. Why it is wrong: Other features sharing the cache collide with them, so one edit invalidates unrelated entries. Instead: Prefix tags with the owning context.
  • Mistake: Long LocalCacheExpiration with tag invalidation. Why it is wrong: Other pods keep serving their L1 copy. Instead: Keep L1 short for data that changes.
  • Mistake: The same TTL for keys written together. Why it is wrong: Synchronised expiry causes stampedes. Instead: Jitter by 10-20%.
  • Mistake: Fire-and-forget refresh that captures the request's CancellationToken or scoped services. Why it is wrong: It's cancelled or uses disposed objects after the request ends. Instead: Use CancellationToken.None (or app stopping) and singleton-safe dependencies.

🏛 Senior insight: trade-offs

Invalidation fails in two predictable ways: a dual write (the database commits but the cache delete never happens, because of a crash, timeout or bug) and an unknown dependant (some cached view includes the changed data and nobody deletes it). The senior approach is to make staleness an explicit, agreed number per data class, back it with a TTL so both failures are bounded, and then use the cheapest invalidation that meets the number: delete for one key, tags for groups, version bumps for bulk, events across services.

Technique When it fits Cost When not to
TTL only Tolerant data, cold data Staleness up to TTL User-visible edits that must show quickly
Explicit delete One key per change Dual-write risk Many dependent keys
Tags Many entries per entity L1 lag on other pods Raw IDistributedCache without HybridCache
Versioned keys Bulk publish Orphaned memory until expiry Frequent per-item changes
Stale-while-revalidate Expensive rebuilds, hot keys Serves stale for a while Data that must be fresh on every read

Measure staleness directly: sample cached values and compare their version with the database, and track time-to-visible after edits.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions output caching or tags Why: Checks they can apply tag invalidation to ASP.NET Core output caching across instances
    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.

  2. When: Candidate mentions a CDN or several instances Why: Checks they can invalidate across instances and edge caches
    How to answer

    Use a shared output cache store (Redis) so EvictByTagAsync clears every instance, not just the one that handled the write. At the CDN, keep s-maxage short or purge by path through the CDN API (an Azure Front Door purge can take minutes). For data that must change quickly, avoid purging altogether: content-hash or versioned URLs (/catalogue?v=42) make the new version a new cache key, and ETags let clients revalidate cheaply with If-None-Match and get 304 when nothing changed. Decide the acceptable staleness per endpoint; stale-while-revalidate keeps responses fast while the edge refreshes, and the client should re-read after its own write so users see their change.

  3. When: Candidate mentions RemoveByTagAsync Why: Checks they understand HybridCache's L1/L2 behaviour when invalidating
    How to 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.

🛠 Real-world problems: how you handle them

Merchandisers wait ten minutes to see product edits
Situation
An e-commerce catalogue cached category and product pages for [10 minutes] with TTL-only expiry across [8] pods. Merchandisers edited [~2,000] products a day.
Signals
Repeated support tickets that edits 'didn't save'; editors re-saving the same product several times; hit ratio of [82%] with SQL reads spiking on the hour when many keys expired together.
Investigation
Traced an edit through Application Insights: the save succeeded in [40 ms], but subsequent reads came from cache for up to 10 minutes. Cache metrics showed synchronised expiries because pages were warmed together by a job.
Resolution
Immediate: documented the delay and added a 'refresh' action for editors that removed the specific keys. Fix: tagged entries with `product:{id}` and `category:{id}`, called `RemoveByTagAsync` on save, set L1 to 30 s, raised the hard TTL to 60 minutes with 15% jitter, and used a version bump for nightly catalogue imports.
Prevention
An end-to-end test that edits a product and asserts the change is visible on another instance within [45 s]; dashboards for hit ratio and time-to-visible; a caching guideline that every cached type records its staleness tolerance.

How to tell it (STAR)

**S:** At [company] merchandisers kept reporting that product edits weren't saving, because pages were cached for ten minutes with no invalidation. **T:** I needed edits to show quickly without losing the cache's benefit. **A:** I confirmed the cause with Application Insights traces, then moved the pages to tag-based invalidation in HybridCache with a short local cache, raised the overall TTL with jitter, and used version bumps for bulk imports. I added a test that checks an edit is visible on another instance within the target. **R:** Edits became visible in [under 30 seconds], the hit ratio rose from [82% to 96%], and the 'not saved' tickets stopped.

↩ Usually asked after

More in Caching

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me