.NET › Caching (In-Memory, Distributed & Redis)
What is IDistributedCache, and how does it differ from IMemoryCache in a multi-instance deployment?
AdvancedAnswer
IDistributedCache is an abstraction over an external, shared cache store (like Redis or SQL Server) that all instances of a horizontally-scaled application read from and write to consistently, unlike IMemoryCache where each instance maintains its own separate, unsynchronized in-process cache. This ensures cache coherency across multiple servers/pods -- a value cached by one instance is immediately visible to all others -- at the cost of network latency per cache operation compared to in-memory access.
builder.Services.AddStackExchangeRedisCache(options => {
options.Configuration = "localhost:6379";
});
public class ProductService {
private readonly IDistributedCache _cache;
public async Task<Product?> GetProductAsync(int id) {
var cached = await _cache.GetStringAsync($"product-{id}");
if (cached != null) return JsonSerializer.Deserialize<Product>(cached);
// ... fetch and cache
}
}Real-world example A horizontally-scaled API running behind a load balancer with 10 instances uses Redis-backed IDistributedCache so a product cached by instance A is immediately available to instances B through J, avoiding 10x redundant database queries for the same data.