Skip to content

Chaos Engineering & Game Days ​

"Chaos Engineering is the discipline of experimenting on a system in order to build confidence in the system’s capability to withstand turbulent conditions in production." — Principles of Chaos Engineering, principlesofchaos.org

Summary: Chaos engineering is controlled experimentation: you state what "healthy" looks like in numbers, inject one realistic failure into a small part of the system, and check whether the numbers stay healthy; game days are the same idea practised by people, with runbooks, roles and a debrief. Focus: Steady state and hypothesis, the five principles, the history (Chaos Monkey, Chaos Kong, FIT, GameDay, DiRT), experiment design with abort conditions and blast radius, the fault catalogue (latency, errors, instance, AZ and region loss, dependency outage, resource exhaustion, clock skew, partition, DNS, certificate expiry, disk full), tooling (Chaos Mesh, LitmusChaos, Gremlin, AWS Fault Injection Service, Toxiproxy, tc netem, Istio, Envoy), application-level injection, game days, chaos in CI, observability prerequisites, safety and culture, measuring resilience, anti-patterns. Learning goal: Write a one-page experiment (steady-state SLI, hypothesis, fault, blast radius, abort condition, kill switch), run it safely in a test and then in a small slice of production, run a game day that validates a runbook, and know which experiments you should not run yet.

This chapter closes the resilience story. Cascading Failures explains how one slow service takes down the rest; Timeouts, Retries & Jitter, the Circuit Breaker, Bulkheads & Graceful Degradation and Load Shedding are the defences. Chaos engineering is how you find out whether those defences work in your system and not just in the library's README. It needs Observability first, hands its findings to Alerting That Actually Works, and its large scenarios are the rehearsal for Capacity Planning, Failure Scenarios & Disaster Recovery. SLO and SLI definitions live in SLAs, SLOs, SLIs & Error Budgets.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why test failure on purposeWhy it exists
Chaos Monkey, Chaos Kong, FIT, GameDay, DiRTWhere it comes from
The five principlesPrinciples
Steady state, hypothesis, SLISteady state
Write an experimentExperiment design
Blast radius, canary, abort, kill switchBlast radius
Which faults to injectThe fault catalogue
Chaos Mesh, Litmus, Gremlin, AWS FIS, Toxiproxy, tc netemTooling
Istio and Envoy fault injectionMesh faults
Faults inside your own codeApplication-level injection
Running a game dayGame days
Chaos in a pipelineContinuous verification
What you must have before startingObservability prerequisites
Blameless culture, change control, complianceOrganisational safety
MTTR, RTO, resilience scoreMeasuring resilience
What goes wrongAnti-patterns
Knobs and error namesMechanics
CodeGo, Laravel
Classic findings and fixesSolving the classic problems
Which experiment nextChoosing
Monolith to multi-regionIn architecture
Run itLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The experiment, step by step.

StepQuestion it answersExample
Steady stateWhat does "working" mean, as a number?Checkout success rate at least 99.5%, p99 below 800 ms
HypothesisWhat do we believe will not change?"If the recommendations service returns 503, checkout success stays at 99.5%"
VariableWhat real-world event do we introduce?60% of calls to recommendations fail with 503
Blast radiusHow many users can this hurt?Header-tagged test users, then 1% of traffic
Abort conditionWhen do we stop automatically?Checkout success below 98% for 20 consecutive probes
Kill switchHow do we stop by hand, in seconds?Feature flag off, stop() function, FIS stop condition
VerdictWhat did we learn?HELD, REFUTED, ABORTED or INVALID (steady state was not steady)

Faults and the real event behind each.

FaultReal event it imitatesTypical tool
Latency injectionOverloaded dependency, GC pause, slow diskToxiproxy latency, tc netem delay, Istio fault.delay
Error injectionDependency returns 500 or 503, resets the connectionIstio fault.abort, Envoy fault filter, middleware
Instance terminationHost crash, spot reclaim, OOM killChaos Monkey, Chaos Mesh PodChaos, AWS FIS aws:ec2:terminate-instances
AZ failurePower or network loss in one data centreAWS FIS network disrupt, a drain script
Region failureProvider-wide eventChaos Kong style evacuation drill
Dependency outageA third-party API is downToxiproxy down, Http::fake
Resource exhaustionCPU, memory, file descriptors, threadsChaos Mesh StressChaos, Gremlin resource attacks
Clock skewNTP failure, leap second, VM pauseChaos Mesh TimeChaos, faketime or a VM clock offset
Network partitionSwitch failure, bad routeChaos Mesh NetworkChaos partition, iptables drop
DNS failureResolver down, record deletedChaos Mesh DNSChaos, blackhole port 53
Certificate expiryA forgotten cert on a timerTest CA with a short-lived cert
Disk fullLog or WAL growthfallocate a big file, Chaos Mesh IOChaos

Where to run what.

EnvironmentWhat you learnRiskRule
Unit test with fakes (Http::fake, a fake RoundTripper)Your fallback code path exists and returnsNoneRun on every commit
Staging with Toxiproxy or a meshTimeouts, retries and breakers are tunedLowRun nightly
Production canary or header-tagged usersReal traffic, real dependenciesContainedNeeds observability, abort, kill switch
Production at a percentageCapacity and cross-service effectsRealNeeds on-call present, business hours
Game day, AZ or regionPeople, runbooks, communicationPlannedNeeds announcement and a debrief

The vocabulary of numbers.

TermMeaningWhere used
SLIA measured indicator, such as success rateSteady state
SLOThe target for an SLIHypothesis threshold
MTTRMean time to recoveryResilience measure
RTORecovery time objective: how long an outage may lastGame day pass mark
RPORecovery point objective: how much data may be lostFailover drills
Error budgetAllowed unreliability per windowGate for running chaos

Why it exists ​

Every component has a failure mode that you only discover in an incident. Reading code, review and unit tests find logic bugs; they do not find "the retry policy of service A multiplies the load that service B cannot take". Those are properties of the whole system, and they appear only when a dependency misbehaves in a particular way. You can wait for that to happen at 3 a.m., or you can arrange for it to happen at 11 a.m. on a Tuesday, in a small slice, with the team watching, and with a stop button.

Wait for incidentsRun experiments
Failure arrives at a random time, at full scaleFailure arrives at a chosen time, at a chosen scale
People are tired, the runbook is untestedPeople are present, the runbook is the thing under test
You learn the cause after the damageYou learn the weakness before the damage
One data point per quarterMany small data points per week
Fixes are rushedFixes are planned work

Everyday picture used through the page: a fire drill. Nobody sets the building on fire to test the exits. You pick a time, tell the wardens, close one staircase, and watch where people go. You time it, then you write down that the third-floor door was locked. Chaos engineering closes one staircase; a game day is the drill with all the wardens.

Three common misunderstandings, up front ​

  1. "Chaos engineering means breaking things randomly in production." The value is in the hypothesis, the small blast radius and the measurement. Random breakage without those is just an outage.
  2. "We need Kubernetes and a chaos platform first." The first experiment can be a tabletop on paper, or a test with a fake that returns 503. Tools matter after the question is clear.
  3. "If the experiment passes, the system is resilient." It passes for that fault, at that load, on that day. It is evidence, not proof, and it decays when the system changes.

