Offloading State with Redis
Session state, rate-limit counters, and expensive query results all benefit from an external cache. Azure Cache for Redis gives you a managed, low-latency store that sits outside your app's process memory.
Connection and Configuration
Add the Microsoft.Extensions.Caching.StackExchangeRedis package, then wire it into Startup.cs with the connection string from your app settings. The default serializer works for most DTOs, but switch to MessagePack if you need smaller payloads.
// Register Redis as the distributed cache in Startup.ConfigureServices.
// The connection string should come from environment variables, not source code.
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = Environment.GetEnvironmentVariable("REDIS_CONNECTION");
options.InstanceName = "myapp-cache";
// Setting a reasonable size limit prevents memory bloat on the Redis node.
options.SizeLimit = 100 * 1024 * 1024; // 100 MB
});
// Example usage inside a controller action:
// cache.StringSet("user:42", userData, TimeSpan.FromMinutes(10));
// var cached = cache.StringGet("user:42");
Monitor eviction rates and memory usage in the Azure portal. If you see frequent evictions, either increase the SKU size or rethink your key TTL strategy.