Skip to content

Cascading Failures: How One Service Takes Down Everything ​

"A cascading failure is a failure that grows over time as a result of positive feedback." — Mike Ulrich, Addressing Cascading Failures, Google SRE Book, chapter 22

Summary: A cascade starts small (a spike, a lost zone, a bad deploy, a cold cache), and the system's own reactions (retries, health-check kills, failover, autoscaling, queues that grow without limit) turn it into a total outage that often outlives the trigger. Focus: The anatomy of the death spiral (overload, latency, retries, pool exhaustion, upstream timeouts, failing health checks, capacity removal), every positive feedback loop practitioners meet (retry storms, cache stampedes, autoscaler lag, GC pressure, connection-pool queueing, DNS/TTL herds, synchronized cron, leader thrash), slow vs down, queue depth and unbounded queues, resource exhaustion (CPU, memory, file descriptors, threads, connections, ephemeral ports), load testing to find the knee, prevention (deadlines, retry budgets and jitter, circuit breakers, bulkheads, load shedding and admission control, backpressure, graceful degradation, headroom), detection (the four golden signals), recovery (shed, stop retries, block at the edge, slow start, gradual recovery), five public postmortems, and a Go simulator whose numbers are on this page. Learning goal: Look at an architecture diagram and point to the loops that can turn a small fault into an outage, put a cheap breaker on each loop, prove it with a load test past the knee, and know the order of operations that gets a collapsed system back without a second collapse.

This chapter opens the Resilience group. It owns the system-level picture: how failures spread, the numbers behind it, the trade-off tables and the recovery playbook. The individual defences have their own chapters, linked in one sentence each where they appear: Timeouts, Retries & Jitter, Circuit Breaker, Bulkheads & Graceful Degradation, Load Shedding, Rate Limiting and Chaos Engineering. Neighbours: per-hop budgets in Latency Budgets & Tail Latency, health checks in Load Balancing and Service Discovery, autoscaling in Scaling Strategies, SLO burn in SLAs, SLOs, SLIs & Error Budgets, ports and sockets in Ports, Sockets & Connections, database pools in Connection Pooling, and message-level backpressure in Backpressure & Flow Control.

Page map ​

If you are looking forGo to
The whole page in three tables and one pictureEverything in one minute
Why a 1-minute blip becomes a 2-hour outageWhy it exists
Nygard, Google SRE, AWS, the metastable-failures paperWhere it comes from
Positive feedback, overload, goodput, the kneeCascading failure, Overload and goodput
The death spiral and metastable failureDeath spiral
Retry storms and retry amplificationRetry storm
Why slow is worse than down; bimodal latencySlow vs down
Queue depth, unbounded queues, head-of-line blockingQueues
CPU, memory and GC, threads, file descriptors, connections, ephemeral portsResource exhaustion
Health check flapping and capacity removalHealth checks
Thundering herd, cache stampede, cold cachesThundering herd
Autoscaler lag; synchronized cron, DNS TTL, leader thrashAutoscaler lag, Synchronized load
Query of death, rollouts, drains, organic growthTriggers
Deadlines, propagation and cancellationDeadlines
Retry budgets and jitterRetry budget
Load shedding, admission control, bounded queues, backpressureLoad shedding
Circuit breakers, bulkheads, dependency isolation, fail fastIsolation
Graceful degradation and criticalityDegradation
Headroom, N + 2, load testing to the kneeHeadroom and load tests
Hedged requests and their limitsHedging
Four golden signals, saturation, SLO burnDetection
Shed, stop retries, block at the edge, slow startRecovery
Blameless postmortemsPostmortems
S3 2017, Cloudflare 2019, GitHub 2018, Slack 2021, Google 2020Case studies
Formulas, knobs, error messagesMechanics
Code and the simulatorGo, Laravel
Classic incidents and their fixesSolving the classic problems
Which defence for which symptomChoosing
Monolith to multi-regionIn architecture
Run the death spiral yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The anatomy of a cascade (Google SRE ch. 22 and Nygard), step by step.

StepWhat happensWhy it feeds the next step
1. TriggerA spike, a lost cluster or zone, a deploy, a query of death, a cache flushLoad per healthy server rises above what it can serve
2. OverloadRequests arrive faster than workers finish themThe surplus waits somewhere: a queue, a socket backlog, memory
3. Latency risesQueueing delay is added to every requestCallers' deadlines start to expire
4. Retries amplifyTimed-out callers try again, often at several layersOffered load grows while useful work shrinks
5. Pools exhaustThreads, connections, file descriptors and memory are held by slow workEven cheap requests (and health checks) cannot be served
6. Upstream times outThe callers of the slow service now hold their own threadsThe failure climbs the call graph
7. Health checks failProbes wait behind real traffic or check a slow dependencyLoad balancers eject and schedulers kill busy servers
8. Capacity removedFewer servers, and the ones that restart have cold cachesThe remaining servers get even more load: back to step 2

Positive feedback loops and the cheap breaker for each.

LoopWhat amplifiesBreakerOwner chapter
Retry stormAttempts per request, multiplied per layerRetry at one layer, retry budget (10%), full jitterTimeouts, Retries & Jitter
Doomed workServers process requests whose caller already gave upDeadline propagation, check the deadline before each stageDeadlines
Queue growthUnbounded queues: latency and memory grow without limitBounded queue (about 50% of the worker pool), fast 503Load Shedding
GC death spiralMore in-flight requests, more heap, more GC, less CPUAdmission control, memory limits, fewer in-flight requestsResource exhaustion
Health-check killsBusy servers declared dead and restartedLiveness that ignores load; readiness for draining onlyHealth checks
Failover overloadTraffic of a lost cluster moves to the survivorsHeadroom (N + 2), shed sheddable traffic firstHeadroom
Cache stampedeCold or flushed cache sends every request to the databaseRequest coalescing, stale-while-revalidate, cache warmingCaching
Autoscaler lag or wrong signalScaling too slowly, or down when threads wait on I/OScale on saturation, keep headroom, pre-warmScaling Strategies
Synchronized clientsRetries, cron jobs and TTL expiries fire at the same instantJitter everything that is scheduledSynchronized load
Slow dependencyEvery caller's threads pinned by one slow backendTimeouts, bulkheads, circuit breakers, fail fastCircuit Breaker

What the simulator on this page measured (10 servers, 2,000 requests/s capacity, 1,400 requests/s normal load, a 2,600 requests/s spike from 20 s to 30 s; model numbers, not production numbers).

SystemGoodput during the spikeGoodput 30–90 s, load back to 70%Attempts per request after the spike
Naive (5 s timeout, 3 immediate retries, unbounded queue, probe in the queue)44.2%6.4%, then 6.2%: it never recovers3.50x
Naive + retry budget and jitter only44.2%14.0%1.08x
Naive + bounded queue only76.8%100%1.01x
Protected (deadlines, budget, bounded queue, liveness-only probe)76.5% (about 1,990/s, the capacity)100%1.01x
Triggerspike, lost zone, deploy, cold cacheOverloadoffered load above capacityQueues grow, latency risesthreads and connections heldTimeouts and retrieseach layer multiplies attemptsMemory and GC pressureevery request gets slowerHealth checks failprobe waits in the same queueCapacity removedkill, eject, OOM, crash loopCold restartsempty caches, new connectionsmore loadslower = less capacityremaining nodestake the loadBreak the loop: bounded queue + shed (fast 503) | deadline checked before work | retry budget + jitter | liveness that ignores load

The picture is the chapter: every box makes the next one worse, and the arrows that close the loop (more load, less capacity) are the ones the defences cut. A system with a loop and no breaker is not unlucky when it falls over; it was waiting for a trigger.

Why it exists ​

Distributed systems are built from replicas and dependencies precisely so that one failure does not matter. The same structure, however, gives a failure many ways to move: load from a dead replica moves to its peers, delay in a backend moves to its callers, retries move work back into the place that is already drowning, and automation that is supposed to heal (health checks, failover, autoscaling, restarts) moves capacity out of the system at the worst moment. Nygard's description of tight coupling is exactly this: "A failure in one component causes load to be redistributed to its peers and introduces delays and stress to its callers. This increased stress makes it extremely likely that another component in the system will fail."

Built for the steady stateBuilt to survive overload
Retries hide transient errorsRetries are capped per request and per client, and happen at one layer
Generous timeouts so slow requests eventually succeedDeadlines tied to what the user waits for; doomed work is dropped
Queues absorb bursts, as many as memory allowsQueues are short; the excess is rejected fast and cheaply
Health checks remove anything that looks unhealthyHealth checks distinguish dead from busy; ejection has a ceiling
Caches make the service fast (and quietly carry the load)The service can survive an empty cache, or warms it before traffic
Autoscaling replaces headroomHeadroom covers the loss of a zone; autoscaling is the second line
Every request is equally importantTraffic has criticality; sheddable work goes first
Load tests stop at the expected peakLoad tests go past the knee and check that goodput stays flat

The everyday picture used through this page: a busy restaurant kitchen. Orders arrive faster than the cooks can plate them (overload). The ticket rail fills up (an unbounded queue), so every dish is late (latency). Waiters, seeing nothing come out, re-send the same order (retries), which makes the rail longer. The manager, seeing cooks who "are not producing", sends two of them home (health-check kills). The replacements do not know where anything is (cold cache). Long after the rush is over, the kitchen is still burning dishes nobody is waiting for. The fix is not more cooks first: it is to stop taking orders at the door for ten minutes, throw away tickets for customers who already left, tell waiters to stop re-sending, and reopen the door slowly.

Three common misunderstandings, up front ​

  1. "It went down because of the trigger." The trigger only starts it. The Bronson et al. metastable-failures paper: "It is common for an outage that involves a metastable failure to be initially blamed on the trigger, but the true root cause is the sustaining effect." In the simulator, the spike ends at 30 s and the naive system is still at 6% goodput at 90 s.
  2. "Retries make us more reliable." For independent, transient errors, yes. Under overload they are fuel: the Google SRE book shows three layers of three retries turning one user action into 64 database attempts, and AWS shows five layers turning into 243x the load, "making it unlikely to ever recover."
  3. "Add capacity and it will recover." Google SRE: "if the service has entered a death spiral of some sort, adding more resources may not be sufficient to recover." In the simulator, adding 50% more servers during the collapse moved goodput from 4.6% to 15.2% for ten seconds and then back to 8%; blocking 90% of traffic at the edge and ramping back over 20 s recovered fully.

Where it comes from ​

text
     Year   Who / what                                     What it added
1    1994   Floyd & Jacobson (cited by Google SRE as Flo94) Retry ripples scheduled together amplify themselves; randomize
2    2015   Marc Brooker, AWS Architecture Blog             "Exponential Backoff And Jitter": Full, Equal, Decorrelated jitter
3    2016   Google SRE book (online edition (c) 2017), ch. 21-22  Overload handling, retry budgets, deadlines, the death spiral
4    2017   AWS S3 us-east-1 summary (Feb 28)                Capacity removed too fast; full restarts of index/placement
5    2018   Nygard, Release It! 2nd edition (Jan 2018)       Stability antipatterns: Cascading Failures, Chain Reactions, Slow Responses...
6    2018   GitHub, October 21 post-incident analysis        43 s partition, cross-country failover, 24 h 11 min degradation
7    2019   Cloudflare, July 2 outage                        One regex rule exhausted CPU worldwide for 27 minutes
8    2020   Google, incident 20013 (Dec 14)                  Quota automation starved the User ID Service: 47 minutes
9    2021   Slack, January 4 outage                          Saturated AWS Transit Gateways, autoscaling and provisioning loops
10   2021   Bronson et al., HotOS (metastable failures)      Trigger vs sustaining effect; stable, vulnerable, metastable states

Nygard. Release It! names the pattern from the operator's side. Its stability antipatterns chapter lists Integration Points, Chain Reactions, Cascading Failures, Blocked Threads, Self-Denial Attacks, Scaling Effects, Unbalanced Capacities, Dogpile, Force Multiplier, Slow Responses and Unbounded Result Sets, and the stability patterns that answer them: Timeouts, Circuit Breaker, Bulkheads, Steady State, Fail Fast, Let It Crash, Handshaking, Test Harnesses, Decoupling Middleware, Shed Load, Create Back Pressure and Governor (table of contents on the publisher's page). The free excerpt explains why slowness is the dangerous mode: "Clearly, a slow response is a lot worse than no response."

Google SRE. Chapter 22 (Mike Ulrich) is the canonical anatomy: causes (server overload, resource exhaustion, service unavailability), prevention in priority order (load test to failure, serve degraded results, reject when overloaded, rate-limit at higher layers, capacity planning), queue management, load shedding, retries, deadlines, slow startup and cold caches, triggering conditions, testing and the immediate steps. Chapter 21 (Handling Overload) adds client-side adaptive throttling, criticality and the per-request and per-client retry budgets. Footnote 110 of chapter 22 says "write a simple simulator and see how the amount of useful work the backend can do varies with how much it's overloaded and how many retries are permitted"; the Go section does exactly that.

AWS Builders' Library. Using load shedding to avoid overload introduces goodput versus throughput and the load-test shape to aim for; Timeouts, retries, and backoff with jitter gives the 243x multiplication and the token-bucket retry limit added to the AWS SDK in 2016.

Metastable failures. Bronson, Charapko, Aghayev and Zhu (HotOS 2021) give the vocabulary used on this page: "Metastable failures occur in open systems with an uncontrolled source of load where a trigger causes the system to enter a bad state that persists even when the trigger is removed." Leaving it "requires a strong corrective push, such as rebooting the system or dramatically reducing the load."

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what products provide, and the fix. The first twelve blocks describe how cascades happen; the rest describe how to stop them.

Cascading failure and the positive feedback loop Must-know ​

In plain words: one part fails, and that failure makes it more likely that the next part fails, which makes it more likely again. It is dominoes, but the dominoes push back.

Common misunderstanding: "A cascade is several independent failures at once." It is one failure spreading through coupling. The second server did not fail by coincidence; it failed because it received the first server's load.

Definition: Google SRE: a cascading failure "can occur when a portion of an overall system fails, increasing the probability that other portions of the system fail." The engine is a positive feedback loop: an output (errors, latency, lost capacity) increases its own input (load per server). Negative feedback (shedding, backoff, throttling) is what keeps systems stable.

text
     t       Cluster A (capacity 1,000 QPS)               Cluster B
1    0 s     1,000 QPS, healthy                           1,000 QPS, healthy
2    10 s                                                 fails
3    10 s    the load balancer sends B's share: 1,200 QPS
4    40 s    A runs out of resources: crashes, misses deadlines; useful work falls well below 1,000
5    60 s    the global load balancer moves A's traffic to C and D, which overload in turn
6    2 min   "service-wide overload failure" (Google SRE: "on the order of a couple minutes")

Real scenario: a zone outage moves a third of traffic onto two zones already at 70%; a Kafka consumer group rebalances under load and every consumer restarts from older offsets; a payment provider slows down and every checkout thread waits for it; a cache cluster restarts and the database receives the full read load.

What provides the coupling (and the brake):

CouplingProduct exampleBrake
Load redistribution among replicasAWS ALB, Envoy, NGINX upstreams, Kubernetes ServicesHeadroom; per-server admission control
Delay propagation to callersAny synchronous RPC: HTTP, gRPCDeadlines, bulkheads, circuit breakers
Retry re-injectionClient libraries, SDKs, proxies (Envoy retries), browsersRetry budgets (gRPC retryThrottling, AWS SDK quota)
Automation that removes capacityKubernetes liveness probes, Borg restarts, ASG health replacementSeparate liveness from readiness; ejection ceilings (Envoy max_ejection_percent)
Shared cachesRedis, Memcached, CDNLatency caches, request coalescing, Cache::flexible

Fix / how to use it: draw the dependency graph and mark every arrow along which load, delay or retries can travel; each arrow needs a brake (Choosing has the table).

Overload, goodput and the knee Must-know ​

In plain words: a server has a maximum rate of useful work. Push more than that and the useful rate does not stay flat; for most naive servers it falls, sometimes to almost zero.

Common misunderstanding: "At 120% load we serve 100% and the extra 20% waits." Without shedding, the extra waits in front of everybody, latency grows for all requests, deadlines expire, and the useful rate collapses (Google SRE: at 1,200 QPS "the rate of successfully handled requests in A dips well below 1,000 QPS").

Definition: throughput is the request rate sent to the server; goodput is "the subset of the throughput that is handled without errors and with low enough latency for the client to make use of the response" (AWS). The knee is the load at which goodput stops tracking offered load. A well-protected service plateaus at the knee; a fragile one falls off a cliff.

text
     Offered (req/s)   Naive goodput   Protected goodput     (simulator, 2,000 req/s capacity)
1    1,000             1,000           1,000
2    1,800             1,799           1,798
3    2,000             1,713           1,908
4    2,200             236             1,956
5    3,000             108             1,998
beyond capacity0500100015002000100014001800220026003000offered load (req/s, steady for 30 s)goodput (req/s)ideal: goodput = offeredprotected 1,998naive 108knee: 1,713AWS: "The ideal load test result is for goodput to plateau ... and to remain flat even when more throughput is applied."