Where it comes from {#history} Good to know ​

YearEventSource status
2003Jesse Robbins starts "GameDay" exercises at Amazon (he is described as holding the title "Master of Disaster")Inference from memory; not fetched for this page
2006Google starts DiRT (Disaster Recovery Testing), later described by Kripa Krishnan in ACM Queue ("Weathering the Unexpected", 2012)ACM Queue page could not be fetched here; treat as unverified
2010 to 2011Netflix builds Chaos Monkey after moving to AWS; it terminates instances at random in business hours; later grouped with Latency Monkey, Chaos Gorilla (an AZ) and others as the Simian Army (2011 blog post)Chaos Monkey confirmed by the 2016 paper below; the Simian Army post could not be fetched here
2014Netflix describes FIT (Failure Injection Testing): fail requests between services, scoped by requestNamed in the 2016 paper's reference list
2016Basiri et al., "Chaos Engineering", IEEE Software 33(3)Fetched and read (arXiv:1702.05843)
2016Principles of Chaos Engineering publishedFetched and read
2017Netflix ChAP (Chaos Automation Platform) runs experiments as a canary against a baselineNetflix blog could not be fetched; treat as unverified
2020sManaged services: AWS Fault Injection Service, Gremlin; CNCF projects Chaos Mesh and LitmusChaosVendor docs fetched

What the 2016 paper says about the origin, in its own words: Netflix had been "running an internal service called Chaos Monkey, which randomly selects virtual machine instances that host our production services and terminates them", and it runs "during normal working hours so that engineers can respond quickly". It then extended the approach: "we perform 'Chaos Kong' exercises that simulate the failure of an entire Amazon EC2 region", and run FIT exercises "where we cause requests between Netflix services to fail and verify that the system degrades gracefully". On cadence it says Chaos Monkey runs continuously on weekdays while Chaos Kong runs about once a month.

Google's SRE book describes the people side of the same practice as "Wheel of Misfortune" (also "Walk the Plank"), a regular disaster role-playing exercise for on-call engineers; see References.

The AWS "GameDay" page you can fetch today describes a gamified learning event for AWS customers, which is a different thing from the internal reliability exercise; do not conflate them.

The concept catalogue ​

The five principles Must-know ​

In plain words: you do not "try random failures"; you follow a recipe: define normal, guess it will stay normal, introduce a realistic failure, use real traffic, automate, and keep the damage small.

Common misunderstanding: "Production testing is reckless." The site's own principle is that the engineer must keep the fallout of experiments "minimized and contained"; the recklessness is in skipping the safeguards, not in using production.

Definition: The Principles of Chaos Engineering list: build a hypothesis around steady-state behaviour; vary real-world events; run experiments in production; automate experiments to run continuously; minimise blast radius.

1  Define steady state    -> success rate >= 99.5%, p99 <= 800 ms
2  Hypothesise            -> it stays inside bounds in control AND experiment group
3  Vary real-world events -> kill instance, add 300 ms, return 503, drop DNS
4  Run on real traffic    -> start tiny: canary, then 1%
5  Automate + minimise    -> abort condition, kill switch, budget, schedule

Real scenario: an e-commerce team states that the product page must keep serving when "reviews" is down. Principle 3 turns that into "return 503 for reviews"; principle 5 makes it a nightly job so a refactor that removes the fallback fails the next run.

PrincipleWording on principlesofchaos.org (shortened)What it forbids
Hypothesis around steady stateFocus on measurable output, not internal attributes"CPU stays low" as the hypothesis
Vary real-world eventsServers that crash, hard drives that malfunction, connections severedExotic, unrealistic faults
Run in productionBehaviour depends on environment and trafficConcluding from staging alone
AutomateManual runs are "labor-intensive and ultimately unsustainable"One-off heroics
Minimise blast radiusFallout "minimized and contained"Whole-fleet first runs

Fix / how to use it: write the five lines above on the experiment page before touching a tool. The Go runner in Go has these as fields: Hypothesis, Inject, AbortBelow, a probe on real endpoints.

Steady state and the hypothesis Must-know ​

In plain words: pick one or two numbers customers feel (orders per minute, successful requests, p99 latency), measure them while nothing is wrong, and promise that the number will not move when you break something.

Common misunderstanding: "Steady state means no errors." It means the normal band, including normal noise. If the success rate is normally 99.7% with a daily dip to 99.4%, a hypothesis of "stays above 99.9%" is already false before you inject anything.

Definition: Steady state is the typical behaviour of a business-level metric over time at the system boundary; the hypothesis states it holds in the experimental group as in the control group. The 2016 paper stresses measuring "metrics at the system boundary" rather than internal attributes.

 t        control group        experiment group      verdict
 1  10:00 99.7% ok  p99 410ms   99.6% ok  p99 430ms   within noise
 2  10:05 99.7% ok  p99 405ms   97.1% ok  p99 2.9s    hypothesis refuted
 3  10:06 fault removed         99.6% ok  p99 440ms   recovered

Real scenario: a payment service SLI is "authorisations answered in under 2 s". During a Toxiproxy latency test the SLI falls to 91% because the fraud service call has no timeout. The steady-state metric caught what a CPU graph would not.

Good steady-state metricPoor metricWhy
Successful checkouts per minuteCPU utilisationUsers do not feel CPU
p99 latency of the user-facing callAverage latencyThe mean hides the tail
Fraction of requests served from fallbackNumber of retriesRetries are an internal attribute
Messages processed per second at the consumerQueue length aloneLength is a symptom, rate is the outcome

Compare control and experiment groups when you can (a canary vs the baseline, header-tagged vs untagged traffic); that is how Netflix's ChAP approach removes daily traffic swings from the comparison.

sql
-- Store experiment results so verdicts are comparable over time.
CREATE TABLE chaos_runs (
  id            bigserial PRIMARY KEY,
  experiment    text        NOT NULL,
  started_at    timestamptz NOT NULL DEFAULT now(),
  verdict       text        NOT NULL CHECK (verdict IN ('HELD','REFUTED','ABORTED','INVALID')),
  before_ok     numeric(6,4) NOT NULL,
  during_ok     numeric(6,4) NOT NULL,
  after_ok      numeric(6,4) NOT NULL,
  during_p99_ms integer,
  aborted_at    integer,
  notes         text
);

-- Which experiments keep failing (candidates for a fix or a retirement)?
SELECT experiment,
       count(*) FILTER (WHERE verdict = 'REFUTED') AS refuted,
       count(*) AS runs
FROM chaos_runs
WHERE started_at > now() - interval '90 days'
GROUP BY experiment
ORDER BY refuted DESC;

Experiment design Must-know ​

In plain words: an experiment is a one-page contract written before the run: what, how big, when to stop, who is watching.

Common misunderstanding: "More faults at once finds more bugs." Two faults at once make the result ambiguous; change one variable per run, then combine them in a later scenario on purpose.

Definition: an experiment has a steady-state SLI, a hypothesis, one injected variable, a scope (blast radius), an abort condition, a kill switch, a duration, an owner and a rollback.

experiment: recommendations-503
owner:      payments-oncall            window: weekdays 10:00-15:00
steady:     checkout_success >= 99.5%  p99 <= 800ms (5 min rolling)
hypothesis: checkout_success stays >= 99.5% when recs returns 503 for 60% of calls
variable:   Istio fault.abort 503 on 60% of requests to recs
scope:      header x-chaos-cohort=canary (about 0.5% of traffic)
abort:      checkout_success < 98% for 20 consecutive probes  -> stop() automatically
kill:       VirtualService rollback via one command / flag off
duration:   10 min        after: verify SLI recovered within 2 min
FieldQuestionBad answerGood answer
Steady stateHow do we know it works?"No alerts"A numeric SLI and a band
VariableWhat changes?"Stress the system"One named fault, one parameter
ScopeWho can be hurt?"Production"A cohort, a percentage, a budget
AbortWhen do we stop alone?"If it looks bad"A threshold over a window, automated
KillHow do we stop by hand?"Redeploy"One command that takes seconds
OwnerWho is watching?"Everyone"One named person on call

Blast radius, canary, abort condition, kill switch Must-know ​

In plain words: blast radius is how many users can be hurt; abort condition is the automatic "stop" when the numbers go bad; the kill switch is the manual one.

Common misunderstanding: "A kill switch is the same as an abort condition." The abort condition is a rule evaluated by a machine on metrics; the kill switch is a button for a human who noticed something the metrics did not. You need both, and you must test the kill switch before the experiment, not during it.

Definition: blast radius is the set of users, requests and resources an experiment can affect. A canary experiment applies the fault to a small, comparable slice and keeps the rest as the control. AWS Fault Injection Service calls its automatic stop a "stop condition": "a mechanism to stop an experiment if it reaches a threshold that you define".

T0   probe baseline 200 samples       ok=100%  p99=170us   (steady, go)
T1   arm fault: 60% of recs calls -> 503, budget 10000 faults
T2   probe #1..#20                    ok=45%               abort window full
T3   window ok 45% < 20%? no          continue
T4   probe #136                       window ok=15% < 20%  -> ABORT
T5   stop(): injector disabled, flag off
T6   probe 200 samples                ok=100%              recovered
ControlTypeTriggered byTested how
Allowlist (hosts, paths, cohort)ScopeConfigurationTest that a non-listed path is untouched
Budget (max faults)ScopeCounterTest that the injector disarms itself
Abort conditionAutomaticMetric threshold over a windowRun a fault you know will trip it
Kill switchManualA humanRun it in staging before every production run
Time boxAutomaticClockThe job ends even if the controller dies
Business-hours windowPolicySchedulerReview the cron

Climb in steps: a fake in a unit test, then staging, then one canary instance or header-tagged test users, then 1% of production, then an AZ, then a region (see the picture).

CI testHttp::fakeStagingToxiproxygame dayCanary1 instance orheader-taggedtest users1% of prodbudget capbusiness hoursOne AZplanned gameday, on callRegionevacuationdrillearn each step: previous step passed, abort condition tightened, kill switch tested

The fault catalogue Must-know ​

In plain words: start with the failures you have actually had or are most afraid of, not the exotic ones.

Common misunderstanding: "Killing a server is the main chaos test." Instances usually die cleanly and cheaply; slow, partial and wrong behaviour (latency, 20% errors, truncated bodies, skewed clocks) does far more damage because nothing flips a health check.

Definition: the catalogue below lists faults by what they imitate and what usually goes wrong.

FaultHow to inject (product)What usually breaks
Latency injectionToxiproxy latency toxic, tc netem delay 300ms 50ms, Istio fault.delay, Envoy delayMissing timeouts, thread pool exhaustion, retry storms
Error injectionIstio fault.abort.httpStatus, Envoy abort, middleware returning 503Retries on non-idempotent calls, no fallback
Partial responseToxiproxy limit_data, slicer, body truncationJSON parse crashes, half-written cache entries
Instance terminationChaos Monkey, Chaos Mesh PodChaos pod-kill, AWS FIS aws:ec2:terminate-instances, kubectl delete podLocal state lost, slow warm-up, in-flight requests dropped
Process freezekill -STOP <pid> then kill -CONT <pid>Failure detectors, leader leases, TCP half-open connections
AZ failureAWS FIS network disrupt for one subnet, draining a zoneSingle-AZ dependencies, uneven capacity
Region failureChaos Kong style evacuation, DNS weight to zeroHidden cross-region dependencies, cold caches
Dependency outageToxiproxy down, firewall drop, Http::fake failuresMissing circuit breaker or fallback
Resource exhaustionChaos Mesh StressChaos (CPU, memory), Gremlin resource attacks, file descriptor limitAutoscaling lag, OOM kills, no load shedding
Clock skewChaos Mesh TimeChaos, faketime or a VM clock offsetToken validation, lease expiry, ordering by timestamp
Network partitionChaos Mesh NetworkChaos, iptables drop between groupsSplit brain, double leaders, unavailable minority
Packet loss and jittertc netem loss 5%, delay with jitterTCP stalls, gRPC deadline misses
DNS failureChaos Mesh DNSChaos, block UDP/TCP 53, wrong TTLCached-forever resolvers, connection pools holding dead IPs
Certificate expiryA test CA issuing 5-minute certificatesMissing rotation, no alert before expiry
Disk fullfallocate -l to fill a volume, Chaos Mesh IOChaosLogging blocks requests, database stops writing
$ sudo tc qdisc add dev eth0 root netem delay 200ms 50ms loss 2%
$ sudo tc qdisc show dev eth0
qdisc netem 8001: root refid 1 limit 1000 delay 200ms  50ms loss 2%
$ sudo tc qdisc del dev eth0 root          # the "kill switch"

Expected, not run; the netem options (delay, loss, corrupt, duplicate, reorder) come from the tc-netem manual page.

The next four blocks take the faults that most often teach something new.

Latency, timeouts and retries Must-know ​

In plain words: a dependency that is slow is worse than one that is dead, because callers wait.

Common misunderstanding: "Our timeout is 30 seconds, so we are safe." Thirty seconds of threads held per request, multiplied by traffic, is the outage; see Timeouts, Retries & Jitter.

Definition: latency injection adds delay before a call proceeds. The experiment's hypothesis is usually "p99 of the caller stays inside its budget" (Latency Budgets).

caller  --(timeout 2s, 3 retries)--> dependency (+3s injected)
1  t=0.0  attempt 1 sent
2  t=2.0  timeout, retry 2
3  t=4.0  timeout, retry 3
4  t=6.0  give up: the user waited 6 s and the dependency saw 3x load

Real scenario: a checkout flow calls a loyalty service. With +400 ms the p99 goes from 0.8 s to 1.3 s. With +4 s the pool of 50 workers fills in seconds and unrelated endpoints time out too: a bulkhead was missing.

What you verifyPass condition
Timeout shorter than the caller's own deadlineCaller answers within budget
Retries bounded and jitteredDependency load rises less than 2x
Circuit opensCalls fail fast after N failures (Circuit Breaker)
Fallback existsDegraded answer, not a stack trace

Resource exhaustion, clock skew and kill -STOP Important ​

In plain words: machines fail slowly and strangely: full disks, frozen processes, drifting clocks.

Common misunderstanding: "The health check will notice." A process stopped with kill -STOP still holds its listening socket; the kernel completes TCP handshakes, and a TCP-only check says healthy while no request is ever answered.

Definition: these faults leave the machine up but wrong. kill -STOP freezes a process (resume with kill -CONT), which imitates a long GC pause or a hung VM and tests failure detectors and leader leases (Leader Election, Gossip Protocols).

1  kill -STOP 4242         # leader process frozen, socket still open
2  lease expires at +10 s  # follower elects itself
3  kill -CONT 4242         # old leader wakes, still believes it leads
4  without fencing tokens: two writers

Real scenario: a job runner dedupes with timestamps; with a 90-second clock skew on one node, it accepts a replayed message as new. Disk-full on the log volume blocks every request thread that writes a log line synchronously.

FaultCheck
Disk fullService degrades but keeps serving reads; alert fires at 80%
CPU stressAutoscaler adds capacity before p99 breaches; Load Shedding works
Clock skewTokens, leases and ordering tolerate the skew you promised
Frozen processFailure detector removes it within the stated time; fencing tokens protect writes

Partition, DNS failure and certificate expiry Important ​

In plain words: the network lies: some machines can talk to some others, names stop resolving, a certificate quietly runs out.

Common misunderstanding: "Certificate expiry is a security topic, not a resilience one." It is a perfectly predictable outage that many companies still have; you can rehearse it with a certificate that lasts five minutes.

Definition: a partition is loss of connectivity between groups of nodes; DNS failure is loss of name resolution or a stale answer; certificate expiry is a time bomb in the TLS layer (TLS in practice, Cryptography in Practice).

1  t=0    drop traffic between {A,B} and {C} with iptables
2  t=5s   C cannot reach the leader; C is a minority
3  t=10s  CP system: C refuses writes. AP system: C accepts writes -> conflicts later
4  t=60s  heal partition, check reconciliation  (see CAP and PACELC)

Real scenario: a client library caches DNS answers forever; after a failover, half the fleet keeps connecting to the dead IP. A mutual-TLS certificate between two services expires on a Sunday; nobody had an alert for "30 days to expiry".

FaultExpected behaviourVerify
PartitionMatches the documented side of CAPMinority refuses or reconciles
DNS failureCached answers used for TTL; clear error afterwardsResolver cache, connection pool refresh
Certificate expiryAlert 30 days and 7 days before; automated rotationShort-lived cert test

Dependency outage and AZ or region failure Must-know ​

In plain words: pretend a whole dependency or a whole data centre is gone.

Common misunderstanding: "We run in three AZs, so an AZ loss is fine." Only if the remaining two can carry the load, the load balancer drains the third, the database fails over and no component quietly lives in one AZ. Each of those has been the surprise in a real drill.

Definition: dependency outage means all calls to one dependency fail; AZ or region failure removes a failure domain. The Netflix paper's Chaos Kong exercise simulates the loss of an entire EC2 region and, per the paper, runs about monthly.

1  drain AZ-b                       (load balancer deregisters targets)
2  remaining AZs take +50% traffic  (capacity check: headroom >= 50%?)
3  database primary was in AZ-b     -> failover 30-60 s (measured, not guessed)
4  cache cold in new primary region -> origin load spike
5  record: time to steady state = MTTR for this scenario
ScenarioQuestionEvidence
One dependency downDoes the product degrade or die?Fallback hit rate
One AZ goneDo the other AZs hold the peak?CPU and queue depth after drain
Region evacuationDoes DNS or traffic steering move users in the time we promise?Time to 99% of traffic elsewhere
Backups and failoverDoes restore work?Restore test; see Capacity Planning & DR

Tooling Important ​

In plain words: pick the cheapest tool that can inject the fault you need.

Common misunderstanding: "Gremlin or Chaos Mesh is chaos engineering." The tool is only the actuator. A kill-the-pods run without a steady-state check and an abort rule is a demo.

Definition: the tools differ in where they act (process, container, network, cloud API) and in what safety features they bring.

ToolActs atFaultsSafety featuresNotes
Chaos Monkey (Netflix)VM instanceTerminate instanceBusiness hours, opt-in groupsThe origin
Chaos Mesh (CNCF)KubernetesPodChaos, NetworkChaos, StressChaos, IOChaos, TimeChaos, DNSChaosNamespace scoping, schedules, workflows, dashboardOpen source; chaos-daemon runs privileged
LitmusChaos (CNCF)KubernetesPod, node, network, cloud faults via ChaosHub experimentsChaosCenter, probes that check steady stateOpen source, "cross-cloud support"
GremlinHosts, containers, KubernetesResource, network and state attacksReliability Score, scenarios (verify other safety features in vendor docs)Commercial
AWS Fault Injection ServiceAWS control planeStop or terminate EC2, throttle APIs, network disruptionExperiment templates with stop conditions, IAM roleManaged; "carries out real actions on real AWS resources"
Toxiproxy (Shopify)TCP proxylatency, down, bandwidth, slow_close, timeout, reset_peer, slicer, limit_dataToxics added and removed over an HTTP APIBest for tests and staging
tc netem (Linux)Kernel qdiscdelay, loss, corrupt, duplicate, reorder, ratetc qdisc del to removeRoot needed; whole interface
Istio fault injectionEnvoy sidecarHTTP delay, HTTP abortPer route, per header match, percentageNo app change
Envoy fault filterEnvoydelay, abort, rate limit; header controlledPercentages, header-driven overridesx-envoy-fault-delay-request, x-envoy-fault-abort-request
Kubernetes pod deletionAPIDelete a podNone built in; use --grace-period, namespacesThe simplest chaos test
$ toxiproxy-cli create --listen 127.0.0.1:26379 --upstream 127.0.0.1:6379 redis
$ toxiproxy-cli toxic add -t latency -a latency=1000 redis
$ toxiproxy-cli toxic remove -n latency_downstream redis
# Expected, not run; syntax from the Toxiproxy README.
Applicationfeature-flagged middleware, fault-injecting HTTP client, test hooks- most precise, cheapest, you must ship the codeSidecar / mesh / gatewayIstio fault injection (delay, abort), Envoy fault filter, header-driven- no code change, per route and per headerTCP proxyToxiproxy toxics: latency, down, bandwidth, timeout, reset_peer, slicer- great for tests and stagingKernel / networktc qdisc netem delay, loss, duplicate, reorder; iptables drop for a partition- needs root; affects the whole interfacePlatformChaos Mesh, LitmusChaos, Gremlin: pod kill, kill -STOP, CPU, disk, clock; AWS FIS: stop EC2, AZ- widest blast radius, needs guardrails

Mesh faults: Istio and Envoy Important ​

In plain words: if you already run a mesh, you can ask the sidecar to be the broken dependency.

Common misunderstanding: "Mesh fault injection tests the service." It tests the caller. The sidecar of the caller returns the fault, so the target service never sees the request; to test the target's own overload behaviour you need load, not a mesh abort.

Definition: Istio's VirtualService has fault.delay (fixed delay, percentage) and fault.abort (httpStatus, percentage). The Envoy HTTP fault filter delays or aborts requests with user-specified error codes, and the headers x-envoy-fault-delay-request (milliseconds) and x-envoy-fault-abort-request (status code) let a single request choose its own fault when the filter is configured to honour them.

yaml
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata: {name: recommendations}
spec:
  hosts: [recommendations]
  http:
  - match: [{headers: {x-chaos-cohort: {exact: canary}}}]
    fault:
      abort: {httpStatus: 503, percentage: {value: 60}}
    route: [{destination: {host: recommendations}}]
  - route: [{destination: {host: recommendations}}]

Expected, not run. The header match keeps the blast radius to tagged traffic; deleting the first http rule is the kill switch. See Service Mesh & the Sidecar Pattern and Containers & Kubernetes.

AspectIstio faultEnvoy fault filterApp middleware
Needs code changeNoNo (config)Yes
Fault typesdelay, abortdelay, abort, response rate limitAnything
Per request controlHeader matchFault headersHeader with token
Fault inside the calleeNo (caller side)NoYes

Application-level fault injection Must-know ​

In plain words: put the switch inside your own code, behind a feature flag, so developers can break a dependency on purpose from a test or a header.

Common misunderstanding: "Test hooks in production code are dangerous." Unprotected ones are. A hook that is off by default, behind a flag, allowlisted, token protected, capped by a budget and logged is safer than a sleep someone adds during an incident.

Definition: fault-injection middleware or a fault-injecting HTTP client chooses a fault for a request based on a feature flag, an allowlist, a probability and an optional signed header, and reports what it injected.

1  request arrives, flag "chaos-faults" is OFF         -> pass through (default)
2  flag ON, path not on allowlist                     -> pass through
3  flag ON, allowlisted, header X-Chaos token wrong   -> ignore header, use probability
4  flag ON, allowlisted, budget left, rule fires      -> sleep / 503 / truncate, set X-Chaos-Injected
5  budget spent                                       -> injector disarms itself
Safety propertyGo implementationLaravel implementation
Off by defaultInjector zero value injects nothingPennant flag defined as false
Kill switchDisable()Feature::for('global')->deactivate(...)
AllowlistAllowHosts, AllowPrefixesconfig('chaos.allow'), deny list
BudgetMaxInjectionsCache::increment in a time window
Secret headerTokenhash_equals on the token
Cap on latency10 s in parseHeadermax_latency_ms

Game days Must-know ​

In plain words: a game day is a scheduled rehearsal of a bad day, with the real team, the real runbook and a facilitator who breaks something.

Common misunderstanding: "A game day is a chaos test with an audience." The thing under test is the people and the process: can on-call find the dashboard, does the runbook's command still work, who tells customer support?

Definition: a game day is a planned exercise that injects a failure (live) or describes one (tabletop exercise) and measures detection, diagnosis, mitigation and communication. Google's SRE book describes the paper version as the "Wheel of Misfortune" role-play.

Week -2  choose scenario, owner, facilitator, scribe; read the runbook
Week -1  announce to support, stakeholders; confirm abort criteria; test the kill switch
Day 0    09:30 briefing      10:00 inject      10:00-11:00 respond
         11:00 stop (or earlier on abort)      11:15 hot debrief
Day +2   written debrief, blameless; action items with owners and dates
Day +30  rerun the scenario; did the fix work?
RoleDuty
Facilitator (game master)Runs the clock, injects, can pause or abort
RespondersThe people on call, using normal tools and the runbook
Observer / scribeRecords timestamps: detected, diagnosed, mitigated
Safety officerOwns the abort criteria and the kill switch
CommunicationsPlays customer support or status page owner
FormWhat it testsCostWhen
Tabletop exerciseDecisions, communication, runbook readingLow (one hour, no systems)First, and for scary scenarios
Live staging game dayRunbook commands, tooling, alertsMediumQuarterly
Live production game dayReal behaviour at real scaleHighAfter staging passes, announced
Surprise drillDetection and escalation without warningHigh; needs consentMature teams only

Runbook validation is the quiet win: every step is executed by a person who did not write it. Typical findings: a command that needs a role nobody has, a dashboard link that is dead, a "page the DBA" step with no DBA on call.

Communication rules: a named channel, a status-page owner, a rule that the facilitator always speaks as "exercise" so nobody calls a real incident by mistake, and a stated end time.

Debrief: timeline of detection and mitigation, what surprised us, what worked, action items. Blameless means asking "what made this the reasonable thing to do?" instead of "who did it?". Action items without owners and dates are wishes.

Chaos in CI: continuous verification Important ​

In plain words: run the cheap experiments on every build so a refactor cannot silently delete a fallback.

Common misunderstanding: "Chaos in CI means running Chaos Mesh in the pipeline." Most value comes from small deterministic tests: a fake that returns 503, a latency injected by a test double, and assertions on the fallback and the number of attempts.

Definition: continuous verification runs experiments automatically and on a schedule: fast fault-injection tests per commit, a nightly Toxiproxy suite in staging, a weekly small production canary. The fourth principle: "Automate Experiments to Run Continuously".

commit  -> unit:    Http::fake sequence 503,503 -> fallback used, 2 attempts   (seconds)
merge   -> staging: Toxiproxy latency +1s on db   -> p99 < 800 ms             (minutes)
nightly -> staging: kill 1 of 3 pods under load   -> success >= 99.5%
weekly  -> prod:    header-tagged 503 on recs     -> HELD, else ticket
LayerRunsFailure means
Unit fault testEvery commitFallback code removed or broken
Integration with ToxiproxyEvery merge or nightlyTimeout or retry config regressed
Staging pod or node killNightlyReadiness, graceful shutdown, PDB wrong
Production canaryScheduled, business hoursReal-world dependency changed

Resilience patterns, verified Important ​

In plain words: each pattern in the previous chapters is a claim; chaos experiments are the test of the claim.

Common misunderstanding: "We added a circuit breaker, so we are resilient." A breaker with wrong thresholds never opens, or opens on healthy traffic. Only a fault shows which.

Definition: map each pattern to the experiment that would falsify it.

PatternClaimExperimentPass
Timeout (Timeouts, Retries & Jitter)A slow call ends in N ms+3 s latency on the dependencyp99 inside budget
Retry with jitterBlips are absorbed, storms are not created20% errors for 5 minDependency load rises under 2x
Circuit breaker (Circuit Breaker)Opens after repeated failure, recovers100% errors for 60 s, then healthyOpens, then closes within the wait time
Bulkhead (Bulkheads)One slow dependency cannot starve others+10 s latency on AEndpoint B unaffected
Load shedding (Load Shedding)Overload degrades gracefully3x loadGoodput stable, low-priority dropped
Idempotency (API Idempotency)Retries do not double-chargeDrop the response after the writeOne charge
Cascading (Cascading Failures)One failure stays containedKill the slowest dependencyNo upstream pool exhaustion

Observability prerequisites Must-know ​

In plain words: if you cannot see the steady state, you cannot tell whether an experiment hurt.

Common misunderstanding: "We have logs, so we are observable." You need user-level SLIs updating within seconds, a way to split control from experiment traffic, traces to find the broken hop, and an annotation of when the fault was on.

Definition: the observability prerequisite is a checklist you must satisfy before the first production experiment (Observability, Alerting That Actually Works).

PrerequisiteWhy
SLI dashboard with a short window (1 min)The abort condition needs fresh numbers
Metric split by cohort or versionCompare canary against baseline
Distributed traces with request idsFind which hop produced the error
Event annotation on graphs ("fault on")Correlate cause and effect
Alerts that page a humanDetection time is part of the result
Tested rollback pathThe kill switch must work
On-call present and awareA person must be able to react

Organisational safety Important ​

In plain words: chaos works only when people trust it: they know when it happens, nobody is blamed for what it finds, and legal knows what it touches.

Common misunderstanding: "Asking permission kills the point." Surprise belongs to the mature stage and the failure, not to the process; people agree to the experiment class in advance.

Definition: safety covers blameless culture, change management, and compliance.

AreaPractice
Blameless cultureDebrief about conditions and decisions, never individuals
Change managementExperiments registered like changes; freeze periods respected (the Laravel job checks chaos:paused)
Legal and complianceNever inject into regulated data paths without sign-off; check contracts and SLAs; PCI, health or financial flows get tabletops first (Secure SDLC, Incident Response)
Customer impactExclude paying-critical cohorts; define compensation if the SLO is breached
Error budgetRun chaos only while budget remains; pause when it is spent
AccessThe chaos tool has narrow IAM roles; AWS FIS uses an IAM role, Chaos Mesh uses RBAC and namespace filters
RecordsKeep the experiment page, the result, the action items

Measuring resilience Important ​

In plain words: count how fast you recover and how often the hypothesis holds.

Common misunderstanding: "A resilience score tells you how resilient you are." Scores from vendors are useful as a to-do list; they are not a measurement of your reliability. Your real measures are recovery time and customer impact.

Definition: MTTR is the mean time from fault start to restored steady state; RTO is the target for that time; RPO is the target data loss. A resilience score is a composite (for example, share of experiments HELD, or a vendor's reliability score); define it yourself before comparing it.

MeasureFormulaUse
Hypothesis hold rateHELD runs / valid runs, per serviceWhere defences are weak
Time to detectAlert time minus fault startAlert quality
Time to mitigate (MTTR)Steady-state time minus fault startCompare to RTO
Recovery checkAfter-phase SLI inside boundsThe fix reverts cleanly
Experiment coverageServices with a recent HELD experiment / servicesGaps
Findings closedClosed actions / openedDoes learning turn into fixes
sql
SELECT date_trunc('month', started_at) AS month,
       round(100.0 * count(*) FILTER (WHERE verdict = 'HELD')
             / nullif(count(*) FILTER (WHERE verdict <> 'INVALID'), 0), 1) AS hold_rate_pct
FROM chaos_runs GROUP BY 1 ORDER BY 1;

Anti-patterns Important ​

In plain words: the ways chaos turns into an incident or into theatre.

Common misunderstanding: "More chaos is always better." Without hypotheses and observability it only generates noise.

Definition: recurring mistakes.

Anti-patternWhy it hurtsFix
Random chaos without hypothesisNothing to learn; the result is "it broke"Write the one-page experiment
Chaos in production without a kill switchA mistake becomes an outageTest the stop path first
Breaking things you cannot observeYou cannot tell harm from noiseMeet the observability prerequisites
Starting with the whole fleetMaximum blast radius on the first runCanary, then 1%
Injecting during a deploy or incidentTwo changes at onceCheck deploy and incident status first
Not removing the faultA forgotten fault is a future outagedefer the stop; time box it
Experiments nobody readsFindings rotOwners and dates on action items
Chaos as a test of peopleFear, hidden problemsBlameless debrief
Testing only instance deathMisses slow and partial faultsUse the catalogue
Assuming a pass lastsSystems changeAutomate the experiment

Mechanics ​

Knobs, in one place ​

KnobProductMeaning
fault.delay.fixedDelay, percentage.valueIstio VirtualServiceDelay and share of requests
fault.abort.httpStatus, percentage.valueIstio VirtualServiceStatus code returned and share
x-envoy-fault-delay-request (ms), x-envoy-fault-abort-request (status 200 to 599)Envoy fault filterPer-request fault via headers
latency, jitter attributes of the latency toxicToxiproxyAdded milliseconds and variation
delay, loss, corrupt, duplicate, reorder, ratetc netemKernel network emulation
action: pod-kill, mode: one, selector.namespacesChaos Mesh PodChaosWhat to kill and where
Stop conditions (CloudWatch alarm based)AWS FIS experiment templateAutomatic stop
MaxInjections, AllowHosts, TokenThe Go injectorBudget, scope, secret
chaos.probability, chaos.budget, chaos.allowThe Laravel middlewareSame three ideas

Error names and statuses you will see ​

Message or codeSourceMeaning
faultinject: injected connection errorThe Go snippetA deliberate connection failure
HTTP 503 with X-Chaos-InjectedGo and Laravel snippetsAn injected status
fault filter abortEnvoy access log (response flag FI)Envoy injected the failure
context deadline exceededGo clientsTimeout fired: the expected result of latency injection
Illuminate\Http\Client\ConnectionExceptionLaravel HTTP clientConnection failed or timed out
Illuminate\Http\Client\RequestExceptionLaravel HTTP clientA 4xx or 5xx after throw()
INVALIDThe Go runnerThe steady state did not hold before injection

Time arithmetic for abort windows ​

With one probe per second and AbortWindow=20, AbortBelow=0.5, the experiment aborts after at least 20 s and at most when 10 of the last 20 probes fail, so the worst-case harm is about 20 s of traffic of the blast radius. With the cohort at 0.5% of 2000 requests per second that is about 200 affected requests. Choose window, threshold and cohort so that this number is one you have agreed to.

Go ​

Before ​

Random sleeps and errors pasted into a handler: no scope, no switch, no budget, no record of what was hit. It is "bad design", not broken code.

go
// Before: "chaos" as a random sleep pasted into a handler. No allowlist,
// no kill switch, no budget, no way to say which requests were hit, and
// it ships to production by accident.
package main

import (
	"math/rand"
	"net/http"
	"time"
)

func orders(w http.ResponseWriter, r *http.Request) {
	if rand.Intn(10) == 0 { // 10% of ALL traffic, forever
		time.Sleep(3 * time.Second)
	}
	if rand.Intn(20) == 0 {
		http.Error(w, "boom", http.StatusInternalServerError)
		return
	}
	_, _ = w.Write([]byte("ok"))
}

func main() {
	http.HandleFunc("/orders", orders)
	_ = http.ListenAndServe("127.0.0.1:8080", nil)
}

After ​

A reusable injector (client RoundTripper and server middleware) with the safety properties of the table above, and a runner that measures the SLI before, during and after, with an abort condition.

go
// Package faultinject injects latency, errors and truncated bodies into HTTP
// traffic, on the client side (RoundTripper) or the server side (middleware).
//
// Safety properties, all enforced here and covered by tests:
//   - off by default: a zero Injector injects nothing;
//   - kill switch: Disable() stops every injection immediately;
//   - allowlist: only listed hosts/paths are ever touched;
//   - budget: at most MaxInjections faults, then it turns itself off;
//   - header control only with a matching secret token.
package faultinject

import (
	"bytes"
	"context"
	"errors"
	"io"
	"math/rand/v2"
	"net/http"
	"strconv"
	"strings"
	"sync/atomic"
	"time"
)

// ErrInjected is returned by the client transport for injected connection errors.
var ErrInjected = errors.New("faultinject: injected connection error")

// Rule describes one fault. Probability is in [0,1]; zero means never.
type Rule struct {
	Name         string
	Probability  float64
	Latency      time.Duration // added before the call proceeds
	Status       int           // if non-zero, answer with this status instead of calling the dependency
	ConnError    bool          // client side only: return ErrInjected
	TruncateBody int           // if > 0, cut the response body to this many bytes
}

// Injector holds the rules and the safety state.
type Injector struct {
	Rules         []Rule
	AllowHosts    map[string]bool // client side: URL host allowlist
	AllowPrefixes []string        // server side: path prefix allowlist
	Token         string          // secret for the X-Chaos header; empty disables header control
	MaxInjections int64           // budget; 0 means unlimited (not recommended)

	Rand  func() float64                             // injectable for tests
	Sleep func(context.Context, time.Duration) error // injectable for tests

	enabled  atomic.Bool
	injected atomic.Int64
}

// Enable arms the injector. Disable is the kill switch.
func (i *Injector) Enable()       { i.enabled.Store(true) }
func (i *Injector) Disable()      { i.enabled.Store(false) }
func (i *Injector) Enabled() bool { return i.enabled.Load() }

// Injected reports how many faults have fired.
func (i *Injector) Injected() int64 { return i.injected.Load() }

func (i *Injector) rnd() float64 {
	if i.Rand != nil {
		return i.Rand()
	}
	return rand.Float64()
}

func (i *Injector) sleep(ctx context.Context, d time.Duration) error {
	if i.Sleep != nil {
		return i.Sleep(ctx, d)
	}
	t := time.NewTimer(d)
	defer t.Stop()
	select {
	case <-t.C:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

// take reserves one unit of budget; false means the budget is spent and the
// injector disarms itself.
func (i *Injector) take() bool {
	n := i.injected.Add(1)
	if i.MaxInjections > 0 && n > i.MaxInjections {
		i.injected.Add(-1)
		i.Disable()
		return false
	}
	return true
}

// pick chooses the rule for a request. A valid header overrides probability:
// X-Chaos: token=<secret>;latency=200ms;status=503
func (i *Injector) pick(h http.Header) (Rule, bool) {
	if i.Token != "" {
		if r, ok := parseHeader(h.Get("X-Chaos"), i.Token); ok {
			return r, true
		}
	}
	for _, r := range i.Rules {
		if r.Probability > 0 && i.rnd() < r.Probability {
			return r, true
		}
	}
	return Rule{}, false
}

func parseHeader(v, token string) (Rule, bool) {
	if v == "" {
		return Rule{}, false
	}
	r := Rule{Name: "header"}
	authed := false
	for _, part := range strings.Split(v, ";") {
		k, val, _ := strings.Cut(strings.TrimSpace(part), "=")
		switch k {
		case "token":
			authed = val == token
		case "latency":
			if d, err := time.ParseDuration(val); err == nil && d <= 10*time.Second {
				r.Latency = d
			}
		case "status":
			if n, err := strconv.Atoi(val); err == nil && n >= 400 && n < 600 {
				r.Status = n
			}
		case "truncate":
			if n, err := strconv.Atoi(val); err == nil && n > 0 {
				r.TruncateBody = n
			}
		}
	}
	return r, authed && (r.Latency > 0 || r.Status > 0 || r.TruncateBody > 0)
}

// Transport wraps a RoundTripper (client side fault injection).
func (i *Injector) Transport(base http.RoundTripper) http.RoundTripper {
	if base == nil {
		base = http.DefaultTransport
	}
	return roundTripper(func(req *http.Request) (*http.Response, error) {
		if !i.Enabled() || !i.AllowHosts[req.URL.Host] {
			return base.RoundTrip(req)
		}
		rule, ok := i.pick(req.Header)
		if !ok || !i.take() {
			return base.RoundTrip(req)
		}
		if rule.Latency > 0 {
			if err := i.sleep(req.Context(), rule.Latency); err != nil {
				return nil, err
			}
		}
		if rule.ConnError {
			return nil, ErrInjected
		}
		if rule.Status != 0 {
			return &http.Response{
				StatusCode: rule.Status,
				Status:     strconv.Itoa(rule.Status) + " " + http.StatusText(rule.Status),
				Header:     http.Header{"X-Chaos-Injected": {rule.Name}},
				Body:       io.NopCloser(strings.NewReader("injected")),
				Request:    req,
			}, nil
		}
		resp, err := base.RoundTrip(req)
		if err != nil || rule.TruncateBody <= 0 {
			return resp, err
		}
		b, _ := io.ReadAll(io.LimitReader(resp.Body, int64(rule.TruncateBody)))
		_ = resp.Body.Close()
		resp.Body = io.NopCloser(bytes.NewReader(b))
		resp.ContentLength = -1
		resp.Header.Set("X-Chaos-Injected", rule.Name)
		return resp, nil
	})
}

type roundTripper func(*http.Request) (*http.Response, error)

func (f roundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }

// Middleware wraps a server handler (server side fault injection).
func (i *Injector) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if !i.Enabled() || !i.pathAllowed(r.URL.Path) {
			next.ServeHTTP(w, r)
			return
		}
		rule, ok := i.pick(r.Header)
		if !ok || !i.take() {
			next.ServeHTTP(w, r)
			return
		}
		if rule.Latency > 0 {
			if err := i.sleep(r.Context(), rule.Latency); err != nil {
				return
			}
		}
		w.Header().Set("X-Chaos-Injected", rule.Name)
		if rule.Status != 0 {
			http.Error(w, "injected", rule.Status)
			return
		}
		if rule.TruncateBody > 0 {
			next.ServeHTTP(&truncWriter{ResponseWriter: w, left: rule.TruncateBody}, r)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func (i *Injector) pathAllowed(p string) bool {
	for _, pre := range i.AllowPrefixes {
		if strings.HasPrefix(p, pre) {
			return true
		}
	}
	return false
}

type truncWriter struct {
	http.ResponseWriter
	left int
}

func (t *truncWriter) Write(b []byte) (int, error) {
	if t.left <= 0 {
		return len(b), nil // pretend success; the client sees a short body
	}
	if len(b) > t.left {
		b = b[:t.left]
	}
	n, err := t.ResponseWriter.Write(b)
	t.left -= n
	return n, err
}
go
package faultinject

import (
	"context"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

func backend() *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("0123456789"))
	}))
}

func always() float64 { return 0 }

func newInj(rules ...Rule) *Injector {
	return &Injector{Rules: rules, Rand: always, Token: "s3cret",
		Sleep: func(context.Context, time.Duration) error { return nil }}
}

func do(t *testing.T, rt http.RoundTripper, url string, hdr map[string]string) (*http.Response, error) {
	t.Helper()
	req, _ := http.NewRequest(http.MethodGet, url, nil)
	for k, v := range hdr {
		req.Header.Set(k, v)
	}
	return rt.RoundTrip(req)
}

func TestOffByDefault(t *testing.T) {
	srv := backend()
	defer srv.Close()
	inj := newInj(Rule{Name: "e", Probability: 1, Status: 503})
	inj.AllowHosts = map[string]bool{srv.Listener.Addr().String(): true}
	resp, err := do(t, inj.Transport(nil), srv.URL, nil)
	if err != nil || resp.StatusCode != 200 {
		t.Fatalf("disabled injector must pass through: %v %v", resp, err)
	}
}

func TestAllowlistAndKillSwitch(t *testing.T) {
	srv := backend()
	defer srv.Close()
	inj := newInj(Rule{Name: "e", Probability: 1, Status: 503})
	inj.Enable()
	rt := inj.Transport(nil)
	// host not on the allowlist: untouched
	if resp, _ := do(t, rt, srv.URL, nil); resp.StatusCode != 200 {
		t.Fatal("non-allowlisted host was hit")
	}
	inj.AllowHosts = map[string]bool{srv.Listener.Addr().String(): true}
	if resp, _ := do(t, rt, srv.URL, nil); resp.StatusCode != 503 {
		t.Fatal("allowlisted host should receive the fault")
	}
	inj.Disable() // kill switch
	if resp, _ := do(t, rt, srv.URL, nil); resp.StatusCode != 200 {
		t.Fatal("kill switch must stop injection at once")
	}
}

func TestBudgetDisarms(t *testing.T) {
	srv := backend()
	defer srv.Close()
	inj := newInj(Rule{Name: "e", Probability: 1, Status: 500})
	inj.MaxInjections = 2
	inj.AllowHosts = map[string]bool{srv.Listener.Addr().String(): true}
	inj.Enable()
	rt := inj.Transport(nil)
	hits := 0
	for range 5 {
		resp, _ := do(t, rt, srv.URL, nil)
		if resp.StatusCode == 500 {
			hits++
		}
	}
	if hits != 2 || inj.Enabled() || inj.Injected() != 2 {
		t.Fatalf("hits=%d enabled=%v injected=%d", hits, inj.Enabled(), inj.Injected())
	}
}

func TestLatencyAndConnError(t *testing.T) {
	srv := backend()
	defer srv.Close()
	var slept time.Duration
	inj := newInj(Rule{Name: "slow", Probability: 1, Latency: 300 * time.Millisecond, ConnError: true})
	inj.Sleep = func(_ context.Context, d time.Duration) error { slept += d; return nil }
	inj.AllowHosts = map[string]bool{srv.Listener.Addr().String(): true}
	inj.Enable()
	_, err := do(t, inj.Transport(nil), srv.URL, nil)
	if !errors.Is(err, ErrInjected) || slept != 300*time.Millisecond {
		t.Fatalf("err=%v slept=%v", err, slept)
	}
}

func TestPartialResponse(t *testing.T) {
	srv := backend()
	defer srv.Close()
	inj := newInj(Rule{Name: "partial", Probability: 1, TruncateBody: 4})
	inj.AllowHosts = map[string]bool{srv.Listener.Addr().String(): true}
	inj.Enable()
	resp, err := do(t, inj.Transport(nil), srv.URL, nil)
	if err != nil {
		t.Fatal(err)
	}
	b, _ := io.ReadAll(resp.Body)
	if string(b) != "0123" {
		t.Fatalf("body=%q", b)
	}
}

func TestHeaderNeedsToken(t *testing.T) {
	srv := backend()
	defer srv.Close()
	inj := newInj() // no probabilistic rules
	inj.AllowHosts = map[string]bool{srv.Listener.Addr().String(): true}
	inj.Enable()
	rt := inj.Transport(nil)
	if resp, _ := do(t, rt, srv.URL, map[string]string{"X-Chaos": "token=wrong;status=503"}); resp.StatusCode != 200 {
		t.Fatal("wrong token must be ignored")
	}
	if resp, _ := do(t, rt, srv.URL, map[string]string{"X-Chaos": "token=s3cret;status=503"}); resp.StatusCode != 503 {
		t.Fatal("right token must inject")
	}
	if resp, _ := do(t, rt, srv.URL, map[string]string{"X-Chaos": "token=s3cret;latency=1h"}); resp.StatusCode != 200 {
		t.Fatal("latency above the 10s cap must be ignored")
	}
}

func TestMiddlewarePathAllowlist(t *testing.T) {
	inj := newInj(Rule{Name: "e", Probability: 1, Status: 502})
	inj.AllowPrefixes = []string{"/api/recommendations"}
	inj.Enable()
	h := inj.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) }))
	for path, want := range map[string]int{"/api/recommendations/1": 502, "/api/payments": 200} {
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
		if rec.Code != want {
			t.Fatalf("%s: got %d want %d", path, rec.Code, want)
		}
	}
}
go
// Package experiment runs one chaos experiment: measure the steady-state SLI
// before, inject, measure during (with an abort condition), remove the fault,
// measure after, and return a verdict.
package experiment

