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

📚 Interview question

A hot cache key expires at peak and your database CPU hits 100%, timeouts spread across the API, and it recovers a few minutes later. You suspect a cache stampede. How do you confirm it, stop it now, and prevent it with locking, early refresh and jittered TTLs?

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.

Senior Debugging Advanced cache-stampede caching debugging hybridcache performance redis

🎯 Key points

  • Signature: spike of identical queries right after a key's expiry, DB CPU/DTU spike, recovery once one load succeeds
  • Confirm by aligning cache miss rate, dependency calls per key and expiry times in Application Insights
  • Query Store: execution count jumps for one query_id while avg duration and CPU/lock waits rise
  • Per-process coalescing: HybridCache or Lazy<Task> in a ConcurrentDictionary; one factory per key per pod
  • Cluster-wide: short-lived distributed lock (SET NX PX) with fallback to stale value; lock is for efficiency, not correctness
  • Early refresh: refresh before expiry (probabilistic XFetch or a background refresher) so the key never goes cold
  • Jitter TTLs (e.g. +/-10-20%) so many keys don't expire together; serve stale on failure
  • User impact: timeouts spread to unrelated endpoints, so protect the source with a bulkhead and timeouts

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

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


Diagnosis checklist

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

Fixes compared

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can diagnose a stampede from evidence and fix it in layers, knowing the limits of each technique.

Green flags

  • Confirms with telemetry aligned to expiry before fixing
  • Knows per-process vs cluster-wide coalescing and HybridCache's scope
  • Proposes early refresh, stale-while-revalidate and jitter
  • Protects the source with a bulkhead or timeout

Red flags

  • Just "increase the TTL"
  • Global lock around all cache reads
  • Blocking waiters with no timeout

📚 Learn in depth

1. Why stampedes are self-reinforcing

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.

2. Per-process 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.

3. Cluster-wide locking

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.

4. Early refresh

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.

5. Stale-while-revalidate and fail-safe

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.

6. Jitter

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.

Try it yourself

  1. Build an endpoint whose cache factory sleeps 1 s and increments a counter; hit it with k6 at 500 rps with a 10 s TTL and count factory calls per expiry.
  2. Switch to HybridCache and repeat with one instance, then two.
  3. Add a background refresher at 80% TTL and show the factory count drops to one per interval regardless of load.
  4. Add 20% jitter to 1,000 keys set at once and plot expiry times.
  5. Watch threadpool-queue-length with dotnet-counters during the stampede to see requests pile up.

💻 Code

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;

⚠ Common mistakes

  • Mistake: Guessing it's a stampede and adding locks without measuring. Why it is wrong: The spike might be a bad plan or a batch job; locks add latency for nothing. Instead: Confirm with dependency calls per query, miss rate and expiry timing.
  • Mistake: Micro-optimising cold paths by locking every cache key. Why it is wrong: Most keys are never contended; a lock round trip on every miss costs more than it saves. Instead: Protect hot, expensive keys only.
  • Mistake: Assuming HybridCache stops cluster-wide stampedes. Why it is wrong: Its coalescing is per process; 30 pods can still run 30 loads. Instead: Add early refresh or a distributed lock for keys where 30 loads hurt.
  • Mistake: Distributed locks without expiry or owner checks. Why it is wrong: A crashed holder blocks everyone, or one process deletes another's lock. Instead: SET NX PX with a token and a compare-and-delete release.
  • Mistake: Making waiters block until the lock is free. Why it is wrong: Requests pile up and time out, recreating the outage. Instead: Serve stale or wait briefly with a timeout.
  • Mistake: Identical TTLs for keys warmed together. Why it is wrong: They expire together forever. Instead: Add jitter.
  • Mistake: Caching the failure from a timed-out rebuild. Why it is wrong: Errors are served for the full TTL. Instead: Don't cache exceptions; keep the previous value.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions HybridCache Why: Checks they know exactly what HybridCache's stampede protection covers
    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 uses ConcurrentDictionary.GetOrAdd to de-duplicate loads Why: Checks they know GetOrAdd can run the value factory more than once and why Lazy fixes it
    How to answer

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

  3. When: Candidate mentions a SemaphoreSlim per key Why: Checks they can use SemaphoreSlim as an async lock or throttle correctly
    How to answer

    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.

🛠 Real-world problems: how you handle them

Home-page aggregate expiry takes Azure SQL to 100% every five minutes
Situation
A consumer web API on [12] pods served a home-page aggregate cached for [5 minutes] in Redis; rebuilding it took [1.5 s] of heavy SQL. Peak load was [2,000] rps.
Signals
Azure SQL DTU at 100% in [~90 s] bursts every 5 minutes; Application Insights showed timeouts on unrelated endpoints; dotnet-counters showed `threadpool-queue-length` and `current-requests` climbing during bursts; error rate peaked at [8%].
Investigation
Application Insights dependencies grouped by command showed the aggregate query going from [~1/min] to [~400] in two seconds at each burst; the cache miss counter spiked at the same moments; the key's TTL matched the period. Query Store showed execution count and CPU wait spikes for that query only.
Resolution
Immediate: raised the TTL to [30 minutes] and added a bulkhead (max [4] concurrent rebuilds per pod). Fix: moved to HybridCache for per-process coalescing, added a background refresher at 80% of TTL that keeps the old value on failure, and jittered TTLs on related keys.
Prevention
A k6 test that flushes the cache mid-run and asserts DB CPU and p99 stay in budget; an alert on factory calls per key per minute; a design checklist item for expensive keys: coalesce, refresh early, jitter.

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.

↩ Usually asked after

More in Caching

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me