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

📚 Interview question

Your Redis cache becomes unreachable during peak hours. Within a minute every request falls through to SQL Server, database CPU hits 100%, the API starts timing out, and even when Redis comes back the database doesn't recover. Walk me through the incident: how you stop the collapse, how you bring the cache back without a second stampede, and how you redesign so a cache failure degrades the service instead of taking it down.

A production playbook for a cache outage that collapses the database: why fall-through overloads SQL, immediate load shedding and protection, warming the cache safely, and designing cache-failure handling with timeouts, circuit breakers, a local L1 cache, stampede protection and capacity for a cold cache.

Senior Debugging Advanced caching hybridcache production redis resilience sql-server

🎯 Key points

  • Cache hit rate hides the real load: at a 95% hit rate the database sees 5%, so losing Redis multiplies database load by 20×
  • Redis client timeouts make it worse: every request waits for the Redis timeout before falling through
  • First five minutes: shed load (rate limit, disable expensive features), protect SQL with a concurrency limit, fail fast on Redis with a circuit breaker
  • The database doesn't recover on its own because queued and retried work keeps it saturated; you must cut the inflow
  • Bring the cache back gradually: warm hot keys, use single-flight (HybridCache) so one request per key hits the database
  • Design: short Redis timeouts, a breaker around the cache, an in-process L1 cache, stale-on-error, jittered TTLs
  • Capacity rule: the database must survive a cold cache at peak, or you need a degraded mode; alert on hit rate drop and database CPU together
  • For new designs use Azure Managed Redis with HA and zone redundancy (Azure Cache for Redis Basic/Standard/Premium retire 30 September 2028, Enterprise tiers March 2027)

⏱ 30-second answer

A cache with a 95% hit rate means the database only sees 5% of reads; lose Redis and it gets 20× its normal load at once, and every request also waits for the Redis timeout first. The database then can't recover because retries and queued work keep it saturated. So I cut the inflow: shed load, put a concurrency limit in front of SQL, and fail fast on Redis with a circuit breaker. When Redis returns I warm it with single-flight loading (HybridCache) so one request per key reaches the database. The redesign treats the cache as optional: short timeouts, an in-process L1 cache, stale-on-error, jittered TTLs, and either a database sized for a cold cache at peak or a degraded mode. The trade-off is serving stale data versus taking the service down.

🗣 Full answer (senior)

How I would answer this in an interview

"The important insight is that a cache isn't just making things faster, it's carrying load. If 95% of reads hit Redis, the database is sized for the other 5%. When Redis disappears, the database gets twenty times its normal read load in seconds. On top of that, if the Redis client has a 5-second timeout, every request waits 5 seconds before it even tries SQL, so threads and connections pile up. And when Redis comes back, the database often stays down, because there's a queue of retried and timed-out work still hammering it, and the cache is empty, so the first wave of requests all miss at once.

For example, at [company] we had [a catalogue API] where exactly that happened [during a sale]. In the first minutes I cut the inflow: turned on a rate limit at the gateway, switched off recommendations and search suggestions with feature flags, and set a concurrency limit on the database calls so SQL got a manageable number of queries and the rest failed fast with a friendly error. Once SQL recovered, we brought Redis back and let HybridCache refill it with single-flight loading, so each hot key was fetched once rather than by a thousand requests. Full recovery took [about 25 minutes]; with the redesign, a later Redis failover was invisible to users.

The redesign is about making the cache optional. Redis calls get a short timeout, a few hundred milliseconds, behind a circuit breaker, so a dead cache costs nothing per request. An in-process L1 cache absorbs the hottest keys even with Redis down. Entries can be served stale on error. TTLs are jittered so keys don't expire together. And we decide explicitly: either SQL is sized to survive a cold cache at peak, or there's a degraded mode that doesn't need it. The mistake I see is treating Redis like a database dependency: if your service can't run without the cache, it isn't a cache, it's a single point of failure."


The playbook, in order

Step What I do Tool or command
1. Symptom Redis connection errors, then SQL CPU 100%, then API timeouts App Insights dependency failures (target = Redis), Azure SQL metrics
2. First five minutes Shed load, limit concurrency to SQL, fail fast on Redis Gateway rate limit, feature flags, breaker or config switch
3. Data to collect Redis health, hit rate before and after, SQL top queries Azure Managed Redis metrics, Query Store, KQL
4. Rule out A bad query plan (would show one query regressing), a deploy Query Store regressed queries, deployment history
5. Root cause Why Redis failed (patching, failover, memory, connections) and why the app couldn't survive it Redis resource health, client logs
6. Fix Warm gradually; add breaker, L1, stale-on-error, timeouts HybridCache, resilience pipeline
7. Prevention Cold-cache load test, chaos test that kills Redis, capacity rule Azure Chaos Studio, load test