import (
	"context"
	"fmt"
	"sort"
	"time"
)

// Sample is one probe of the system as a user would see it.
type Sample struct {
	OK      bool
	Latency time.Duration
}

// Probe performs one user-visible request.
type Probe func(ctx context.Context) Sample

// SLI summarises a phase.
type SLI struct {
	N           int
	SuccessRate float64
	P99         time.Duration
}

// Hypothesis is the steady-state claim: the SLI stays inside these bounds.
type Hypothesis struct {
	MinSuccess float64
	MaxP99     time.Duration
}

// Holds reports whether an SLI satisfies the hypothesis.
func (h Hypothesis) Holds(s SLI) bool {
	return s.N > 0 && s.SuccessRate >= h.MinSuccess && s.P99 <= h.MaxP99
}

// Verdict is the outcome of an experiment.
type Verdict string

const (
	// Invalid: the steady state did not hold before injection; the experiment proves nothing.
	Invalid Verdict = "INVALID"
	// Held: the hypothesis survived the fault.
	Held Verdict = "HELD"
	// Refuted: the system did not tolerate the fault; fix it, then rerun.
	Refuted Verdict = "REFUTED"
	// Aborted: the abort condition fired; the fault was removed early.
	Aborted Verdict = "ABORTED"
)

// Experiment is one experiment definition.
type Experiment struct {
	Name        string
	Probe       Probe
	Inject      func() (stop func()) // start the fault; the returned func is the kill switch
	Hypothesis  Hypothesis
	Samples     int     // probes per phase
	AbortBelow  float64 // abort when the success rate of the last AbortWindow probes drops below this
	AbortWindow int
}

