Introduction
In the previous lessons, we integrated Redis, strengthened the cache-aside flow, designed invalidation strategies, and addressed cache stampede problems. In this lesson, we will move the application from a single process to multiple servers or containers. The goal is to make cache data available independently of which application instance receives a request.
Using IMemoryCache can be very practical in a single-server application. However, when the application runs as two or more instances, each instance has its own process memory. A value written to instance A does not automatically appear in instance B’s memory. When a load balancer distributes requests across instances, this difference can produce inconsistent results and unexpected behavior.
Redis moves cache data outside the application processes and provides a shared access point. Application instances connect to the same Redis server or Redis cluster and use the same cache keys.
1. Instance, process, and shared state
Each running copy of an ASP.NET Core application can be called an instance. Two containers started from the same Docker image usually represent two different instances and two different processes. Each process has its own heap, static variables, and IMemoryCache object.
For example, the following class keeps a separate counter inside each instance:
public sealed class LocalVisitCounter
{
private int _count;
public int Increment() => Interlocked.Increment(ref _count);
}Even if this service is registered as a singleton, it is only a singleton within its own process. If two containers are running, two separate singleton instances exist. Therefore, static variables, singleton services, and data stored in IMemoryCache are not automatically shared across servers.
For state that must be shared, common options include:
- Using Redis or another distributed cache,
- Storing durable business data in a database,
- Communicating between instances through messaging or events,
- Keeping temporary, non-critical data in an instance-local cache.
A cache should never be the application’s only source of truth. If Redis is unavailable, the application should use a designed fallback path to the database or another authoritative data source.
2. Multi-instance behavior with IMemoryCache
Let us first create a diagnostic endpoint. It returns an instance-specific identifier and the value stored in that instance’s local cache:
public sealed class InstanceDiagnostics
{
public string InstanceId { get; init; } = string.Empty;
public int Visits { get; init; }
}
public sealed class InstanceDiagnosticsService
{
private readonly IMemoryCache _cache;
private readonly string _instanceId = $"{Environment.MachineName}-{Guid.NewGuid():N}";
public InstanceDiagnosticsService(IMemoryCache cache)
{
_cache = cache;
}
public InstanceDiagnostics Get()
{
var visits = _cache.GetOrCreate("diagnostics:visits", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
return 0;
});
var nextValue = visits + 1;
_cache.Set("diagnostics:visits", nextValue);
return new InstanceDiagnostics
{
InstanceId = _instanceId,
Visits = nextValue
};
}
}Register the service and endpoint:
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<InstanceDiagnosticsService>();
app.MapGet("/diagnostics/local", (InstanceDiagnosticsService service) =>
Results.Ok(service.Get()));With one instance, repeated requests increase the counter as 1, 2, 3. With two instances behind a load balancer, results may progress as 1, 1, 2, 2, 3, 3. The exact order depends on the routing algorithm; the important point is that each instance maintains its own counter.
This behavior is unacceptable for a global visit counter or a user shopping cart. It can be appropriate for a short-lived local optimization that reduces an expensive computation only on a particular instance.
3. Creating a shared cache with Redis
To use Redis through IDistributedCache, add the StackExchange.Redis provider:
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedisKeep the connection string in appsettings.json:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}Register the Redis distributed cache in Program.cs:
var redisConnection = builder.Configuration.GetConnectionString("Redis")
?? throw new InvalidOperationException("Redis connection was not configured.");
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConnection;
options.InstanceName = "catalog-api:";
});InstanceName helps separate keys when multiple applications share the same Redis database. For more advanced connection settings, use StackExchange.Redis’ ConfigurationOptions model. In production, password, TLS, timeout, and reconnect settings should be selected according to the security and availability requirements of the environment.
Now create a service that uses distributed cache instead of local memory:
public sealed class SharedVisitCounter
{
private const string Key = "diagnostics:shared-visits";
private readonly IDistributedCache _cache;
public SharedVisitCounter(IDistributedCache cache)
{
_cache = cache;
}
public async Task<int> IncrementAsync(CancellationToken cancellationToken)
{
var current = await _cache.GetStringAsync(Key, cancellationToken);
var nextValue = int.TryParse(current, out var parsed) ? parsed + 1 : 1;
await _cache.SetStringAsync(
Key,
nextValue.ToString(CultureInfo.InvariantCulture),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
},
cancellationToken);
return nextValue;
}
}Add using System.Globalization; and using Microsoft.Extensions.Caching.Distributed; at the top of the file. The endpoint can be registered as follows:
builder.Services.AddScoped<SharedVisitCounter>();
app.MapGet("/diagnostics/shared", async (
SharedVisitCounter counter,
CancellationToken cancellationToken) =>
{
var visits = await counter.IncrementAsync(cancellationToken);
return Results.Ok(new { visits });
});Because both instances connect to the same Redis database, they read and update the same key even when requests are routed to different containers.
The read-modify-write operation in this example is vulnerable to a race condition. Two concurrent requests may read the same value and write the same next value. Real counters should use Redis atomic commands, Lua scripts, or a suitable distributed locking strategy. The example remains intentionally simple so that the shared-state behavior is easy to observe.
4. Running two application instances with Docker
To verify the behavior, run two API containers and one Redis container. Docker Compose networking allows both API containers to reach the same Redis service:
services:
redis:
image: redis:7
ports:
- "6379:6379"
api-a:
build: .
environment:
ConnectionStrings__Redis: redis:6379
INSTANCE_NAME: api-a
depends_on:
- redis
api-b:
build: .
environment:
ConnectionStrings__Redis: redis:6379
INSTANCE_NAME: api-b
depends_on:
- redisIn a real project, image tags, health checks, secret management, network policies, and Redis persistence must also be configured. depends_on controls startup order only; it does not guarantee that Redis is ready to accept application connections. The application should handle connection failures and, where appropriate, retry connection attempts.
After placing both API instances behind a reverse proxy, compare these endpoints:
/diagnostics/local: The instance identifier and local counter vary by instance./diagnostics/shared: The Redis value is shared regardless of which instance receives the request.
To make the observation clearer, include the INSTANCE_NAME environment variable in the response. This lets you distinguish where the load balancer sent the request from where the cache value was stored.
5. Comparing load balancing and sticky sessions
A sticky session attempts to route the same client to the same application instance. This can make applications that use local memory or local session state appear to work. However, local state can disappear when an instance restarts, the application scales out, or traffic moves to another node.
Sticky sessions do not remove the need for distributed state. They only reduce the probability that the problem is visible. They can also reduce load distribution quality and introduce operational complexity during deployments. For session data or coordination data that truly must be shared, a centralized or distributed provider such as Redis is generally more predictable.
If you use ASP.NET Core session, the session provider should also use an IDistributedCache implementation in a web farm. In addition, every instance should have access to the same Data Protection key ring. Otherwise, authentication or antiforgery cookies created by one instance may not be readable by another instance.
6. Instance-specific state problems
In a multi-server environment, the following types of data are risky to store only in process memory:
- Session information and shopping carts,
- Rate-limit counters,
- Idempotency keys used to prevent duplicate operations,
- Background job locks,
- Temporary tokens created by one instance and read by another,
- Global counters and coordination metadata.
Not every instance-specific value must be moved to distributed cache. For example, a short-lived computation result used only to reduce CPU usage on one instance can remain in local memory. The decision should consider whether the data must be shared, the impact of losing it, its freshness requirements, and the network cost of accessing Redis.
7. Performance testing and observability
Distributed cache provides sharing between instances, but every access introduces a network call. Therefore, measure latency and error rates in addition to cache hit ratio. At minimum, observe:
- Local cache hit and miss counts,
- Redis cache hit and miss counts,
- Average and high-percentile Redis command latency,
- Timeout, connection error, and reconnect counts,
- Request distribution across application instances,
- Calls reaching the authoritative data source.
For a simple test, run the local endpoint and then the shared endpoint with the same request count. In the first case, every instance populates its own cache. In the second case, all instances use the same Redis key space. Do not evaluate the test only by average duration. Inspect p95 or p99 latency and verify the fallback behavior when Redis is unavailable.
The goal of distributed caching is not to be faster than local memory in every situation. Its goal is to provide predictable sharing and scale-out behavior. It is also possible to combine local memory and Redis for frequently read, rarely changing data. This two-level design can reduce network traffic, but it requires careful invalidation and consistency rules.
Common mistakes
- Treating local memory as a global store: Every container has separate memory.
- Making Redis the only critical path: Define a safe fallback for cache failures.
- Moving every value to Redis: Local cache may be better for non-shared, short-lived data.
- Assuming read-modify-write is atomic: Analyze races for counters, stock, and limits.
- Relying too heavily on sticky sessions: Scaling and deployment events can break the assumption.
- Failing to share Data Protection keys: Authentication and antiforgery cookies may not work across instances.
- Adding the container name to every cache key: Do not create instance-specific keys for data that must be shared.
Short practice exercise
- Start the application as two containers and add the instance identifier to each response.
- Create one endpoint using
IMemoryCacheand another using Redis. - Send at least 20 requests through the load balancer.
- Verify that the local counters are separated per instance while the Redis counter uses a shared key.
- Stop Redis and observe application errors and fallback behavior.
- Compare p95 latency and authoritative data-source calls for both approaches.
Conclusion
In a multi-server architecture, the key question is not only whether a cache is fast, but also which instances can see the data. IMemoryCache is process-local and is appropriate for local optimizations. Redis-backed IDistributedCache provides a shared cache area and more predictable behavior under load balancing.
Sticky sessions can be a temporary compatibility technique, but shared session, idempotency, rate limiting, and coordination data require a centralized or distributed design. In the final lesson, we will combine these strategies with measurement, capacity planning, and production-oriented decisions to evaluate the complete cache architecture.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed
- https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state
- https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/default-settings
- https://github.com/StackExchange/StackExchange.Redis/blob/main/docs/Configuration.md
- https://redis.io/docs/latest/operate/oss_and_stack/management/replication/