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?
Diagnostics & PerformanceEntity Framework Core & Data Access
Cache-Control directives (max-age, no-cache, private/public) tell browsers and intermediary caches/CDNs how long a response can be reused without re-requesting. ETag provides a version identifier for a resource; clients can send If-None-Match with a previously seen ETag, and the server responds with a lightweight 304 Not Modified if unchanged, avoiding retransmitting the full response body -- these HTTP-layer mechanisms complement server-side application caching by reducing load even before a request reaches your application code.
[HttpGet("{id}")]
public IActionResult GetProduct(int id) {
var product = _service.GetProduct(id);
var etag = ComputeETag(product);
if (Request.Headers.IfNoneMatch == etag) return StatusCode(304);
Response.Headers.ETag = etag;
Response.Headers.CacheControl = "public, max-age=300";
return Ok(product);
}
Real-world example
A public API serving rarely-changing reference data (like country lists) sets long Cache-Control max-age values and ETags, letting a CDN and client browsers serve repeat requests without ever reaching the origin server.
Likely follow-ups
How does a CDN's cache differ from browser caching in terms of who benefits?
What's the risk of overly aggressive Cache-Control settings for frequently-changing data?
RESTful Web APIs & ControllersASP.NET Core Middleware & Request Pipeline
IDistributedCache's core API (GetAsync/SetAsync) works with raw byte[], so caching complex objects requires manual serialization (commonly System.Text.Json to UTF-8 bytes) before storing and deserialization after retrieval -- extension methods (GetStringAsync/SetStringAsync) simplify the string case, but for full object graphs you typically write a small helper or use a library wrapping this boilerplate consistently across your application.
public static class DistributedCacheExtensions {
public static async Task SetObjectAsync<T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options) {
var bytes = JsonSerializer.SerializeToUtf8Bytes(value);
await cache.SetAsync(key, bytes, options);
}
public static async Task<T?> GetObjectAsync<T>(this IDistributedCache cache, string key) {
var bytes = await cache.GetAsync(key);
return bytes == null ? default : JsonSerializer.Deserialize<T>(bytes);
}
}
Real-world example
A team writes a shared SetObjectAsync/GetObjectAsync extension method pair once, standardizing JSON serialization for distributed cache usage across dozens of services instead of each developer reimplementing serialization logic inconsistently.
Likely follow-ups
What are the performance trade-offs of JSON versus binary serialization formats like MessagePack for caching?
How do you handle versioning when a cached object's schema changes?
Entity Framework Core & Data AccessMicroservices & Distributed Architecture Patterns
Caching sensitive data (like another user's personal information) under a shared or predictable cache key risks accidentally serving one user's private data to another -- a critical security bug -- so cache keys for user-specific data must always incorporate the user's identity (or session) to prevent cross-user leakage, and truly sensitive data (passwords, tokens) generally shouldn't be cached at all, or only in short-lived, tightly-scoped caches.
// DANGEROUS: shared key regardless of user
var cacheKey = "user-profile"; // BUG: same key for every user!
// CORRECT: key includes user identity
var cacheKey = $"user-profile-{userId}";
Real-world example
A critical security incident occurs when a response-caching misconfiguration caches a personalized dashboard response without varying by user, causing one user's private financial data to be served to the next user who happened to hit the same cached response.
Likely follow-ups
How does VaryByHeader help prevent this specific class of bug in response caching?
What data should never be cached regardless of key scoping?
GetOrCreateAsync atomically checks for an existing cache entry and, if missing, invokes a factory delegate to compute and store the value in one operation, resulting in cleaner code than manually calling TryGetValue, checking the result, and then calling Set separately -- and critically, IMemoryCache's implementation of this pattern also provides built-in per-key locking to reduce (though not eliminate under heavy load) cache stampede risk for the same key.
A product catalog service consistently uses GetOrCreateAsync throughout its caching code instead of manual TryGetValue/Set pairs, resulting in more concise code and automatic protection against the most common cache-miss race conditions.
Likely follow-ups
What does the entry parameter inside the factory delegate let you configure?
How does this differ from IDistributedCache, which has no built-in equivalent?