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.
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.
"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
HybridCacherefill 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."
| 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 |
| 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 |
| 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 |
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.
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
Red flags
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.
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.
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.
Options after recovery:
Avoid a blind warm-up script that loads everything: it is itself a stampede.
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.
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.
docker stop Redis and watch SQL CPU and API latency.HybridCache with a Redis L2 and repeat; observe that hot keys still serve from L1.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);
}
Retry-After while shedding.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 |
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:
The trade-off is slightly staler data in exchange for a database that survives expiry.
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.
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.
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.
Last updated 23 Nov 2026.