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
CacheWhereUse
HTTP caching headers (Cache-Control, ETag)Client/CDN/proxyPublic GET resources
Output caching (.NET 7)Server memory (or Redis)Whole responses; tag-based eviction
IMemoryCacheProcess memorySingle instance, fast
IDistributedCache (Redis, SQL)SharedMultiple instances / scale-out
HybridCache (.NET 9)L1 memory + L2 distributedStampede 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.