Real scenario: a ticket on-sale at 10:00:00; a TV mention (the SRE book's Shakespeare example after a documentary airs in Japan); Slack's first working Monday of the year when "client caches are cold and clients pull down more data than usual on their first connection".

What provides it:

ProductMechanism that keeps goodput flat
Google internal RPC (SRE ch. 21)Per-task utilisation signals ("executor load average"), criticality-aware rejection
EnvoyCircuit breakers on connections, pending requests, requests and retries (upstream_rq_pending_overflow)
AWS services (Builders' Library)Brownout protection with a target false-positive rate of zero
LaravelRoute throttle middleware per client, queue-time shedding middleware (Laravel)
GoAdmission middleware with a bounded queue (Go)

Fix / how to use it: load-test past the knee, then add the cheapest rejection path you can (a fixed limit on in-flight requests, a bounded queue) until the curve plateaus. The Load Shedding chapter covers the algorithms.

The death spiral and metastable failure Must-know ​

In plain words: the system is broken in a way that keeps itself broken. Even after the original problem is gone, the reactions to it (retries, restarts, cold caches, backlog) keep the load above what the remaining capacity can serve.

Common misunderstanding: "Load dropped back to normal, so it will heal by itself." Google SRE: "if a service was healthy at 10,000 QPS, but started a cascading failure due to crashes at 11,000 QPS, dropping the load to 9,000 QPS will almost certainly not stop the crashes." With only 10% of servers healthy, "the request rate would need to drop to about 1,000 QPS in order for the system to stabilize and recover."

Definition: a metastable failure state is a bad state with low goodput that persists after the trigger is removed because a sustaining effect (work amplification or reduced efficiency) keeps it there. Bronson et al. describe three phases: stable, vulnerable (healthy but efficient enough that a trigger can tip it over; "many production systems choose to run in the vulnerable state all the time") and metastable. The "GC death spiral" in Google SRE is the memory variant: "less CPU is available, resulting in slower requests, resulting in increased RAM usage, resulting in more GC, resulting in even lower availability of CPU."

text
     t (s)   Offered   Attempts   Good   Up   Queue   What happens (naive run of the simulator)
1    18      1,400     1,400      1,396  10   7       vulnerable but healthy: 70% utilisation
2    20      2,600     2,600      1,955  10   628     trigger: spike to 130%
3    25      2,600     2,600      1,537  10   4,729   queues grow, GC slows every request
4    26      2,600     2,600      765    6    3,527   health checks wait in the queue: 4 servers killed
5    28      2,600     10,377     0      0    0       every attempt times out; retries; no server up
6    30      1,400     12,726     0      0    0       trigger gone, retry wave of 9x
7    32-90   1,400     1,400-13,017  0-252  0-10  ...  restarts come back cold, are overloaded, killed again

Real scenario: the "lame duck" fleet where servers keep failing health checks the moment they come back; a Java service in a GC loop; Memcached restart where each restarted node is flooded with misses; a queue consumer fleet that crashes on a poison batch, restarts and re-reads the same batch.

What provides it (ways out, all "strong corrective pushes"):

ExitProductNote
Drop traffic at the edge, ramp backCloudflare WAF/rate-limit rules, AWS WAF, NGINX limit_req, Envoy local rate limitGoogle SRE: "only allow, say, 1% of the traffic through"
Stop the retriesFeature flags, client config push, gRPC retryThrottlingOften needs a code or config push
Disable the killing health checkKubernetes probe edit, Borg health-check disableGoogle SRE: "temporarily disabling health checks may permit the system to stabilize"
Global kill switch for the faulty componentCloudflare "global terminate"Used at 14:07 in the 2019 outage

Fix / how to use it: design so that the vulnerable state is visible (headroom alarms, load tests that cross the knee) and so that every loop has a breaker that engages automatically; keep a manual exit (edge blocking with a ramp) ready and drilled. The simulator run is in the Lab.

spike 130%01000200030000102030405060708090time (s)good responses per secondcapacity 2,000offered load (dotted)naive: stuck below 260/s at 70% loadretry waves of 13,000 attempts/s every 8 sthick line: protected (deadlines, retry budget, bounded queue, liveness-only checks); dash-dot: naive

Retry storm and retry amplification Must-know ​

In plain words: when things are slow, everyone asks again, so the service that is too busy receives the same work two, four or sixty-four times.

Common misunderstanding: "We only retry three times, that is modest." Three retries at each of three layers is 4 × 4 × 4 = 64 attempts per click. Retries multiply per layer; they do not add.

Definition: retry amplification is attempts per logical request at the bottom of the stack. Google SRE's example: a backend limited to 10,000 QPS receiving 10,100 QPS rejects 100, those are retried, it now receives 10,200, "The volume of retries grows: 100 QPS of retries in the first second leads to 200 QPS, then to 300 QPS, and so on." A retry storm is the resulting self-sustaining flood. AWS: "Retries are a way for clients to assert the importance of their request and demand that the service spend more of its resources to handle it."

text
     Layer               Attempts per user action (each layer: 3 retries = 4 attempts)
1    JavaScript client   4
2    Frontend            4 x 4 = 16
3    Backend -> DB       4 x 4 x 4 = 64     (Google SRE ch. 22)
4    Five layers, three tries each: 3^5 = 243x   (AWS Builders' Library)
5    With retries at one layer only: 4x; with a 10% retry budget: about 1.1x   (SRE ch. 21)
User click1 requestJavaScript4 attemptsFrontend4 x 4 = 16Backend to DB4 x 4 x 4 = 64Google SRE ch. 22: three layers, 3 retries each (4 attempts)AWS Builders' Library: five layers, three tries each = 3^5 = 243x the load on the database"making it unlikely to ever recover"Retry at one layer onlyworst case = attempts at that layer (4x)other layers fail fast and pass errors upPlus a 10% retry budgetSRE ch. 21: about 3x drops to about 1.1xsimulator: 3.50x naive vs 1.01x protected

Real scenario: a mobile app that retries every failed sync immediately (the SRE book mentions "an offline sync protocol that retries aggressively"); service meshes that retry by default plus application retries; a database failover during which every service retries connection attempts at the same moment; Kubernetes CrashLoopBackOff pods re-reading the same Kafka batch.

What provides protection:

ProductRetry controlDefault or note
gRPCretryPolicy.maxAttempts, retryThrottling (maxTokens, tokenRatio)Retries pause when tokens fall below half of maxTokens
AWS SDKsRetry quota (token bucket) since 2016"AWS added this behavior to the AWS SDK in 2016"
Envoyretry_budget or max_retries circuit breakerDocs: "we recommend using retry budgets"
Laravel HTTP clientretry($times, $sleep, $when, throw:)No budget built in; this page's RetryBudget adds one
Gonone in net/httpThis page's resilience.Client

Fix / how to use it: retry at one layer only (usually the one closest to the user or the one with idempotency guarantees), cap attempts per request at 2–3, add a client-wide budget of about 10%, use full-jitter backoff, never retry 4xx or explicit overload (429), and return a specific status when overloaded. Details in Timeouts, Retries & Jitter and Retry, Backoff & Delayed Delivery.

Slow vs down: why slow is worse Must-know ​

In plain words: a dead dependency answers "no" in a millisecond, and you move on. A slow dependency answers "maybe" after thirty seconds, and while you wait you hold a thread, a connection, memory and a user.

Common misunderstanding: "A slow service is half-working, which is better than not working." For its callers, slow is the most expensive failure mode: it converts latency into held resources, and held resources into exhaustion.

Definition: Nygard: "Fast network failures cause immediate exceptions in the calling code ... Slow failures, such as a dropped ACK, let threads block for minutes before throwing exceptions. The blocked thread can't process other transactions, so overall capacity is reduced. If all threads end up getting blocked, then for all practical purposes, the server is down." Bimodal latency (Google SRE) is the extreme: most requests fast, a few never finish until the deadline.

text
     Frontend: 10 servers x 100 threads = 1,000 threads, 1,000 QPS at 100 ms = 100 threads busy
1    Event: 5% of requests (one unavailable Bigtable key range) never complete
2    Deadline 100 s: those 50 QPS hold 50 x 100 = 5,000 thread-seconds per second
3    Capacity needed: 5,000 + 95 threads; available: 1,000
4    Served: 1,000 / 5,095 = 19.6% of requests; error rate 80.4% (Google SRE)
5    Same event with a fail-fast error after 100 ms: 5% errors, 95% served

Real scenario: a payment partner with a 60 s default timeout during their brownout; a DNS resolver that drops packets instead of refusing; a database waiting on a lock queue; Slack's web tier, where packet loss raised latency to backends and "saturated system resources in our web tier".

What turns slow into fast:

ProductKnobDefault (from the docs)
Laravel HTTP clienttimeout(), connectTimeout()30 s and 10 s
NGINXproxy_connect_timeout, proxy_read_timeout60s each
Go net/httphttp.Client.Timeout, Transport.ResponseHeaderTimeout, context deadlinesnone: zero means no timeout
PostgreSQLstatement_timeout, lock_timeout, idle_in_transaction_session_timeout0 (disabled)
Kubernetes probestimeoutSeconds1s
PHP-FPMrequest_terminate_timeout0 (off)

Fix / how to use it: every outbound call gets a deadline sized from the callee's latency distribution (about its p99.9) and never longer than what the caller has left; if a dependency is known to be down, fail immediately (circuit breaker); watch latency distributions, not means ("When you see a latency increase, try to look at the distribution of latencies in addition to the averages").

Queue depth, unbounded queues and head-of-line blocking Must-know ​

In plain words: a queue turns "too busy" into "late". A short queue absorbs a burst; a long one just makes every request late and uses memory doing it.

Common misunderstanding: "A bigger queue means fewer errors." Under sustained overload, no queue size is big enough; it only delays the errors and turns them into timeouts, which are more expensive than rejections.

Definition: queue depth is the number of requests waiting for a worker. Its cost in time is depth × service time / workers. Google SRE: "if the queue size is 10x the number of threads, the time to handle the request on a thread is 100 milliseconds. If the queue is full, then a request will take 1.1 seconds to handle, most of which time is spent on the queue." Recommended: "small queue lengths relative to the thread pool size (e.g., 50% or less)"; Gmail "often uses queueless servers". An unbounded queue has no limit, so overload becomes memory growth and eventually an OOM kill. Head-of-line blocking is when one slow item at the front delays everything behind it in a FIFO.

text
     Workers 8, service 40 ms, arrivals 2,600/s vs capacity 200/s per server (one server shown)
1    t=0     queue 0     wait 0 ms
2    t=1 s   queue 60    wait 300 ms     (60 x 40 / 8)
3    t=5 s   queue 300   wait 1.5 s      client timeout 1 s: every request now times out
4    t=10 s  queue 600   wait 3 s        all work served is work nobody waits for
5    bounded queue of 4: wait at most 20 ms; the excess 60/s gets a 503 in under a millisecond

Real scenario: a Laravel Redis queue that grew to millions of jobs during an outage and needs hours to drain; GitHub's backlog of "over five million hook events and 80 thousand Pages builds"; a Go service using an unbuffered goroutine per request with no limit; the PHP-FPM listen backlog (default 511 on Linux) where requests wait in the kernel while every child is busy.

What provides bounds:

ProductQueueBound / knob
PHP-FPMChildren and the socket backlogpm.max_children, listen.backlog (511 on Linux)
EnvoyPending requests per clustermax_pending_requests circuit breaker
GoGoroutines and channelsBuffered channel or semaphore as admission (Go)
Laravel queuesRedis/SQS/database queuequeue:monitor --max=100 plus a QueueBusy listener; pendingSize()
LinuxTCP accept queuelisten() backlog, net.core.somaxconn

Fix / how to use it: bound every queue, size it to the burst you want to absorb (time, not count), reject at the limit with a fast 503, and consider LIFO or CoDel-style dropping: Google SRE: "Changing the queuing method from the standard first-in, first-out (FIFO) to last-in, first-out (LIFO) or using the controlled delay (CoDel) algorithm ... can reduce load by removing requests that are unlikely to be worth processing."

Resource exhaustion: CPU, memory and GC, threads, file descriptors, connections, ephemeral ports Must-know ​

In plain words: every request holds some resources while it runs. When requests run longer, they hold more of everything at once, and whichever resource runs out first becomes the outage.

Common misunderstanding: "We alert on CPU, so we will see it coming." Many cascades exhaust something that CPU graphs do not show: threads waiting on I/O (CPU goes down), file descriptors, pool connections, ephemeral ports, process IDs.

Definition: Google SRE lists the effects. CPU: more in-flight requests, long queues, thread starvation, watchdog kills, missed deadlines, reduced cache efficiency. Memory: dying tasks, "Increased rate of garbage collection (GC) in Java, resulting in increased CPU usage", lower cache hit rates. Threads: "Thread starvation can directly cause errors or lead to health check failures"; "In extreme cases, thread starvation can also cause you to run out of process IDs". File descriptors: "the inability to initialize network connections, which in turn can cause health checks to fail". These resources depend on one another, so "a service experiencing overload often has a host of secondary symptoms that can look like the root cause".

ResourceExhaustion symptom (verbatim where standard)Typical triggerOwner page
CPUEvery request slower, watchdogs fireExpensive request mix, regex backtracking (Cloudflare 2019)Latency Budgets
Memory / GC pressureOOM kill, GC pauses, cache shrinkIn-flight requests, unbounded queuesthis page
Threads / workersNo worker for health checks; PHP-FPM server reached pm.max_children settingSlow dependencythis page
File descriptorsaccept() fails with EMFILE ("Too many open files")Connection leaks, many slow sockets, Slack's provision-servicePorts, Sockets & Connections
Pool connectionsWaits for a pool slot; PostgreSQL SQLSTATE 53300 too_many_connectionsSlow queries hold connectionsConnection Pooling
Ephemeral portsconnect() fails with EADDRNOTAVAIL ("Cannot assign requested address")Connection churn without keep-alive, TIME_WAIT pile-upNetwork Troubleshooting
QuotasAPI 429s, cloud quota errorsMass provisioning (Slack hit "an AWS quota limit")Capacity Planning
text
     Google SRE's chain: which symptom is the root cause?
1    Java frontend has poorly tuned GC parameters
2    Under high (but expected) load, CPU runs out due to GC
3    Requests complete more slowly -> more in-flight requests -> more RAM in use
4    Less RAM left for the cache -> fewer entries, lower hit rate
5    More cache misses fall through to the backend
6    Backend runs out of CPU or threads
7    Health checks fail: the cascade starts (and the backend team is paged first)

Real scenario: connection pool exhaustion when one slow query holds 20 of 20 pool slots; thread pool exhaustion in a Tomcat or PHP-FPM tier behind a slow partner; file descriptor exhaustion when a client keeps sockets open to a slow backend; ephemeral port exhaustion on a NAT gateway or a host making short-lived connections without keep-alive.

Fix / how to use it: cap in-flight work per process (admission control) so that every resource has a known upper bound; reuse connections (Go MaxIdleConnsPerHost, default 2, is the classic trap); set ulimit -n and container memory limits deliberately; emit saturation metrics for each pool (in use / capacity).

Health check flapping and capacity removal Must-know ​

In plain words: the system that is supposed to protect you from broken servers sees busy servers, decides they are broken and removes them, so the remaining servers become busier and are removed next.

Common misunderstanding: "A deep health check that tests the database is more honest." When the database is slow, every web pod fails at once, and the orchestrator restarts the whole fleet. Health checking a shared dependency turns one slow component into zero capacity.

Definition: Google SRE separates process health checking ("is this binary responding at all?"), relevant to the scheduler, from service health checking ("is this binary able to respond to this class of requests right now?"), relevant to the load balancer, and warns of "a failure mode in which health-checking itself makes the service unhealthy". Health check flapping is a server alternating between healthy and unhealthy because the check itself depends on load. Capacity removal is any automated or manual action that takes serving capacity out (ejection, kill, drain, scale-in).

text
     t      Server 3 (busy, alive)                    Load balancer / scheduler
1    0 s    queue wait 2.4 s; probe timeout 2 s        probe 1 fails
2    1 s    still serving real requests                 probe 2 fails
3    2 s                                                probe 3 fails: kill and restart
4    2 s    its 400 queued requests are lost            their clients time out and retry elsewhere
5    7 s    comes back, cold cache (3x slower)          receives a full share at once
6    9 s    queue wait 3 s                              probes fail again: the flapping loop

Real scenario: Kubernetes liveness probes pointing at an endpoint that queries PostgreSQL; AWS Auto Scaling groups replacing instances that fail ELB health checks during a dependency outage (Slack 2021: instances "marked unhealthy by our automation because they couldn't reach the backends that they depended on"); Envoy outlier detection ejecting most hosts of a cluster that is uniformly slow.

What products provide:

ProductProtection against capacity removalDocs wording
EnvoyPanic threshold (default 50%): balance across all hosts when too few are healthy"used to avoid a situation in which host failures cascade throughout the cluster as load increases"
Envoyoutlier_detection.max_ejection_percentEjection skipped if above the threshold
KubernetesSeparate livenessProbe, readinessProbe, startupProbe"The readiness and liveness probes do not depend on each other to succeed"
Slack's load balancers"panic mode", which "balances requests across all instances when many are failing health checks"Slack 2021 postmortem
LaravelBuilt-in /up route: 200 "if the application has booted without exceptions"DiagnosingHealth event for extra checks
AWS ALBTarget group slow start (slow_start.duration_seconds)Linear ramp for targets that become healthy

Fix / how to use it: liveness checks only the process (no dependencies, no queueing behind traffic: serve it on its own path or listener); readiness fails only while starting up or draining; report saturation in the body instead of failing; give ejection a ceiling; never let a health check be the thing that removes the last 50% of a fleet.

Thundering herd and cache stampede Important ​

In plain words: many clients wake up at the same moment and ask for the same thing: after a restart, when a cache entry expires, or when a dependency comes back.

Common misunderstanding: "The cache only makes us faster; if it is down we are just slower." Google SRE distinguishes a latency cache (the service survives without it) from a capacity cache ("a service using a capacity cache cannot sustain its expected load under an empty cache"). Most mature caches quietly become capacity caches.

Definition: a thundering herd is a burst of synchronized requests from many waiting clients; a cache stampede (dogpile, in Nygard's list) is the special case where an expired or cold key sends every reader to the origin at once. Cache warming pre-loads a cache before it takes traffic.

text
     t        Cache                     Database (capacity 2,000 QPS)
1    0        95% hit rate, 20,000 QPS   1,000 QPS of misses
2    10:00    cache cluster restarted    20,000 QPS: 10x capacity
3    10:00+   every miss is slow, so it holds a connection longer
4    10:01    pool exhausted; app threads wait; health checks fail; cascade
5    Fix:     coalesce misses per key, serve stale while one request refreshes, ramp traffic to the new cache

Real scenario: a Redis failover that empties a cache; a popular product's key expiring during a sale; mobile clients reconnecting together after a network blip; Slack's January 4: "client caches are cold"; the SRE book's warning about "an externally triggered software update" that "might clear an offline client's cache".

Fix / how to use it: coalesce concurrent misses (Go singleflight, Laravel Cache::lock or Cache::flexible), jitter TTLs, keep stale-while-revalidate windows, warm caches before readiness, bring cache nodes back gradually. The algorithms live in Caching.

Autoscaler lag and scaling realities Important ​

In plain words: autoscaling reacts to what already happened, needs minutes to deliver capacity, and can scale in the wrong direction when the metric lies.

Common misunderstanding: "We have autoscaling, so we do not need headroom." New instances must boot, provision, pass health checks and warm caches; during that time the old ones carry the spike, and the provisioning system itself is under load.

Definition: autoscaler lag is the time between the start of overload and new capacity actually serving. Slack's postmortem shows two realities at once: the signal can invert ("threads were spending more time waiting, which caused CPU utilization to drop. This drop in CPU utilization initially triggered some automated downscaling") and the scale-up can overload its own machinery ("provision-service hit two separate resource bottlenecks (the most significant one was the Linux open files limit, but we also exceeded an AWS quota limit)").

text
     Slack, Jan 4 2021 (times PST, from the postmortem)
1    ~6:57   99% of messages sent successfully (normally above 99.999%)
2    7:00    hourly mini-peak + packet loss -> web tier saturated
3    7:0x    CPU falls (threads wait on the network) -> autoscaler scales DOWN
4    7:01-7:15  thread utilisation rises -> attempt to add 1,200 servers
5    7:xx    provision-service hits the open files limit and an AWS quota
6    8:15    provision-service back; 9:15 enough hosts to serve; 10:40 TGW capacity raised by AWS

Fix / how to use it: scale on saturation (worker utilisation, queue age) rather than CPU alone for I/O-bound tiers; keep enough static headroom for the loss of a zone; load-test the scaling path itself; disable scale-in during incidents; pre-scale for known events (Slack: "request a preemptive upscaling of our TGWs at the end of the next holiday season"). See Scaling Strategies.

Synchronized load: cron, DNS TTL and leader thrash Good to know ​

In plain words: independent clients end up doing the same thing at the same second because a clock, a timer or a shared event lines them up.

Common misunderstanding: "Random arrivals average out." Arrivals are random only until something aligns them: the top of the hour, a shared TTL, a restart, a config push.

Definition: Google SRE: if retries "aren't randomly distributed over the retry window, a small perturbation (e.g., a network blip) can cause retry ripples to schedule at the same time, which can then amplify themselves" (citing Floyd and Jacobson). Variants: synchronized cron (Slack: "mini-peaks at the top of each hour and half hour ... much of this is external — cronjobs from all over the world"), DNS records with the same TTL expiring together after a failover, and leader thrash, where a leader election under load keeps moving leadership and each move triggers reconnects and cache rebuilds (Leader Election).

text
     Clients: 10,000, all with retry after exactly 1 s, network blip at t = 0
1    t=0.0   10,000 requests fail together
2    t=1.0   10,000 retries arrive in the same 10 ms
3    t=1.0   overload -> most fail again
4    t=2.0   10,000 retries again (the wave sustains itself)
5    full jitter: retries spread over 0-1 s, then 0-2 s: about 10 per ms instead of 1,000

Fix / how to use it: jitter every schedule (backoff, cron start offsets, TTLs, health-check intervals, cache refresh), randomize client start-up, stagger deploys and leader leases, and pre-scale for known peaks. In the simulator, health checks are already staggered per server; the naive run still shows retry waves every 8 seconds because timeouts, restarts and immediate retries line up.

Triggers: query of death, rollouts, drains, organic growth Important ​

In plain words: the thing that tips a vulnerable system over. It is usually small, often a change, sometimes just growth.

Common misunderstanding: "Find the trigger, fix it, done." The trigger is necessary to explain the timing but the loop explains the size. Both need action items.

Definition: Google SRE's triggering conditions: process death (including a query of death, "an RPC whose contents trigger a failure in the process"), process updates, new rollouts, organic growth, planned changes, drains or turndowns, request profile changes, and resource limits (relying on slack CPU in a shared cluster is "dangerous").

TriggerPublic exampleLoop it started
Operator command with a wrong inputAWS S3 2017: "a larger set of servers was removed than intended"Full restart of index and placement subsystems
Global config pushCloudflare 2019: a WAF rule deployed through Quicksilver "went global in seconds"CPU exhaustion on every HTTP core
Network partition, 43 sGitHub 2018Automated cross-region failover, then replication backlog
Seasonal traffic + cloud network saturationSlack 2021Autoscaling and provisioning feedback
Automation acting on a wrong metricGoogle 2020: quota reduced because usage "incorrectly reported ... as 0"Paxos leader could not write; authentication failed

Fix / how to use it: canary and stage every change including configuration (Cloudflare's WAF bypassed its own staged DOG, PIG, Canary process "because of the need to respond rapidly to threats"); add rate limits to tools that remove capacity; keep change logs so "check for recent changes and consider reverting them" is fast.

Deadlines, deadline propagation and cancellation Must-know ​

In plain words: decide once, at the top, how long the user will wait; pass the remaining time to everyone below; and stop working on anything whose time is up.

Common misunderstanding: "Long timeouts are safer because fewer requests fail." Long timeouts keep doomed work alive and hold resources; Google SRE: "Having deadlines several orders of magnitude longer than the mean request latency is usually bad."

Definition: a deadline is the absolute time after which a result is worthless. Deadline propagation: "a deadline is set high in the stack (e.g., in the frontend). The tree of RPCs emanating from an initial request will all have the same absolute deadline." Cancellation propagation sends "fatal errors or timeouts up the stack" and cancels sibling RPCs. Servers should check the deadline before each stage: "you don't get credit for late assignments with RPCs."

text
     Without propagation (Google SRE)              With propagation
1    A -> B, deadline 10 s                         A -> B, deadline 10 s
2    B starts after 8 s, calls C with 20 s          B starts after 8 s, calls C with 2 s
3    C dequeues after 5 s, works "with 15 s left"  C dequeues after 5 s: deadline passed, drops it
4    A gave up 3 s ago: C's work is wasted         C's worker is free for a live request

What provides it:

ProductPrimitivePropagates across hops?
gRPCDeadline, grpc-timeout headerYes, when the incoming context is reused
Gocontext.WithTimeout, context.WithDeadline, context.AfterFunc; DeadlineExceededIn-process yes; across HTTP you stamp a header (Go)
LaravelHttp::timeout() per callNo; this page's middleware stores deadline_at
EnvoyRoute timeout, per_try_timeout, x-envoy-expected-rq-timeout-msInside the mesh
PostgreSQLstatement_timeout, transaction_timeoutSet per session from the application

Fix / how to use it: the edge sets one budget; each hop sends remaining − margin and caps it by what the callee needs; servers drop expired work before starting it. The full mechanics (headers, gRPC, budgets) are in Latency Budgets and Timeouts, Retries & Jitter.

Retry budgets and jitter Must-know ​

In plain words: allow retries only as a small fraction of normal traffic, and spread them out randomly so they do not arrive together.

Common misunderstanding: "Exponential backoff is enough." Backoff without jitter keeps clients synchronized (AWS: "there are still clusters of calls"), and backoff per request does nothing about the total retry volume of a million requests.

Definition: a retry budget caps retries per client or per process: Google SRE uses "a per-request retry budget of up to three attempts" and "a per-client retry budget ... A request will only be retried as long as this ratio is below 10%", which reduces worst-case growth from "just below 3X" to "just 1.1x". Jitter randomizes the delay; AWS's Full Jitter is sleep = random_between(0, min(cap, base * 2 ** attempt)), and of the variants, "Equal Jitter" is "the loser".

text
     Overloaded backend, every first attempt fails; client sends 1,000 requests/s
1    No limits, 3 retries:            up to 4,000 attempts/s
2    Per-request cap only (3 tries):  just below 3,000 attempts/s
3    + per-client budget 10%:         about 1,100 attempts/s
4    Simulator, 30-60 s: naive 3.50x, naive + budget 1.08x, protected 1.01x

Fix / how to use it: resilience.RetryBudget and resilience.FullJitter in Go; App\Support\RetryBudget with Http::retry in Laravel. Budgets per dependency, shared across goroutines or PHP workers, exported as metrics (granted vs denied).

Load shedding, admission control, bounded queues and backpressure Must-know ​

In plain words: when you are full, say no immediately and cheaply to some requests, so you can say yes properly to the rest.

Common misunderstanding: "Rejecting requests lowers availability." Rejecting 20% keeps 80% fast; accepting 100% can serve 0%. AWS: "Load shedding lets a server maintain its goodput and complete as many requests as it can, even as offered throughput increases."

Definition: load shedding drops excess load as a server approaches overload; Google SRE: "return an HTTP 503 (service unavailable) to any incoming request when there are more than a given number of client requests in flight". Admission control is the decision point (limit on in-flight work, token bucket, utilisation threshold). Backpressure propagates "slow down" upstream instead of buffering (bounded channels, TCP windows, Kafka consumer lag, RabbitMQ flow control). Client-side throttling (Google's adaptive throttling) lets clients reject locally once requests exceeds K × accepts over two minutes.

text
     Simulator, spike 2,600/s against 2,000/s capacity (per second)
1    Naive:     accepts all 2,600 -> queue grows -> 1,955, 1,838 ... 765, 0 good
2    Protected: about 2,860 attempts, about 870 shed with a fast 503, about 1,990 good
3    After the spike: protected 1,400 good from the first second; naive never recovers

What provides it:

ProductMechanism
EnvoyCircuit breakers (max_connections, max_pending_requests, max_requests, max_retries); overflow counters
NGINXlimit_req, limit_conn; max_conns per upstream server
HAProxymaxconn per frontend and server with a queue and timeout queue
KafkaConsumer pull model, max.poll.records; backpressure is consumer lag
GoSemaphore / buffered channel admission (Go)
Laravelthrottle rate limiter, queue-time shedding middleware, queue RateLimited job middleware

Fix / how to use it: shed at the edge for global overload and in each process for local overload; make the rejection path cost almost nothing (no logging per rejection, no database call); prioritise by criticality. Algorithms in Load Shedding and Rate Limiting; broker-side flow control in Backpressure & Flow Control.

Circuit breakers, bulkheads, dependency isolation and fail fast Important ​

In plain words: keep one bad dependency from using up everything: give it a fixed share of threads and connections (bulkhead), stop calling it when it is clearly failing (circuit breaker), and say "no" quickly instead of waiting (fail fast).

Common misunderstanding: "A circuit breaker solves cascades by itself." It stops calls to one dependency, but AWS warns that breakers "introduce modal behavior into systems that can be difficult to test, and can introduce significant addition time to recovery"; AWS prefers a local retry token bucket. Breakers help most for dependencies that fail hard; bulkheads help for dependencies that fail slow.

Definition: dependency isolation means one dependency's failure cannot exhaust shared resources. A bulkhead partitions resources (pools per dependency, per tenant, per criticality); Google SRE suggests limiting "25% of your threads" per client for fairness. A circuit breaker tracks failures and short-circuits calls while open. Fail fast: "if a backend is unavailable, it's usually best to immediately return an error for that backend, rather than consuming resources until the backend is available." Also always go downward in the stack (a Google SRE section title): avoid intra-layer calls, which can create distributed deadlocks.

text
     Product page calls: inventory (critical), recommendations (optional), reviews (optional)
1    Shared pool of 200 threads, recommendations hangs: all 200 wait -> page down
2    Bulkheads: inventory 120, recommendations 40, reviews 40
3    Recommendations hangs: its 40 are busy, its calls fail fast; page renders without it
4    Breaker opens after N failures: calls skipped for 30 s, then a probe request

Fix / how to use it: Bulkhead channel in resilience.Client; Envoy circuit breakers per cluster; Laravel ThrottlesExceptions job middleware as a breaker for queued work. Patterns in depth: Circuit Breaker, Bulkheads & Graceful Degradation.

Graceful degradation and criticality Important ​

In plain words: when capacity is short, do less per request (fewer features, cached answers, cheaper ranking) and drop the requests that matter least first.

Common misunderstanding: "Degraded mode is a nice-to-have we can add later." It has to be built and exercised: "the code path you never use is the code path that (often) doesn't work."

Definition: Google SRE: "Graceful degradation takes the concept of load shedding one step further by reducing the amount of work that needs to be performed." Criticality labels requests (Google uses CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLE), propagated automatically to downstream calls, so an overloaded backend rejects lower criticalities first.

text
     Capacity        Product page behaviour
1    100%            full page: stock, price, reviews, recommendations, images
2    80%             recommendations from a precomputed list; reviews cached
3    60%             no reviews, no recommendations; stock "estimate" from the last good value
4    40%             static page from CDN, checkout only for logged-in users with a cart

Fix / how to use it: decide per feature what "degraded" means, wire a switch that is fast to flip and slow to break, and run a small slice of servers near overload regularly to keep the code path alive. The Go example serves a stale copy with X-Degraded; the Laravel example returns stock_is_estimate. Patterns in Bulkheads & Graceful Degradation.

Capacity headroom and load testing to the knee Important ​

In plain words: keep enough spare capacity to lose your biggest failure domain at peak, and know (from tests, not hopes) where your system breaks and how it behaves past that point.

Common misunderstanding: "Capacity planning prevents cascades." Google SRE: it "reduces the probability of triggering a cascading failure, but it is not sufficient to protect the service from cascading failures."

Definition: headroom is capacity minus peak load. Google SRE's example: breaking point 5,000 QPS per cluster, peak 19,000 QPS, "approximately six clusters are needed to run the service at N + 2". A load test to the knee raises load until goodput stops tracking it, then keeps going: "Load test components until they break", test "both gradual and impulse load patterns", and test the return to normal ("If a couple of servers crash under heavy load, how much does the load need to drop in order for the system to stabilize?").

text
     Peak 19,000 QPS, break point 5,000 QPS per cluster
1    N = 4 clusters: 20,000 capacity, 95% utilisation, one cluster loss = 15,000 -> cascade
2    N + 1 = 5: one loss leaves 20,000 -> survives, barely
3    N + 2 = 6: one loss during maintenance of another leaves 20,000 -> survives
4    Load test result to look for: goodput flat at the knee (AWS), not a cliff

Fix / how to use it: run the Lab shape against staging and a small production slice (Google SRE lists "Reducing task counts quickly or slowly", "Rapidly losing a cluster's worth of capacity", "Blackholing various backends"); test noncritical backends that never respond; capacity method in Capacity Estimation and Capacity Planning; fault injection in Chaos Engineering.

Request hedging and its limits Good to know ​

In plain words: send a second copy of a slow request to another replica and take whichever answers first. Good for tail latency on a healthy fleet; dangerous on an overloaded one.

Common misunderstanding: "Hedging makes us more resilient." It adds load. When the whole fleet is slow because it is overloaded, hedges are retries by another name.

Definition: a hedged request is a duplicate sent after a delay (about p95); Google SRE notes it requires cancellation propagation so that the losers stop. Safe only with a load budget (for example 5% extra) and only for idempotent reads; turn it off when saturation is high.

text
     Healthy fleet, one slow replica         Overloaded fleet
1    p95 delay passes, hedge to replica B    p95 delay passes, hedge to replica B
2    B answers in 10 ms, A cancelled          B is also saturated; now two copies queue
3    tail latency improves, load +2%          load +100% on the slowest requests: amplification

Fix / how to use it: cap hedges with a token bucket, disable them when the retry budget is exhausted, cancel losers. Details in Latency Budgets.

Detection: four golden signals, saturation, latency SLO burn, error ratio Must-know ​

In plain words: watch how slow, how much, how many failures, and how full; full is the one that warns you before the others go red.

Common misunderstanding: "Error rate is the first signal." In a cascade, latency and saturation move first; errors arrive when deadlines start expiring, and by then the loop is closing.

Definition: Google SRE: "The four golden signals of monitoring are latency, traffic, errors, and saturation." Track error latency separately ("a slow error is even worse than a fast error"). Saturation: "Latency increases are often a leading indicator of saturation. Measuring your 99th percentile response time over some small window (e.g., one minute) can give a very early signal of saturation." Latency SLO burn is the rate at which slow requests consume the error budget (SLAs, SLOs, SLIs & Error Budgets); error ratio is errors / requests (and retries / requests, which is the retry-storm detector).

SignalMetricCascade meaning
Latencyp99 per route, separate for errorsQueueing has started
TrafficRequests/s, and attempts/s vs first attempts/sRetry amplification above about 1.1 is an alarm
Errors5xx ratio, 503 shed ratio, timeoutsDeadlines expiring; shedding engaged
SaturationIn-flight / limit, queue depth and queue age, pool usage, FD count, GC timeThe loop's input, before errors
CapacityHealthy hosts, ejections, restarts, CrashLoopBackOffCapacity removal in progress
text
     Typical order in a cascade (watch for it on dashboards)
1    saturation: queue age 0.1 s -> 2 s
2    latency: p99 300 ms -> 5 s
3    traffic: attempts/s 1.0x -> 3x first attempts (retries)
4    errors: timeouts, then 5xx; shed 503s if protected
5    capacity: health-check failures, restarts, ejections

Fix / how to use it: alert on SLO burn rate and on saturation, export retry-budget denials and shed counts, and keep monitoring independent of the system it watches (Slack's dashboards depended on the same Transit Gateways; AWS's status dashboard depended on S3). See Observability and Alerting That Works.

Recovery: shed load, reduce retries, scale, restart with slow start, block at the edge Must-know ​

In plain words: first stop the loop, then fix the trigger, then let traffic back in slowly. Doing these in the wrong order restarts the cascade.

Common misunderstanding: "Restart everything." A simultaneous restart produces a thundering herd on restart: every server comes back cold at the same moment and receives full traffic. In the simulator, letting 100% back in at once after the shed re-collapsed the system (goodput 8.1%, then 4.9%).

Definition: Google SRE's immediate steps: increase resources (may not be enough in a death spiral), stop health check failures/deaths, restart servers (only for GC death spirals, deadlocks, requests without deadlines; "Canary this change, and make it slowly"), drop traffic ("Reducing load enough so that the crashing stops ... Gradually ramping up the load"), enter degraded modes, eliminate batch load, eliminate bad traffic. Slow start lets a load balancer ramp traffic to newly healthy hosts (AWS ALB: "linearly increases the number of requests"; Envoy slow start mode). Gradual recovery is the whole ramp, including queued backlog.

text
     Simulator: naive system collapsed; one action at 40 s (goodput by window)
1    do nothing                          30-40 s 4.6%   40-50 s 9.0%    50-70 s 5.4%    70-90 s 6.7%
2    scale out +50% (5 cold servers)     4.6%           15.2%           8.2%            7.9%
3    edge 10% for 10 s, ramp over 20 s   4.6%           4.8%            54.6%           100.0%
4    edge 10% for 10 s, then 100%        4.6%           4.8%            8.1%            4.9%

Real scenario: Cloudflare's global terminate of the WAF, then re-enabling after tests "in a single city using a subset of traffic"; GitHub pausing webhooks and Pages builds, then processing the backlog while watching partners' load (and discovering TTL-expired payloads); Google Workspace services with "a traffic spike following initial recovery".

Fix / how to use it: the runbook order is in Solving the classic problems. Keep edge blocking rules ready (Cloudflare, AWS WAF, NGINX limit_req), keep a switch to disable retries and batch work, and configure slow start on load balancers.

Postmortems: blameless, focused on loops Important ​

In plain words: after the incident, write down what happened and why the system allowed it to grow, without blaming the person who pressed the button.

Common misunderstanding: "Root cause: human error." In each case study below a person or a tool made a small mistake; the outage was the size of the loops the system had.

Definition: Google SRE: "For a postmortem to be truly blameless, it must focus on identifying the contributing causes of the incident without indicting any individual or team for bad or inappropriate behavior." Cloudflare's 2019 postmortem is a model: "Getting to a single root cause, while satisfying, may obscure the reality", followed by a list of the vulnerabilities that converged.

text
     Postmortem sections that matter for cascades
1    Trigger and timeline (with times from the incident channel)
2    Sustaining effect: which loop kept it down, and how long after the trigger
3    Detection: which signal moved first, which alert fired, how late
4    Recovery: what broke the loop, what re-triggered it
5    Action items per loop: breaker, test, alert, runbook

Fix / how to use it: a template with a "feedback loops" section; action items that include a load test past the knee; process in Secure SDLC & Incident Response.

Case studies from public postmortems ​

Only facts from the companies' own postmortems are stated as facts; anything else is labelled inference.

AWS S3, us-east-1, February 28, 2017 (S3 2017) ​

AspectFrom the AWS summary
TriggerAt 9:37AM PST a command "intended to remove a small number of servers" for the billing subsystem; "one of the inputs to the command was entered incorrectly and a larger set of servers was removed than intended"
What depended on itThe index subsystem ("necessary to serve all GET, LIST, PUT, and DELETE requests") and the placement subsystem
Amplifier"Removing a significant portion of the capacity caused each of these systems to require a full restart"; "we have not completely restarted the index subsystem or the placement subsystem in our larger regions for many years"
Blast radiusS3 console, EC2 new instance launches, EBS volumes needing S3 snapshots, AWS Lambda; the Service Health Dashboard could not be updated "because of a dependency the SHD administration console has on Amazon S3"
RecoveryGET, LIST, DELETE from 12:26PM; fully by 1:18PM; PUT at 1:54PM; other services had "accumulated a backlog of work"
FixesTool removes capacity "more slowly" with "safeguards to prevent capacity from being removed when it will take any subsystem below its minimum required capacity level"; faster recovery through "cells"

Loop on this page: capacity removal and cold, slow restart (death spiral). Inference: the multi-hour recovery is the cost of a restart path that had not been exercised at that scale, which is exactly what load tests "until failure and beyond" exercise.

Cloudflare, July 2, 2019 (Cloudflare 2019) ​

AspectFrom the Cloudflare postmortem
TriggerAt 13:42 a WAF Managed Rules change for XSS detection; a regular expression "that backtracked enormously and exhausted CPU used for HTTP/HTTPS serving"
Why it was globalRules are deployed through Quicksilver, which "can push changes globally in seconds"; the rule was in "simulate" mode but "the rules actually need to execute"
Missing breaker"A protection that would have helped prevent excessive CPU use by a regular expression was removed by mistake during a refactoring of the WAF weeks prior"
User impact502 errors from front-line servers "unable to reach the processes that serve HTTP/HTTPS traffic"; outage of 27 minutes
RecoveryGlobal WAF termination at 14:07; traffic and CPU normal at 14:09; slowed because "with our Access service down we couldn't authenticate to our internal control panel"
FixesRe-introduce the CPU protection, inspect all 3,868 rules, move to re2 or the Rust regex engine "which both have run-time guarantees"

Loop on this page: CPU exhaustion with no deadline on a single operation, plus a recovery path that depended on the failing system. Inference: a per-request CPU budget is the regex equivalent of a deadline.

GitHub, October 21, 2018 (GitHub 2018) ​

AspectFrom the GitHub post-incident analysis
TriggerAt 22:52 UTC, optical equipment maintenance cut East Coast hub to data centre connectivity; "restored in 43 seconds"
AutomationOrchestrator (on Raft) failed clusters over to the US West Coast; afterwards "we were unable to fail the primary back over to the US East Coast data center safely"
AmplifierCross-country latency for writes; replicas "multiple hours delayed"; replication catch-up "adhered to a power decay function instead of a linear trajectory" as users woke up
Degradation by choice"pausing webhook delivery and GitHub Pages builds"; "prioritize data integrity over site usability and time to recovery"
Backlog recovery"over five million hook events and 80 thousand Pages builds queued"; "~200,000 webhook payloads that had outlived an internal TTL and were dropped"
Duration and fixes"24 hours and 11 minutes of service degradation"; configure Orchestrator "to prevent the promotion of database primaries across regional boundaries"

Loop on this page: automation that moved capacity (capacity removal) and gradual recovery of a backlog. Inference: the backlog phase is a second, smaller overload risk; GitHub explicitly balanced it against "potentially overloading our ecosystem partners with notifications".

Slack, January 4, 2021 (Slack 2021) ​

AspectFrom Slack's postmortem
Trigger"one of our Transit Gateways became overloaded"; first working day of the year, "client caches are cold"
SaturationMini-peak at 7am PST plus packet loss "led to saturation of our web tier"
Wrong-way automationInstances "marked unhealthy" because they could not reach backends; CPU dropped and "triggered some automated downscaling"; then an attempt "to add 1,200 servers" between 7:01 and 7:15am PST
The scaler's own exhaustionprovision-service hit "the Linux open files limit" and "an AWS quota limit"; broken instances hit "autoscaling-group size limits"
What helpedLoad balancers' "panic mode" plus "retries and circuit breaking"; by 9:15am PST "degraded, not down"
FixesAWS increased TGW capacity manually (by 10:40am PST); monitoring moved into the same VPC as its database; load test provision-service; preemptive TGW upscaling after holidays

Loop on this page: autoscaler lag, health check flapping, file descriptor exhaustion and a monitoring dependency on the failing component (detection).

Google, December 14, 2020 (Google 2020, incident 20013) ​

AspectFrom the Google Cloud incident report
TriggerA quota migration left parts of the old system that "incorrectly reported the usage for the User ID Service as 0"; after a grace period, automation decreased its quota
Mechanism"the quota for the account database was reduced, which prevented the Paxos leader from writing. Shortly after, the majority of read operations became outdated which resulted in errors on authentication lookups"
Missing safety checkExisting checks "did not cover the scenario of zero reported load for a single service"
Impact47 minutes; "credential issuance and account metadata lookups for all Google user accounts failed"; "5xx errors on virtually all authenticated traffic"
Recovery tailCalendar and Workspace Admin "served errors up to 05:21 due to a traffic spike following initial recovery"; Gmail errors "due to caching of errors from identity services"
Fixes"prevent fast implementation of global changes"; "Improve resilience of GCP Services to more strictly limit the impact to the data plane during User ID Service failures"

Loop on this page: a shared dependency (dependency isolation) plus a thundering herd on recovery. Inference: caching errors from a dependency extended the outage after the dependency was healthy, the inverse of a stale-while-revalidate fallback.

Mechanics ​

The arithmetic of a cascade ​

QuantityFormulaExample
Busy workers (Little's law)arrival rate × time in system1,000 QPS × 0.1 s = 100 threads (Google SRE)
Workers needed when a share hangsrate × (share × deadline + (1 − share) × latency)1,000 × (0.05 × 100 + 0.95 × 0.1) = 5,095
Share served with W workersW / workers needed1,000 / 5,095 = 19.6%
Queueing delayqueue depth × service time / workers80 × 100 ms / 8 = 1 s
Retry amplification, k layers, a attempts eacha^k4^3 = 64; 3^5 = 243
Budgeted retry overhead1 + ratio1.1x with a 10% budget
Recovery load after collapsenormal load × healthy share10,000 QPS with 10% healthy: about 1,000 QPS (Google SRE)
Headroom for N + 2ceil(peak / break point) + 2ceil(19,000 / 5,000) + 2 = 6 clusters

Knobs that decide whether a loop closes ​

ProductKnobDefault / noteLoop it controls
Go net/httpClient.Timeout, Transport.ResponseHeaderTimeout, DialContext timeout0 = noneSlow dependency
Go net/httpTransport.MaxConnsPerHost, MaxIdleConnsPerHost0 = unlimited; idle default 2Connection and port exhaustion
Go net/httpServer.ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout0 = noneSlow clients pin goroutines
Laravel HTTP clienttimeout(), connectTimeout(), retry()30 s, 10 sSlow dependency, retries
Laravel queue worker--timeout, --memory, --max-jobs, --max-time, --tries, retry_aftertimeout 60 s; memory 128 MB; timeout below retry_afterStuck jobs, leaks, double processing
Laravel Octane--workers, --task-workers, --max-requestsone worker per CPU core; restart after 500 requestsMemory leaks, worker exhaustion
PHP-FPMpm.max_children, listen.backlog, request_terminate_timeoutbacklog 511 on Linux; terminate 0 (off)Worker exhaustion, queueing
NGINXproxy_connect_timeout, proxy_read_timeout, proxy_next_upstream_tries60s, 60s, 0 (unlimited)Slow upstreams, proxy retries
EnvoyCircuit breakers: max_connections, max_pending_requests, max_requests, max_retries"modest default values, e.g. 1024 connections"Pools, queues, retries
EnvoyPanic threshold, max_ejection_percent, slow startpanic 50%Capacity removal, cold hosts
gRPCretryPolicy.maxAttempts, retryThrottling.maxTokens/tokenRatio, deadlinesexample: 10 tokens, ratio 0.1Retry storms
KuberneteslivenessProbe, readinessProbe, startupProbe, timeoutSecondstimeout 1sHealth-check kills
AWS ALBslow_start.duration_seconds, health check thresholdsslow start off by defaultCold hosts after recovery
PostgreSQLstatement_timeout, lock_timeout, idle_in_transaction_session_timeout, transaction_timeout, max_connectionstimeouts 0 = disabledSlow queries holding pool slots
Linuxulimit -n, net.ipv4.ip_local_port_range, net.core.somaxconndistribution defaultsFD, port, backlog exhaustion

Error messages you will actually see ​

SourceMessage / codeMeaning in a cascade
Gocontext deadline exceeded (context.DeadlineExceeded)A deadline expired; do not retry if it was the caller's
LaravelIlluminate\Http\Client\ConnectionException (cURL error 28)timeout() or connectTimeout() exceeded
HTTP503 Service Unavailable with Retry-AfterDeliberate shedding: back off
HTTP429 Too Many RequestsRate limit: do not retry at this layer
NGINXupstream timed out (110: Connection timed out) while reading response header from upstreamproxy_read_timeout hit; a slow upstream
NGINX502 Bad GatewayUpstream refused or reset (Cloudflare 2019 users saw 502s)
PHP-FPMserver reached pm.max_children settingWorker exhaustion; requests now wait in the backlog
LinuxEMFILE "Too many open files"; EADDRNOTAVAIL "Cannot assign requested address"FD exhaustion; ephemeral port exhaustion
PostgreSQLSQLSTATE 53300 too_many_connections ("sorry, too many clients already")Connection exhaustion
PostgreSQLSQLSTATE 57014 query_canceled ("canceling statement due to statement timeout")A database-side deadline worked
EnvoyCounters upstream_rq_pending_overflow, upstream_rq_retry_overflow, upstream_cx_overflowCircuit breakers shedding
KubernetesLiveness probe failed, CrashLoopBackOffCapacity removal by the kubelet

Go ​

The module academy/cascading-failures uses only the standard library. resilience holds the defences; spiral is the simulator; cmd/spiral prints the tables on this page; before and after are a service before and after the fixes.

Before ​

The SRE book's naive retry loop in net/http form: http.DefaultClient with no timeout, ten immediate retries, no admission control, a deep health check and a server without timeouts.

go
// Command before is the service most cascades start from. Every line is
// common and looks harmless; together they build the death spiral.
package main

import (
	"io"
	"log"
	"net/http"
)

const inventory = "http://inventory.internal/stock" // documentation host

func fetchStock() ([]byte, error) {
	var lastErr error
	// "Try up to 10 times": the Google SRE book's naive retry example.
	// No backoff, no jitter, no budget: an overloaded inventory service
	// receives up to 10x the traffic exactly when it can serve the least.
	for attempt := 0; attempt < 10; attempt++ {
		// http.Get uses http.DefaultClient: no timeout at all. A slow
		// inventory pins this goroutine, its socket and its memory forever.
		resp, err := http.Get(inventory)
		if err != nil {
			lastErr = err
			continue
		}
		body, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err == nil && resp.StatusCode == http.StatusOK {
			return body, nil
		}
		lastErr = err
	}
	return nil, lastErr
}

func main() {
	// No admission control: net/http starts one goroutine per connection,
	// so the only queue is memory, and it is unbounded.
	http.HandleFunc("/product", func(w http.ResponseWriter, r *http.Request) {
		stock, err := fetchStock() // ignores r.Context(): no deadline propagation
		if err != nil {
			http.Error(w, "inventory down", http.StatusInternalServerError) // 500: clients retry
			return
		}
		_, _ = w.Write(stock)
	})
	// A "deep" health check: if inventory is slow, every product pod fails
	// its liveness probe, Kubernetes restarts them all, and capacity
	// disappears exactly when load is highest.
	http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		if _, err := fetchStock(); err != nil {
			w.WriteHeader(http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})
	// http.ListenAndServe: no ReadHeaderTimeout, no WriteTimeout, no IdleTimeout.
	log.Fatal(http.ListenAndServe(":8080", nil))
}

After ​

Retry budget (token bucket: each request deposits 0.1, each retry costs 1) and full jitter:

go
// Package resilience holds the small building blocks that stop a cascade:
// a retry budget, jittered backoff, deadline propagation, admission control
// (bounded concurrency + bounded queue + load shedding) and health endpoints
// that report saturation without removing capacity.
package resilience

import "sync"

// RetryBudget is a token bucket that caps retries to a fraction of first
// attempts, the shape of gRPC retryThrottling (maxTokens, tokenRatio), the
// AWS SDK retry quota and Google SRE's "per-client retry budget" (10%).
//
// Every first attempt deposits Ratio tokens; every retry withdraws one.
// When the bucket is empty, the caller fails instead of retrying, so the
// extra load created by retries can never exceed about Ratio of the traffic.
type RetryBudget struct {
	mu     sync.Mutex
	tokens float64
	max    float64
	ratio  float64

	retries int64
	denied  int64
}

// NewRetryBudget returns a budget that allows retries worth ratio of first
// attempts (0.1 = 10%), with burst tokens available up front.
func NewRetryBudget(ratio, burst float64) *RetryBudget {
	if burst < 1 {
		burst = 1
	}
	return &RetryBudget{tokens: burst, max: burst, ratio: ratio}
}

// OnRequest records a first attempt and deposits ratio tokens.
func (b *RetryBudget) OnRequest() {
	b.mu.Lock()
	b.tokens += b.ratio
	if b.tokens > b.max {
		b.tokens = b.max
	}
	b.mu.Unlock()
}

// TryRetry withdraws one token. It returns false when the budget is spent:
// the caller must surface the error instead of retrying.
func (b *RetryBudget) TryRetry() bool {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.tokens >= 1 {
		b.tokens--
		b.retries++
		return true
	}
	b.denied++
	return false
}

// Stats reports granted and denied retries (export them as metrics).
func (b *RetryBudget) Stats() (granted, denied int64) {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.retries, b.denied
}
go
package resilience

import (
	"math/rand/v2"
	"time"
)

// FullJitter returns the sleep before retry number attempt (0-based) using
// the "Full Jitter" schedule from the AWS Architecture Blog:
// sleep = random_between(0, min(cap, base * 2^attempt)).
//
// Spreading retries over the whole window is what stops synchronized retry
// waves (a thundering herd) after a blip.
func FullJitter(attempt int, base, maxDelay time.Duration, rnd *rand.Rand) time.Duration {
	if attempt < 0 {
		attempt = 0
	}
	ceiling := maxDelay
	if attempt < 30 { // avoid overflow of the shift
		if d := base << attempt; d > 0 && d < maxDelay {
			ceiling = d
		}
	}
	if ceiling <= 0 {
		return 0
	}
	var n int64
	if rnd != nil {
		n = rnd.Int64N(int64(ceiling))
	} else {
		n = rand.Int64N(int64(ceiling))
	}
	return time.Duration(n)
}

Deadline propagation with a refusal for doomed calls:

go
package resilience

import (
	"context"
	"errors"
	"net/http"
	"strconv"
	"time"
)

// HeaderTimeout carries the caller's remaining budget in milliseconds.
// Relative time, not an absolute timestamp, so clock skew between hosts
// does not matter (gRPC's grpc-timeout header works the same way).
const HeaderTimeout = "Request-Timeout-Ms"

// ErrBudgetExhausted means there is not enough time left to do useful work.
var ErrBudgetExhausted = errors.New("resilience: deadline budget exhausted")

// FromRequest derives the request context from the incoming budget header,
// capped by maxBudget. Without a header the server picks maxBudget itself.
func FromRequest(r *http.Request, maxBudget time.Duration) (context.Context, context.CancelFunc) {
	budget := maxBudget
	if v := r.Header.Get(HeaderTimeout); v != "" {
		if ms, err := strconv.Atoi(v); err == nil && ms >= 0 {
			if d := time.Duration(ms) * time.Millisecond; d < budget {
				budget = d
			}
		}
	}
	return context.WithTimeout(r.Context(), budget)
}

// ForHop returns a child context for one downstream call:
// min(hopCap, remaining - margin). It refuses the call (ErrBudgetExhausted)
// when less than minUseful is left: the callee could not finish in time,
// and starting the call would only add load to an overloaded system.
func ForHop(ctx context.Context, hopCap, margin, minUseful time.Duration) (context.Context, context.CancelFunc, error) {
	timeout := hopCap
	if dl, ok := ctx.Deadline(); ok {
		left := time.Until(dl) - margin
		if left < minUseful {
			return ctx, func() {}, ErrBudgetExhausted
		}
		if left < timeout {
			timeout = left
		}
	}
	c, cancel := context.WithTimeout(ctx, timeout)
	return c, cancel, nil
}

// Stamp writes the remaining budget of ctx into the outgoing request.
func Stamp(req *http.Request) {
	if dl, ok := req.Context().Deadline(); ok {
		ms := time.Until(dl).Milliseconds()
		if ms < 0 {
			ms = 0
		}
		req.Header.Set(HeaderTimeout, strconv.FormatInt(ms, 10))
	}
}

Admission control: bounded concurrency, bounded queue, bounded wait, fast 503 with Retry-After:

go
package resilience

import (
	"context"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

// Admission is admission control for one process: at most MaxInFlight
// requests run, at most MaxQueue wait, and nobody waits longer than MaxWait
// or past its own deadline. Everything else is shed immediately with 503 and
// Retry-After: a fast, cheap "no" instead of a slow "maybe".
//
// It is a bulkhead (a fixed pool that one dependency or client cannot grow),
// a bounded queue and a load shedder in about sixty lines.
type Admission struct {
	slots    chan struct{}
	maxQueue int64
	maxWait  time.Duration

	waiting  atomic.Int64
	shed     atomic.Int64
	admitted atomic.Int64
}

// NewAdmission builds an admission controller. Google SRE suggests a queue of
// 50% of the worker pool or less for steady traffic.
func NewAdmission(maxInFlight, maxQueue int, maxWait time.Duration) *Admission {
	return &Admission{
		slots:    make(chan struct{}, maxInFlight),
		maxQueue: int64(maxQueue),
		maxWait:  maxWait,
	}
}

// Acquire takes a slot or returns false. The caller must call Release once.
func (a *Admission) Acquire(ctx context.Context) bool {
	select {
	case a.slots <- struct{}{}:
		a.admitted.Add(1)
		return true
	default:
	}
	if a.waiting.Add(1) > a.maxQueue {
		a.waiting.Add(-1)
		a.shed.Add(1)
		return false
	}
	defer a.waiting.Add(-1)
	t := time.NewTimer(a.maxWait)
	defer t.Stop()
	select {
	case a.slots <- struct{}{}:
		a.admitted.Add(1)
		return true
	case <-t.C:
	case <-ctx.Done():
	}
	a.shed.Add(1)
	return false
}

// Release frees a slot.
func (a *Admission) Release() { <-a.slots }

// Saturation is in-flight / capacity, the "S" of the four golden signals.
type Saturation struct {
	InFlight int     `json:"in_flight"`
	Capacity int     `json:"capacity"`
	Waiting  int64   `json:"waiting"`
	Shed     int64   `json:"shed_total"`
	Admitted int64   `json:"admitted_total"`
	Ratio    float64 `json:"ratio"`
}

// Stats returns the current saturation.
func (a *Admission) Stats() Saturation {
	in, capacity := len(a.slots), cap(a.slots)
	return Saturation{
		InFlight: in, Capacity: capacity, Waiting: a.waiting.Load(),
		Shed: a.shed.Load(), Admitted: a.admitted.Load(),
		Ratio: float64(in) / float64(capacity),
	}
}

// Middleware sheds load before any expensive work starts.
func (a *Admission) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if !a.Acquire(r.Context()) {
			w.Header().Set("Retry-After", strconv.Itoa(1))
			http.Error(w, "overloaded, retry later", http.StatusServiceUnavailable)
			return
		}
		defer a.Release()
		next.ServeHTTP(w, r)
	})
}

Health that separates liveness from readiness and reports saturation without failing:

go
package resilience

import (
	"encoding/json"
	"net/http"
	"sync/atomic"
)

// Health separates the two questions Google SRE says must not be mixed:
// "is this binary responding at all?" (liveness, for the scheduler) and
// "should the load balancer send traffic now?" (readiness).
//
// Neither depends on downstream dependencies or on momentary saturation:
// a liveness probe that fails under load makes Kubernetes restart busy pods,
// which removes capacity exactly when it is needed (the death spiral).
type Health struct {
	adm      *Admission
	ready    atomic.Bool // set after warm-up (caches, connections)
	draining atomic.Bool // set on SIGTERM
}

// NewHealth wires the probes to the admission controller for reporting.
func NewHealth(adm *Admission) *Health { return &Health{adm: adm} }

// MarkReady ends warm-up; MarkDraining starts graceful shutdown.
func (h *Health) MarkReady()    { h.ready.Store(true) }
func (h *Health) MarkDraining() { h.draining.Store(true) }

// Live answers 200 while the process can run a handler at all.
func (h *Health) Live(w http.ResponseWriter, _ *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("ok\n"))
}

// Ready answers 503 only while warming up or draining. Saturation is
// reported in the body (for dashboards and load-aware balancing) but does
// not flip readiness: shedding happens per request in Admission instead.
func (h *Health) Ready(w http.ResponseWriter, _ *http.Request) {
	body := struct {
		Ready      bool       `json:"ready"`
		Draining   bool       `json:"draining"`
		Saturation Saturation `json:"saturation"`
	}{h.ready.Load(), h.draining.Load(), h.adm.Stats()}
	w.Header().Set("Content-Type", "application/json")
	if !body.Ready || body.Draining {
		w.WriteHeader(http.StatusServiceUnavailable)
	}
	_ = json.NewEncoder(w).Encode(body)
}

A client that cannot start a retry storm (bulkhead, per-hop deadline, budget, jitter, no retry on 429 or 4xx):

go
package resilience

import (
	"context"
	"errors"
	"fmt"
	"io"
	"math/rand/v2"
	"net/http"
	"time"
)

// Client is an HTTP client that cannot start a retry storm: a per-hop
// deadline taken from the caller's budget, at most MaxAttempts per request,
// a shared RetryBudget, full-jitter backoff, no retry on overload signals
// that mean "the whole fleet is busy", and a bounded number of concurrent
// calls (a bulkhead per dependency).
type Client struct {
	HTTP        *http.Client
	Budget      *RetryBudget
	Bulkhead    chan struct{}
	MaxAttempts int
	HopCap      time.Duration
	Margin      time.Duration
	MinUseful   time.Duration
	BackoffBase time.Duration
	BackoffMax  time.Duration
	Rand        *rand.Rand
}

// ErrBulkheadFull is returned when the dependency's pool is exhausted.
var ErrBulkheadFull = errors.New("resilience: bulkhead full")

// Get performs a budgeted GET and returns the body of a 2xx response.
func (c *Client) Get(ctx context.Context, url string) ([]byte, error) {
	select {
	case c.Bulkhead <- struct{}{}:
		defer func() { <-c.Bulkhead }()
	default:
		return nil, ErrBulkheadFull // fail fast instead of queueing threads
	}
	c.Budget.OnRequest()
	var lastErr error
	for attempt := 0; attempt < c.MaxAttempts; attempt++ {
		if attempt > 0 {
			if !c.Budget.TryRetry() {
				return nil, fmt.Errorf("retry budget spent: %w", lastErr)
			}
			sleep := FullJitter(attempt-1, c.BackoffBase, c.BackoffMax, c.Rand)
			select {
			case <-time.After(sleep):
			case <-ctx.Done():
				return nil, ctx.Err()
			}
		}
		body, retry, err := c.once(ctx, url)
		if err == nil {
			return body, nil
		}
		lastErr = err
		if !retry {
			return nil, err
		}
	}
	return nil, lastErr
}

func (c *Client) once(ctx context.Context, url string) (body []byte, retry bool, err error) {
	hop, cancel, err := ForHop(ctx, c.HopCap, c.Margin, c.MinUseful)
	if err != nil {
		return nil, false, err
	}
	defer cancel()
	req, err := http.NewRequestWithContext(hop, http.MethodGet, url, nil)
	if err != nil {
		return nil, false, err
	}
	Stamp(req)
	resp, err := c.HTTP.Do(req)
	if err != nil {
		// The caller's own deadline is gone: retrying cannot help.
		if ctx.Err() != nil {
			return nil, false, ctx.Err()
		}
		return nil, true, err // per-hop timeout or connection error
	}
	defer resp.Body.Close()
	b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
	switch {
	case err != nil:
		return nil, true, err
	case resp.StatusCode >= 200 && resp.StatusCode < 300:
		return b, false, nil
	case resp.StatusCode == http.StatusTooManyRequests:
		// Explicit overload signal: back off, do not retry at this layer.
		return nil, false, fmt.Errorf("upstream throttled: %d", resp.StatusCode)
	case resp.StatusCode >= 500:
		return nil, true, fmt.Errorf("upstream %d", resp.StatusCode)
	default:
		return nil, false, fmt.Errorf("upstream %d", resp.StatusCode) // 4xx never succeeds on retry
	}
}
go
package resilience

import (
	"context"
	"encoding/json"
	"errors"
	"math/rand/v2"
	"net/http"
	"net/http/httptest"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

func TestRetryBudgetCapsRetriesToRatio(t *testing.T) {
	b := NewRetryBudget(0.1, 10)
	granted := 0
	for i := 0; i < 1000; i++ {
		b.OnRequest()
		// every request fails and asks for a retry: the worst case
		if b.TryRetry() {
			granted++
		}
	}
	// 10 burst tokens + 0.1 * 1000 deposits = about 110 retries, not 1000
	if granted < 100 || granted > 111 {
		t.Fatalf("granted %d retries, want about 110", granted)
	}
}

func TestFullJitterStaysInsideWindow(t *testing.T) {
	r := rand.New(rand.NewPCG(1, 2))
	base, maxDelay := 50*time.Millisecond, time.Second
	for attempt := 0; attempt < 8; attempt++ {
		ceiling := base << attempt
		if ceiling > maxDelay {
			ceiling = maxDelay
		}
		for i := 0; i < 200; i++ {
			d := FullJitter(attempt, base, maxDelay, r)
			if d < 0 || d >= ceiling {
				t.Fatalf("attempt %d: %v outside [0,%v)", attempt, d, ceiling)
			}
		}
	}
}

func TestForHopRefusesDoomedCalls(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
	defer cancel()
	if _, _, err := ForHop(ctx, time.Second, 10*time.Millisecond, 40*time.Millisecond); !errors.Is(err, ErrBudgetExhausted) {
		t.Fatalf("want ErrBudgetExhausted, got %v", err)
	}
	ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel2()
	hop, c, err := ForHop(ctx2, 300*time.Millisecond, 10*time.Millisecond, 20*time.Millisecond)
	if err != nil {
		t.Fatal(err)
	}
	defer c()
	dl, _ := hop.Deadline()
	if left := time.Until(dl); left > 300*time.Millisecond {
		t.Fatalf("hop cap not applied: %v left", left)
	}
}

func TestFromRequestHonoursCallerBudget(t *testing.T) {
	r := httptest.NewRequest(http.MethodGet, "/", nil)
	r.Header.Set(HeaderTimeout, "120")
	ctx, cancel := FromRequest(r, 5*time.Second)
	defer cancel()
	dl, ok := ctx.Deadline()
	if !ok || time.Until(dl) > 120*time.Millisecond {
		t.Fatalf("deadline not taken from header")
	}
}

func TestAdmissionShedsBeyondPoolAndQueue(t *testing.T) {
	adm := NewAdmission(2, 1, 50*time.Millisecond)
	release := make(chan struct{})
	h := adm.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		<-release
	}))
	srv := httptest.NewServer(h)
	defer srv.Close()

	var ok, shed atomic.Int64
	var wg sync.WaitGroup
	for i := 0; i < 6; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, err := http.Get(srv.URL)
			if err != nil {
				t.Error(err)
				return
			}
			resp.Body.Close()
			if resp.StatusCode == http.StatusServiceUnavailable {
				if resp.Header.Get("Retry-After") == "" {
					t.Error("503 without Retry-After")
				}
				shed.Add(1)
			} else {
				ok.Add(1)
			}
		}()
	}
	time.Sleep(150 * time.Millisecond) // the waiting one times out after 50 ms
	close(release)
	wg.Wait()
	if ok.Load() != 2 || shed.Load() != 4 {
		t.Fatalf("ok=%d shed=%d, want 2 and 4", ok.Load(), shed.Load())
	}
}

