Cache-aside (most common) checks the cache first and, on a miss, loads from the data source and populates the cache reactively -- appropriate for read-heavy workloads. Write-through caching instead updates the cache synchronously on every write, guaranteeing the cache is never stale for writes that went through that path, at the cost of added write latency and more complex write-path code -- the right choice depends on whether staleness-until-next-read (cache-aside) or guaranteed freshness (write-through) matters more for the specific resource.
// Cache-aside (most common)
public async Task<Product> GetProductAsync(int id) {
var cached = await _cache.GetAsync<Product>($"product-{id}");
if (cached is not null) return cached;
var product = await _db.GetProductAsync(id);
await _cache.SetAsync($"product-{id}", product);
return product;
}
// Write-through: update cache immediately on write
public async Task UpdateProductAsync(Product product) {
await _db.UpdateAsync(product);
await _cache.SetAsync($"product-{product.Id}", product); // cache updated immediately
}
Real-world example
A read-heavy product catalog uses cache-aside since reads vastly outnumber writes, while a financial account balance endpoint uses write-through caching to guarantee the cache never briefly shows stale balance data after a transaction.
Likely follow-ups
What is write-behind (write-back) caching and when is it appropriate?
How does cache-aside handle the stampede problem differently than write-through?
Entity Framework Core & Data AccessDiagnostics & Performance
Absolute expiration removes an entry at a fixed point in time regardless of access frequency, guaranteeing data won't become stale beyond a hard limit. Sliding expiration resets the expiration timer every time the entry is accessed, keeping frequently-used data cached indefinitely while letting rarely-accessed entries expire -- combining both gives a 'refresh on access, but never beyond X duration' behavior.
_cache.Set("key", value, new MemoryCacheEntryOptions {
SlidingExpiration = TimeSpan.FromMinutes(5), // resets on each access
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) // hard cap regardless of access
});
Real-world example
A frequently-accessed session cache uses a 5-minute sliding expiration combined with a 1-hour absolute cap, so active users keep their cached session alive while inactive sessions are forcibly cleared within an hour at most.
Likely follow-ups
What happens if only sliding expiration is set with no absolute cap?
How does cache eviction interact with memory pressure signals under IMemoryCache?
Include all parameters that affect the query's result set (page number, page size, sort order, filter values) as part of the cache key, since caching under a key that ignores a parameter would return the wrong page/filtered results to a subsequent request with different parameters -- Output Caching's VaryByQueryKeys handles this declaratively for HTTP-level caching, while application-level caching requires manually composing a sufficiently unique key string.
// Application-level: composite key including all relevant parameters
var cacheKey = $"products-page{page}-size{pageSize}-sort{sortBy}-category{category}";
// Output Caching: declarative equivalent
[HttpGet]
[OutputCache(VaryByQueryKeys = new[] { "page", "pageSize", "sortBy", "category" })]
public IActionResult GetProducts(int page, int pageSize, string sortBy, string category) { ... }
Real-world example
A bug where users saw identical results regardless of their selected sort order was traced to a cache key that only included the page number, not the sortBy parameter, causing the first-cached sort order to be returned for every subsequent request.
Likely follow-ups
What happens if you forget to include a parameter that affects the query in the cache key?
How does an overly granular cache key (too many parameter combinations) hurt cache hit rate?
VaryByValue accepts a delegate computing a custom string value from the HttpContext, letting you vary cached output based on arbitrary logic (like a tenant ID derived from a claim, or a feature flag's current state) that doesn't map directly to a simple query parameter or header, giving fine-grained control over cache key composition beyond the built-in VaryByQueryKeys/VaryByHeader options.
app.MapGet("/dashboard", GetDashboard)
.CacheOutput(policy => policy.SetVaryByValue(context => {
var tenantId = context.User.FindFirst("tenant_id")?.Value ?? "anonymous";
return new KeyValuePair<string, string>("tenant", tenantId);
}));
Real-world example
A multi-tenant SaaS dashboard varies its output cache by a computed tenant ID extracted from the user's claims, ensuring each tenant sees only their own cached dashboard data despite the same URL being requested by users across different tenants.
Likely follow-ups
How does VaryByValue's computed key interact with other Vary options used simultaneously?
What's the performance cost of a complex VaryByValue delegate evaluated on every request?
Instrument cache access points with custom metrics (via the System.Diagnostics.Metrics Meter API) tracking hits versus misses per cache key pattern, exposed through dotnet-counters locally or an OpenTelemetry-based observability platform in production -- without this visibility, it's easy to assume a caching layer is helping when it might have a low hit rate (e.g., overly specific cache keys causing near-constant misses) that provides little actual benefit while still adding complexity and memory overhead.
private static readonly Counter<long> _cacheHits = _meter.CreateCounter<long>("cache.hits");
private static readonly Counter<long> _cacheMisses = _meter.CreateCounter<long>("cache.misses");
public async Task<Product> GetProductAsync(int id) {
if (_cache.TryGetValue($"product-{id}", out Product cached)) {
_cacheHits.Add(1);
return cached;
}
_cacheMisses.Add(1);
// ... fetch and cache
}
Real-world example
A team discovers via cache hit-rate metrics that a recently-added caching layer for a highly-parameterized search endpoint has a hit rate under 5% due to overly specific cache keys, prompting a redesign of the caching strategy to group more broadly cacheable query variations together.
Likely follow-ups
What hit rate threshold typically indicates a caching strategy isn't worth its added complexity?
How would you use dotnet-counters to observe these custom metrics live?