What is IDistributedCache, and how does it differ from IMemoryCache in a horizontally-scaled ASP.NET Core deployment?
Short answer
IDistributedCache is an abstraction over an external, shared cache store (commonly Redis) that all instances of a scaled-out application read from and write to consistently, ensuring cache coherency across multiple servers -- unlike IMemoryCache, where each instance maintains…
Advertisement
AModel answer
IDistributedCache is an abstraction over an external, shared cache store (commonly Redis) that all instances of a scaled-out application read from and write to consistently, ensuring cache coherency across multiple servers -- unlike IMemoryCache, where each instance maintains its own separate, unsynchronized cache, meaning a value cached by one instance wouldn't be visible to another.
builder.Services.AddStackExchangeRedisCache(options => {
options.Configuration = builder.Configuration.GetConnectionString("Redis");
});
public async Task<Product?> GetProductAsync(int id) {
var cached = await _distributedCache.GetStringAsync($"product-{id}");
return cached is not null ? JsonSerializer.Deserialize<Product>(cached) : null;
}Real-world example
An API running behind a load balancer with 10 instances uses Redis-backed IDistributedCache so a product cached by instance A is immediately visible to instances B through J, avoiding 10x redundant database queries for the same data.
Likely follow-ups
- Why does IDistributedCache only support byte[]/string, requiring manual serialization?
- What's the latency trade-off of a network-based cache versus in-process memory access?
Related topics