func TestReadinessReportsSaturationButStaysReady(t *testing.T) {
	adm := NewAdmission(4, 2, time.Millisecond)
	h := NewHealth(adm)
	rec := httptest.NewRecorder()
	h.Ready(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
	if rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("not warmed up yet: want 503, got %d", rec.Code)
	}
	h.MarkReady()
	for i := 0; i < 4; i++ { // fully saturated
		adm.Acquire(context.Background())
	}
	rec = httptest.NewRecorder()
	h.Ready(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
	var body struct {
		Saturation Saturation `json:"saturation"`
	}
	if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
		t.Fatal(err)
	}
	if rec.Code != http.StatusOK || body.Saturation.Ratio != 1 {
		t.Fatalf("saturated pod must stay ready and report ratio 1: code=%d ratio=%v", rec.Code, body.Saturation.Ratio)
	}
	h.MarkDraining()
	rec = httptest.NewRecorder()
	h.Ready(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
	if rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("draining: want 503, got %d", rec.Code)
	}
}

func TestClientStopsRetryingWhenBudgetIsSpent(t *testing.T) {
	var hits atomic.Int64
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		hits.Add(1)
		http.Error(w, "boom", http.StatusInternalServerError)
	}))
	defer srv.Close()
	c := &Client{
		HTTP: srv.Client(), Budget: NewRetryBudget(0.1, 2), Bulkhead: make(chan struct{}, 8),
		MaxAttempts: 3, HopCap: time.Second, Margin: time.Millisecond, MinUseful: time.Millisecond,
		BackoffBase: time.Millisecond, BackoffMax: 5 * time.Millisecond, Rand: rand.New(rand.NewPCG(3, 4)),
	}
	for i := 0; i < 50; i++ {
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		if _, err := c.Get(ctx, srv.URL); err == nil {
			t.Fatal("expected error")
		}
		cancel()
	}
	// naive client: 50 * 3 = 150 hits; budgeted: 50 + 2 burst + 50*0.1 = about 57
	if n := hits.Load(); n > 60 {
		t.Fatalf("%d upstream hits: retry budget did not cap amplification", n)
	}
}

