Diagnosing a cache stampede (thundering herd) from Application Insights, Query Store and cache metrics, and fixing it with request coalescing, HybridCache, distributed locks, probabilistic early refresh, stale-while-revalidate and TTL jitter.
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.
"The shape gives it away: a sharp database spike that lines up with a cache expiry, lots of identical queries, then recovery as soon as one of those queries finishes and repopulates the key. I'd confirm it rather than assume. In Application Insights I'd chart dependency calls grouped by the SQL statement and look for one query jumping from a few a minute to hundreds in a second; I'd chart cache misses from our own metric; and I'd check the key's TTL to see if the timing matches. Query Store would show the same query's execution count spiking while its per-execution duration grows, because the executions are queuing on CPU and locks.
For example, at [company] a [home-page aggregate] key with a [5-minute] TTL took [1.5 seconds] to rebuild. At [2,000] requests per second, each expiry sent [several hundred] identical queries to Azure SQL, DTU hit 100%, and every other endpoint timed out for [about 90 seconds]. The immediate fix was to stop the herd in each process: I moved the key to HybridCache so concurrent misses share one factory call. That took us from hundreds of queries per expiry to one per pod, which was [12]. Then I made the key never go cold: a background refresher reloads it at 80% of its lifetime, and if the reload fails we keep serving the old value. Finally I added 10-20% jitter to the TTLs of the other aggregates so they stopped expiring on the same minute.
The mistake I see is reaching for a distributed lock first. It adds a Redis round trip to every miss, and if the lock holder dies you need timeouts and a fallback. Per-process coalescing plus early refresh fixes most stampedes; I only add a cluster-wide lock when even one load per pod is too many."
| Evidence | Tool | What a stampede looks like |
|---|---|---|
| Identical dependency calls | Application Insights (dependencies grouped by command) | One query jumps 100x for seconds |
| Cache misses | Custom OpenTelemetry counter / HybridCache metrics | Spike aligned with expiry |
| Query execution count and waits | Query Store, sys.dm_exec_requests |
Count spike, CPU and RESOURCE_SEMAPHORE/lock waits |
| ThreadPool and request queue | dotnet-counters (threadpool-queue-length, current-requests) |
Requests pile up behind the slow query |
| Timing | Key TTL and set time | Spikes at a fixed period |
| Fix | Scope | Effect | Cost |
|---|---|---|---|
HybridCache / Lazy<Task> coalescing |
Per process | One load per key per pod | Minimal |
Distributed lock (SET NX PX) + serve stale |
Cluster | One load overall | Extra round trip; lock expiry handling |
| Background refresh / early expiry | Per key | Key never goes cold | Load even if no one reads; refresher to run |
| Probabilistic early refresh (XFetch) | Per request | Random early reload before expiry | Slight extra loads |
| TTL jitter | Many keys | Spreads expiries | Less predictable staleness |
| Bulkhead on the expensive query | Source | Caps concurrent executions | Callers wait or get fallback |
After the change, database calls for that key went from ~400 per expiry to 12 (one per pod) and then to ~1 per refresh interval with the background refresher. DTU peaks fell from 100% to 40%, and the 90-second outage windows disappeared.
Checks that the candidate can diagnose a stampede from evidence and fix it in layers, knowing the limits of each technique.
Green flags
Red flags
key expires -> N concurrent misses -> N identical queries
-> DB CPU saturates -> each query slower -> more requests arrive and miss
-> ThreadPool queues grow -> timeouts everywhere -> retries add more load
The rebuild time T multiplied by the request rate R is roughly how many callers miss: 1.5 s x 2,000 rps = 3,000 attempts per expiry without coalescing.
Keep one in-flight task per key and let everyone await it. A ConcurrentDictionary<string, Lazy<Task<T>>> works because Lazy guarantees the factory runs once even if GetOrAdd creates two wrappers. Remove the entry when the task completes (including on failure) so errors aren't cached. HybridCache implements this for you.
SET lock:key <token> NX PX 5000 -> got it? load and set the value, then release with a check-and-delete script
-> didn't? serve the stale value, or wait briefly and re-read
The lock must expire (the holder may die) and must only be released by its owner (compare the token). It is an efficiency optimisation: if two loaders run occasionally, nothing breaks.
Background refresh: a BackgroundService reloads known hot keys at ~80% of TTL. Probabilistic early expiration (XFetch): each reader recomputes early with probability rising as expiry approaches, now - delta * beta * ln(rand()) >= expiry, where delta is the last rebuild time. One reader refreshes slightly early; the others still hit.
Store a soft expiry (refresh after) and a hard expiry (must not serve after). Between them, serve the stale value and trigger one refresh. If the refresh fails, keep serving stale until the hard expiry. HybridCache doesn't do this out of the box; FusionCache does, or you can store the soft expiry in the value.
ttl = baseTtl * (1 + Random.Shared.NextDouble() * 0.2). This matters most for keys populated together (start-up warm-up, a nightly job), which otherwise expire together forever.
threadpool-queue-length with dotnet-counters during the stampede to see requests pile up.Coalescing per process with a Lazy<Task>, plus a background refresher and TTL jitter. In new code HybridCache gives you the coalescing part; the hand-rolled version shows the mechanism.
using System.Collections.Concurrent;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Home.Caching;
public sealed record HomePage(IReadOnlyList<string> Featured, DateTimeOffset BuiltAt);
public interface IHomePageBuilder
{
Task<HomePage> BuildAsync(CancellationToken ct); // ~1.5 s, expensive query
}
public sealed class RequestCoalescer<T>
{
private readonly ConcurrentDictionary<string, Lazy<Task<T>>> _inFlight = new();
// factory must not depend on one caller's CancellationToken: the result is shared by all waiters.
public Task<T> RunOnceAsync(string key, Func<Task<T>> factory, CancellationToken callerToken)
{
// GetOrAdd may create two Lazy wrappers under a race, but only the stored one is ever .Value'd,
// and ExecutionAndPublication guarantees its factory runs exactly once.
var lazy = _inFlight.GetOrAdd(key,
_ => new Lazy<Task<T>>(() => RunAndRemoveAsync(key, factory), LazyThreadSafetyMode.ExecutionAndPublication));
// Each caller can stop waiting on its own token without cancelling the shared load.
return lazy.Value.WaitAsync(callerToken);
}
private async Task<T> RunAndRemoveAsync(string key, Func<Task<T>> factory)
{
try { return await factory(); }
finally { _inFlight.TryRemove(key, out _); } // removed once, by the load itself; failures aren't cached
}
}
public static class Ttl
{
// +0-20% jitter so keys written together don't expire together.
public static TimeSpan WithJitter(TimeSpan baseTtl) =>
baseTtl * (1 + Random.Shared.NextDouble() * 0.2);
}
// Early refresh: the hot key is rebuilt before it expires, so readers never see a cold miss.
public sealed class HomePageRefresher(HybridCache cache, IHomePageBuilder builder, ILogger<HomePageRefresher> logger)
: BackgroundService
{
public const string Key = "home:v3";
private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(Lifetime * 0.8);
do
{
try
{
var page = await builder.BuildAsync(stoppingToken);
await cache.SetAsync(Key, page,
new HybridCacheEntryOptions { Expiration = Ttl.WithJitter(Lifetime) },
cancellationToken: stoppingToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Keep serving the existing value; it still has ~20% of its lifetime left.
logger.LogWarning(ex, "Home page refresh failed; serving cached value");
}
}
while (await timer.WaitForNextTickAsync(stoppingToken));
}
}
// Endpoint: GetOrCreateAsync still coalesces any misses (e.g. on cold start).
app.MapGet("/home", (HybridCache cache, IHomePageBuilder builder, CancellationToken ct) =>
cache.GetOrCreateAsync(HomePageRefresher.Key, builder,
static async (b, token) => await b.BuildAsync(token), cancellationToken: ct));
-- Query Store: confirm one query's execution count spikes at expiry while its duration rises.
SELECT TOP (10) q.query_id, i.start_time, s.count_executions, s.avg_duration / 1000.0 AS avg_ms, s.avg_cpu_time / 1000.0 AS avg_cpu_ms
FROM sys.query_store_runtime_stats AS s
JOIN sys.query_store_runtime_stats_interval AS i ON i.runtime_stats_interval_id = s.runtime_stats_interval_id
JOIN sys.query_store_plan AS p ON p.plan_id = s.plan_id
JOIN sys.query_store_query AS q ON q.query_id = p.query_id
WHERE i.start_time > DATEADD(HOUR, -2, SYSUTCDATETIME())
ORDER BY s.count_executions DESC;
SET NX PX with a token and a compare-and-delete release.The senior insight is that a stampede is a load-shape problem, not a cache bug: the fix is to make the expensive load happen once and off the request path. Per-process coalescing is cheap and usually enough; early refresh removes the cold miss entirely; distributed locks are a last resort. And the source needs its own protection, because the cache will be cold sometimes (deploys, Redis failover, a flush).
| Technique | When it fits | Cost | When not to |
|---|---|---|---|
| HybridCache coalescing | Always, for read paths | None meaningful | n/a |
| Background refresh | Few, known, very hot keys | Loads even with no readers | Large or long-tail key sets |
| Probabilistic early refresh | Many hot keys, no central list | Small extra load | Very cheap rebuilds (pointless) |
| Distributed lock + stale | Rebuild is very expensive and pods are many | Extra round trip; lock correctness | When N loads per expiry is fine |
| Bulkhead on the source | Always for expensive queries | Some callers wait or fail fast | n/a |
I'd measure success with factory calls per expiry, DB CPU/DTU at expiry time and endpoint p99 during a deliberate cache flush in a load test.
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.
System.Collections.Concurrent types are safe for many threads at once. ConcurrentDictionary uses lock-free reads and fine-grained (striped) locks for writes. Each single method is atomic, but check-then-act across two calls is not, so use GetOrAdd, AddOrUpdate, TryUpdate or TryRemove. Caveat: the value factory in GetOrAdd/AddOrUpdate can run more than once under contention (only one result is stored), so wrap expensive or side-effecting work in Lazy<T>. Count, IsEmpty and ToArray take every lock, so avoid them in hot paths. ConcurrentQueue/ConcurrentStack are lock-free FIFO/LIFO. ConcurrentBag is unordered, optimised for the same thread adding and taking. BlockingCollection adds bounding and blocking Take but blocks threads; for async producer/consumer use Channel<T>.
SemaphoreSlim is a lightweight, in-process counting semaphore that supports WaitAsync, so it works with async/await. With a count of 1 it is an async lock: await gate.WaitAsync(ct); try { ... } finally { gate.Release(); }. With a count of N it limits how many async operations run at once, for example ten concurrent calls to a partner API. It is not re-entrant and has no owner, so calling it again from inside the protected section deadlocks, and every successful wait must be paired with exactly one Release in finally.
How to tell it (STAR)
**S:** At [company] our API had [90-second] partial outages every five minutes at peak, with error rates up to [8%]. **T:** I led the investigation. **A:** I lined up Application Insights dependency counts with cache expiry and saw [around 400] identical aggregate queries per expiry, which confirmed a stampede. I added a bulkhead and a longer TTL to stop the bleeding, then moved the key to HybridCache, added a background refresher that serves the old value on failure, and jittered related TTLs. I proved it with a k6 run that flushed the cache mid-test. **R:** Rebuilds dropped to [one per refresh interval], DTU peaks fell from [100% to 40%], and the error bursts stopped completely.
Last updated 23 Nov 2026.