Lesson 3 of 8
Redis Distributed Cache - IDistributedCache
Redis is the production distributed cache for multi-instance deployments: multiple API pods share the same cache, preventing per-instance cold starts. It also enables session sharing, rate limiting storage, and pub/sub messaging.
Redis Cache - Production Usage
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
// ━━ Registration ━━
// dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("Redis");
options.InstanceName = "myapp:"; // prefix all keys: "myapp:product:123"
});
// ━━ Generic cache helper - avoids repeating JSON + options setup ━━
public class DistributedCacheHelper(IDistributedCache cache)
{
public async Task<T?> GetAsync<T>(string key, CancellationToken ct = default)
{
var bytes = await cache.GetAsync(key, ct);
return bytes is null
? default
: JsonSerializer.Deserialize<T>(bytes);
}
public async Task SetAsync<T>(
string key, T value,
TimeSpan? absoluteExpiry = null,
TimeSpan? slidingExpiry = null,
CancellationToken ct = default)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(value);
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = absoluteExpiry,
SlidingExpiration = slidingExpiry
};
await cache.SetAsync(key, bytes, options, ct);
}
public Task RemoveAsync(string key, CancellationToken ct = default) =>
cache.RemoveAsync(key, ct);
// GetOrSet - atomic get-or-fetch pattern
public async Task<T> GetOrSetAsync<T>(
string key,
Func<CancellationToken, Task<T>> factory,
TimeSpan expiry,
CancellationToken ct = default)
{
var cached = await GetAsync<T>(key, ct);
if (cached is not null) return cached;
var value = await factory(ct);
await SetAsync(key, value, absoluteExpiry: expiry, ct: ct);
return value;
}
}
// ━━ Usage in service ━━
public class ProductCacheService(
IProductRepository repo,
DistributedCacheHelper cache,
ILogger<ProductCacheService> logger)
{
public async Task<ProductDto?> GetByIdAsync(Guid id, CancellationToken ct)
{
var key = $"product:{id}";
return await cache.GetOrSetAsync(
key,
async token =>
{
logger.LogInformation("Redis miss for {ProductId} - fetching from DB", id);
var product = await repo.GetByIdAsync(id, token);
return product is null ? null : Map(product);
},
expiry: TimeSpan.FromMinutes(5),
ct: ct);
}
public async Task InvalidateAsync(Guid id, CancellationToken ct)
{
await cache.RemoveAsync($"product:{id}", ct);
await cache.RemoveAsync("products:list:*"); // pattern delete needs StackExchange.Redis directly
}
private static ProductDto? Map(Product p) => p is null ? null : new ProductDto(p.Id, p.Name, p.Price);
}
record ProductDto(Guid Id, string Name, decimal Price);
class Product { public Guid Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } }
interface IProductRepository { Task<Product?> GetByIdAsync(Guid id, CancellationToken ct); }Tip
Tip
Practice Redis Distributed Cache IDistributedCache in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Redis Distributed Cache IDistributedCache from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Redis Distributed Cache IDistributedCache is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?