func TestClientDoesNotRetry429(t *testing.T) {
	var hits atomic.Int64
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		hits.Add(1)
		w.WriteHeader(http.StatusTooManyRequests)
	}))
	defer srv.Close()
	c := &Client{HTTP: srv.Client(), Budget: NewRetryBudget(1, 10), Bulkhead: make(chan struct{}, 1),
		MaxAttempts: 3, HopCap: time.Second, Margin: time.Millisecond, MinUseful: time.Millisecond,
		BackoffBase: time.Millisecond, BackoffMax: time.Millisecond}
	_, _ = c.Get(context.Background(), srv.URL)
	if hits.Load() != 1 {
		t.Fatalf("429 retried %d times", hits.Load()-1)
	}
}

The service, fixed:

go
// Command after is the same service with the cheap defences that stop a
// cascade: server timeouts, admission control (bounded concurrency, bounded
// queue, fast 503), deadline propagation, a retry budget with full jitter,
// a bulkhead and connection cap per dependency, graceful degradation from a
// stale copy, liveness separated from readiness, warm-up before readiness,
// and draining on shutdown.
package main

import (
	"context"
	"errors"
	"log"
	"math/rand/v2"
	"net"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"academy/cascading-failures/resilience"
)

const inventory = "http://inventory.internal/stock" // documentation host

