Advertisement
Advanced .NET, Caching (In-Memory, Distributed & Redis)

How would you implement cache tag-based invalidation to clear a group of related cache entries at once?

Short answer

Since neither IMemoryCache nor plain IDistributedCache natively support tag-based bulk invalidation, common approaches include maintaining a secondary index (a set of keys per tag) that you iterate through to remove entries when a tag is invalidated, using…

Save .NET mock interview
Advertisement
AModel answer
Since neither IMemoryCache nor plain IDistributedCache natively support tag-based bulk invalidation, common approaches include maintaining a secondary index (a set of keys per tag) that you iterate through to remove entries when a tag is invalidated, using CancellationTokenSource-based eviction tokens shared across related entries (native to IMemoryCache), or using a caching library (like FusionCache or the newer HybridCache with tagging support) that implements this pattern for you.
// IMemoryCache eviction token approach
var cts = new CancellationTokenSource();
_tagTokens["category-electronics"] = cts;

_cache.Set("product-1", product, new MemoryCacheEntryOptions()
    .AddExpirationToken(new CancellationChangeToken(cts.Token)));

// Invalidate the whole tag group at once:
_tagTokens["category-electronics"].Cancel();  // evicts all entries using this token
Real-world example
An e-commerce catalog tags every cached product entry with its category, so updating a category-wide promotional price invalidates all affected product cache entries in one operation instead of tracking and clearing each product's key individually.
Likely follow-ups
  • How does this compare to Redis's native support for pattern-based key deletion (SCAN + DEL)?
  • What's the memory overhead of maintaining a tag-to-keys index?
Related topics