// Report is the result.
type Report struct {
	Name                  string
	Before, During, After SLI
	Verdict               Verdict
	RecoveredAfter        bool
	AbortedAt             int // probe index in the during phase, 0 if not aborted
}

func (r Report) String() string {
	f := func(s SLI) string {
		return fmt.Sprintf("n=%d ok=%.1f%% p99=%s", s.N, s.SuccessRate*100, s.P99)
	}
	return fmt.Sprintf("%s: %s\n  before: %s\n  during: %s\n  after:  %s\n  recovered=%v",
		r.Name, r.Verdict, f(r.Before), f(r.During), f(r.After), r.RecoveredAfter)
}

func measure(ctx context.Context, p Probe, n int) SLI {
	return summarize(collect(ctx, p, n))
}

func collect(ctx context.Context, p Probe, n int) []Sample {
	out := make([]Sample, 0, n)
	for range n {
		out = append(out, p(ctx))
	}
	return out
}

func summarize(ss []Sample) SLI {
	if len(ss) == 0 {
		return SLI{}
	}
	ok := 0
	lat := make([]time.Duration, 0, len(ss))
	for _, s := range ss {
		if s.OK {
			ok++
		}
		lat = append(lat, s.Latency)
	}
	sort.Slice(lat, func(i, j int) bool { return lat[i] < lat[j] })
	idx := (len(lat)*99 + 99) / 100 // nearest-rank p99
	if idx > 0 {
		idx--
	}
	return SLI{N: len(ss), SuccessRate: float64(ok) / float64(len(ss)), P99: lat[idx]}
}