// staleCache keeps the last good answer for graceful degradation.
type staleCache struct {
	mu   sync.RWMutex
	body []byte
	at   time.Time
}

func (c *staleCache) put(b []byte) { c.mu.Lock(); c.body, c.at = b, time.Now(); c.mu.Unlock() }
func (c *staleCache) get() ([]byte, time.Time) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.body, c.at
}

func main() {
	transport := &http.Transport{
		DialContext:           (&net.Dialer{Timeout: 200 * time.Millisecond}).DialContext,
		MaxConnsPerHost:       64, // bounded connection pool per dependency
		MaxIdleConnsPerHost:   64, // default is 2: churn costs handshakes and ports
		IdleConnTimeout:       90 * time.Second,
		ResponseHeaderTimeout: 800 * time.Millisecond,
	}
	inv := &resilience.Client{
		HTTP:        &http.Client{Transport: transport}, // per-call deadlines come from ctx
		Budget:      resilience.NewRetryBudget(0.1, 10), // retries <= ~10% of calls
		Bulkhead:    make(chan struct{}, 64),            // inventory can hold at most 64 goroutines
		MaxAttempts: 3,
		HopCap:      300 * time.Millisecond, // about the callee's p99.9
		Margin:      20 * time.Millisecond,
		MinUseful:   30 * time.Millisecond, // about the callee's p50: less is doomed
		BackoffBase: 25 * time.Millisecond,
		BackoffMax:  250 * time.Millisecond,
		Rand:        rand.New(rand.NewPCG(uint64(time.Now().UnixNano()), 1)),
	}
	stale := &staleCache{}
	adm := resilience.NewAdmission(256, 128, 100*time.Millisecond) // queue = 50% of the pool
	health := resilience.NewHealth(adm)

	mux := http.NewServeMux()
	mux.Handle("GET /product", adm.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := resilience.FromRequest(r, time.Second) // caller's budget, capped at 1 s
		defer cancel()
		body, err := inv.Get(ctx, inventory)
		if err == nil {
			stale.put(body)
			_, _ = w.Write(body)
			return
		}
		if b, at := stale.get(); b != nil && time.Since(at) < 10*time.Minute {
			// graceful degradation: an older answer beats an error page
			w.Header().Set("X-Degraded", "stale-inventory")
			_, _ = w.Write(b)
			return
		}
		// overload is a 503 with Retry-After, not a 500 that invites retries
		log.Printf("product: degraded, no stale copy: %v", err)
		w.Header().Set("Retry-After", "1")
		http.Error(w, "inventory unavailable", http.StatusServiceUnavailable)
	})))
	mux.HandleFunc("GET /livez", health.Live)   // Kubernetes livenessProbe
	mux.HandleFunc("GET /readyz", health.Ready) // Kubernetes readinessProbe / LB health check

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 2 * time.Second, // slow clients cannot pin goroutines
		ReadTimeout:       5 * time.Second,
		WriteTimeout:      5 * time.Second,
		IdleTimeout:       60 * time.Second,
	}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()
	go func() {
		warmUp(ctx, inv, stale) // fill caches and connection pools before taking traffic
		health.MarkReady()
	}()
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	<-ctx.Done()
	health.MarkDraining() // readiness fails first so the LB stops sending
	time.Sleep(5 * time.Second)
	shutdown, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	_ = srv.Shutdown(shutdown)
}

// warmUp primes the stale cache and the connection pool (cache warming).
func warmUp(ctx context.Context, inv *resilience.Client, stale *staleCache) {
	for i := 0; i < 3; i++ {
		c, cancel := context.WithTimeout(ctx, time.Second)
		b, err := inv.Get(c, inventory)
		cancel()
		if err == nil {
			stale.put(b)
			return
		}
		time.Sleep(resilience.FullJitter(i, 200*time.Millisecond, 2*time.Second, nil))
	}
}

The death-spiral simulator (1 ms ticks, deterministic seed; models retries, GC pressure, health-check kills, OOM, cold restarts, slow start, edge shedding and scale-out):

go
// Package spiral is a deterministic, single-process simulator of the
// cascading-failure death spiral described in Google SRE chapter 22
// (footnote 110 invites exactly this exercise). It runs in 1 ms ticks:
//
//	users -> frontend (thread pool) -> load balancer -> N servers (workers + queue)
//
// Positive feedback loops it models: client timeouts and retries amplify load;
// queued work makes requests slower (GC pressure); health checks that wait in
// the same queue fail and the orchestrator kills busy servers (capacity
// removal); restarted servers start with cold caches; unbounded queues grow
// until OOM. Protections it can switch on: per-request deadlines with
// server-side expiry checks, a retry budget with full jitter, bounded queues
// (load shedding) and liveness-only health checks.
package spiral

import (
	"math/rand/v2"
	"time"

	"academy/cascading-failures/resilience"
)

// Config describes one run. All times are in milliseconds.
type Config struct {
	Name       string
	Seed       uint64
	DurationMs int

	// Capacity: Servers * Workers / ServiceMs * 1000 requests per second.
	Servers   int
	Workers   int
	ServiceMs float64

	// Offered load: BaseRPS, and SpikeRPS between SpikeFromMs and SpikeToMs
	// (the trigger). After the spike, load returns to BaseRPS.
	BaseRPS     float64
	SpikeRPS    float64
	SpikeFromMs int
	SpikeToMs   int

	// Client (frontend) behaviour.
	FrontendThreads int     // 0 = unlimited; each logical request holds one
	TimeoutMs       int     // per-attempt client timeout (the deadline)
	MaxAttempts     int     // 1 = no retries
	RetryBudget     float64 // 0 = unlimited retries; 0.1 = 10% of first attempts
	BackoffBaseMs   int     // 0 = retry on the next tick (no backoff, no jitter)
	BackoffMaxMs    int
	PatienceMs      int // a success later than this is useless to the user

	// Server behaviour.
	QueueCap    int  // 0 = unbounded
	DropExpired bool // skip work whose client deadline already passed

	// Feedback loops.
	GCPerQueued     float64 // service time grows by this fraction per queued item
	MaxSlowdown     float64
	OOMQueue        int  // crash when the queue exceeds this (0 = never)
	HealthViaQueue  bool // health check waits behind requests (naive)
	HealthTimeoutMs int
	HealthFailures  int // consecutive failed checks before a kill
	RestartMs       int
	ColdFactor      float64 // service time multiplier right after a restart
	ColdMs          int     // linear warm-up from ColdFactor to 1
	SlowStartMs     int     // LB ramps traffic to a restarted server over this
	BucketMs        int     // stats resolution, default 1000

	// Operator actions during an incident.
	AddServersAtMs int     // scale out: add AddServers cold servers at this time
	AddServers     int     // how many
	EdgeShedFromMs int     // block traffic at the edge from this time...
	EdgeShedMs     int     // ...for this long, admitting only EdgeAdmit of it,
	EdgeAdmit      float64 // then ramp linearly back to 100%
	EdgeRampMs     int     // over EdgeRampMs (gradual recovery)
}

// Second is one row of output.
type Second struct {
	T          int // seconds since start
	Offered    int // new user requests
	Attempts   int // attempts sent, including retries
	Good       int // successes within user patience
	Late       int // successes after the user gave up
	Failed     int // final failures seen by users
	Shed       int // fast rejections (503) at servers or frontend
	WastedMs   int // worker time spent on attempts nobody waits for
	ServersUp  int
	QueueTotal int
	Kills      int
	InFlight   int // frontend threads held
}

// Result is a whole run.
type Result struct {
	Config  Config
	Seconds []Second
}

type request struct {
	arrived  int
	attempts int
	done     bool
}

type attempt struct {
	req      *request
	sent     int
	deadline int
	finished bool // completed or timed out from the client's view
}

type worker struct {
	busyUntil int
	att       *attempt
	startedAt int
}

type server struct {
	up        bool
	upAt      int // when it last came up (for cold cache and slow start)
	downUntil int
	queue     []*attempt
	head      int
	workers   []worker
	fails     int
}

func (s *server) qlen() int { return len(s.queue) - s.head }

func (s *server) push(a *attempt) { s.queue = append(s.queue, a) }

func (s *server) pop() *attempt {
	a := s.queue[s.head]
	s.queue[s.head] = nil
	s.head++
	if s.head > 1024 && s.head*2 > len(s.queue) {
		s.queue = append([]*attempt(nil), s.queue[s.head:]...)
		s.head = 0
	}
	return a
}

type sim struct {
	cfg      Config
	rnd      *rand.Rand
	budget   *resilience.RetryBudget
	servers  []*server
	timeouts [][]*attempt
	retries  [][]*request
	inFlight int
	stats    []Second
	acc      float64
}

// Run executes the simulation. It is deterministic for a given Config.
func Run(cfg Config) Result {
	if cfg.BucketMs == 0 {
		cfg.BucketMs = 1000
	}
	if cfg.MaxSlowdown == 0 {
		cfg.MaxSlowdown = 4
	}
	s := &sim{cfg: cfg, rnd: rand.New(rand.NewPCG(cfg.Seed, cfg.Seed^0x9e3779b97f4a7c15))}
	if cfg.RetryBudget > 0 {
		s.budget = resilience.NewRetryBudget(cfg.RetryBudget, 10)
	}
	horizon := cfg.DurationMs + cfg.TimeoutMs + cfg.BackoffMaxMs + 2
	s.timeouts = make([][]*attempt, horizon)
	s.retries = make([][]*request, horizon)
	for i := 0; i < cfg.Servers; i++ {
		s.servers = append(s.servers, &server{up: true, upAt: -1 << 30, workers: make([]worker, cfg.Workers)})
	}
	s.stats = make([]Second, cfg.DurationMs/cfg.BucketMs+1)
	for i := range s.stats {
		s.stats[i].T = i * cfg.BucketMs / 1000
	}
	for t := 0; t < cfg.DurationMs; t++ {
		s.tick(t)
	}
	return Result{Config: cfg, Seconds: s.stats[:cfg.DurationMs/cfg.BucketMs]}
}

func (s *sim) row(t int) *Second { return &s.stats[t/s.cfg.BucketMs] }

func (s *sim) rps(t int) float64 {
	if t >= s.cfg.SpikeFromMs && t < s.cfg.SpikeToMs {
		return s.cfg.SpikeRPS
	}
	return s.cfg.BaseRPS
}