Arithmetic of a lost cache

Normal Redis down
Read requests/s 10,000 10,000
Hit rate 95% 0%
Reads reaching SQL 500/s 10,000/s (20×)
Extra latency per request ~1 ms Redis timeout (e.g. 5 s) before falling through

Design options

Technique What it protects Cost
Short Redis timeout + breaker Threads and latency when Redis is down A few false 'cache down' periods
In-process L1 (HybridCache) Hot keys survive Redis loss Memory per instance; staleness across instances
Stale-on-error Serve last known value Users may see old data
Single-flight loading One database call per key on a miss Slight latency for waiters
Concurrency limit to SQL The database stays alive Some requests rejected
Database sized for cold cache Everything Higher database cost

Production example

In a typical case, a catalogue API serves 8,000 reads/s at a 96% hit rate, so SQL normally sees about 320 queries/s. A Redis failover during peak drops the hit rate to zero for 40 seconds; with a 5 s client timeout and no breaker, SQL receives over 6,000 queries/s and DTU hits 100% for 25 minutes. After adding a 250 ms Redis timeout, a breaker, a 30-second L1 cache and stale-on-error, a deliberate Redis reboot in a chaos test raises SQL load only to about 900 queries/s and p95 stays under 300 ms.

🔍 What the interviewer is checking

Checks whether the candidate understands caches as load carriers, can stop a metastable collapse by cutting inflow, can recover without a second stampede, and designs so cache loss degrades the service.

Green flags

  • Does the hit-rate arithmetic and explains why the database stays down
  • Cuts inflow first: shedding, limits, fail-fast on Redis
  • Recovers with single-flight loading and a gradual ramp
  • Designs short timeouts, a breaker, an L1, stale-on-error and a cold-cache capacity answer
  • Knows the current Azure Redis offerings

Red flags

  • "Restart Redis and it will be fine"
  • Adds retries everywhere
  • No plan for the recovery stampede

📚 Learn in depth

1. Why the database doesn't recover on its own

Redis down
   │
   ▼
every request: wait Redis timeout ──► miss ──► SQL
                                             │
         SQL saturated ◄── retries, queued requests, background refreshes
             │
             ▼
   queries slower ──► connections held longer ──► pool exhaustion ──► more timeouts ──► more retries

This is a metastable failure: the system has a healthy state and a failed state, and the trigger (Redis down) can disappear while the failed state persists, sustained by retries and work queues. The only way out is to reduce load below capacity long enough for queues to drain.

2. How StackExchange.Redis behaves when Redis is gone

StackExchange.Redis multiplexes all commands over a few connections. When the server is unreachable, commands queue in the client until SyncTimeout/AsyncTimeout (default 5 seconds) expires, then throw RedisTimeoutException or RedisConnectionException. AbortOnConnectFail=false lets the multiplexer keep retrying in the background, which is right, but you still need your own fast failure per call. A breaker that opens after a burst of failures means calls return immediately instead of waiting 5 seconds each.

3. HybridCache as the L1/L2 pattern

HybridCache (Microsoft.Extensions.Caching.Hybrid, GA since .NET 9) combines an in-process L1 cache with an optional IDistributedCache L2 (Redis). It provides stampede protection: concurrent requests for the same key share one factory call. If the L2 is down, the L1 still serves recent entries. It doesn't on its own add a breaker to L2 calls, so you still keep Redis timeouts short.

4. Warming the cache

Options after recovery:

  1. Lazy with single-flight: let traffic refill it, one database call per key.
  2. Pre-warm hot keys: a job loads the top N keys (from access logs) before traffic is fully restored.
  3. Gradual traffic ramp: raise the gateway rate limit in steps while watching SQL CPU.

Avoid a blind warm-up script that loads everything: it is itself a stampede.

5. Redis on Azure today

As of late 2026, Microsoft's recommended offering is Azure Managed Redis (built on Redis Enterprise). Azure Cache for Redis is retiring: Basic, Standard and Premium tiers retire on 30 September 2028, with creation blocked for new customers from April 2026; Enterprise and Enterprise Flash retire in March 2027. For new designs, use Azure Managed Redis with high availability (a replica) and zone redundancy in Australia East; plan for failovers during maintenance, which cause brief connection drops your client must ride through.

6. The capacity question

Write down the answer to: "what happens at peak with a cold cache?" Either the database can handle it (measured with a load test that disables the cache), or the service has a degraded mode: serve stale data, disable expensive features, queue writes. Both are valid; not knowing is not.

