Course contentsShow
← C#
Lesson 1888 of 1,90817. Deployment and Cloud ArchitectureFree lesson

Configuring Distributed Caching for Scalability

Implement Redis backplanes for shared state across horizontally scaled .NET services.

In this lesson, you will learn how to synchronize memory across horizontally scaled .NET services using a Redis backplane to ensure state consistency.

The Challenge of Horizontal Scaling

When you scale your .NET services horizontally, each instance maintains its own local memory. If you use standard in-memory caching (IMemoryCache), your instances quickly fall out of sync. User A might update their profile settings on Instance 1, but Instance 2—which handles the user’s next request—remains unaware of this change, leading to inconsistent behavior.

Implementing the Redis Backplane

To solve this, we move from local memory to a distributed cache, using Redis as the "source of truth." In the .NET ecosystem, we leverage the Microsoft.Extensions.Caching.StackExchangeRedis library to create a shared backplane.

By configuring a shared Redis instance, all your microservices point to the same global memory space. When a service writes data, it is persisted in Redis rather than the local RAM of a single container.

Configuration Example

In your Program.cs, you register the distributed cache to replace the local provider:

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("RedisConnection");
    options.InstanceName = "AppSharedState_";
});

Once configured, you inject IDistributedCache into your services instead of IMemoryCache.

public class UserProfileService(IDistributedCache cache)
{
    public async Task SetProfileAsync(string userId, UserProfile profile)
    {
        var data = JsonSerializer.SerializeToUtf8Bytes(profile);
        await cache.SetAsync($"user:{userId}", data);
    }
}

Why This Matters for Scalability

By using a Redis backplane, your application becomes truly stateless regarding its data layer. You can spin up ten, fifty, or one hundred instances of your service, and each one will fetch the identical state from Redis. Because Redis is an external, high-performance store, it handles the concurrency and eviction policies that would otherwise cause "cache drift" in a distributed environment. This architecture ensures that your scaling strategy doesn't compromise the reliability or consistency of your user experience.

Key Takeaway: A Redis backplane eliminates local memory silos by centralizing state, ensuring that all scaled service instances operate on the same data set.