// Run executes the experiment. The fault is always removed, even on panic.
func (e Experiment) Run(ctx context.Context) Report {
	rep := Report{Name: e.Name}
	rep.Before = measure(ctx, e.Probe, e.Samples)
	if !e.Hypothesis.Holds(rep.Before) {
		rep.Verdict = Invalid
		return rep
	}
	stop := e.Inject()
	var stopped bool
	remove := func() {
		if !stopped {
			stopped = true
			stop()
		}
	}
	defer remove()

	during := make([]Sample, 0, e.Samples)
	for i := 1; i <= e.Samples; i++ {
		during = append(during, e.Probe(ctx))
		if e.AbortWindow > 0 && len(during) >= e.AbortWindow {
			w := summarize(during[len(during)-e.AbortWindow:])
			if w.SuccessRate < e.AbortBelow {
				rep.AbortedAt = i
				remove()
				break
			}
		}
	}
	rep.During = summarize(during)
	remove()
	rep.After = measure(ctx, e.Probe, e.Samples)
	rep.RecoveredAfter = e.Hypothesis.Holds(rep.After)
	switch {
	case rep.AbortedAt > 0:
		rep.Verdict = Aborted
	case e.Hypothesis.Holds(rep.During):
		rep.Verdict = Held
	default:
		rep.Verdict = Refuted
	}
	return rep
}
go
package experiment

