.NET › Caching (In-Memory, Distributed & Redis)

How does HybridCache (introduced in .NET 9) combine in-memory and distributed caching to solve common pain points?

Advanced

Answer

HybridCache provides a unified API that transparently layers a fast local in-memory cache in front of a distributed cache (like Redis), automatically handling cache stampede protection (built-in request coalescing for concurrent identical requests) and serialization, giving you both the speed of local caching and the consistency of distributed caching without hand-rolling the two-tier logic yourself.
builder.Services.AddHybridCache();

public class ProductService {
    private readonly HybridCache _cache;
    public async Task<Product> GetProductAsync(int id) {
        return await _cache.GetOrCreateAsync($"product-{id}", async ct => {
            return await _repository.GetByIdAsync(id, ct);
        }, new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(10) });
    }
}
Real-world example A team previously hand-rolling a two-tier cache (check IMemoryCache, fall back to Redis, populate both on miss) replaces dozens of lines of custom coordination logic with a single HybridCache.GetOrCreateAsync call after upgrading to .NET 9.

Common follow-ups: How does HybridCache handle stampede protection across multiple server instances, not just within one process?;What serialization options does HybridCache support for complex objects?