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.
I treat the TTL as the upper bound on staleness and explicit invalidation as a way to do better for changes I control.
RemoveByTagAsync) to invalidate groups, such as every cached view of product 42, without tracking keys.catalogue:v{n}:...): bump n and old entries are simply never read again.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.
"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, andRemoveByTagAsync("product:42")invalidates all of them logically, without me knowing every key. Another technique is versioned keys: the key includes a version, saycatalogue: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."
| 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 |
| 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 |
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%.
Checks that the candidate can turn business freshness requirements into a concrete TTL and invalidation design, and knows the tools in .NET.
Green flags
Red flags
KEYSEvery 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
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.
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.
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.
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.
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.
RemoveByTagAsync on save, and measure time-to-visible on a second instance with different LocalCacheExpiration values.INCR and show a bulk publish invalidates everything in one operation.RefreshAfter) and serve stale while a background task refreshes.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;
}
}
KEYS prefix*. Why it is wrong: O(n) and blocks Redis. Instead: Tags or versioned keys.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.LocalCacheExpiration with tag invalidation. Why it is wrong: Other pods keep serving their L1 copy. Instead: Keep L1 short for data that changes.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.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.
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.
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.
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.
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.
Last updated 23 Nov 2026.