import (
	"context"
	"testing"
	"time"
)

// fakeSystem succeeds with latency 10ms; while faulty, a fixed fraction of
// calls fail (deterministic pattern, no randomness).
type fakeSystem struct {
	faulty    bool
	failEvery int // fail every Nth call while faulty
	calls     int
	stopped   int
}

func (f *fakeSystem) probe(context.Context) Sample {
	f.calls++
	if f.faulty && f.failEvery > 0 && f.calls%f.failEvery == 0 {
		return Sample{OK: false, Latency: 2 * time.Second}
	}
	return Sample{OK: true, Latency: 10 * time.Millisecond}
}

func (f *fakeSystem) inject() func() {
	f.faulty = true
	return func() { f.faulty = false; f.stopped++ }
}

func base(f *fakeSystem) Experiment {
	return Experiment{
		Name: "dep-down", Probe: f.probe, Inject: f.inject, Samples: 100,
		Hypothesis: Hypothesis{MinSuccess: 0.99, MaxP99: 200 * time.Millisecond},
		AbortBelow: 0.5, AbortWindow: 10,
	}
}

func TestHeld(t *testing.T) {
	f := &fakeSystem{failEvery: 0} // fault has no visible effect: the system tolerates it
	r := base(f).Run(context.Background())
	if r.Verdict != Held || !r.RecoveredAfter {
		t.Fatalf("%v", r)
	}
}

func TestRefutedAndRecovers(t *testing.T) {
	f := &fakeSystem{failEvery: 5} // 20% errors during the fault, abort threshold not reached
	r := base(f).Run(context.Background())
	if r.Verdict != Refuted || !r.RecoveredAfter || r.During.SuccessRate > 0.85 {
		t.Fatalf("%v", r)
	}
}

func TestAbortRemovesFaultEarly(t *testing.T) {
	f := &fakeSystem{failEvery: 1} // everything fails
	r := base(f).Run(context.Background())
	if r.Verdict != Aborted || r.AbortedAt != 10 || r.During.N != 10 {
		t.Fatalf("%v at=%d n=%d", r.Verdict, r.AbortedAt, r.During.N)
	}
	if f.stopped != 1 || f.faulty {
		t.Fatalf("fault must be stopped exactly once, stopped=%d", f.stopped)
	}
}

func TestInvalidWhenNotSteadyBefore(t *testing.T) {
	f := &fakeSystem{faulty: true, failEvery: 2} // already broken before we inject
	e := base(f)
	injected := false
	e.Inject = func() func() { injected = true; return func() {} }
	r := e.Run(context.Background())
	if r.Verdict != Invalid || injected {
		t.Fatalf("must not inject into a system that is not steady: %v injected=%v", r.Verdict, injected)
	}
}

func TestSummarizeP99(t *testing.T) {
	ss := make([]Sample, 100)
	for i := range ss {
		ss[i] = Sample{OK: true, Latency: time.Duration(i+1) * time.Millisecond}
	}
	if got := summarize(ss).P99; got != 99*time.Millisecond {
		t.Fatalf("p99=%s", got)
	}
}
go
// Command gameday runs one experiment in a single process: a client with
// retries calls a flaky "recommendations" dependency through the fault
// injecting transport. No network beyond loopback, no containers.
package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"time"

	"academy/chaos-engineering/experiment"
	"academy/chaos-engineering/faultinject"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = io.WriteString(w, "recommendations")
	}))
	defer srv.Close()
	host := srv.Listener.Addr().String()

	for _, withFallback := range []bool{false, true} {
		inj := &faultinject.Injector{
			Rules:         []faultinject.Rule{{Name: "dep-503", Probability: 0.6, Status: 503}},
			AllowHosts:    map[string]bool{host: true},
			MaxInjections: 10_000,
		}
		client := &http.Client{Transport: inj.Transport(nil), Timeout: time.Second}
		probe := func(ctx context.Context) experiment.Sample {
			start := time.Now()
			req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
			resp, err := client.Do(req)
			ok := err == nil && resp.StatusCode == 200
			if resp != nil {
				_ = resp.Body.Close()
			}
			if !ok && withFallback {
				ok = true // degraded answer: show a static "popular items" list
			}
			return experiment.Sample{OK: ok, Latency: time.Since(start)}
		}
		rep := experiment.Experiment{
			Name:  fmt.Sprintf("recommendations-503 (fallback=%v)", withFallback),
			Probe: probe,
			Inject: func() func() {
				inj.Enable()
				return inj.Disable
			},
			Hypothesis:  experiment.Hypothesis{MinSuccess: 0.99, MaxP99: 250 * time.Millisecond},
			Samples:     200,
			AbortBelow:  0.2,
			AbortWindow: 20,
		}.Run(context.Background())
		fmt.Println(rep)
		if rep.Verdict == experiment.Invalid {
			os.Exit(1)
		}
	}
}

The Go angle ​

http.RoundTripper is the natural seam for client faults: everything built on http.Client passes through it, including retries you wrote yourself. net/http/httptest gives a real loopback server, so tests exercise the full HTTP path with no containers. Randomness and sleeping are injected (Rand, Sleep) so tests are deterministic and instant; the kill switch is an atomic.Bool so it is safe to flip from another goroutine. The runner removes the fault with defer, so a panic in a probe cannot leave a fault armed. Run go test -race ./... because the injector is shared by many requests.

Laravel ​

Before ​

The same anti-pattern in PHP is a sleep() and abort(503) guarded by if (app()->environment('production')) somebody forgot to remove. Do not do it; use a flag and an allowlist.

After ​

Laravel 13 pieces: a middleware (see the middleware docs) behind a Pennant flag, Http::fake sequences for rehearsals (HTTP client docs), and a scheduled job on a dedicated Horizon queue.

php
<?php

// config/chaos.php: every knob is explicit and reviewable.
return [
    // Paths (Request::is patterns) that may ever receive a fault.
    'allow' => ['api/recommendations*', 'api/reviews*'],

    // Never inject here, even if the allowlist is widened by mistake.
    'deny' => ['api/payments*', 'api/checkout*', 'up'],

    // Secret for the X-Chaos header; empty disables header control.
    'token' => env('CHAOS_TOKEN', ''),

    // Probabilistic fault applied to allowlisted paths when the flag is on.
    'probability' => (float) env('CHAOS_PROBABILITY', 0.05),
    'latency_ms' => (int) env('CHAOS_LATENCY_MS', 400),
    'status' => (int) env('CHAOS_STATUS', 503),

    // Hard cap on one latency value, whatever the header asks for.
    'max_latency_ms' => 5000,

    // Budget: after this many faults in the window the middleware stops injecting.
    'budget' => (int) env('CHAOS_BUDGET', 500),
    'budget_window_seconds' => 300,
];
php
<?php

namespace App\Chaos;