func (s *sim) tick(t int) {
	c := s.cfg
	if c.AddServers > 0 && t == c.AddServersAtMs {
		for i := 0; i < c.AddServers; i++ {
			s.servers = append(s.servers, &server{up: true, upAt: t, workers: make([]worker, c.Workers)})
		}
	}
	// 1. new user requests
	s.acc += s.rps(t) / 1000
	admit := s.edgeAdmit(t)
	for s.acc >= 1 {
		s.acc--
		s.row(t).Offered++
		if admit < 1 && s.rnd.Float64() >= admit {
			s.row(t).Failed++ // blocked at the edge (CDN/WAF/LB rule): cheap
			s.row(t).Shed++
			continue
		}
		if c.FrontendThreads > 0 && s.inFlight >= c.FrontendThreads {
			s.row(t).Failed++ // thread pool exhausted: the frontend itself refuses
			s.row(t).Shed++
			continue
		}
		r := &request{arrived: t}
		s.inFlight++
		if s.budget != nil {
			s.budget.OnRequest()
		}
		s.send(t, r)
	}
	// 2. scheduled retries
	for _, r := range s.retries[t] {
		s.send(t, r)
	}
	s.retries[t] = nil
	// 3. client-side timeouts (the attempt may still sit in a server queue)
	for _, a := range s.timeouts[t] {
		if !a.finished {
			a.finished = true
			s.fail(t, a.req)
		}
	}
	s.timeouts[t] = nil
	// 4. servers
	for _, sv := range s.servers {
		s.serve(t, sv)
	}
	// 5. health checks once per second, staggered per server
	for i, sv := range s.servers {
		if (t+i*97)%1000 == 0 {
			s.healthCheck(t, sv)
		}
	}
	if (t+1)%c.BucketMs == 0 {
		row := s.row(t)
		for _, sv := range s.servers {
			if sv.up {
				row.ServersUp++
				row.QueueTotal += sv.qlen()
			}
		}
		row.InFlight = s.inFlight
	}
}

// edgeAdmit is the share of traffic the edge lets through at time t.
func (s *sim) edgeAdmit(t int) float64 {
	c := s.cfg
	if c.EdgeShedMs == 0 || t < c.EdgeShedFromMs {
		return 1
	}
	if t < c.EdgeShedFromMs+c.EdgeShedMs {
		return c.EdgeAdmit
	}
	if into := t - c.EdgeShedFromMs - c.EdgeShedMs; c.EdgeRampMs > 0 && into < c.EdgeRampMs {
		return c.EdgeAdmit + (1-c.EdgeAdmit)*float64(into)/float64(c.EdgeRampMs)
	}
	return 1
}

// slowdown is the service-time multiplier: GC pressure from queued work and
// a cold cache after a restart.
func (s *sim) slowdown(t int, sv *server) float64 {
	f := 1 + s.cfg.GCPerQueued*float64(sv.qlen())
	if s.cfg.ColdMs > 0 && t-sv.upAt < s.cfg.ColdMs {
		left := 1 - float64(t-sv.upAt)/float64(s.cfg.ColdMs)
		f *= 1 + (s.cfg.ColdFactor-1)*left
	}
	if f > s.cfg.MaxSlowdown {
		f = s.cfg.MaxSlowdown
	}
	return f
}

func (s *sim) pick(t int) *server {
	var up []*server
	for _, sv := range s.servers {
		if sv.up {
			up = append(up, sv)
		}
	}
	for tries := 0; tries < 4 && len(up) > 0; tries++ {
		sv := up[s.rnd.IntN(len(up))]
		if s.cfg.SlowStartMs > 0 && t-sv.upAt < s.cfg.SlowStartMs {
			// slow start: accept a growing share of traffic while warming up
			if s.rnd.Float64() > float64(t-sv.upAt)/float64(s.cfg.SlowStartMs) {
				continue
			}
		}
		return sv
	}
	if len(up) == 0 {
		return nil
	}
	return up[s.rnd.IntN(len(up))]
}

func (s *sim) send(t int, r *request) {
	r.attempts++
	s.row(t).Attempts++
	a := &attempt{req: r, sent: t, deadline: t + s.cfg.TimeoutMs}
	sv := s.pick(t)
	if sv == nil { // connection refused: nobody is up
		a.finished = true
		s.fail(t, r)
		return
	}
	if s.cfg.QueueCap > 0 && sv.qlen() >= s.cfg.QueueCap && !hasFreeWorker(t, sv) {
		a.finished = true // fast 503: cheap for the server, quick for the client
		s.row(t).Shed++
		s.fail(t, r)
		return
	}
	sv.push(a)
	s.timeouts[a.deadline] = append(s.timeouts[a.deadline], a)
}

func hasFreeWorker(t int, sv *server) bool {
	for _, w := range sv.workers {
		if w.att == nil || w.busyUntil <= t {
			return true
		}
	}
	return false
}

// fail decides between a retry and a final error.
func (s *sim) fail(t int, r *request) {
	if r.done {
		return
	}
	c := s.cfg
	if r.attempts < c.MaxAttempts && (s.budget == nil || s.budget.TryRetry()) {
		delay := 1
		if c.BackoffBaseMs > 0 {
			d := resilience.FullJitter(r.attempts-1, time.Duration(c.BackoffBaseMs)*time.Millisecond,
				time.Duration(c.BackoffMaxMs)*time.Millisecond, s.rnd)
			delay = 1 + int(d/time.Millisecond)
		}
		at := t + delay
		// a deadline-aware client does not retry past the user's patience
		if at < len(s.retries) && (c.PatienceMs == 0 || !c.DropExpired || at-r.arrived < c.PatienceMs) {
			s.retries[at] = append(s.retries[at], r)
			return
		}
	}
	r.done = true
	s.inFlight--
	s.row(t).Failed++
}

func (s *sim) serve(t int, sv *server) {
	c := s.cfg
	if !sv.up {
		if t >= sv.downUntil {
			sv.up, sv.upAt, sv.fails = true, t, 0
		}
		return
	}
	for i := range sv.workers {
		w := &sv.workers[i]
		if w.att != nil && w.busyUntil <= t {
			a := w.att
			w.att = nil
			if a.finished || a.req.done {
				s.row(t).WastedMs += t - w.startedAt // nobody is waiting: wasted work
				continue
			}
			a.finished = true
			a.req.done = true
			s.inFlight--
			if c.PatienceMs > 0 && t-a.req.arrived > c.PatienceMs {
				s.row(t).Late++
			} else {
				s.row(t).Good++
			}
		}
		for w.att == nil && sv.qlen() > 0 {
			a := sv.pop()
			if c.DropExpired && (a.finished || a.req.done || t >= a.deadline) {
				continue // deadline check before work: free
			}
			svc := int(c.ServiceMs*s.slowdown(t, sv) + 0.5)
			if svc < 1 {
				svc = 1
			}
			w.att, w.busyUntil, w.startedAt = a, t+svc, t
		}
	}
	if c.OOMQueue > 0 && sv.qlen() > c.OOMQueue {
		s.kill(t, sv) // out of memory
	}
}

func (s *sim) healthCheck(t int, sv *server) {
	c := s.cfg
	if !sv.up || !c.HealthViaQueue {
		return // liveness answered on its own path: busy is not dead
	}
	wait := float64(sv.qlen()) * c.ServiceMs * s.slowdown(t, sv) / float64(c.Workers)
	if wait > float64(c.HealthTimeoutMs) {
		sv.fails++
		if sv.fails >= c.HealthFailures {
			s.kill(t, sv)
		}
		return
	}
	sv.fails = 0
}

// kill removes a server: queued and running attempts are lost (clients will
// time out), and it comes back after RestartMs with a cold cache.
func (s *sim) kill(t int, sv *server) {
	sv.up = false
	sv.downUntil = t + s.cfg.RestartMs
	sv.queue, sv.head = nil, 0
	for i := range sv.workers {
		sv.workers[i].att = nil
	}
	s.row(t).Kills++
}

// Window sums rows with fromS <= T < toS.
func (r Result) Window(fromS, toS int) Second {
	var w Second
	for _, x := range r.Seconds {
		if x.T >= fromS && x.T < toS {
			w.Offered += x.Offered
			w.Attempts += x.Attempts
			w.Good += x.Good
			w.Late += x.Late
			w.Failed += x.Failed
			w.Shed += x.Shed
			w.WastedMs += x.WastedMs
			w.Kills += x.Kills
		}
	}
	return w
}

// Goodput is good successes / offered requests in a window.
func (r Result) Goodput(fromS, toS int) float64 {
	w := r.Window(fromS, toS)
	if w.Offered == 0 {
		return 0
	}
	return float64(w.Good) / float64(w.Offered)
}

// Amplification is attempts sent per offered request in a window.
func (r Result) Amplification(fromS, toS int) float64 {
	w := r.Window(fromS, toS)
	if w.Offered == 0 {
		return 0
	}
	return float64(w.Attempts) / float64(w.Offered)
}
go
package spiral

// The scenario: 10 servers x 8 workers x 40 ms = 2,000 requests/s of
// capacity. Users send 1,400 requests/s (70% utilisation). Between 20 s and
// 30 s a spike of 2,600 requests/s (130%) hits: a marketing email, a
// failover from another region, the first Monday after the holidays.
// The question is what happens at 30 s, when load is back to 70%.
func base(name string) Config {
	return Config{
		Name: name, Seed: 42, DurationMs: 90_000,
		Servers: 10, Workers: 8, ServiceMs: 40,
		BaseRPS: 1400, SpikeRPS: 2600, SpikeFromMs: 20_000, SpikeToMs: 30_000,
		FrontendThreads: 20_000, PatienceMs: 2_000,
		GCPerQueued: 0.0005, MaxSlowdown: 4,
		RestartMs: 5_000, ColdFactor: 3, ColdMs: 10_000,
	}
}

// Naive is the system most teams ship first: a 5 s client timeout, three
// immediate retries, an unbounded queue that dies of OOM at 6,000 entries,
// a health check that waits in the request queue (2 s timeout, 3 strikes)
// and no deadline check on the server.
func Naive() Config {
	c := base("naive")
	c.TimeoutMs, c.MaxAttempts = 5_000, 4
	c.HealthViaQueue, c.HealthTimeoutMs, c.HealthFailures = true, 2_000, 3
	c.OOMQueue = 6_000
	return c
}

// Protected adds the four cheap defences: a 1 s deadline that servers check
// before doing work, a 10% retry budget with full-jitter backoff (max 3
// attempts), a bounded queue of 4 per server (50% of the worker pool, the
// SRE book's rule of thumb) and a liveness-only health check.
func Protected() Config {
	c := base("protected")
	c.TimeoutMs, c.MaxAttempts = 1_000, 3
	c.DropExpired = true
	c.RetryBudget, c.BackoffBaseMs, c.BackoffMaxMs = 0.1, 50, 1_000
	c.QueueCap = 4
	c.SlowStartMs = 10_000
	return c
}

// Ablations remove one defence at a time from Protected.
func Ablations() []Config {
	noDeadline := Protected()
	noDeadline.Name, noDeadline.DropExpired, noDeadline.TimeoutMs = "protected - deadlines", false, 5_000

	noBudget := Protected()
	noBudget.Name, noBudget.RetryBudget, noBudget.BackoffBaseMs, noBudget.MaxAttempts = "protected - retry budget/jitter", 0, 0, 4

	unbounded := Protected()
	unbounded.Name, unbounded.QueueCap, unbounded.OOMQueue = "protected - bounded queue", 0, 6_000

	naiveHealth := Protected()
	naiveHealth.Name = "protected + queue-based health check"
	naiveHealth.HealthViaQueue, naiveHealth.HealthTimeoutMs, naiveHealth.HealthFailures = true, 2_000, 3

	return []Config{Naive(), noDeadline, noBudget, unbounded, naiveHealth, Protected()}
}

// Additions add one defence at a time to Naive.
func Additions() []Config {
	deadline := Naive()
	deadline.Name, deadline.DropExpired, deadline.TimeoutMs = "naive + deadlines", true, 1_000

	budget := Naive()
	budget.Name = "naive + retry budget/jitter"
	budget.RetryBudget, budget.BackoffBaseMs, budget.BackoffMaxMs, budget.MaxAttempts = 0.1, 50, 1_000, 3

	bounded := Naive()
	bounded.Name, bounded.QueueCap = "naive + bounded queue", 4

	health := Naive()
	health.Name, health.HealthViaQueue = "naive + liveness-only health", false

	return []Config{Naive(), deadline, budget, bounded, health}
}

// Recoveries start from a collapsed Naive system and apply one operator
// action at 40 s.
func Recoveries() []Config {
	nothing := Naive()
	nothing.Name = "do nothing"

	scale := Naive()
	scale.Name, scale.AddServersAtMs, scale.AddServers = "scale out +50% (5 cold servers)", 40_000, 5

	edge := Naive()
	edge.Name = "edge admits 10% for 10 s, ramp over 20 s"
	edge.EdgeShedFromMs, edge.EdgeShedMs, edge.EdgeAdmit, edge.EdgeRampMs = 40_000, 10_000, 0.1, 20_000

	snap := Naive()
	snap.Name = "edge admits 10% for 10 s, then 100% at once"
	snap.EdgeShedFromMs, snap.EdgeShedMs, snap.EdgeAdmit = 40_000, 10_000, 0.1

	return []Config{nothing, scale, edge, snap}
}
go
package spiral

import "testing"

func TestNaiveSystemStaysDownAfterTheTriggerEnds(t *testing.T) {
	r := Run(Naive())
	if g := r.Goodput(0, 20); g < 0.99 {
		t.Fatalf("healthy phase goodput %.3f, want >= 0.99", g)
	}
	// load is back to 70% of capacity, yet the system does not recover:
	// a metastable failure sustained by retries, kills and cold restarts
	if g := r.Goodput(30, 90); g > 0.2 {
		t.Fatalf("naive goodput after the spike %.3f, want collapse (< 0.2)", g)
	}
	if a := r.Amplification(30, 60); a < 2 {
		t.Fatalf("retry amplification %.2fx, want >= 2x", a)
	}
	if r.Window(20, 90).Kills == 0 {
		t.Fatal("expected health-check or OOM kills (capacity removal)")
	}
}

func TestProtectedSystemShedsAndRecovers(t *testing.T) {
	r := Run(Protected())
	// during the 130% spike, goodput stays near capacity: 2,000 of 2,600
	if g := r.Goodput(20, 30); g < 0.74 {
		t.Fatalf("protected goodput during spike %.3f, want >= 0.74", g)
	}
	if g := r.Goodput(31, 90); g < 0.99 {
		t.Fatalf("protected goodput after spike %.3f, want >= 0.99", g)
	}
	if a := r.Amplification(20, 30); a > 1.15 {
		t.Fatalf("protected amplification %.2fx, want <= 1.15x (10%% budget)", a)
	}
	if k := r.Window(0, 90).Kills; k != 0 {
		t.Fatalf("protected run killed %d servers", k)
	}
}

func TestBoundedQueueNeverGrows(t *testing.T) {
	c := Protected()
	r := Run(c)
	for _, x := range r.Seconds {
		if x.QueueTotal > c.QueueCap*c.Servers {
			t.Fatalf("t=%d queue %d exceeds cap %d", x.T, x.QueueTotal, c.QueueCap*c.Servers)
		}
	}
}

func TestGradualRecoveryBeatsScaleOutAndSnapBack(t *testing.T) {
	rs := Recoveries()
	nothing, scale, ramp, snap := Run(rs[0]), Run(rs[1]), Run(rs[2]), Run(rs[3])
	if g := ramp.Goodput(70, 90); g < 0.99 {
		t.Fatalf("edge shed + ramp: goodput %.3f after ramp, want >= 0.99", g)
	}
	for name, r := range map[string]Result{"nothing": nothing, "scale": scale, "snap": snap} {
		if g := r.Goodput(70, 90); g > 0.3 {
			t.Fatalf("%s recovered (%.3f): the death spiral should persist", name, g)
		}
	}
}

func TestKneeOfTheLoadTest(t *testing.T) {
	steady := func(c Config, rps float64) float64 {
		c.DurationMs, c.BaseRPS, c.SpikeFromMs, c.SpikeToMs = 30_000, rps, 0, 0
		return float64(Run(c).Window(10, 30).Good) / 20
	}
	// below the knee both are fine; above it naive goodput collapses while
	// protected goodput plateaus near capacity (2,000 req/s)
	if n, p := steady(Naive(), 1400), steady(Protected(), 1400); n < 1390 || p < 1390 {
		t.Fatalf("70%% load: naive %.0f protected %.0f", n, p)
	}
	if n := steady(Naive(), 2600); n > 500 {
		t.Fatalf("naive at 130%%: %.0f req/s, want collapse", n)
	}
	if p := steady(Protected(), 2600); p < 1900 {
		t.Fatalf("protected at 130%%: %.0f req/s, want plateau near 2,000", p)
	}
}

func TestDeterministic(t *testing.T) {
	a, b := Run(Naive()), Run(Naive())
	for i := range a.Seconds {
		if a.Seconds[i] != b.Seconds[i] {
			t.Fatalf("second %d differs between identical runs", i)
		}
	}
}
go
// Command spiral prints the tables used on the cascading-failures page.
// It is deterministic (seeded) and finishes in about a second.
package main

import (
	"fmt"

	"academy/cascading-failures/spiral"
)

func main() {
	fmt.Println("1) Timeline: 2,000 req/s capacity, 1,400 req/s load, spike to 2,600 req/s from 20 s to 30 s")
	for _, cfg := range []spiral.Config{spiral.Naive(), spiral.Protected()} {
		r := spiral.Run(cfg)
		fmt.Printf("\n%s\n%4s %7s %8s %6s %6s %6s %6s %5s %7s %6s\n", cfg.Name,
			"t(s)", "offered", "attempts", "good", "late", "failed", "shed", "up", "queue", "kills")
		for _, x := range r.Seconds {
			if x.T%5 == 0 || (x.T >= 18 && x.T <= 40 && x.T%2 == 0) {
				fmt.Printf("%4d %7d %8d %6d %6d %6d %6d %5d %7d %6d\n", x.T, x.Offered, x.Attempts,
					x.Good, x.Late, x.Failed, x.Shed, x.ServersUp, x.QueueTotal, x.Kills)
			}
		}
	}

	fmt.Println("\n2) One defence at a time (goodput = good / offered)")
	fmt.Printf("%-38s %8s %8s %8s %8s %9s\n", "config", "0-20s", "20-30s", "30-60s", "60-90s", "ampl30-60")
	for _, cfg := range append(spiral.Additions(), spiral.Ablations()[1:]...) {
		r := spiral.Run(cfg)
		fmt.Printf("%-38s %7.1f%% %7.1f%% %7.1f%% %7.1f%% %8.2fx\n", cfg.Name,
			100*r.Goodput(0, 20), 100*r.Goodput(20, 30), 100*r.Goodput(30, 60), 100*r.Goodput(60, 90),
			r.Amplification(30, 60))
	}

	fmt.Println("\n3) Recovering the collapsed naive system with one action at 40 s (goodput)")
	fmt.Printf("%-44s %8s %8s %8s %8s\n", "action", "30-40s", "40-50s", "50-70s", "70-90s")
	for _, cfg := range spiral.Recoveries() {
		r := spiral.Run(cfg)
		fmt.Printf("%-44s %7.1f%% %7.1f%% %7.1f%% %7.1f%%\n", cfg.Name,
			100*r.Goodput(30, 40), 100*r.Goodput(40, 50), 100*r.Goodput(50, 70), 100*r.Goodput(70, 90))
	}

	fmt.Println("\n4) Load test to find the knee: steady load for 30 s, goodput in req/s")
	fmt.Printf("%8s %10s %12s\n", "offered", "naive", "protected")
	for _, rps := range []float64{1000, 1400, 1800, 2000, 2200, 2600, 3000} {
		var out [2]float64
		for i, cfg := range []spiral.Config{spiral.Naive(), spiral.Protected()} {
			cfg.DurationMs, cfg.BaseRPS, cfg.SpikeFromMs, cfg.SpikeToMs = 30_000, rps, 0, 0
			r := spiral.Run(cfg)
			out[i] = float64(r.Window(10, 30).Good) / 20
		}
		fmt.Printf("%8.0f %10.0f %12.0f\n", rps, out[0], out[1])
	}
}

The Go angle ​

