Recipe 3.5 · C#
Distributed Caching with IDistributedCache and Redis
Problem
The application now runs on four servers behind a load balancer. Each has its own in-memory cache, so each loads the same data, invalidation on one server does not reach the others, and a user can see a new value on one request and the old value on the next. Some data also needs to survive an application restart, such as an expensive report result.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: binary serialization into a shared store.
var formatter = new BinaryFormatter();
using (var ms = new MemoryStream())
{
formatter.Serialize(ms, report);
redis.StringSet("Report_" + id, ms.ToArray());
}
BinaryFormatter is a remote-code-execution risk when it reads data it did not write, it is obsolete, and starting with .NET 9 it throws on every call. Code like this also tends to connect to Redis directly in every class, with no expiration and no plan for what happens when Redis is down.
The improved recipe
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Caching;
public sealed class JsonDistributedCache(
IDistributedCache cache, ILogger<JsonDistributedCache> logger)
{
private static readonly JsonSerializerOptions Json =
new(JsonSerializerDefaults.Web);
public async Task<T> GetOrCreateAsync<T>(
string key,
Func<CancellationToken, Task<T>> factory,
TimeSpan timeToLive,
CancellationToken ct = default)
{
byte[]? bytes = null;
try
{
bytes = await cache.GetAsync(key, ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "Cache read failed for {Key}", key);
}
if (bytes is not null)
{
return JsonSerializer.Deserialize<T>(bytes, Json)!;
}
T value = await factory(ct);
try
{
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = timeToLive
};
await cache.SetAsync(
key,
JsonSerializer.SerializeToUtf8Bytes(value, Json),
options,
ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "Cache write failed for {Key}", key);
}
return value;
}
public async Task RemoveAsync(
string key, CancellationToken ct = default) =>
await cache.RemoveAsync(key, ct);
}
public static class DistributedCacheSetup
{
public static IServiceCollection AddAppDistributedCache(
this IServiceCollection services, string? redisConnection)
{
if (string.IsNullOrWhiteSpace(redisConnection))
{
// Development and single-server fallback.
services.AddDistributedMemoryCache();
}
else
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConnection;
options.InstanceName = "appdb:";
});
}
services.AddSingleton<JsonDistributedCache>();
return services;
}
}
How it works
IDistributedCache is a small interface for storing byte arrays by string key, with expiration. The application codes against the interface, and the registration picks the store: Redis through AddStackExchangeRedisCache, or an in-process implementation through AddDistributedMemoryCache for development. SQL Server is a third option, through the Microsoft.Extensions.Caching.SqlServer package.
JsonDistributedCache adds the two things the raw interface lacks: typed values and resilience. Values are serialized with System.Text.Json into UTF-8 bytes, which is safe, fast and readable when you inspect Redis by hand. Read and write failures are logged and treated as misses, so when Redis restarts, the application gets slower for a minute instead of failing every request. A cache should never be a single point of failure for data that lives in the database anyway.
InstanceName prefixes every key, so several applications can share one Redis server without colliding.
Wire it up in Program.cs:
// Usage snippet
builder.Services.AddAppDistributedCache(
builder.Configuration.GetConnectionString("Redis"));
Variations and pitfalls
- Every read is a network call. A Redis read takes about a millisecond, which is far faster than a database query and far slower than memory. For data read many times per request, put a short in-memory level in front. That two-level design is exactly what
HybridCacheprovides. - Version your keys. When the shape of a cached type changes, old JSON may not deserialize into the new type. Put a version in the key (
report:v2:42) and bump it with the change. - Mind the size. Large values slow down every server that reads them. Cache the summary, not the 50,000-row result.
- Sliding expiration costs a write. In Redis, every sliding-expiration read also refreshes the key's lifetime. Prefer absolute expiration unless you need sliding.
- Sensitive data. Redis is often less protected than the database. Do not cache personal data, tokens or anything secret unless the Redis server is secured with TLS and authentication and the data is needed there.
- Stampedes again. This class does not deduplicate loads. Combine it with the in-flight logic from Recipe 3.4, or use
HybridCache.