use Illuminate\Support\ServiceProvider;
use Laravel\Pennant\Feature;

class ChaosServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Default: off everywhere. Turn on with Feature::for('global')->activate('chaos-faults').
        Feature::define('chaos-faults', fn (mixed $scope) => false);
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Laravel\Pennant\Feature;
use Symfony\Component\HttpFoundation\Response;

/**
 * Server-side fault injection behind a Pennant feature flag.
 * Off unless the "chaos-faults" flag is active; the flag is the kill switch:
 * `Feature::for('global')->deactivate('chaos-faults')` stops it on the next request.
 */
class InjectFaults
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! Feature::for('global')->active('chaos-faults')) {
            return $next($request);
        }

        if ($request->is(config('chaos.deny')) || ! $request->is(config('chaos.allow'))) {
            return $next($request);
        }

        $fault = $this->chooseFault($request);
        if ($fault === null || ! $this->takeBudget()) {
            return $next($request);
        }

        if ($fault['latency_ms'] > 0) {
            usleep(min($fault['latency_ms'], config('chaos.max_latency_ms')) * 1000);
        }

        if ($fault['status'] !== null) {
            return response('injected', $fault['status'])->header('X-Chaos-Injected', 'status');
        }

        return $next($request)->header('X-Chaos-Injected', 'latency');
    }

    /** @return array{latency_ms:int,status:?int}|null */
    private function chooseFault(Request $request): ?array
    {
        $token = (string) config('chaos.token');
        $header = (string) $request->header('X-Chaos', '');

        if ($token !== '' && $header !== '') {
            parse_str(str_replace(';', '&', $header), $p);
            if (hash_equals($token, (string) ($p['token'] ?? ''))) {
                return [
                    'latency_ms' => (int) ($p['latency'] ?? 0),
                    'status' => isset($p['status']) ? (int) $p['status'] : null,
                ];
            }
        }

        if (random_int(1, 1_000_000) / 1_000_000 < config('chaos.probability')) {
            return ['latency_ms' => (int) config('chaos.latency_ms'), 'status' => (int) config('chaos.status')];
        }

        return null;
    }

    /** Fixed-window budget in the shared cache: blast radius as a number. */
    private function takeBudget(): bool
    {
        $key = 'chaos:budget:'.intdiv(time(), (int) config('chaos.budget_window_seconds'));
        Cache::add($key, 0, (int) config('chaos.budget_window_seconds'));

        return Cache::increment($key) <= (int) config('chaos.budget');
    }
}
php
<?php

namespace App\Chaos;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;

/** The code under rehearsal: a dependency call with timeout, bounded retries and a fallback. */
class RecommendationsClient
{
    public const FALLBACK = ['popular-1', 'popular-2', 'popular-3'];

    /** @return array{items:array<int,string>,degraded:bool} */
    public function forUser(int $userId): array
    {
        try {
            $items = Http::baseUrl('https://recs.internal.example')
                ->timeout(0.5)
                ->retry(2, 100, throw: false)
                ->get("/v1/users/{$userId}/recommendations")
                ->throw()
                ->json('items');

            return ['items' => $items, 'degraded' => false];
        } catch (ConnectionException|RequestException) {
            return ['items' => self::FALLBACK, 'degraded' => true];
        }
    }
}
php
<?php

namespace Tests\Feature;

use App\Chaos\RecommendationsClient;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

/**
 * Game day rehearsal in CI: scripted failures with Http::fake, no network.
 * It proves the fallback and the retry count; it does not prove production
 * behaviour (that needs a real experiment).
 */
class GameDayRehearsalTest extends TestCase
{
    public function test_one_blip_is_absorbed_by_a_retry(): void
    {
        Http::preventStrayRequests();
        Http::fake([
            'recs.internal.example/*' => Http::sequence()
                ->pushStatus(503)                          // first attempt fails
                ->push(['items' => ['a', 'b']], 200),      // retry succeeds
        ]);

        $out = (new RecommendationsClient)->forUser(7);

        $this->assertFalse($out['degraded']);
        $this->assertSame(['a', 'b'], $out['items']);
        Http::assertSentCount(2);
    }

    public function test_dependency_outage_returns_the_fallback_with_bounded_attempts(): void
    {
        Http::preventStrayRequests();
        Http::fake([
            'recs.internal.example/*' => Http::sequence()
                ->pushStatus(503)->pushStatus(503)->pushStatus(503),
        ]);

        $out = (new RecommendationsClient)->forUser(7);

        $this->assertTrue($out['degraded']);
        $this->assertSame(RecommendationsClient::FALLBACK, $out['items']);
        Http::assertSentCount(2); // retry(2, ...) means two attempts in total, not unbounded
    }

    public function test_connection_failure_returns_the_fallback(): void
    {
        Http::fake(['recs.internal.example/*' => Http::failedConnection()]);

        $this->assertTrue((new RecommendationsClient)->forUser(7)['degraded']);
    }
}
php
<?php

namespace App\Console;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Laravel\Pennant\Feature;

/**
 * Scheduled, tiny experiment on the "chaos" queue (a Horizon supervisor with
 * its own small worker pool, so it can never starve real jobs).
 * 1. check the steady state, 2. arm the flag, 3. probe, 4. ALWAYS disarm.
 */
class RunChaosExperiment implements ShouldQueue
{
    use Dispatchable, Queueable;

    public int $tries = 1;      // never retry an experiment
    public int $timeout = 60;

    public function __construct()
    {
        $this->onQueue('chaos');
    }

    public function handle(): void
    {
        if (Cache::get('chaos:paused') === true) {   // organisational kill switch (change freeze, incident)
            Log::info('chaos.skipped', ['reason' => 'paused']);

            return;
        }

        $steady = $this->successRate(30);
        if ($steady < 0.99) {
            Log::warning('chaos.invalid', ['steady_success' => $steady]);

            return;
        }

        Feature::for('global')->activate('chaos-faults');
        try {
            $during = $this->successRate(30);
        } finally {
            Feature::for('global')->deactivate('chaos-faults');
        }

        Log::info('chaos.result', [
            'steady' => $steady,
            'during' => $during,
            'verdict' => $during >= 0.99 ? 'held' : 'refuted',
        ]);
    }

    private function successRate(int $n): float
    {
        $ok = 0;
        for ($i = 0; $i < $n; $i++) {
            if (Http::timeout(2)->get(config('app.url').'/api/recommendations/probe')->successful()) {
                $ok++;
            }
        }

        return $ok / $n;
    }
}
php
<?php

// routes/console.php (excerpt)
use App\Console\RunChaosExperiment;
use Illuminate\Support\Facades\Schedule;

// Business hours only, weekdays, never overlapping: people are around to react.
Schedule::job(new RunChaosExperiment)
    ->weekdays()
    ->between('10:00', '15:00')
    ->hourly()
    ->name('chaos-recommendations')
    ->withoutOverlapping()
    ->onOneServer();
php
<?php

// config/horizon.php (excerpt): a dedicated, tiny supervisor for chaos jobs.
return [
    'environments' => [
        'production' => [
            'supervisor-chaos' => [
                'connection' => 'redis',
                'queue' => ['chaos'],
                'balance' => 'false',
                'maxProcesses' => 1,
                'tries' => 1,
            ],
        ],
    ],
];

The Laravel angle ​

Http::fake with Http::sequence()->pushStatus(503)->push(...) scripts a dependency that fails, then recovers, and Http::failedConnection() imitates an unreachable host; Http::preventStrayRequests() fails the test if code calls anything you did not script; Http::assertSentCount() checks the number of attempts. These are rehearsal tools: they prove your fallback and retry count, not real network behaviour. Register the middleware with withMiddleware in bootstrap/app.php (for example appending it to the api group) and the service provider in bootstrap/providers.php. Pennant is a first-party package (laravel/pennant); the flag scope 'global' here is a plain string used as one shared scope. The Horizon supervisor with one process keeps chaos jobs from competing with real work. The Laravel snippets were syntax checked with php -l only; they were not run against a Laravel 13 application, and the interaction of retry(..., throw: false) with ConnectionException should be confirmed in your version.

Solving the classic problems ​

The fallback was never exercised ​

SymptomCauseFixVerify
Recommendations down, whole page 500Fallback code path never ran in productionAdd the fallback; add a Http::fake rehearsalRun the experiment; fallback rate rises, success holds

Retries amplify the outage ​

SymptomCauseFixVerify
Dependency at 3x load during blipThree retries, no jitter, no budgetBounded retries with jitter (Timeouts, Retries & Jitter)Dependency load stays under 2x in the experiment

One slow dependency starves the pool ​

SymptomCauseFixVerify
Unrelated endpoints time outShared worker poolBulkhead per dependencyLatency injected on A, endpoint B unaffected

The runbook is wrong ​

SymptomCauseFixVerify
Responders stuck at step 4Command needs a permission or points to a retired hostFix the runbook; test every step in a game dayRerun the scenario in 30 days

The failover takes five minutes, not thirty seconds ​

SymptomCauseFixVerify
Measured MTTR far above RTOLong DNS TTL, cold cache, connection pool pinned to old IPLower TTL, warm caches, refresh poolsMeasure MTTR again

The experiment itself caused harm ​

SymptomCauseFixVerify
Customers affected beyond the cohortAllowlist too wide or abort missingNarrow scope; automate abort; tighten windowAbort test passes in staging

Choosing ​

Which experiment next ​

SituationFirst experimentToolReason
New service, no testsFake returns 503 and +2 sHttp::fake or a Go fake RoundTripperCheapest proof the fallback exists
Timeouts changed+latency in stagingToxiproxyVerifies the new numbers
Kubernetes deploymentDelete one pod under loadkubectl delete pod, Chaos Mesh PodChaosReadiness and graceful shutdown
Mesh in placeAbort 503 for a header cohortIstio fault.abortNo code change
AWS shop with budgetStop instances in one AZAWS FIS with stop conditionsManaged guardrails
Team is new to thisTabletop exerciseA meetingBuilds the habit
Mature team, tested runbooksProduction game dayChosen tool plus announcementTests people at scale

Tool selection ​

NeedPick
Open source on KubernetesChaos Mesh or LitmusChaos
Commercial, many platforms, scoringGremlin
AWS-native with IAM and stop conditionsAWS Fault Injection Service
Test-time network faultsToxiproxy
Kernel-level network faults on a hosttc netem
Faults inside your codeFeature-flagged middleware or RoundTripper

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

Monolith: one process, one database ​

A monolith has few failure edges: the database, the cache, a payment API. Experiments are cheap: kill the process under load and check the restart time, add latency to the database with Toxiproxy and check the pool and timeouts, fill the disk and check what the app does. Use Http::fake for the third-party APIs. Example: with +2 s on Redis the Laravel app should fall back to the database for sessions or fail with a clear error, not hang.

Modular monolith: boundaries without the network ​

Modules call each other in-process, so there is no network to break, but each module still has dependencies of its own. Inject faults at the module's port (a fake adapter that throws or sleeps). The experiment verifies that a failing module (for example Recommendations) degrades only its own screen, not the request: the bulkhead is a try/catch plus a timeout at the module boundary.

