IDistributedCache over Redis: the byte-array API, serialisation cost, network latency, Redis data structures and features, connection management, and Azure Managed Redis versus the retiring Azure Cache for Redis.
IDistributedCache is a minimal, byte-array cache API: GetAsync, SetAsync, RefreshAsync, RemoveAsync with absolute or sliding expiration. With AddStackExchangeRedisCache the values live in Redis, so every instance shares them and they survive deployments.
For new Azure work I'd pick Azure Managed Redis, because Azure Cache for Redis is retiring. The trade-off is shared consistency versus a network hop and another dependency.
"
IDistributedCacheis deliberately minimal: get, set, refresh and remove abyte[]by string key, with absolute or sliding expiration. That means it works over Redis, SQL Server or Cosmos DB, but it also means serialisation is my job. In ASP.NET Core I register it withAddStackExchangeRedisCache, which uses StackExchange.Redis underneath with a single multiplexed connection per process.The thing I keep in mind is that every call is a network round trip. In the same Azure region, Redis usually answers in well under a millisecond on the server, so you see roughly half a millisecond to two milliseconds end to end, plus the time to serialise and deserialise. That's great compared with a 40 ms SQL query, but if a request reads the same key twenty times it adds up, so for hot keys I put an in-memory layer in front, which is exactly what
HybridCachedoes. I also keep values small: Redis runs commands on a single main thread, so one 5 MB value slows every other client on that node.Redis is good at much more than caching:
INCRfor rate limits and counters, sorted sets for leaderboards, pub/sub for invalidation messages, streams, and distributed locks with care. On Azure today I'd choose Azure Managed Redis. Microsoft has announced Azure Cache for Redis is retiring, the Enterprise tiers on 31 March 2027 and Basic, Standard and Premium on 30 September 2028, so new caches should not go there. The mistake I see is treating the cache as a database: it can fail over, evict or be flushed, so the app must work, slower, on a miss."
| Member | Notes |
|---|---|
GetAsync(key) |
Returns byte[]?; null on miss |
SetAsync(key, value, options) |
DistributedCacheEntryOptions: absolute, relative or sliding expiration |
RefreshAsync(key) |
Resets sliding expiration without reading the value |
RemoveAsync(key) |
Explicit invalidation |
| Extension methods | GetStringAsync/SetStringAsync (UTF-8) |
| Serialiser | Size | Speed | Notes |
|---|---|---|---|
| System.Text.Json (source-generated) | Medium | Fast, no reflection | Good default; readable in redis-cli |
| MessagePack | Small | Very fast | Binary; version contracts carefully |
| Protobuf | Small | Fast | Needs schema |
| BinaryFormatter | n/a | n/a | Removed and insecure; never |
| Offering | Status | Notes |
|---|---|---|
| Azure Managed Redis | Current, recommended | Built on Redis Enterprise; Memory/Balanced/Compute Optimised tiers; available in Australia East |
| Azure Cache for Redis Enterprise / Enterprise Flash | Retiring 31 March 2027; new creation blocked since April 2026 | Migrate to Azure Managed Redis |
| Azure Cache for Redis Basic/Standard/Premium | Retiring 30 September 2028 | Migration tooling available; plan the move now |
A quoting service moved product prices from per-pod IMemoryCache to Redis so all 8 pods agreed after a price change. Reads went from ~100 ns to ~0.9 ms p50 and 2.5 ms p99, which was fine for one read per request. Switching from reflection-based JSON to source-generated System.Text.Json cut serialisation CPU on that path by about 40%.
Checks that the candidate understands what a distributed cache costs (network, serialisation, an extra dependency), uses Redis correctly from .NET and knows the current Azure landscape.
Green flags
Red flags
BinaryFormatter or creates a connection per callrequest -> serialise key/value -> StackExchange.Redis multiplexer -> TCP/TLS (port 6380/10000)
-> Redis main thread executes GET/SET -> response -> deserialise
StackExchange.Redis pipelines all commands from a process over a small number of connections. Creating a ConnectionMultiplexer per request is a classic bug: it's expensive and leaks sockets. AddStackExchangeRedisCache manages one for you.
Redis keeps everything in RAM and executes commands on a single main thread (I/O threads help with networking), so each command is atomic and there are no locks. The flip side: an O(n) command (KEYS *, a huge HGETALL) or a large value blocks everyone. Keep values in the KB range and use SCAN instead of KEYS.
The Redis provider stores each entry as a hash with the data, absolute expiration and sliding expiration fields, and sets a Redis TTL. Sliding expiration therefore needs an extra round trip on read to refresh the TTL. Use absolute expiration where you can.
| Failure | Effect | Mitigation |
|---|---|---|
| Failover or patching | Seconds of timeouts | Short timeouts, retry once, fall back to source |
Eviction (maxmemory-policy) |
Unexpected misses | Monitor evicted keys; size the cache |
| Large values | Latency spikes for all clients | Compress or split; keep < 100 KB |
| ThreadPool starvation in client | RedisTimeoutException with busy worker counts |
Fix sync-over-async; read the timeout message's WORKER/IOCP numbers |
INCR + EXPIRE: fixed-window rate limiting across instances.SET key value NX PX): fine for efficiency, not for correctness without fencing tokens.AddStackExchangeRedisCache, and time 1,000 GetAsync calls; compare with IMemoryCache.JsonSerializerContext for your DTO with [MemoryDiagnoser].redis-cli --latency from another terminal while reading it in a loop.INCR with EXPIRE to build a per-client counter and test it from two app instances.A typed wrapper over IDistributedCache with source-generated JSON, short timeouts and a fallback to the source when Redis is unavailable.
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
namespace Pricing.Caching;
public sealed record ProductPrice(string Sku, decimal Amount, DateTimeOffset AsOf);
[JsonSerializable(typeof(ProductPrice))]
internal sealed partial class PricingJsonContext : JsonSerializerContext;
public interface IPriceRepository
{
Task<ProductPrice?> GetAsync(string sku, CancellationToken ct);
}
public sealed class PriceCache(IDistributedCache cache, IPriceRepository repository, ILogger<PriceCache> logger)
{
private static readonly DistributedCacheEntryOptions Options = new()
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) // absolute: no refresh round trip
};
public async Task<ProductPrice?> GetAsync(string sku, CancellationToken ct)
{
var key = $"price:v1:{sku}";
try
{
var bytes = await cache.GetAsync(key, ct);
if (bytes is not null)
{
return JsonSerializer.Deserialize(bytes, PricingJsonContext.Default.ProductPrice);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// The cache is an optimisation: degrade to the database, don't fail the request.
logger.LogWarning(ex, "Redis read failed for {CacheKey}", key);
}
var price = await repository.GetAsync(sku, ct);
if (price is not null)
{
var payload = JsonSerializer.SerializeToUtf8Bytes(price, PricingJsonContext.Default.ProductPrice);
try { await cache.SetAsync(key, payload, Options, ct); }
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "Redis write failed for {CacheKey}", key);
}
}
return price;
}
}
// Program.cs
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("Redis");
options.InstanceName = "pricing:"; // key prefix so services sharing a cache don't collide
});
builder.Services.AddSingleton<PriceCache>();
ConnectionMultiplexer per request. Why it is wrong: Slow handshakes and socket exhaustion. Instead: One shared multiplexer per process (the DI registration handles it).KEYS * to find keys to delete. Why it is wrong: O(n) and blocks the server. Instead: Versioned keys, tags (HybridCache) or SCAN.A senior answer treats the distributed cache as an optimisation that can disappear at any moment: failover, eviction, a flush during patching. The app must stay correct (and acceptably fast) on a miss, with timeouts tuned well below the request budget, and the database must be sized to survive a cold cache. It also recognises that IDistributedCache alone has no L1 and no stampede protection; in .NET 9+ HybridCache layers those on top of the same IDistributedCache registration.
| Store behind IDistributedCache | When it fits | Cost | When not to |
|---|---|---|---|
| Redis (Azure Managed Redis) | Low latency, high throughput, shared | Another managed service; memory-priced | Tiny workloads where a single pod is enough |
| SQL Server distributed cache | No extra infrastructure; small scale | Adds load to the database you are protecting | High read rates |
| Cosmos DB | Already on Cosmos; global distribution | RU cost per read | Latency-critical hot paths |
Monitoring is part of the design. I track and alert on:
| Signal | Where | Alert when |
|---|---|---|
| Hit ratio (your own hit/miss counters) | OpenTelemetry metrics | Drops sharply (keys changed, cache flushed) |
| Redis dependency p95 and failures | Application Insights | p95 above a few ms or failure rate rises |
| Server load, used memory, evicted keys, connected clients | Azure Monitor metrics for the Redis resource | Memory near the limit, evictions climbing, server load > 80% |
RedisTimeoutException count |
Logs | Any sustained rate (often client ThreadPool starvation) |
| Source (SQL) load during cache incidents | Query Store / Azure SQL metrics | Spikes that track cache misses |
The built-in middleware keeps counters in each process, so 10 instances allow roughly 10x the limit. Options: divide the limit by the instance count (cheap, approximate, and wrong as soon as autoscaling changes the count); enforce at a shared edge such as Azure API Management rate-limit-by-key / quota-by-key; or use a Redis-backed limiter (sliding window or token bucket in an atomic Lua script) for exact limits, at the cost of a network hop per request. Decide up front what happens when Redis is unreachable: fail open with a per-instance local limiter as a fallback, or fail closed for abuse-sensitive endpoints such as login.
Use a shared output cache store (Redis) so EvictByTagAsync clears every instance, not just the one that handled the write. At the CDN, keep s-maxage short or purge by path through the CDN API (an Azure Front Door purge can take minutes). For data that must change quickly, avoid purging altogether: content-hash or versioned URLs (/catalogue?v=42) make the new version a new cache key, and ETags let clients revalidate cheaply with If-None-Match and get 304 when nothing changed. Decide the acceptable staleness per endpoint; stale-while-revalidate keeps responses fast while the edge refreshes, and the client should re-read after its own write so users see their change.
The decorator implements IProductRepository and reads through HybridCache.GetOrCreateAsync, sending misses to the inner repository. HybridCache gives an in-memory L1 cache, an optional distributed L2, and stampede protection: 500 concurrent misses for a key make one database call.
product:v1:{tenant}:{id}.null is a deliberate choice with a short TTL.Register it with a factory delegate or a keyed inner service, or use Scrutor's Decorate<,>(). The trade-off is staleness: choose the TTL from how stale the business can tolerate.
Last updated 23 Nov 2026.