Roadmap › ASP.NET Core Web API & REST › Module: Performance, Versioning and Docs
Lessons in this course (15)
11. Caching: response, output, in-memory, distributed, HybridCache
Intermediate★ Must knowLesson 11 of 15
| Cache | Where | Use |
|---|---|---|
HTTP caching headers (Cache-Control, ETag) | Client/CDN/proxy | Public GET resources |
| Output caching (.NET 7) | Server memory (or Redis) | Whole responses; tag-based eviction |
IMemoryCache | Process memory | Single instance, fast |
IDistributedCache (Redis, SQL) | Shared | Multiple instances / scale-out |
HybridCache (.NET 9) | L1 memory + L2 distributed | Stampede protection, tags, one API |
csharp
builder.Services.AddHybridCache();
public class ProductService(HybridCache cache, AppDbContext db)
{
public ValueTask<ProductDto?> GetAsync(int id, CancellationToken ct) =>
cache.GetOrCreateAsync($"product:{id}", async token =>
await db.Products.Where(p => p.Id == id).Select(p => new ProductDto(p.Id, p.Name, p.Price)).FirstOrDefaultAsync(token),
cancellationToken: ct);
}Cache invalidation strategies: expiration (absolute/sliding), explicit removal on write, tags, versioned keys.