Microservices: every arrow is a decision ​

Every network call is a place for the fault catalogue. Typical first runs: abort 503 from one downstream and watch the upstream's success rate; add latency and watch pool saturation; kill pods and watch retries. Use tracing to find the hop. Mesh or proxy faults need no code change. Example flow:

user -> gateway -> checkout -> recommendations   (fault: 60% 503, header cohort)
                         |-> payments            (never injected; deny list)
steady: checkout success >= 99.5%; fallback rate expected to rise to ~60% for the cohort

Distributed data: replicas, caches, regions ​

Test replica lag (delay replication, then read your own write), primary failover (measure the write outage), cache loss (does the database survive the stampede? see Caching), partitions (CP or AP behaviour; see CAP and PACELC), clock skew (leases, tokens), and region evacuation. These experiments are the dangerous ones: do the tabletop first, then staging, then a planned production game day with a data owner present.

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

ScalePractice
1x: one team, one serviceFake-based tests, one tabletop a quarter
10x: tens of servicesToxiproxy or mesh faults in staging, nightly; weekly production canary
100x: hundreds of services, several regionsChaos platform with RBAC and stop conditions, game day calendar, region evacuation drills, resilience tracked as a metric and as an error-budget gate

Lab: break a dependency, with numbers ​

Experiment 1: run the Go experiment in one process (run) ​

$ cd docs/snippets/system-design/chaos-engineering/go && go run ./cmd/gameday
recommendations-503 (fallback=false): ABORTED
  before: n=200 ok=100.0% p99=171.875µs
  during: n=136 ok=40.4% p99=77.041µs
  after:  n=200 ok=100.0% p99=101.667µs
  recovered=true
recommendations-503 (fallback=true): HELD
  before: n=200 ok=100.0% p99=62.75µs
  during: n=200 ok=100.0% p99=65.542µs
  after:  n=200 ok=100.0% p99=61.042µs
  recovered=true

This was actually run once on a laptop. The abort index and microsecond values vary from run to run because 60% of calls fail at random; what is stable is the verdict pattern: without a fallback the experiment aborts, with a fallback the hypothesis holds.

Experiment 2: the tests with the race detector (run) ​

$ go test -race ./...
ok  	academy/chaos-engineering/experiment
ok  	academy/chaos-engineering/faultinject

Experiment 3: a latency toxic in front of a database (expected, not run) ​

$ toxiproxy-server &
$ toxiproxy-cli create --listen 127.0.0.1:25432 --upstream 127.0.0.1:5432 pg
$ toxiproxy-cli toxic add -t latency -a latency=1500 pg
# point the app at 25432: expect p99 near 1.5 s, pool saturation if no timeout
$ toxiproxy-cli toxic remove -n latency_downstream pg

Experiment 4: Istio abort for a cohort (expected, not run) ​

$ kubectl apply -f virtualservice-chaos.yaml
$ curl -H 'x-chaos-cohort: canary' http://shop/recommendations   # expect 503 fault filter abort
$ curl http://shop/recommendations                                # expect 200
$ kubectl delete -f virtualservice-chaos.yaml                     # kill switch

Experiment 5: the Laravel rehearsal (expected, not run) ​

$ php artisan test --filter=GameDayRehearsalTest
  PASS  Tests\Feature\GameDayRehearsalTest
  ✓ one blip is absorbed by a retry
  ✓ dependency outage returns the fallback with bounded attempts
  ✓ connection failure returns the fallback

Experiment 6: a tabletop game day (no tools) ​

1  Facilitator: "At 10:02 the primary database in AZ-b stops responding."
2  Responders: open the runbook; say aloud which dashboard they check first.
3  Scribe: write the minute each question is answered.
4  Facilitator: "The status page shows green. What do you do?"
5  Debrief: which step was unclear, which command lacked permission?

Common misconceptions ​

BeliefReality
Chaos engineering is random breaking in productionIt is hypothesis-driven experimentation with scope and abort rules
You need production to startStart with fakes, staging and tabletops; production comes later
A tool gives us chaos engineeringA tool injects; the discipline is the hypothesis and the measurement
Instance kill is the main testSlow and partial failures are more damaging and more common
If it passes once we are resilientIt is evidence for that fault, at that load, on that day
Chaos replaces testingIt complements unit, integration and load tests
Game days are for ops onlyDevelopers, support and product take part
A kill switch is optional if the abort rule is goodAbort rules miss things; keep both and test the switch
A resilience score is a measure of reliabilityIt is a to-do list; MTTR and customer impact are the measures
Findings are a failure of the teamThey are the product; blameless debriefs depend on this

Cheat sheet ​

TopicRemember
DefinitionExperiment on a system to build confidence it withstands turbulence in production
Five principlesSteady-state hypothesis, real-world events, production, automate, minimise blast radius
Experiment pageSLI, hypothesis, one variable, scope, abort, kill switch, owner
VerdictsHELD, REFUTED, ABORTED, INVALID
Blast radius ladderFake, staging, canary, 1%, AZ, region
Abort vs killAbort is automatic, kill is manual; test both
Faults to startLatency, 503, dependency down, pod delete
ToolsToxiproxy tests; mesh for no code; Chaos Mesh, Litmus, Gremlin, AWS FIS for platforms
Application-levelFlag, allowlist, token, budget, header, log it
Game dayPlan, roles, inject, respond, hot debrief, written debrief, action items
CIFake-based tests per commit; nightly staging; weekly canary
PrerequisiteObservability with cohort split and annotations
MeasureMTTR vs RTO, hold rate, findings closed
NeverRandom chaos, no kill switch, unobserved systems

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 — What is the difference between steady state and "no errors"? Must-know ​

Answer

Answer: Steady state is the normal band of a business metric, including normal noise; "no errors" is not what the system does in practice.

2 — Why does a hypothesis need a control group? Important ​

Answer

Answer: Daily traffic swings can look like fault effects; comparing a canary with a baseline separates them.

3 — When is the verdict INVALID? Important ​

Answer

Answer: When the SLI does not satisfy the hypothesis before injection; the experiment proves nothing.

4 — Abort condition vs kill switch? Important ​

Answer

Answer: The abort condition is automatic on metrics; the kill switch is a manual stop. Test both.

5 — Why is kill -STOP a better test than kill -9 for some systems? Good to know ​

Answer

Answer: The socket stays open, health checks may pass, and leases expire while the old process still believes it leads.

6 — Name three safety properties of application-level injection. Important ​

Answer

Answer: Off by default, allowlist, budget (also token and kill switch).

7 — What does a tabletop exercise test that a live test does not? Important ​

Answer

Answer: Decisions, communication and runbook reading, without risk to systems.

8 — How does Http::sequence() help rehearsal? Good to know ​

Answer

Answer: It scripts a series of responses (for example 503 then 200) so retries and fallbacks are tested deterministically.

9 — What must exist before a production experiment? Must-know ​

Answer

Answer: Fresh SLI dashboards with cohort split, traces, alerts, a tested kill switch, an on-call person.

10 — What does MTTR measure in a game day? Must-know ​

Answer

Answer: Time from fault start to restored steady state, compared with the RTO.

Glossary ​

TermMeaning
Chaos engineeringExperimenting on a system to build confidence in its resilience
Steady stateNormal measurable behaviour of the system at its boundary
HypothesisThe claim that steady state holds under a fault
SLI / SLOMeasured indicator / target for it
Blast radiusThe set of users and resources an experiment can affect
Abort conditionAutomatic rule that stops an experiment
Kill switchManual immediate stop
Canary experimentFault applied to a small comparable slice
Chaos MonkeyNetflix tool terminating instances in business hours
Simian ArmyNetflix family of failure-injecting tools
Chaos KongNetflix exercise simulating region loss
FITFailure Injection Testing, request-scoped failure at Netflix
ChAPNetflix Chaos Automation Platform
GameDayPlanned failure exercise (Amazon)
DiRTGoogle's Disaster Recovery Testing
Game dayRehearsal of an incident with people and runbooks
Tabletop exerciseDiscussion-based game day without live faults
Runbook validationExecuting a runbook to prove each step works
DebriefBlameless review with action items
Fault injectionIntroducing a fault on purpose
Latency injectionAdding delay to calls
Error injectionReturning errors instead of real answers
Chaos MeshCNCF Kubernetes chaos platform
LitmusChaosCNCF Kubernetes chaos project
GremlinCommercial chaos platform
AWS Fault Injection ServiceAWS managed fault injection with stop conditions
ToxiproxyShopify TCP proxy with toxics
tc netemLinux network emulation qdisc
Envoy fault filterEnvoy HTTP filter for delay and abort
Istio fault injectionVirtualService delay and abort
Feature flagRuntime switch; here the chaos kill switch
Continuous verificationExperiments run automatically and repeatedly
MTTRMean time to recovery
RTO / RPORecovery time / point objective
Resilience scoreComposite measure you define yourself
BlamelessReview culture that studies conditions, not people
Observability prerequisiteMetrics, traces, alerts needed before experiments

References ​

  1. Principles of Chaos Engineering — https://principlesofchaos.org/
  2. Basiri et al., "Chaos Engineering", IEEE Software 33(3), 2016 — https://arxiv.org/abs/1702.05843
  3. AWS Fault Injection Service: What is AWS FIS — https://docs.aws.amazon.com/fis/latest/userguide/what-is.html
  4. AWS FIS actions reference — https://docs.aws.amazon.com/fis/latest/userguide/fis-actions-reference.html
  5. Chaos Mesh documentation — https://chaos-mesh.org/docs/
  6. LitmusChaos: What is Litmus — https://docs.litmuschaos.io/docs/introduction/what-is-litmus
  7. Gremlin: Chaos Engineering — https://www.gremlin.com/chaos-engineering
  8. Toxiproxy README — https://raw.githubusercontent.com/Shopify/toxiproxy/main/README.md
  9. Istio: Fault Injection — https://istio.io/latest/docs/tasks/traffic-management/fault-injection/
  10. Envoy HTTP fault filter — https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/fault_filter
  11. Google SRE Book, "Accelerating SREs to On-Call" (Wheel of Misfortune) — https://sre.google/sre-book/accelerating-sre-on-call/
  12. tc-netem(8) — https://man7.org/linux/man-pages/man8/tc-netem.8.html
  13. AWS GameDay (learning event) — https://aws.amazon.com/gameday/
  14. Laravel 13 HTTP client (faking, sequences) — https://laravel.com/docs/13.x/http-client
  15. Laravel 13 middleware — https://laravel.com/docs/13.x/middleware
  16. Laravel 13 Pennant — https://laravel.com/docs/13.x/pennant

Not fetched, therefore not linked: the Netflix Tech Blog posts "The Netflix Simian Army" and "ChAP: Chaos Automation Platform" (the host returned 403 to automated requests), and Kripa Krishnan's ACM Queue article on DiRT. Claims that depend on them are labelled above.

Built by Morteza Negahi