Real-world cascading failure: diagnosing with Application Insights dependency telemetry, dotnet-counters (thread pool, SqlClient pool, HTTP connections) and dotnet-dump; root causes (HttpClient 100 s default timeout, retries multiplying load, DB connections held across the external call, health checks including the dependency); mitigation with a feature flag; the real fix with attempt and total timeouts, a single jittered retry, a tuned circuit breaker, a concurrency-limit bulkhead, a flat-rate fallback, moving the call out of the transaction, and chaos testing.
Unrelated requests failing means the slow API exhausted a shared resource: usually database connections held while waiting, sockets, or thread-pool threads (from sync-over-async).
Diagnose: Application Insights dependency durations, then dotnet-counters for the thread pool, SqlClient pool and HTTP connections, then dotnet-dump to see what requests are waiting on. Look for the 100 s HttpClient default timeout multiplied by retries.
Mitigate: a feature flag that switches to a fallback (flat-rate shipping).
Fix:
The trade-off is a slightly degraded feature against a whole service going down.
"The clue is in 'including requests that never call that API'. A slow dependency on its own should only slow the requests that use it; if everything fails, the slow calls have exhausted something shared. So my first question is: what are those requests holding while they wait? In practice it's database connections held inside a transaction, a connection limit to a host, thread-pool threads if there's a
.Resultsomewhere, or plain request capacity. I'd open Application Insights and look at the dependency map: the shipping dependency at 30 seconds, then SQL failures with 'timeout expired prior to obtaining a connection from the pool' across every endpoint. Thendotnet-counterson a live instance: SqlClient active connections pinned at the pool maximum of 100, ThreadPool queue length growing if there's blocking, and HTTP connections to the shipping host climbing. Adotnet-dumpof async state machines shows hundreds of requests awaiting the shipping client. Then I'd read the code and config: the defaultHttpClient.Timeoutof 100 seconds, a retry of three, and the call made inside the order transaction.For example, at [company] we [hit exactly this during a carrier outage]: [checkout was down for [n] minutes]. The first move was mitigation, not a fix: I [flipped a feature flag to flat-rate shipping], which [restored checkout within [n] minutes]. Then I fixed it properly in layers. I moved the shipping call out of the transaction, so a slow carrier can't hold database connections. I set a 2-second attempt timeout and a 5-second total budget, one retry with jitter, a circuit breaker with thresholds suited to our traffic so it opens within seconds, and a concurrency limit of [30] on the shipping client as a bulkhead. When any of those reject, the client returns the cached rate for that postcode zone or a flat rate, flagged so the warehouse can reconcile. I also found our liveness probe called the carrier, so Kubernetes was restarting healthy pods, which made it worse; I moved that to a readiness or diagnostic check. Finally, I [added a chaos test that slows the carrier stub to 30 seconds and asserts checkout p95 stays under a second], and [the next carrier outage cost us nothing but [n] flat-rate orders].
The lesson I take from cascades is that resilience is about resource boundaries: every external call needs a time limit, a concurrency limit and an answer for when it fails."
| Question | Tool | What it shows |
|---|---|---|
| Which dependency is slow? | Application Insights application map, dependency durations | Shipping p95 30 s |
| Why are unrelated endpoints failing? | Application Insights failures, exception messages | SQL pool timeouts across all endpoints |
| What's exhausted? | dotnet-counters monitor (System.Runtime, Microsoft.Data.SqlClient.EventSource, System.Net.Http) |
SQL connections at 100, HTTP connections climbing, ThreadPool queue |
| What are requests waiting on? | dotnet-dump analyze + dumpasync |
Hundreds of awaits on the shipping client inside a transaction |
| Why so long? | Code/config review | 100 s default timeout x retries; call inside transaction |
| Why are pods restarting? | Kubernetes events, probe config | Liveness probe calls the carrier |
| Layer | Setting | Effect |
|---|---|---|
| Architecture | Shipping call outside the DB transaction | DB pool no longer shared with the carrier |
| Attempt timeout | 2 s | Hung calls end quickly and count as failures |
| Total timeout | 5 s | User never waits longer than the budget |
| Retry | 1, jittered | Survives blips without multiplying load |
| Circuit breaker | Thresholds sized to traffic | Fails fast during sustained outage |
| Bulkhead | 30 concurrent calls, no queue | Carrier can only use its compartment |
| Fallback | Cached zone rate or flat rate, flagged | Checkout keeps working |
| Health checks | Third party excluded from liveness | No restart loops |
Before the fix, a 40-minute carrier slowdown caused about 25 minutes of checkout outage. After it, a similar slowdown opened the breaker within 10 seconds, about 1,900 orders used flat-rate shipping (reconciled the next day at a cost of roughly A$2,300 in shipping differences), and checkout p95 stayed at 520 ms.
Checks structured incident diagnosis (finding the shared resource), mitigation before fixing, and a correctly layered resilience design.
Green flags
dotnet-counters, dotnet-dump.Red flags
Carrier API slows (0.2 s -> 30 s)
|
Checkout requests wait 100 s (default timeout) x up to 4 attempts
| while holding a DB connection inside the order transaction
v
SqlClient pool (Max Pool Size = 100) exhausted
|
Every endpoint needing the DB times out acquiring a connection <- unrelated requests fail
|
Liveness probe (calls carrier) fails -> pods restart -> cold starts -> less capacity
Cascades almost always follow this shape: a slow dependency, no time limit, no concurrency limit, and a shared resource held during the wait.
dotnet-counters monitor -p <pid> --counters System.Runtime,Microsoft.Data.SqlClient.EventSource,System.Net.Http. Watch threadpool-queue-length, threadpool-thread-count, SqlClient active-hard-connections, number-of-pooled-connections, and HTTP current-requests/http11-connections-current-total.dotnet-dump collect, then dumpasync in dotnet-dump analyze to list awaiting async state machines and what they're waiting on; clrstack -all for blocked threads if sync-over-async is suspected.HttpClient.Timeout (100 s default), retry settings, Max Pool Size, probes.| Pattern | Without it |
|---|---|
| Timeout | Calls hold resources for 100 s each |
| Retry (bounded) | Blips fail requests; too many retries multiply load |
| Circuit breaker | Every request still pays the timeout during an outage |
| Bulkhead | In-flight calls can grow until a shared resource is exhausted |
| Fallback | Breaker and bulkhead rejections still fail the user |
They're complementary: timeouts bound each call, the breaker stops calling when it's clearly down, the bulkhead caps how much can be waiting at once, and the fallback turns all rejections into a degraded success.
Outer to inner: concurrency limiter (bulkhead) → total timeout → retry → circuit breaker → attempt timeout. That's the shape of AddStandardResilienceHandler; the fallback sits outside the pipeline in the client (catching TimeoutRejectedException, BrokenCircuitException and RateLimiterRejectedException) or as a Polly fallback strategy outermost.
Never await an external service inside a database transaction. Get the rate before starting the transaction, or record the intent in an outbox and call the carrier asynchronously. This one change removes the DB pool from the blast radius.
Liveness should answer "is this process able to run?", and never depend on third parties; failing it restarts pods. Readiness can reflect critical internal dependencies; third parties belong in a separate diagnostic health endpoint or monitoring.
The product owner chooses: last known rate for the postcode zone (HybridCache), a flat rate, or "shipping calculated later". Flag such orders so finance or the warehouse can reconcile.
Chaos testing: inject latency into the carrier stub (Polly's chaos strategies AddChaosLatency/AddChaosFault, or a fault-injecting proxy) in staging under load (k6), and assert unrelated endpoints keep their p95.
dotnet-dump and dumpasync to find the waiting calls.AddChaosLatency to the pipeline in a staging configuration and run a k6 test.Before: the call inside the transaction with defaults. After: rate fetched first, a layered pipeline, and a fallback.
// BEFORE (the cascade): external call inside the transaction, 100 s default timeout, retries x3
// await using var tx = await db.Database.BeginTransactionAsync(ct);
// db.Orders.Add(order);
// await db.SaveChangesAsync(ct);
// order.ShippingCost = await shipping.GetRateAsync(order.Postcode, order.WeightKg, ct); // holds a DB connection for up to minutes
// await db.SaveChangesAsync(ct);
// await tx.CommitAsync(ct);
using Microsoft.Extensions.Http.Resilience;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHybridCache();
builder.Services.AddHttpClient<ShippingRatesClient>(c => c.BaseAddress = new Uri("https://rates.carrier.example"))
.AddStandardResilienceHandler(o =>
{
o.RateLimiter.DefaultRateLimiterOptions.PermitLimit = 30; // bulkhead: carrier gets its own compartment
o.RateLimiter.DefaultRateLimiterOptions.QueueLimit = 0;
o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(5); // user-facing budget
o.Retry.MaxRetryAttempts = 1; // one jittered retry, no amplification
o.CircuitBreaker.MinimumThroughput = 20; // sized to our traffic so it opens fast
o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(10); // >= 2x attempt timeout
o.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);
o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
});
// Liveness never depends on third parties (a failing carrier must not restart pods)
builder.Services.AddHealthChecks();
var app = builder.Build();
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.Run();
using Microsoft.Extensions.Caching.Hybrid;
using Polly.CircuitBreaker;
using Polly.RateLimiting;
using Polly.Timeout;
public sealed record ShippingQuote(decimal Amount, bool IsFallback);
public sealed class ShippingRatesClient(HttpClient http, HybridCache cache, ILogger<ShippingRatesClient> logger)
{
private const decimal FlatRate = 14.95m;
public async Task<ShippingQuote> GetRateAsync(string postcode, decimal weightKg, CancellationToken ct)
{
var zoneKey = $"rate:{postcode[..1]}:{Math.Ceiling(weightKg)}"; // zone + weight band
try
{
var amount = await http.GetFromJsonAsync<decimal>($"/rates?postcode={postcode}&kg={weightKg}", ct);
await cache.SetAsync(zoneKey, amount, cancellationToken: ct); // keep the fallback warm
return new ShippingQuote(amount, IsFallback: false);
}
catch (Exception ex) when (ex is BrokenCircuitException or TimeoutRejectedException or RateLimiterRejectedException or HttpRequestException)
{
logger.LogWarning("Shipping rates unavailable ({Reason}); using fallback", ex.GetType().Name);
var cached = await cache.GetOrCreateAsync(zoneKey, _ => ValueTask.FromResult(FlatRate), cancellationToken: ct);
return new ShippingQuote(cached, IsFallback: true); // order flagged for reconciliation
}
}
}
// AFTER: quote first, then a short transaction with no external calls inside
public sealed class PlaceOrderHandler(ShopDbContext db, ShippingRatesClient shipping)
{
public async Task<Guid> HandleAsync(PlaceOrder command, CancellationToken ct)
{
var quote = await shipping.GetRateAsync(command.Postcode, command.WeightKg, ct);
var order = Order.Place(command, quote.Amount, shippingNeedsReview: quote.IsFallback);
db.Orders.Add(order);
await db.SaveChangesAsync(ct); // one short implicit transaction
return order.Id;
}
}
HttpClient.Timeout at the 100-second default. Why it is wrong: Each slow call holds resources for up to 100 s, multiplied by retries. Instead: Per-attempt and total timeouts sized to the user's budget.Cascades are rarely caused by the dependency; they're caused by our lack of boundaries around it. I review every external call with three questions: how long can it take (timeout), how many can be in flight (bulkhead), and what happens when it fails (breaker plus fallback). And I check what each call holds while it waits; a transaction or a lock turns a local slowdown into a global outage.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Standard handler tuned per dependency | Most third-party HTTP calls | Tuning and review | Calls needing custom classification |
| Feature flag kill switch | Any non-critical dependency | Flag management | Critical path with no alternative |
| Cached/flat-rate fallback | Prices, quotes, enrichment | Reconciliation, stale data | Values that must be exact (e.g. payment amounts) |
| Async processing via outbox/queue | Work that needn't block the user | Eventual completion, UX changes | Data the user needs before confirming |
| Chaos tests in staging | Critical user journeys | Test infrastructure | Never skipped for checkout-level flows |
I measure success by unrelated endpoints' p95 during dependency incidents, time-to-open for breakers, fallback rate, and incident duration; the goal is that a third-party outage shows up as a degraded-feature metric, not an outage.
A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.
BrokenCircuitException for the break duration.In Polly v8 it opens when the failure ratio (default 10%) is exceeded over a 30 s sampling window with at least 100 calls, and it breaks for 5 s. AddStandardResilienceHandler puts it inside the retry (each attempt counts, and an open circuit stops retries) and outside the 10 s attempt timeout (a hung call counts as a failure).
Pair it with a fallback and alert when it opens. The trade-off is protection and fast failure against rejecting some calls that would have succeeded.
Retry handles transient faults: a network blip, 503, 429 or a timeout that will probably succeed if you try again shortly.
Retry-After), connection errors and timeouts. Never retry 400, 401, 403, 404, 409 or validation failures.The danger is amplification: retries at the API, service and client layers multiply, which creates a retry storm against a recovering dependency. Retry at one layer and pair it with a circuit breaker.
In .NET 10 it's Polly v8 (AddRetry) or AddStandardResilienceHandler (3 retries, exponential, jitter, 2 s base). The trade-off is higher success rates against extra load and latency.
A timeout should cancel the work, not just stop waiting. Use a CancellationTokenSource with CancelAfter (linked to the caller's token) and pass it down. Task.WaitAsync(timeout) only stops waiting. For HTTP, HttpClient.Timeout is a single total timeout (100 seconds by default) that throws TaskCanceledException with an inner TimeoutException; in production I prefer AddStandardResilienceHandler, which sets attempt and total timeouts plus retries. In ASP.NET Core 8+, the request timeouts middleware cancels RequestAborted after a configured time. Timeouts must be layered: each inner timeout shorter than the outer one.
A bulkhead partitions shared resources so one failing dependency can only exhaust its own share, like the watertight compartments in a ship. In .NET the shared resources are thread-pool threads, sockets, database connection-pool slots, memory and request slots.
AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.AddRateLimiter concurrency policies per endpoint group.MaxConcurrentCalls.A bulkhead limits concurrent work. Rate limiting limits requests per time window. Size limits with Little's Law (concurrency = rate x latency) plus headroom, and pair them with timeouts. The trade-off is containment against rejecting work when a compartment is full.
How to tell it (STAR)
**S:** At [company], a carrier's rates API slowed to 30 seconds and within four minutes our whole checkout, and even account pages, were failing for about [25] minutes. **T:** I was incident lead and then owned the fix. **A:** Application Insights and `dotnet-counters` showed the SQL pool pinned at 100: we called the carrier inside the order transaction with a 100-second timeout and three retries, and the liveness probe was restarting pods. I mitigated with the flat-rate feature flag and a process-only liveness probe, then moved the call out of the transaction, added 2 s/5 s timeouts, one retry, a tuned breaker, a 30-call bulkhead and a cached fallback, and a chaos test to prove it. **R:** In the next carrier slowdown the breaker opened in about [10] seconds, [~1,900] orders used fallback rates, and checkout p95 stayed at [520 ms] with no outage.
Last updated 18 Nov 2026.