ASP.NET Core Interview Question #234
How would you design caching for frequently requested product data?
Senior ASP.NET Core Real-World Scenarios Senior Advanced
Quick Interview Answer
Decide what can be stale and for how long before choosing a cache. For data that is identical for all users, cache a compact DTO using a stable key such as product:{id}. Use explicit expiration and invalidate or replace the entry when the product changes.
Detailed Explanation
Decide what can be stale and for how long before choosing a cache. For data that is identical for all users, cache a compact DTO using a stable key such as product:{id}. Use explicit expiration and invalidate or replace the entry when the product changes.
In a multi-instance application, use a distributed cache if instances need to share the same cached state. Prevent a cache miss from causing excessive simultaneous database work for a hot key when that risk is material.
Never let a cache key omit user, tenant, locale, or other dimensions that change the returned data.
Code Example
var key = $"product:{id}";
var product = await _cache.GetOrCreateAsync(key, async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return await _repository.GetProductDtoAsync(id, ct);
});