Try it yourself

  1. Run an API with Redis and SQL in containers; load it at a steady rate, then docker stop Redis and watch SQL CPU and API latency.
  2. Reduce the StackExchange.Redis timeouts to 250 ms and repeat; compare p95.
  3. Switch to HybridCache with a Redis L2 and repeat; observe that hot keys still serve from L1.
  4. Restart Redis while under load and watch for a second spike as the cache refills; add jittered expiry and compare.
  5. Use Azure Chaos Studio (or a script) to reboot a Redis node in a test environment during a load test.

💻 Code

A cache layer that treats Redis as optional: short timeouts, L1 + L2, and a limiter in front of SQL.

// Program.cs
using Microsoft.Extensions.Caching.Hybrid;
using StackExchange.Redis;
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

var redisOptions = ConfigurationOptions.Parse(builder.Configuration.GetConnectionString("Redis")!);
redisOptions.AbortOnConnectFail = false;  // keep reconnecting in the background
redisOptions.ConnectTimeout = 2_000;
redisOptions.SyncTimeout = 250;           // fail fast: a dead cache must not cost 5 s per request
redisOptions.AsyncTimeout = 250;

builder.Services.AddStackExchangeRedisCache(o => o.ConfigurationOptions = redisOptions);
builder.Services.AddHybridCache(o =>
{
    o.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        LocalCacheExpiration = TimeSpan.FromSeconds(30), // L1 absorbs hot keys even if Redis is down
        Expiration = TimeSpan.FromMinutes(10)
    };
});

// Protect SQL: at most 64 concurrent catalogue queries per instance; others queue briefly, then fail fast.
builder.Services.AddSingleton(new ConcurrencyLimiter(new ConcurrencyLimiterOptions
{
    PermitLimit = 64, QueueLimit = 128, QueueProcessingOrder = QueueProcessingOrder.OldestFirst
}));
builder.Services.AddScoped<CatalogueReader>();

var app = builder.Build();
app.Run();
namespace Catalogue;

using Microsoft.Extensions.Caching.Hybrid;
using System.Threading.RateLimiting;

public sealed record Product(int Id, string Name, decimal Price);

public sealed class CatalogueReader(HybridCache cache, ConcurrencyLimiter sqlLimiter, ICatalogueRepository repo)
{
    public async Task<Product?> GetAsync(int id, CancellationToken ct)
    {
        // Single-flight: concurrent misses for the same key share one factory call.
        return await cache.GetOrCreateAsync($"product:{id}", async token =>
        {
            using var lease = await sqlLimiter.AcquireAsync(1, token);
            if (!lease.IsAcquired)
                throw new DatabaseBusyException(); // mapped to 503 + Retry-After by middleware
            return await repo.FindAsync(id, token);
        }, cancellationToken: ct);
    }
}

public sealed class DatabaseBusyException() : Exception("Database is shedding load");

public interface ICatalogueRepository
{
    Task<Product?> FindAsync(int id, CancellationToken ct);
}

⚠ Common mistakes

  • Mistake: Leaving Redis client timeouts at the 5-second default. Why it is wrong: When Redis is down every request waits 5 seconds before falling through, exhausting threads and connections. Instead: Short timeouts (hundreds of milliseconds) and a breaker.
  • Mistake: Sizing the database only for the cached load. Why it is wrong: The cache is carrying most of the load; losing it overwhelms the database. Instead: Load test with the cache disabled and either size for it or define a degraded mode.
  • Mistake: Restoring Redis and expecting recovery. Why it is wrong: Retries and queues keep the database saturated; the empty cache causes a second stampede. Instead: Cut inflow, let SQL recover, then ramp traffic with single-flight loading.
  • Mistake: Running a full warm-up script immediately. Why it is wrong: Loading every key at once is a self-inflicted stampede. Instead: Warm the top hot keys gradually or let single-flight refill lazily.
  • Mistake: Using the same TTL for everything. Why it is wrong: Keys loaded together expire together, creating periodic stampedes. Instead: Add jitter to expirations.
  • Mistake: Retrying database calls aggressively during the incident. Why it is wrong: Retries multiply load on an already saturated database. Instead: Fail fast with 503 and Retry-After while shedding.
  • Mistake: Treating a single Redis node as fine because 'it's just a cache'. Why it is wrong: If the service can't survive its loss, it's a critical dependency. Instead: High availability, zone redundancy and graceful degradation.

🏛 Senior insight: trade-offs

The senior reframe is that a cache with a high hit rate is part of your capacity plan, so its failure is a capacity event, not just a latency event. Every design review should answer: what happens at peak with a cold cache, and what happens when the cache comes back? The second question catches the recovery stampede that most teams miss.

