Multi-instance cache architecture: L1 per instance vs shared L2, two-level caching with HybridCache, invalidation via Redis pub/sub or Azure Service Bus, bounded staleness, failure modes, cold starts and how to choose per data class.
With 20 instances, a local cache is fastest but each instance holds its own version, while a distributed cache (Redis) gives one shared version at the cost of a network hop. I usually combine them: a short-lived L1 in each instance in front of a shared L2, which is exactly what HybridCache provides.
To keep L1 copies in line, I publish invalidation messages (Redis pub/sub or an Azure Service Bus topic) that every instance uses to evict keys. Messages can be missed, so the L1 lifetime is the real staleness bound.
I choose per data class: data that must agree everywhere skips L1, tolerant data gets longer L1. The trade-off is latency and Redis load versus how long instances may disagree.
"With 20 instances the core tension is that the fastest cache, memory in each process, is also the least consistent: after a change, 20 copies expire at 20 different times, and two requests from the same user can land on different instances and see different answers. A shared Redis cache fixes that, everyone reads the same value, but every read is now a round trip, and Redis becomes something that can be slow, fail over or run out of memory.
So I design it per data class. I ask how long instances may disagree. Reference data like categories can disagree for a minute, so it gets an L1 of a minute or more in front of Redis. Product prices maybe ten seconds. Permissions after a role change, a few seconds, or no L1. Stock at checkout isn't cached at all. HybridCache gives me the two-level shape out of the box. For data where I want L1 to react faster than its lifetime, I add an invalidation channel: on a write, the service publishes the key or tag on a Redis pub/sub channel or a Service Bus topic, and every instance evicts it locally. Pub/sub is fire-and-forget, so an instance that was reconnecting misses it, which is why the L1 lifetime remains the guarantee.
For example, at [company] we had [20] pods each reading [a tenant configuration blob] from Redis [about 15] times per request. Redis was at [70%] server load and contributed [6 ms] to p95. I put a 30-second L1 in front and added pub/sub invalidation on config changes. Redis traffic fell by [about 95%] and p95 dropped by [5 ms]. The mistake I see is using sticky sessions to 'solve' consistency: it hides the issue until an instance restarts or scales in."
| Design | Read latency | Consistency across instances | Load on Redis | Failure behaviour |
|---|---|---|---|---|
L1 only (IMemoryCache) |
~100 ns | Diverges until each expiry | None | Cold on every deploy; N loads per key |
| L2 only (Redis) | ~0.5-2 ms | Single version | Every read | Redis outage = every read hits the source |
| L1 + L2 (HybridCache) | ns on L1 hit | Bounded by L1 lifetime | Only L1 misses | Degrades to L2 or source |
| L1 + L2 + invalidation bus | ns on L1 hit | Usually seconds; bounded by L1 lifetime | Only L1 misses | Missed messages fall back to TTL |
| Channel | Delivery | Latency | Notes |
|---|---|---|---|
| Redis pub/sub | At-most-once, connected subscribers only | ms | Simple; misses during reconnects |
| Redis streams | Persistent, consumer groups | ms | More work; replay possible |
| Azure Service Bus topic | At-least-once, durable | tens of ms | Subscription per instance is awkward with autoscaling; use auto-delete-on-idle subscriptions |
| HybridCache tags alone | Logical, checked on read | Bounded by L1 lifetime | No extra infrastructure |
With L1 at 30 s plus pub/sub, a configuration change propagated to all 20 pods in under a second in normal operation, with a worst case of 30 s when a pod missed the message. Redis ops/sec fell from ~180,000 to ~9,000, and server load dropped from 70% to 12%.
Checks that the candidate can design caching for a horizontally scaled service, reason about consistency per data type, and handle the failure modes.
Green flags
Red flags
+--------------------- Load balancer ---------------------+
| | | |
[pod 1] [pod 2] ... [pod 20] |
L1 (mem) L1 (mem) L1 (mem) |
\______________|_______________/ |
L2: Redis <---- pub/sub "invalidate" ----------+
|
SQL Server (source of truth)
Worst-case staleness for a read is roughly L1 lifetime + L2 staleness. If L2 is invalidated on write (delete after commit), L2 staleness is near zero and L1 lifetime dominates. The invalidation bus lowers the typical staleness, not the worst case.
write request -> SQL commit -> delete L2 key (or RemoveByTagAsync) -> publish "key" on channel
every pod's subscriber -> evict key from its L1 -> next read goes to L2/source
Publish after commit. Messages carry keys or tags, never values, so ordering doesn't matter and duplicates are harmless.
A new pod starts with an empty L1. With L2 present, it warms from Redis rather than SQL. Without L2, 20 pods restarting during a deployment each load every hot key from SQL, which is a stampede of its own. Rolling deployments with surge limits, and warming the most important keys in a hosted service before the readiness probe passes, keep it under control.
Redis becomes part of the critical path for L1 misses. Plan for: client timeouts below the request budget, a fallback to the source protected by a bulkhead, alerting on server load and evictions, and zone-redundant Azure Managed Redis in Australia East if the service is critical. Never let Redis outages turn into database outages.
| Class | L1? | L1 lifetime | Invalidation |
|---|---|---|---|
| Reference/config | Yes | 1-5 min | Pub/sub on change |
| Content/catalogue | Yes | 10-60 s | Tags |
| Permissions/entitlements | Short or none | 0-10 s | Pub/sub + short TTL |
| Money, stock, balances | No | n/a | Read from source |
IMemoryCache only; change a value and record how long each instance serves the old one.LocalCacheExpiration of 5 s and 60 s.Two-level caching with HybridCache plus a Redis pub/sub channel that evicts keys from every instance's L1.
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
namespace Platform.Caching;
public sealed record TenantConfig(string TenantId, IReadOnlyDictionary<string, string> Settings);
public interface ITenantConfigStore
{
Task<TenantConfig> GetAsync(string tenantId, CancellationToken ct);
Task SaveAsync(TenantConfig config, CancellationToken ct);
}
public sealed class TenantConfigCache(HybridCache cache, ITenantConfigStore store, IConnectionMultiplexer redis)
{
public static readonly RedisChannel Channel = RedisChannel.Literal("cache:invalidate");
private static readonly HybridCacheEntryOptions Options = new()
{
Expiration = TimeSpan.FromMinutes(30), // L2 lifetime
LocalCacheExpiration = TimeSpan.FromSeconds(30) // worst-case divergence between instances
};
public static string Tag(string tenantId) => $"platform:tenant-config:{tenantId}";
public ValueTask<TenantConfig> GetAsync(string tenantId, CancellationToken ct) =>
cache.GetOrCreateAsync($"tenant-config:v1:{tenantId}", (store, tenantId),
static async (s, token) => await s.store.GetAsync(s.tenantId, token),
Options, tags: [Tag(tenantId)], cancellationToken: ct);
public async Task SaveAsync(TenantConfig config, CancellationToken ct)
{
await store.SaveAsync(config, ct); // 1. source of truth first
await cache.RemoveByTagAsync(Tag(config.TenantId), ct); // 2. L2 + this pod's L1
await redis.GetSubscriber().PublishAsync(Channel, config.TenantId); // 3. tell the other pods (best-effort)
}
}
// Each instance evicts its own L1 when told. Missed messages are covered by LocalCacheExpiration.
public sealed class CacheInvalidationListener(IConnectionMultiplexer redis, HybridCache cache,
ILogger<CacheInvalidationListener> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var queue = await redis.GetSubscriber().SubscribeAsync(TenantConfigCache.Channel);
stoppingToken.Register(() => queue.Unsubscribe());
await foreach (var message in queue.WithCancellation(stoppingToken))
{
try
{
await cache.RemoveByTagAsync(TenantConfigCache.Tag(message.Message!), stoppingToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning(ex, "Failed to evict tenant config {TenantId}", (string?)message.Message);
}
}
}
}
// Program.cs
builder.Services.AddSingleton<IConnectionMultiplexer>(_ =>
ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("Redis")!));
builder.Services.AddStackExchangeRedisCache(o =>
o.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddHybridCache();
builder.Services.AddSingleton<TenantConfigCache>();
builder.Services.AddHostedService<CacheInvalidationListener>();
The senior framing is bounded staleness as a product decision: for each data class, agree how long instances may disagree, and let that number decide whether L1 is allowed and how long it lives. HybridCache gives you L1 + L2 for free; the invalidation bus is an optimisation on top, never the guarantee. Watch for the second-order effect: L1 hides Redis load, so a mass L1 eviction (deploy, broad tag) can suddenly multiply Redis and SQL traffic.
| Choice | When it fits | Cost | When not to |
|---|---|---|---|
| L2 only | Data must agree everywhere; moderate read rates | Hop per read; Redis on critical path | Very hot keys read many times per request |
| L1 + L2 (HybridCache) | Most data | Bounded divergence | Strongly consistent data |
| + pub/sub invalidation | Fast propagation needed, short L1 not enough | Extra moving part, at-most-once | Data where L1 lifetime is already acceptable |
| + durable bus (Service Bus) | Cross-service invalidation, must not be lost | Latency, subscription management | Same-service L1 eviction |
Measure with L1 and L2 hit ratios, Redis server load and ops/sec, measured propagation time after writes, and SQL load during a rolling deploy.
HybridCache (Microsoft.Extensions.Caching.Hybrid, GA March 2025, works on .NET 8+) replaces hand-written cache-aside code with one call: GetOrCreateAsync(key, factory, options, tags, ct).
MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).RemoveByTagAsync invalidates them as a group.I prove it by counting source calls and measuring p95 under a k6 load test before and after. The trade-off: protection and L1 invalidation are per process, so I keep L1 lifetimes short when data changes.
I treat the TTL as the upper bound on staleness and explicit invalidation as a way to do better for changes I control.
RemoveByTagAsync) to invalidate groups, such as every cached view of product 42, without tracking keys.catalogue:v{n}:...): bump n and old entries are simply never read again.I choose a TTL from how stale the business can accept, how often the data changes and how expensive it is to rebuild, then add jitter. The trade-off is freshness versus load and latency.
A load balancer spreads traffic across healthy instances.
Health checks remove unhealthy instances (in Kubernetes: readiness for traffic, liveness for restarts). Algorithms: round robin, least connections/requests, hashing. Sticky sessions pin a user to one instance, which hurts scaling and failover. Connection draining stops new traffic to an instance before shutdown so in-flight requests finish.
gRPC uses long-lived HTTP/2 connections, so an L4 balancer balances connections, not calls: one client connection carries all its calls to one pod. Use L7 balancing (mesh/Envoy) or client-side load balancing.
How to tell it (STAR)
**S:** At [company] our Redis cache was at [70%] load and adding [several milliseconds] to p95 because every pod read tenant configuration from it [about 15 times] per request. **T:** I needed to cut that load without letting tenants see stale config for long. **A:** I confirmed the pattern with Application Insights traces and dotnet-trace, agreed with the product owner that [30 seconds] of staleness was acceptable, then put a HybridCache L1 in front of Redis and added pub/sub invalidation on config saves, with a test that checks propagation. **R:** Redis ops/sec fell by [about 95%], server load dropped to [12%], p95 improved by [5 ms], and config changes usually propagated in under a second.
Last updated 23 Nov 2026.