📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You run 20 instances of an ASP.NET Core service behind a load balancer. How would you design caching across them? Explain when to use a local cache, a distributed cache or both, how you keep local caches in sync with invalidation messages, and how you trade consistency against latency.

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.

Senior Architecture Advanced architecture caching distributed-systems hybridcache performance redis

🎯 Key points

  • Local (L1) is fastest but each instance diverges; shared (L2) is consistent but costs a network hop
  • Two-level: L1 with short lifetime in front of L2 (HybridCache) gives most of both
  • Invalidation messages (Redis pub/sub, Service Bus topic) evict L1 on all instances; they are best-effort, so L1 TTL still bounds staleness
  • Pick per data class: tolerated staleness decides L1 lifetime or whether L1 is allowed at all
  • Failure modes: Redis outage (fall back to source with a bulkhead), missed messages, cold starts after deploys
  • Sticky sessions are not a cache-consistency strategy
  • Measure: L1/L2 hit ratios, Redis latency and ops/sec, staleness, source load during a cold start

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Options

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

Invalidation channel choices

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

Production example

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%.

🔍 What the interviewer is checking

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

  • Chooses L1/L2 per data class from staleness tolerance
  • Knows pub/sub is best-effort and keeps TTL as the bound
  • Plans for Redis failure, cold starts and deploys
  • Gives measurements: hit ratios, Redis load, propagation time

Red flags

  • In-memory cache only, assuming instances agree
  • Sticky sessions as the consistency answer
  • Treats invalidation messages as guaranteed

📚 Learn in depth

1. The topology

            +--------------------- Load balancer ---------------------+
            |              |               |                          |
        [pod 1]        [pod 2]   ...    [pod 20]                      |
        L1 (mem)       L1 (mem)         L1 (mem)                      |
            \______________|_______________/                          |
                      L2: Redis  <---- pub/sub "invalidate" ----------+
                           |
                      SQL Server (source of truth)

2. Bounded staleness

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.

3. How the invalidation flow works

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.

4. Cold starts and scale-out

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.

5. Redis as a dependency

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.

6. Choosing per data class

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

Try it yourself

  1. Run 3 instances with IMemoryCache only; change a value and record how long each instance serves the old one.
  2. Add HybridCache with Redis and repeat with LocalCacheExpiration of 5 s and 60 s.
  3. Add Redis pub/sub invalidation and measure propagation time; then kill a subscriber's connection during a change and observe the TTL fallback.
  4. Count Redis ops/sec with and without L1 under a k6 load test.
  5. Restart all instances at once under load and watch SQL CPU with and without L2.

💻 Code

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>();

⚠ Common mistakes

  • Mistake: Designing the cache topology without measuring read rates and Redis load. Why it is wrong: You can't tell whether L1 is needed or whether Redis is the bottleneck. Instead: Measure reads per request, Redis ops/sec and latency, then decide.
  • Mistake: Micro-optimising cold paths with L1 plus a bus. Why it is wrong: Rarely read data gains nothing and adds invalidation complexity. Instead: Use L2 only, or no cache.
  • Mistake: Treating pub/sub invalidation as guaranteed. Why it is wrong: Redis pub/sub (including sharded pub/sub in Redis 7 and Azure Managed Redis) is still at-most-once: a subscriber that is disconnected or reconnecting when the message is published never receives it. Instead: Keep L1 lifetimes as the bound, or use Redis streams or Service Bus if every instance must see every message.
  • Mistake: Putting money, stock or permissions in long-lived L1. Why it is wrong: Instances disagree for the full lifetime, causing wrong decisions or security gaps. Instead: No L1 or a few seconds, plus invalidation.
  • Mistake: Relying on sticky sessions for consistency. Why it is wrong: Affinity only keeps one user on one instance while nothing changes. When an instance is restarted, deployed, scaled in or fails a health check, its users move to another instance with a different L1, and they immediately see different data. It also does nothing for data shared between users (one user edits, another on a different pod reads), and it unbalances load. Instead: Design for bounded staleness across instances with short L1 lifetimes and invalidation.
  • Mistake: Letting a Redis outage take out the service. Why it is wrong: Every request falls through to SQL at once. Instead: Timeouts, a bulkhead on the source, and L1 to absorb hot keys.
  • Mistake: Publishing values instead of keys on the invalidation channel. Why it is wrong: Out-of-order delivery can install an older value. Instead: Publish keys or tags and let readers reload.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions HybridCache or two-level caching Why: Checks they know HybridCache's L1/L2 behaviour and limits
    How to answer

    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).

    • Two levels: an in-process L1 (MemoryCache) and an optional L2, whatever IDistributedCache is registered (usually Redis).
    • Stampede protection: concurrent misses for the same key in one process share a single factory call.
    • Tags: entries can carry tags, and 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.

  2. When: Candidate mentions tags or versioned keys Why: Checks they can design the invalidation and TTL strategy in detail
    How to answer

    I treat the TTL as the upper bound on staleness and explicit invalidation as a way to do better for changes I control.

    • Explicit delete after the database commit for single, known keys.
    • Tags (HybridCache RemoveByTagAsync) to invalidate groups, such as every cached view of product 42, without tracking keys.
    • Versioned keys (catalogue:v{n}:...): bump n and old entries are simply never read again.
    • Stale-while-revalidate: after a soft expiry, serve the old value and refresh in the background, with a hard expiry as the limit.

    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.

  3. When: Candidate mentions sticky sessions or the load balancer Why: Checks they understand load balancer behaviour, health checks and sticky sessions
    How to answer

    A load balancer spreads traffic across healthy instances.

    • Layer 4 (TCP/UDP: Azure Load Balancer, AWS NLB, Kubernetes Services via kube-proxy) picks a backend per connection using IPs and ports. Fast, protocol-agnostic, no HTTP awareness.
    • Layer 7 (HTTP: App Gateway, ALB, Front Door, ingress controllers, Envoy, YARP) picks per request, can route by path/host/header, terminate TLS, retry and add headers.

    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.

🛠 Real-world problems: how you handle them

Redis at 70% load from a config blob read 15 times per request
Situation
A multi-tenant API on [20] pods read [tenant configuration] from Redis on every access, [~15] times per request, at [~12,000] requests per second across the fleet.
Signals
Azure Monitor showed Redis server load at [70%] and ops/sec around [180,000]; Application Insights showed Redis dependency p95 of [4 ms] and a growing share of request time; occasional `RedisTimeoutException` at peak.
Investigation
Application Insights end-to-end traces showed many identical Redis GETs per request; a dotnet-trace capture confirmed the config accessor called the cache on every property read. Measured how often configs changed: [a few per day].
Resolution
Immediate: memoised the config per request in a scoped service, cutting reads to one per request. Fix: moved to HybridCache with a 30-second L1 and Redis pub/sub invalidation on config changes, with the L1 lifetime as the agreed worst case.
Prevention
Dashboards for L1/L2 hit ratios and Redis ops/sec; an alert on Redis server load > [60%]; an integration test that changes a config and asserts every instance reflects it within [30 s].

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.

↩ Usually asked after

More in Caching

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me