Go featureUse against cascadesNote
context.WithTimeout, WithDeadline, ctx.Deadline()Deadlines and propagationDeadlineExceeded is "the error returned by Context.Err when the context is canceled due to its deadline passing"
context.AfterFunc, WithCancelCause, CauseCancellation propagation with a reasonDistinguish "caller gave up" from "hop timed out"
http.NewRequestWithContextCancel in-flight calls when the budget endsWithout it, losers keep running
http.Server timeoutsSlow clients cannot hold goroutinesReadHeaderTimeout closes Slowloris-style holds
http.Transport.MaxConnsPerHostBounded connection pool per dependencyPlus MaxIdleConnsPerHost to avoid churn and port exhaustion
Buffered channel / golang.org/x/sync/semaphoreAdmission control and bulkheadssemaphore.Weighted.TryAcquire for fail fast
golang.org/x/sync/singleflightCoalesce cache misses (stampede)One fetch per key, others wait for it
runtime/debug.SetMemoryLimit, GOMEMLIMITKeep GC from running the heap into the container limitPair with admission control: the limit does not stop work arriving
math/rand/v2Jitter without a shared lockSeeded rand.New(rand.NewPCG(...)) in tests
net/http/httptestOverload and shedding tests in-processUsed by resilience_test.go

Laravel ​

Before ​

Http::retry(5, 100) with the 30 s default timeout and a failure that becomes a 500:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;

/**
 * The controller most cascades start from. Every PHP-FPM child that runs it
 * waits up to 30 s (the HTTP client default) per attempt, five attempts with
 * a fixed 100 ms pause: a slow inventory service pins every FPM child for
 * minutes, NGINX starts answering 502/504, and every caller retries.
 */
class ProductControllerBefore extends Controller
{
    public function show(int $id): JsonResponse
    {
        $stock = Http::retry(5, 100)                      // no jitter, no budget
            ->get("http://inventory.internal/stock/{$id}") // default timeout: 30 s
            ->throw()
            ->json();

        return response()->json(['id' => $id, 'stock' => $stock]); // a failure becomes a 500
    }
}

After ​

A fleet-wide retry budget in Redis, shared by every PHP-FPM child and Octane worker:

php
<?php

namespace App\Support;

use Illuminate\Support\Facades\Cache;

/**
 * A fleet-wide retry budget: retries may be at most $ratio of first attempts
 * in the current one-minute window (Google SRE: "per-client retry budget",
 * 10%). Counters live in Redis so every PHP-FPM child and Octane worker
 * shares them; Cache::increment is atomic on the redis store.
 */
class RetryBudget
{
    public function __construct(
        private string $dependency,
        private float $ratio = 0.1,
        private int $minRetriesPerWindow = 10,
    ) {
    }

    public function recordRequest(): void
    {
        $key = $this->key('requests');
        Cache::store('redis')->add($key, 0, 120);
        Cache::store('redis')->increment($key);
    }

    public function tryRetry(): bool
    {
        $store = Cache::store('redis');
        $requests = (int) $store->get($this->key('requests'), 0);
        $allowed = max($this->minRetriesPerWindow, (int) floor($requests * $this->ratio));

        $key = $this->key('retries');
        $store->add($key, 0, 120);

        return $store->increment($key) <= $allowed;
    }

    private function key(string $kind): string
    {
        return sprintf('retry-budget:%s:%s:%s', $this->dependency, $kind, intdiv(time(), 60));
    }
}

The inventory client: connect timeout 0.2 s, response timeout from the request deadline, full jitter, a when callback that consults the budget, throw: false and a stale fallback:

php
<?php

namespace App\Clients;

use App\Support\RetryBudget;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;

/**
 * Inventory client that cannot start a retry storm: tight connect and
 * response timeouts, at most two retries with full jitter, a shared retry
 * budget, no retry on 429 or 4xx, and a stale fallback (graceful degradation).
 */
class InventoryClient
{
    public function __construct(private RetryBudget $budget)
    {
    }

    /**
     * @return array{stock: int|null, degraded: bool}
     */
    public function stock(int $productId, float $deadlineAt): array
    {
        $remaining = $deadlineAt - microtime(true) - 0.02; // keep 20 ms for our own work
        if ($remaining < 0.03) {
            return $this->fallback($productId); // not enough time to succeed: do not call
        }

        $this->budget->recordRequest();

        $response = Http::baseUrl('http://inventory.internal')
            ->connectTimeout(0.2)
            ->timeout(min(0.3, $remaining)) // about the callee's p99.9, never past the deadline
            ->withHeaders(['Request-Timeout-Ms' => (string) (int) ($remaining * 1000)])
            ->retry(
                3,
                fn (int $attempt) => random_int(0, 25 * (2 ** $attempt)), // full jitter, ms
                function (Throwable $e, PendingRequest $request) use ($deadlineAt): bool {
                    $transient = $e instanceof ConnectionException
                        || ($e instanceof RequestException && $e->response->status() >= 500);
                    $left = $deadlineAt - microtime(true) - 0.02;

                    return $transient && $left > 0.03 && $this->budget->tryRetry();
                },
                throw: false,
            )
            ->get("/stock/{$productId}");

        if ($response->successful()) {
            $stock = (int) $response->json('stock');
            Cache::put("inventory:last:{$productId}", $stock, now()->addMinutes(10));

            return ['stock' => $stock, 'degraded' => false];
        }

        return $this->fallback($productId);
    }

    /**
     * @return array{stock: int|null, degraded: bool}
     */
    private function fallback(int $productId): array
    {
        return ['stock' => Cache::get("inventory:last:{$productId}"), 'degraded' => true];
    }
}

Queue-time load shedding: NGINX stamps X-Request-Start; requests that already waited too long in the PHP-FPM backlog get a cheap 503:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Load shedding by queue time. NGINX stamps every request on arrival:
 *   fastcgi_param HTTP_X_REQUEST_START "t=${msec}";
 * If a request waited in the PHP-FPM listen backlog (or the Octane queue)
 * longer than the budget, the user has probably given up: answer a cheap 503
 * instead of doing work nobody will read. Sheddable routes (prefetch,
 * recommendations) get a tighter budget than critical ones (checkout).
 */
class ShedQueuedRequests
{
    public function handle(Request $request, Closure $next, string $criticality = 'critical'): Response
    {
        $header = (string) $request->header('X-Request-Start', '');
        if (preg_match('/^t=(\d+(?:\.\d+)?)$/', $header, $m) === 1) {
            $queuedMs = (microtime(true) - (float) $m[1]) * 1000;
            $budgetMs = $criticality === 'sheddable' ? 200 : 1000;

            if ($queuedMs > $budgetMs) {
                return response('overloaded, retry later', 503, ['Retry-After' => '1']);
            }
        }

        // The absolute deadline for downstream calls, shared by every client.
        $request->attributes->set('deadline_at', microtime(true) + 1.0);

        return $next($request);
    }
}

Graceful degradation with Cache::flexible (stale-while-revalidate against stampedes) and an estimate flag:

php
<?php

namespace App\Http\Controllers;

use App\Clients\InventoryClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ProductController extends Controller
{
    public function show(Request $request, int $id, InventoryClient $inventory): JsonResponse
    {
        $deadlineAt = (float) $request->attributes->get('deadline_at', microtime(true) + 1.0);

        // Cache::flexible serves a stale value while one request refreshes it
        // in the background: no stampede on the database when an entry expires.
        $product = Cache::flexible("product:{$id}", [60, 600], fn () => \App\Models\Product::findOrFail($id)->toArray());

        $stock = $inventory->stock($id, $deadlineAt);

        return response()
            ->json([
                'product' => $product,
                'stock' => $stock['stock'],          // null = "check availability at checkout"
                'stock_is_estimate' => $stock['degraded'],
            ])
            ->header('X-Degraded', $stock['degraded'] ? 'inventory' : 'none');
    }
}

Readiness that reports saturation (queue depth and age through the queue contract's pendingSize, reservedSize, creationTimeOfOldestPendingJob) and liveness on the built-in /up route:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Queue;

/**
 * GET /ready reports saturation for dashboards and autoscalers. It never
 * fails because a dependency is slow (that would remove capacity during a
 * brownout); it fails only during maintenance or draining. Liveness stays on
 * Laravel's built-in /up route, which checks only that the app boots.
 */
class ReadinessController extends Controller
{
    public function __invoke(): JsonResponse
    {
        // Cached for 5 s so a burst of probes cannot become load themselves.
        $saturation = Cache::remember('ready:saturation', 5, function (): array {
            $queue = Queue::connection('redis');
            $oldest = $queue->creationTimeOfOldestPendingJob('default');

            return [
                'queue_pending' => $queue->pendingSize('default'),
                'queue_reserved' => $queue->reservedSize('default'),
                'queue_oldest_age_s' => $oldest === null ? 0 : time() - $oldest,
                'memory_mb' => round(memory_get_usage(true) / 1048576, 1),
            ];
        });

        $draining = app()->isDownForMaintenance() || Cache::get('draining:'.gethostname(), false);

        return response()->json(['ready' => ! $draining, 'saturation' => $saturation], $draining ? 503 : 200);
    }
}
php
<?php

use App\Http\Controllers\ProductController;
use App\Http\Controllers\ReadinessController;
use App\Http\Middleware\ShedQueuedRequests;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up', // liveness: the app boots; no database, no dependencies
        then: function () {
            Route::get('/ready', ReadinessController::class);
            Route::middleware(['throttle:api', 'shed:critical'])
                ->get('/api/products/{id}', [ProductController::class, 'show']);
        },
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->alias(['shed' => ShedQueuedRequests::class]);
        $middleware->throttleWithRedis();
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

Defaults and fairness: Http::globalOptions so no call keeps the 30 s default, and RateLimiter::for per user or IP:

php
<?php

namespace App\Providers;

use App\Clients\InventoryClient;
use App\Support\RetryBudget;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(InventoryClient::class, fn () => new InventoryClient(new RetryBudget('inventory')));
    }

    public function boot(): void
    {
        // Defaults for every outgoing call (Guzzle options): never the 30 s default.
        Http::globalOptions([
            'connect_timeout' => 1,
            'timeout' => 5,
        ]);

        // Per-client fairness: one tenant or crawler cannot take the whole pool.
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(600)
                ->by($request->user()?->id ?: $request->ip())
                ->response(fn (Request $request, array $headers) => response('slow down', 429, $headers));
        });

        // Sheddable traffic gets a much smaller share.
        RateLimiter::for('prefetch', fn (Request $request) => Limit::perMinute(60)->by($request->ip()));
    }
}

A queued job that cannot join the cascade: #[Timeout(30)], retryUntil(), jittered backoff(), ThrottlesExceptions:

php
<?php

namespace App\Jobs;

use DateTime;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Support\Facades\Http;

/**
 * A background job that must not join a cascade: bounded run time (kept
 * below the connection's retry_after), a time-based attempt window, jittered
 * backoff, and ThrottlesExceptions, which behaves like a circuit breaker for
 * jobs: after 10 exceptions further attempts are delayed for 5 minutes instead
 * of hammering the failing partner.
 */
#[Timeout(30)]
class SyncInventory implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $warehouseId)
    {
    }

    public function handle(): void
    {
        Http::connectTimeout(1)
            ->timeout(10) // below the job timeout, which is below retry_after
            ->get("http://warehouse.internal/warehouses/{$this->warehouseId}/stock")
            ->throw();
    }

    /**
     * Time-based attempts, as the docs recommend with ThrottlesExceptions.
     */
    public function retryUntil(): DateTime
    {
        return now()->addMinutes(30);
    }

    /**
     * Jittered exponential backoff in seconds, so 10,000 failed jobs do not
     * come back in the same second.
     */
    public function backoff(): int
    {
        return random_int(0, min(300, 5 * (2 ** $this->attempts())));
    }

    /**
     * @return array<int, object>
     */
    public function middleware(): array
    {
        return [(new ThrottlesExceptions(10, 5 * 60))->backoff(1)];
    }
}

Workers that recycle themselves (Supervisor program with --timeout, --memory, --max-jobs, --max-time):

ini
; Install as /etc/supervisor/conf.d/laravel-worker.conf (Supervisor reads INI syntax).
; Supervisor program for queue workers that recycle themselves before they
; leak memory, never run a job past retry_after, and stop gracefully.
[program:laravel-worker]
command=php /var/www/app/artisan queue:work redis --queue=default --sleep=3 --tries=3 --timeout=60 --max-jobs=1000 --max-time=3600 --memory=256
process_name=%(program_name)s_%(process_num)02d
numprocs=8
autostart=true
autorestart=true
startsecs=5
stopwaitsecs=70
stopasgroup=true
killasgroup=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/app/storage/logs/worker.log

A test that proves the budget caps amplification (22 calls instead of 60):

php
<?php

namespace Tests\Feature;

use App\Clients\InventoryClient;
use App\Support\RetryBudget;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class InventoryClientTest extends TestCase
{
    public function test_overloaded_dependency_gets_bounded_retries_and_a_stale_answer(): void
    {
        config(['cache.stores.redis' => ['driver' => 'array']]); // isolated store for the test
        Cache::put('inventory:last:7', 3, 600);
        Http::fake(['inventory.internal/*' => Http::response('busy', 503)]);

        $client = new InventoryClient(new RetryBudget('inventory', ratio: 0.1, minRetriesPerWindow: 2));
        for ($i = 0; $i < 20; $i++) {
            $result = $client->stock(7, microtime(true) + 1.0);
            $this->assertTrue($result['degraded']);
            $this->assertSame(3, $result['stock']);
        }

        // Without the budget: 20 requests x 3 attempts = 60 calls.
        // With it: 20 first attempts + about 2 retries.
        Http::assertSentCount(22);
    }
}

The Laravel angle ​

Laravel featureUse against cascadesNote (Laravel 13 docs)
Http::timeout() / connectTimeout()Turn slow into fast"By default, the HTTP client will timeout after 30 seconds"; connect default 10 s
Http::retry($times, $sleep, $when, throw: false)Bounded, conditional retries$sleep may be a closure; $when sees the exception and the PendingRequest
Http::globalOptions([...])Safe defaults for every outgoing callCalled in AppServiceProvider::boot
RateLimiter::for + Limit::perMinute()->by()->response()Per-client fairness at the route429 by default; throttleWithRedis() for Redis
RateLimiter::attempt, increment, tooManyAttempts, availableInRate-limit any code pathincrement is atomic on redis, memcached, database stores
Cache::flexible($key, [fresh, stale], fn)Stale-while-revalidate: no stampede on expiryRecalculated in the background
Cache::lockCoalesce rebuilds of one keyAtomic locks across workers
Queue --timeout, --memory, --max-jobs, --max-timeBounded jobs and self-recycling workers--timeout "at least several seconds shorter than your retry_after"
#[Timeout], #[Tries], #[Backoff], #[FailOnTimeout], retryUntil()Per-job limitsAttributes in Illuminate\Queue\Attributes
ThrottlesExceptions, RateLimited, WithoutOverlapping job middlewareBreaker, rate limit, mutual exclusion for jobsThrottlesExceptions pairs with time-based attempts
queue:monitor --max= + QueueBusy eventQueue-depth alertingSchedule every minute
Octane --workers, --max-requestsBounded concurrency per server; leak controlOne worker per CPU core by default; 500 requests
Health route /up + DiagnosingHealthLivenessKeep dependency checks out of liveness

Solving the classic problems ​

A blip turned into a retry storm ​

SolutionHowAdvantageCost / limitation
Retry at one layerInner layers fail fast and return errorsRemoves multiplicationNeeds agreement across teams
Per-request cap2–3 attemptsBounds the worst case per requestDoes not bound total volume
Per-client retry budgetToken bucket, 10% of requestsTotal overhead about 1.1xA few legitimate retries are denied during incidents
Full jitterrandom(0, min(cap, base·2^n))Breaks synchronizationSlightly longer average delay
Explicit overload status503 + Retry-After, 429Clients back off instead of retryingClients must honour it

A slow dependency pins every thread ​

SolutionHowAdvantageCost / limitation
Deadline from the callee's p99.9Http::timeout(0.3), ForHopBounded hold timeSome slow successes become errors
Bulkhead per dependencyPool of 40 for recommendationsOthers keep their threadsPools must be sized
Circuit breakerOpen after N failures, half-open probeCalls fail in microsecondsModal behaviour; tune and test
Degraded responseStale copy, partial pageUsers still servedProduct decisions per feature

The same rule applies inside the database. A per-session deadline in PostgreSQL stops one slow statement from holding a pool slot forever, and pg_stat_activity shows whether the pool is being held by waiting or long-running sessions:

sql
-- PostgreSQL: database-side deadlines for an application role
ALTER ROLE app_web SET statement_timeout = '2s';                       -- SQLSTATE 57014 when hit
ALTER ROLE app_web SET lock_timeout = '500ms';                          -- do not queue behind locks
ALTER ROLE app_web SET idle_in_transaction_session_timeout = '10s';     -- release forgotten transactions

-- Who is holding the connections right now?
SELECT state, wait_event_type, count(*) AS sessions,
       max(now() - query_start) AS longest
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state, wait_event_type
ORDER BY sessions DESC;

-- Headroom against SQLSTATE 53300 (too_many_connections)
SELECT current_setting('max_connections')::int AS max_connections,
       count(*) AS in_use
FROM pg_stat_activity;

-- MySQL equivalent for read queries: per-session SELECT deadline in milliseconds
-- SET SESSION max_execution_time = 2000;

Health checks are killing a busy fleet ​

SolutionHowAdvantageCost / limitation
Liveness without dependencies/livez or Laravel /upBusy is not deadA wedged process may live longer (add a watchdog)
Readiness for start-up and draining503 only while warming or drainingNo flapping under loadSaturation handled per request instead
Ejection ceilingsEnvoy max_ejection_percent, panic thresholdNever eject most of a fleetSome bad hosts keep receiving traffic
Slow startAWS ALB, Envoy slow startRestarted hosts warm upLonger time to full capacity

A cache flush or restart sends everything to the database ​

SolutionHowAdvantageCost / limitation
Request coalescingsingleflight, Cache::lockOne origin fetch per keyWaiters share one failure
Stale-while-revalidateCache::flexible, CDN stale-while-revalidateNo synchronized expiryBriefly stale data
TTL jitterTTL ± 10%Spreads expiriesNone worth mentioning
Warm before readyFill caches before readiness passesNo cold trafficSlower start-up
Treat it as a capacity cacheProvision the database for a cold cache, or protect it with sheddingHonest capacity planningCost

The autoscaler goes the wrong way ​

SolutionHowAdvantageCost / limitation
Scale on saturationWorker utilisation, queue age, in-flight / limitCorrect direction for I/O waitsMore metrics to export
Static headroomN + 1 zones at peakSurvives before scaling actsPaid idle capacity
Disable scale-in during incidentsRunbook stepKeeps capacity and SSH sessionsManual
Load-test the scalerProvision 10x the usual batch in stagingFinds FD and quota limitsTest effort

A deploy or config push under load ​