Model it with numbers rather than opinions: take the peak read rate, multiply by the miss rate with the cache gone (100%), and compare with the database's measured capacity from a load test with caching disabled. If the gap is 10×, you need a degraded mode, and the product owner should choose what users see in it (cached pages, hidden recommendations, a 'busy' message) before an incident forces the choice. Wire alerts to the same model: a sudden hit-rate drop together with rising database CPU is the early warning, minutes before timeouts reach users.

I also push for testing the failure rather than reasoning about it: a chaos experiment that reboots Redis under load in staging tells you more than any diagram, and it validates the timeouts, the breaker and the degraded mode in one go.

Option When it fits Cost When not to
Size SQL for a cold cache Read load is modest, strong freshness needs Higher database tier year-round When the cache absorbs 20× or more
L1 + L2 with stale-on-error Read-heavy, slightly stale data is acceptable Memory, staleness across instances Permissions, balances, prices with legal exactness
Degraded mode (feature flags, static fallback) Peak events, non-critical features Product work to define it Core flows that must be exact
Zone-redundant Redis Any production cache that carries load Higher Redis tier Never a substitute for graceful degradation

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions stampedes when keys expire Why: Checks confirming and preventing a cache stampede
    How to answer

    A cache stampede happens when a hot key expires and hundreds of concurrent requests all miss and run the same expensive query at once. I confirm it by lining up cache miss spikes, identical dependency calls per key and expiry times in Application Insights and Query Store.

    Fixes, in layers:

    • Coalesce concurrent misses so one call loads the value: HybridCache does this per process.
    • Go cluster-wide with a short distributed lock and serve the stale value to everyone else.
    • Refresh early (background or probabilistic) so hot keys never go cold, and jitter TTLs so keys don't expire together.

    The trade-off is slightly staler data in exchange for a database that survives expiry.

  2. When: Candidate proposes HybridCache Why: Checks hands-on knowledge of HybridCache's L1/L2 and stampede protection
    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.

  3. When: Candidate mentions connections piling up on SQL Why: Checks the related connection pool exhaustion playbook
    How to answer

    The message means a request waited the Connect Timeout (15 s by default) for a free connection and the pool was at Max Pool Size (100 by default, per connection string, per process). There are three causes: leaked connections that are never disposed, connections held too long (slow queries, blocking, or a transaction held open across an HTTP call), and more concurrency than the pool. I check the SQL side (sys.dm_exec_sessions grouped by host and status: lots of sleeping sessions with open transactions means leaks or long holds; blocking chains mean slow work) and the app side (SqlClient pool counters and a dump for undisposed SqlConnections). A restart buys time; the fix is await using, shorter transactions and faster queries. Raising Max Pool Size alone usually moves the bottleneck to SQL Server.

🛠 Real-world problems: how you handle them

Redis failover during a sale took the catalogue database down
Situation
A catalogue API on [AKS, twelve pods] serving [about 8,000 reads/s] at a [96%] cache hit rate during [a sale], backed by a single-node Redis cache and an Azure SQL [Business Critical] database sized for [about 500] queries/s.
Signals
Redis connection exceptions in Application Insights at [11:42], followed within a minute by SQL CPU at 100%, connection pool timeouts, and API p95 above [10 s]. Redis recovered after [40 seconds] but SQL stayed at 100% and errors continued.
Investigation
Azure resource health showed a Redis maintenance failover. KQL on dependencies showed every request waiting [5 s] on Redis before calling SQL. Query Store showed no plan regressions, just many more executions of the same product queries. Retries from the mobile app and the API's own retry policy kept SQL saturated after Redis returned.
Resolution
Immediate: enabled a gateway rate limit, turned off recommendations and search suggestions with feature flags, and lowered the SQL concurrency limit, which let SQL recover in [about 10 minutes]; then raised the rate limit in steps. Real fix: 250 ms Redis timeouts, a breaker, `HybridCache` with a 30-second L1 and stampede protection, jittered TTLs and removal of database retries in the request path.
Prevention
Moved to a zone-redundant Azure Managed Redis instance with high availability, added a cold-cache load test to the release checklist, ran a monthly Chaos Studio experiment that reboots Redis under load, and documented the degraded mode in the runbook.

How to tell it (STAR)

**S:** At [company], during [a sale], a routine Redis failover took our catalogue database to 100% CPU, and it stayed there even after Redis came back. **T:** I led the incident and then the redesign. **A:** I cut the inflow first: a gateway rate limit, feature flags to switch off expensive features, and a tighter concurrency limit on SQL, which let the database recover; then I ramped traffic back up. Afterwards I showed the team the arithmetic: a 96% hit rate meant losing Redis multiplied database load by 25. We added short Redis timeouts, a breaker, HybridCache with an in-process layer, jittered TTLs and a monthly chaos test. **R:** The outage lasted [25 minutes]; the next Redis failover, [two months later], raised SQL load by under 3× and users didn't notice.

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me