SolutionHowAdvantageCost / limitation
Stage every change, including configDOG, PIG, Canary, Global (Cloudflare's process)Small blast radiusSlower emergency changes
Capacity-aware rolloutsFewer tasks updated at peakNo capacity dip at peakLonger rollouts
Resource guards per operationRegex engines with run-time guarantees, per-request CPU budgetA bad rule cannot take a coreEngine change
Fast global kill switchCloudflare "global terminate"Minutes to recoverMust not depend on the failing system

Recovering from a collapse ​

text
     Runbook order (Google SRE immediate steps + the simulator's lesson)
1    Declare the incident; check recent changes and revert those that touch capacity or request profile
2    Stop the loop: block or rate-limit at the edge (admit 1-10%), turn off batch load and retries
3    Stop capacity removal: disable killing health checks and scale-in
4    Fix or paper over the trigger (more memory, rollback, kill switch)
5    Let servers become healthy and warm (caches, connections, JIT)
6    Ramp traffic back gradually (slow start, edge ramp over minutes), watching saturation
7    Drain backlogs at a controlled rate (GitHub: watch partners and TTLs)
8    Re-enable retries and batch work last; write the blameless postmortem

Choosing ​

Symptom to first action ​

SymptomFirst actionDefence to add afterwardsReason
Attempts/s far above first attempts/sDisable or cut retries; edge rate limitRetry budget, one retry layer, jitterRetry storm
Latency up, CPU down, threads busyShorten deadlines on the slow dependencyBulkheads, breaker, fail fastSlow vs down
Queue age growingShed at the edge or the processBounded queues, admission controlOverload
Health checks failing on busy hostsDisable the killing check, panic modeLiveness/readiness split, ejection ceilingCapacity removal
Database saturated after cache restartShed reads, serve staleCoalescing, warming, capacity-cache planningStampede
Restarted hosts die immediatelyKeep load low, slow startSlow start config, warm-up before readinessThundering herd on restart
Autoscaler scaling in during an incidentFreeze scale-inSaturation-based scaling, headroomWrong signal
Errors persist after the trigger is goneStrong corrective push: edge shed + rampLoad tests past the knee and backMetastable state

Which defence at which layer ​

LayerDefenceProduct
Edge / CDNGlobal rate limits, block bad traffic, ramp after recoveryCloudflare, AWS WAF, CloudFront, NGINX limit_req
Load balancer / meshCircuit breakers, outlier detection with ceilings, panic threshold, slow start, retry budgetsEnvoy, Istio, AWS ALB, HAProxy
Service processAdmission control, bounded queues, deadlines, liveness/readinessGo resilience, Laravel middleware, Octane worker counts
Client libraryTimeouts, retry budget, jitter, bulkhead, breakerresilience.Client, Laravel HTTP client + RetryBudget, gRPC
Data tierStatement and lock timeouts, connection limits, poolersPostgreSQL, PgBouncer, MySQL max_execution_time
Async workBounded consumers, backpressure, jittered backoff, breakersLaravel queues, Kafka, RabbitMQ
OrganisationLoad tests to the knee, chaos drills, blameless postmortemsChaos Engineering

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Even a monolith cascades internally: a slow report query holds database connections, web workers wait for the pool, the load balancer's health check (which queries the database) fails, and the instance is replaced. Simplest correct setup: one PHP-FPM or Octane pool with a known size, statement_timeout for the web role, HTTP client timeouts everywhere, a liveness route that does not touch the database (/up), queue workers with --timeout and --memory, and a separate database role or pool for reports so they cannot take the web tier's connections.

Modular monolith: boundaries without the network ​

Modules share one process, so they share thread pools, memory and the connection pool; one module's slow dependency starves the others. Bulkheads become in-process: separate HTTP client instances with their own timeouts, separate queues per module (--queue=billing workers apart from --queue=emails), separate connection pools or roles, and criticality labels per route. A module that calls another module synchronously in a loop is the in-process version of intra-layer communication: avoid it in the request path.

Microservices: every arrow is a path for load and delay ​

text
     Browser -> API gateway -> product -> inventory -> PostgreSQL
                                       -> pricing   -> Redis
                                       -> reviews   (optional)
1    inventory slows to 3 s (lock contention)
2    product's threads wait; gateway's connections to product fill
3    gateway retries (3) + product retries (3) = 16 attempts per click on inventory
4    product pods fail liveness (deep check), restart cold; gateway ejects them
5    every page fails, including pages that never call inventory
     With the defences: gateway deadline 800 ms, product deadline to inventory 300 ms,
     retries only in the gateway with a 10% budget, bulkhead of 40 for reviews,
     inventory sheds with 503 above 4 queued per worker, liveness without dependencies

What survives the service boundary: deadlines (as a header), criticality, idempotency keys, explicit overload statuses. What does not: shared memory, transactions, and any assumption that the other side will be fast. Service mesh retries count as a layer of retries; decide which layer owns them (Service Communication, API Gateway & Service Mesh).

Distributed data: replicas, caches, regions ​

Replicas cascade through replication lag (GitHub 2018: read replicas hours behind; adding replicas reduced per-replica utilisation so replication could catch up), failover automation (promotion across regions), and caches that became capacity caches. Regional failover is load redistribution at the largest scale: a region at 70% receiving another region's traffic is at 140%. Rules: headroom per region for the failover you plan, cross-region promotion only when the application can live with the latency, caches warmed before traffic shifts, and control planes (quota, auth, config) isolated from data planes (Google 2020: authentication was a shared dependency of almost everything). Replication mechanics live in Replication, Read Replicas & Failover.

Scaling path: 1x, 10x, 100x ​

ScaleTypical cascadeDefences that become necessary
1x (one region, a few instances)Slow query or partner pins all workersTimeouts everywhere, liveness without dependencies, worker limits
10x (many services, autoscaling)Retry storms across layers, health-check kills, cache stampedesRetry budgets, one retry layer, bounded queues, bulkheads, slow start, load tests past the knee
100x (multi-region, shared control planes)Global config pushes, regional failover overload, control-plane dependenciesStaged config rollout, cells, criticality propagation, edge shedding with ramps, chaos drills, independent monitoring

Lab: reproduce the death spiral and the fixes ​

The simulator and the tests are single-process Go and were run for this page. Everything else is labelled expected, not run.

bash
cd docs/snippets/system-design/cascading-failures/go
go test ./...
# ?    academy/cascading-failures/after        [no test files]
# ?    academy/cascading-failures/before       [no test files]
# ?    academy/cascading-failures/cmd/spiral   [no test files]
# ok   academy/cascading-failures/resilience   0.241s
# ok   academy/cascading-failures/spiral       0.371s
go run ./cmd/spiral          # deterministic, under a second

1. Timeline of the naive and protected systems (excerpt of the real output):

text
naive
t(s) offered attempts   good   late failed   shed    up   queue  kills
  18    1400     1400   1396      0      0      0    10       7      0
  20    2600     2600   1955      0      0      0    10     628      0
  24    2600     2600   1715      0      0      0    10    3783      0
  26    2600     2600    765    660      0      0     6    3527      4
  28    2600    10377      0      0   2590      0     0       0      1
  30    1400    12726      0      0   3776      0     0       0      0
  40    1400     2800    222    202      0      0     9    3586      0
  70    1400    13017      0      0   5179      0     0       0      0
protected
  20    2600     2858   1968      0    575    839    10      29      0
  28    2600     2859   1992      0    608    868    10      28      0
  30    1400     1421   1455      0      3     17    10       0      0
  40    1400     1408   1396      0      0      9    10       4      0

2. One defence at a time (goodput = good / offered; amplification = attempts / offered in 30–60 s):

text
config                                    0-20s   20-30s   30-60s   60-90s ampl30-60
naive                                     99.8%    44.2%     6.4%     6.2%     3.50x
naive + deadlines                         99.8%    25.8%     7.4%     7.2%     2.88x
naive + retry budget/jitter               99.8%    44.2%    14.0%    12.0%     1.08x
naive + bounded queue                     99.8%    76.8%   100.2%   100.0%     1.01x
naive + liveness-only health              99.8%    44.2%     4.5%     1.2%     2.83x
protected - bounded queue                 99.8%    26.0%    99.5%   100.0%     1.01x
protected                                 99.8%    76.5%   100.1%   100.0%     1.01x

What to read from it: in this model the bounded queue is the breaker that matters most, because it keeps latency below the client timeout, so timeouts and retries never start; deadlines alone make it worse (shorter timeouts with immediate retries fire more retries, 2.88x); the retry budget alone cuts amplification to 1.08x but cannot stop the GC and OOM loop of an unbounded queue; and the liveness-only probe alone removes the kills but leaves the queue loop. Values above 100% after the spike are requests from the previous second completing. These are model results that show the shape; your system's weights differ, which is why you run the same experiment against it.

3. Recovery actions and 4. the knee: see the tables in Recovery and Overload.

5. Shedding in the Go service, expected, not run. Start go run ./after with a fake inventory on inventory.internal (for example an /etc/hosts entry to a local stub that sleeps 2 s), then:

bash
hey -z 20s -c 600 http://localhost:8080/product            # expected, not run
# expected shape: a mix of 200 (stale copy, X-Degraded) and 503 with Retry-After;
# p99 latency stays near the 1 s budget instead of growing; no goroutine growth
curl -s localhost:8080/readyz | jq .saturation              # {"in_flight":256,"capacity":256,"waiting":128,...}

6. Health checks that kill, expected, not run. In a kind or minikube cluster, deploy the before service with livenessProbe.httpGet.path: /healthz and make inventory slow:

text
kubectl get pods -w                                          # expected, not run
# product-7c9   0/1   Running            3 (10s ago)
# product-7c9   0/1   CrashLoopBackOff   4 (5s ago)
kubectl describe pod product-7c9 | grep -i liveness
# Warning  Unhealthy  Liveness probe failed: HTTP probe failed with statuscode: 503

Switch the probe to /livez from after and the pods stay up while /readyz reports saturation.

Common misconceptions ​

BeliefReality
"The trigger is the root cause."The sustaining effect is; the trigger only explains the timing (Bronson et al.).
"Retries improve reliability."Under overload they multiply load per layer (64x, 243x); budgets and one retry layer are mandatory.
"Longer timeouts mean fewer failures."They mean more held resources and more doomed work; 5% hanging requests can cause 80% errors.
"A bigger queue absorbs overload."It converts overload into latency and memory; bound it and shed.
"Slow is better than down."Slow is worse for callers: it pins threads, connections and memory.
"Deep health checks are more accurate."They turn a slow dependency into a fleet-wide restart; check only the process for liveness.
"Autoscaling replaces headroom."It lags by minutes, can scale the wrong way, and can overload its own provisioning.
"Adding capacity fixes a death spiral."Often not: new servers arrive cold and are overloaded too; shed first, then ramp.
"Restart everything to clear it."A simultaneous restart is a thundering herd of cold servers; restart canaried and slowly.
"Load shedding lowers availability."It keeps goodput at capacity; accepting everything can serve nothing.
"A circuit breaker is enough."It helps for hard failures of one dependency; slow failures need deadlines and bulkheads.
"Our cache is an optimisation."If the service cannot survive an empty cache, it is a capacity cache and must be planned as one.
"Load tests at expected peak are enough."Test past the knee and the return to normal; that is where cascades live.
"CPU is the saturation signal."Threads waiting on I/O lower CPU; watch in-flight work, queue age and pool usage.

Cheat sheet ​

TopicRemember
DefinitionA failure that grows through positive feedback (Google SRE)
Death spiralOverload → latency → retries → exhaustion → failing checks → capacity removed → more overload
MetastablePersists after the trigger; needs a strong push (shed, then ramp)
GoodputUseful, on-time responses; must plateau at the knee, not fall
RetriesOne layer, 2–3 attempts, 10% budget, full jitter, never on 4xx or 429
DeadlinesSet once at the edge, propagate the remainder, drop expired work before starting it
QueuesShort (50% of workers or less), bounded, fast 503 at the limit; consider LIFO/CoDel
Slow vs downSlow pins resources; make slow into fast with timeouts and fail fast
Health checksLiveness = process only; readiness = start-up and draining; ceilings on ejection
CachesLatency cache vs capacity cache; coalesce misses; warm before traffic
AutoscalingLags; scale on saturation; keep N + 1 or N + 2 headroom
DetectionFour golden signals; saturation and p99 move first; attempts vs first attempts
RecoveryRevert, shed at edge, stop retries and scale-in, fix trigger, warm, ramp, drain backlog
PostmortemBlameless; name the loop and its breaker, not just the trigger
SimulatorNaive 6% goodput after the spike, 3.5x amplification; protected 100%, 1.01x

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A frontend has 1,000 threads and serves 1,000 QPS at 100 ms. 5% of requests start hanging until a 100 s deadline. Roughly what share of requests is served? Important ​

Answer

Answer: About 19.6%: the hanging share needs 50 × 100 = 5,000 thread-seconds per second plus 95 for the rest, against 1,000 available (Google SRE's bimodal-latency example); an 80.4% error rate from a 5% fault.

2 — Three layers each make 4 attempts. How many attempts can one click produce at the bottom, and what are the two cheapest fixes? Must-know ​

Answer

Answer: 4^3 = 64. Retry at one layer only (others fail fast and pass errors up) and add a per-client retry budget of about 10%, which keeps the overhead near 1.1x.

3 — Why did the naive simulator stay collapsed after load returned to 70% at 30 s? Good to know ​

Answer

Answer: A sustaining effect: latency above the client timeout produced retries (3.5x attempts), unbounded queues caused GC slowdown and OOM, health checks that waited in the queue killed servers, and restarted servers came back cold and were overloaded again. The trigger was gone; the loops were not.

4 — What is the difference between process health checking and service health checking, and which one should Kubernetes liveness use? Must-know ​

Answer

Answer: Process health asks whether the binary responds at all and is for the scheduler; service health asks whether it can serve this class of request now and is for the load balancer. Liveness should be process health only, with no dependency checks and no queueing behind traffic.

5 — Why can autoscaling on CPU scale a web tier down during a network incident? Important ​

Answer

Answer: Threads wait on slow I/O, so CPU utilisation drops while saturation (busy workers) rises; Slack's autoscaler first scaled down for exactly this reason. Scale on worker utilisation or queue age for I/O-bound tiers.

6 — A cache cluster restarts and the database falls over. What does "capacity cache" mean here, and name two mitigations. Important ​

Answer

Answer: The service cannot sustain its load with an empty cache, so the cache carries capacity, not just latency. Mitigations: coalesce misses per key (singleflight, Cache::lock), stale-while-revalidate (Cache::flexible), warming before traffic, provisioning or shedding for the cold case.

7 — During a collapse, why is "restart everything" risky, and what does slow start do? Important ​

Answer

Answer: All servers return cold at the same moment and receive full traffic, a thundering herd on restart that re-triggers the overload. Slow start (AWS ALB, Envoy) ramps the share of traffic to newly healthy hosts so caches and connections warm first.

8 — Name the order of a recovery runbook for a metastable failure. Important ​

Answer

Answer: Check and revert recent changes; shed at the edge (admit a small percentage) and stop retries and batch work; stop capacity removal; fix the trigger; let servers warm; ramp traffic gradually; drain backlogs at a controlled rate; re-enable retries and batch work last.

9 — Which of the four golden signals usually moves first in a cascade, and why is "attempts per first attempt" worth graphing? Important ​

Answer

Answer: Saturation and latency (Google SRE: latency increases are often a leading indicator of saturation). Attempts per first attempt above about 1.1 reveals a retry storm before error rates explain it.

10 — What was the sustaining or amplifying mechanism in each of S3 2017, Cloudflare 2019 and Google 2020? Good to know ​

Answer

Answer: S3: removed capacity forced full restarts of the index and placement subsystems, which had not been fully restarted for years. Cloudflare: one regex rule pushed globally in seconds exhausted CPU on every HTTP core, and the CPU protection had been removed. Google: automation cut the User ID Service's quota because usage was misreported as zero, so the Paxos leader could not write and authentication failed for almost every service.

11 — Why is a short client timeout without a retry budget sometimes worse than a long one? Must-know ​

Answer

Answer: Shorter timeouts fire retries sooner, so immediate retries arrive faster and amplification grows; in the simulator "naive + deadlines" was worse (25.8% during the spike, 2.88x amplification) than naive alone. Deadlines must come with retry discipline and server-side expiry checks.

Glossary ​

TermMeaning
Cascading failureA failure that grows through positive feedback, spreading from one part of a system to others
Positive feedback loopAn output (errors, latency, lost capacity) that increases its own input (load)
OverloadOffered load above the rate a server can complete useful work
GoodputResponses that are correct and fast enough to be used; throughput minus waste
KneeThe load at which goodput stops tracking offered load
Death spiralSelf-sustaining collapse: overload, latency, retries, exhaustion, capacity removal, more overload
Metastable failureA bad state that persists after the trigger is removed because of a sustaining effect
Vulnerable stateHealthy but efficient enough that a trigger can tip it into a metastable state
Sustaining effectThe loop (amplification or lost efficiency) that keeps a metastable failure going
TriggerThe event that starts a cascade (spike, deploy, partition, query of death)
Query of deathA request whose content crashes or exhausts the process that handles it
Retry stormA self-sustaining flood of retries against an overloaded service
Retry amplificationAttempts per logical request at the bottom of the stack (a^k across k layers)
Retry budgetA cap on retries as a share of first attempts (about 10%), per client or process
JitterRandomized delay that keeps clients from acting in sync; Full Jitter: random(0, min(cap, base·2^n))
Thundering herdMany clients waking and acting at the same moment
Thundering herd on restartAll servers returning cold at once and receiving full traffic
Cache stampedeMany readers missing the same key at once and hitting the origin (dogpile)
Latency cache / capacity cacheA cache the service can live without / one it cannot sustain load without
Cache warmingFilling a cache before it takes traffic
Connection pool exhaustionAll pool connections held, new work waits or fails
Thread pool exhaustionAll workers busy (often waiting), nothing left for new requests or probes
File descriptor exhaustionPer-process open-file limit reached; EMFILE "Too many open files"
Ephemeral port exhaustionNo free local ports for new outbound connections; EADDRNOTAVAIL
GC pressureGarbage-collection work growing with heap use, stealing CPU (GC death spiral)
Queue depthNumber of requests waiting for a worker; times service time / workers = wait
Unbounded queueA queue with no limit; overload becomes memory growth and OOM
Head-of-line blockingItems behind a slow item in FIFO order wait for it
TimeoutMaximum wait for one operation
DeadlineAbsolute time after which a result is worthless
Deadline propagationPassing the same absolute deadline (as remaining time) to every downstream call
Cancellation propagationTelling downstream calls to stop when the request can no longer succeed
Bimodal latencyMost requests fast, a few hanging until the deadline; holds resources disproportionately
Slow vs downSlow failures hold resources and are worse for callers than fast failures
Fail fastReturn an error immediately when success is impossible or a dependency is known down
Circuit breakerA client-side switch that stops calls to a failing dependency for a while
BulkheadA fixed share of resources per dependency, tenant or criticality
Dependency isolationDesigning so one dependency cannot exhaust shared resources
Load sheddingRejecting part of the load cheaply to keep the rest fast
Admission controlThe decision whether to accept a request (in-flight limit, token bucket, utilisation)
BackpressureA signal upstream to slow down instead of buffering without limit
Client-side throttlingClients reject locally when backends reject many requests (adaptive throttling)
CriticalityRequest importance label (CRITICAL_PLUS ... SHEDDABLE) used to shed the least important first
Graceful degradationDoing less work per request (cheaper or partial results) under overload
HeadroomCapacity above peak load; N + 2 means surviving the loss of two units
Autoscaler lagTime between overload starting and new capacity serving
Health check flappingA host alternating healthy/unhealthy because the check depends on load
Capacity removalAny action that takes serving capacity out (ejection, kill, drain, scale-in)
Lame duckA server that is draining and asks clients to stop sending new work
Panic thresholdEnvoy behaviour: ignore health status when too few hosts are healthy (default 50%)
Slow startA load-balancer ramp of traffic to newly healthy hosts
Gradual recoveryBringing traffic back in steps after a collapse, with warm-up between steps
Four golden signalsLatency, traffic, errors, saturation (Google SRE)
SaturationHow full the service is: in-flight / limit, queue age, pool usage
Latency SLO burnRate at which slow requests consume the latency error budget
Error ratioErrors divided by requests; retries divided by first attempts reveals storms
Synchronized cronScheduled jobs from many clients firing at the same instant
Leader thrashLeadership moving repeatedly under load, each move causing reconnects and rebuilds
Hedged requestA duplicate request sent after a delay to cut tail latency; adds load
PostmortemA written analysis of an incident with action items
BlamelessFocused on contributing causes, without indicting individuals or teams

References ​

Built by Morteza Negahi