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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why test failure on purpose | Why it exists |
| Chaos Monkey, Chaos Kong, FIT, GameDay, DiRT | Where it comes from |
| The five principles | Principles |
| Steady state, hypothesis, SLI | Steady state |
| Write an experiment | Experiment design |
| Blast radius, canary, abort, kill switch | Blast radius |
| Which faults to inject | The fault catalogue |
| Chaos Mesh, Litmus, Gremlin, AWS FIS, Toxiproxy, tc netem | Tooling |
| Istio and Envoy fault injection | Mesh faults |
| Faults inside your own code | Application-level injection |
| Running a game day | Game days |
| Chaos in a pipeline | Continuous verification |
| What you must have before starting | Observability prerequisites |
| Blameless culture, change control, compliance | Organisational safety |
| MTTR, RTO, resilience score | Measuring resilience |
| What goes wrong | Anti-patterns |
| Knobs and error names | Mechanics |
| Code | Go, Laravel |
| Classic findings and fixes | Solving the classic problems |
| Which experiment next | Choosing |
| Monolith to multi-region | In architecture |
| Run it | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The experiment, step by step.
| Step | Question it answers | Example |
|---|---|---|
| Steady state | What does "working" mean, as a number? | Checkout success rate at least 99.5%, p99 below 800 ms |
| Hypothesis | What do we believe will not change? | "If the recommendations service returns 503, checkout success stays at 99.5%" |
| Variable | What real-world event do we introduce? | 60% of calls to recommendations fail with 503 |
| Blast radius | How many users can this hurt? | Header-tagged test users, then 1% of traffic |
| Abort condition | When do we stop automatically? | Checkout success below 98% for 20 consecutive probes |
| Kill switch | How do we stop by hand, in seconds? | Feature flag off, stop() function, FIS stop condition |
| Verdict | What did we learn? | HELD, REFUTED, ABORTED or INVALID (steady state was not steady) |
Faults and the real event behind each.
| Fault | Real event it imitates | Typical tool |
|---|---|---|
| Latency injection | Overloaded dependency, GC pause, slow disk | Toxiproxy latency, tc netem delay, Istio fault.delay |
| Error injection | Dependency returns 500 or 503, resets the connection | Istio fault.abort, Envoy fault filter, middleware |
| Instance termination | Host crash, spot reclaim, OOM kill | Chaos Monkey, Chaos Mesh PodChaos, AWS FIS aws:ec2:terminate-instances |
| AZ failure | Power or network loss in one data centre | AWS FIS network disrupt, a drain script |
| Region failure | Provider-wide event | Chaos Kong style evacuation drill |
| Dependency outage | A third-party API is down | Toxiproxy down, Http::fake |
| Resource exhaustion | CPU, memory, file descriptors, threads | Chaos Mesh StressChaos, Gremlin resource attacks |
| Clock skew | NTP failure, leap second, VM pause | Chaos Mesh TimeChaos, faketime or a VM clock offset |
| Network partition | Switch failure, bad route | Chaos Mesh NetworkChaos partition, iptables drop |
| DNS failure | Resolver down, record deleted | Chaos Mesh DNSChaos, blackhole port 53 |
| Certificate expiry | A forgotten cert on a timer | Test CA with a short-lived cert |
| Disk full | Log or WAL growth | fallocate a big file, Chaos Mesh IOChaos |
Where to run what.
| Environment | What you learn | Risk | Rule |
|---|---|---|---|
Unit test with fakes (Http::fake, a fake RoundTripper) | Your fallback code path exists and returns | None | Run on every commit |
| Staging with Toxiproxy or a mesh | Timeouts, retries and breakers are tuned | Low | Run nightly |
| Production canary or header-tagged users | Real traffic, real dependencies | Contained | Needs observability, abort, kill switch |
| Production at a percentage | Capacity and cross-service effects | Real | Needs on-call present, business hours |
| Game day, AZ or region | People, runbooks, communication | Planned | Needs announcement and a debrief |
The vocabulary of numbers.
| Term | Meaning | Where used |
|---|---|---|
| SLI | A measured indicator, such as success rate | Steady state |
| SLO | The target for an SLI | Hypothesis threshold |
| MTTR | Mean time to recovery | Resilience measure |
| RTO | Recovery time objective: how long an outage may last | Game day pass mark |
| RPO | Recovery point objective: how much data may be lost | Failover drills |
| Error budget | Allowed unreliability per window | Gate 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 incidents | Run experiments |
|---|---|
| Failure arrives at a random time, at full scale | Failure arrives at a chosen time, at a chosen scale |
| People are tired, the runbook is untested | People are present, the runbook is the thing under test |
| You learn the cause after the damage | You learn the weakness before the damage |
| One data point per quarter | Many small data points per week |
| Fixes are rushed | Fixes 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
- "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.
- "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.
- "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
| Year | Event | Source status |
|---|---|---|
| 2003 | Jesse Robbins starts "GameDay" exercises at Amazon (he is described as holding the title "Master of Disaster") | Inference from memory; not fetched for this page |
| 2006 | Google 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 2011 | Netflix 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 |
| 2014 | Netflix describes FIT (Failure Injection Testing): fail requests between services, scoped by request | Named in the 2016 paper's reference list |
| 2016 | Basiri et al., "Chaos Engineering", IEEE Software 33(3) | Fetched and read (arXiv:1702.05843) |
| 2016 | Principles of Chaos Engineering published | Fetched and read |
| 2017 | Netflix ChAP (Chaos Automation Platform) runs experiments as a canary against a baseline | Netflix blog could not be fetched; treat as unverified |
| 2020s | Managed services: AWS Fault Injection Service, Gremlin; CNCF projects Chaos Mesh and LitmusChaos | Vendor 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, scheduleReal 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.
| Principle | Wording on principlesofchaos.org (shortened) | What it forbids |
|---|---|---|
| Hypothesis around steady state | Focus on measurable output, not internal attributes | "CPU stays low" as the hypothesis |
| Vary real-world events | Servers that crash, hard drives that malfunction, connections severed | Exotic, unrealistic faults |
| Run in production | Behaviour depends on environment and traffic | Concluding from staging alone |
| Automate | Manual runs are "labor-intensive and ultimately unsustainable" | One-off heroics |
| Minimise blast radius | Fallout "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 recoveredReal 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 metric | Poor metric | Why |
|---|---|---|
| Successful checkouts per minute | CPU utilisation | Users do not feel CPU |
| p99 latency of the user-facing call | Average latency | The mean hides the tail |
| Fraction of requests served from fallback | Number of retries | Retries are an internal attribute |
| Messages processed per second at the consumer | Queue length alone | Length 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.
-- 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| Field | Question | Bad answer | Good answer |
|---|---|---|---|
| Steady state | How do we know it works? | "No alerts" | A numeric SLI and a band |
| Variable | What changes? | "Stress the system" | One named fault, one parameter |
| Scope | Who can be hurt? | "Production" | A cohort, a percentage, a budget |
| Abort | When do we stop alone? | "If it looks bad" | A threshold over a window, automated |
| Kill | How do we stop by hand? | "Redeploy" | One command that takes seconds |
| Owner | Who 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| Control | Type | Triggered by | Tested how |
|---|---|---|---|
| Allowlist (hosts, paths, cohort) | Scope | Configuration | Test that a non-listed path is untouched |
| Budget (max faults) | Scope | Counter | Test that the injector disarms itself |
| Abort condition | Automatic | Metric threshold over a window | Run a fault you know will trip it |
| Kill switch | Manual | A human | Run it in staging before every production run |
| Time box | Automatic | Clock | The job ends even if the controller dies |
| Business-hours window | Policy | Scheduler | Review 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).
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.
| Fault | How to inject (product) | What usually breaks |
|---|---|---|
| Latency injection | Toxiproxy latency toxic, tc netem delay 300ms 50ms, Istio fault.delay, Envoy delay | Missing timeouts, thread pool exhaustion, retry storms |
| Error injection | Istio fault.abort.httpStatus, Envoy abort, middleware returning 503 | Retries on non-idempotent calls, no fallback |
| Partial response | Toxiproxy limit_data, slicer, body truncation | JSON parse crashes, half-written cache entries |
| Instance termination | Chaos Monkey, Chaos Mesh PodChaos pod-kill, AWS FIS aws:ec2:terminate-instances, kubectl delete pod | Local state lost, slow warm-up, in-flight requests dropped |
| Process freeze | kill -STOP <pid> then kill -CONT <pid> | Failure detectors, leader leases, TCP half-open connections |
| AZ failure | AWS FIS network disrupt for one subnet, draining a zone | Single-AZ dependencies, uneven capacity |
| Region failure | Chaos Kong style evacuation, DNS weight to zero | Hidden cross-region dependencies, cold caches |
| Dependency outage | Toxiproxy down, firewall drop, Http::fake failures | Missing circuit breaker or fallback |
| Resource exhaustion | Chaos Mesh StressChaos (CPU, memory), Gremlin resource attacks, file descriptor limit | Autoscaling lag, OOM kills, no load shedding |
| Clock skew | Chaos Mesh TimeChaos, faketime or a VM clock offset | Token validation, lease expiry, ordering by timestamp |
| Network partition | Chaos Mesh NetworkChaos, iptables drop between groups | Split brain, double leaders, unavailable minority |
| Packet loss and jitter | tc netem loss 5%, delay with jitter | TCP stalls, gRPC deadline misses |
| DNS failure | Chaos Mesh DNSChaos, block UDP/TCP 53, wrong TTL | Cached-forever resolvers, connection pools holding dead IPs |
| Certificate expiry | A test CA issuing 5-minute certificates | Missing rotation, no alert before expiry |
| Disk full | fallocate -l to fill a volume, Chaos Mesh IOChaos | Logging 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 loadReal 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 verify | Pass condition |
|---|---|
| Timeout shorter than the caller's own deadline | Caller answers within budget |
| Retries bounded and jittered | Dependency load rises less than 2x |
| Circuit opens | Calls fail fast after N failures (Circuit Breaker) |
| Fallback exists | Degraded 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 writersReal 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.
| Fault | Check |
|---|---|
| Disk full | Service degrades but keeps serving reads; alert fires at 80% |
| CPU stress | Autoscaler adds capacity before p99 breaches; Load Shedding works |
| Clock skew | Tokens, leases and ordering tolerate the skew you promised |
| Frozen process | Failure 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".
| Fault | Expected behaviour | Verify |
|---|---|---|
| Partition | Matches the documented side of CAP | Minority refuses or reconciles |
| DNS failure | Cached answers used for TTL; clear error afterwards | Resolver cache, connection pool refresh |
| Certificate expiry | Alert 30 days and 7 days before; automated rotation | Short-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| Scenario | Question | Evidence |
|---|---|---|
| One dependency down | Does the product degrade or die? | Fallback hit rate |
| One AZ gone | Do the other AZs hold the peak? | CPU and queue depth after drain |
| Region evacuation | Does DNS or traffic steering move users in the time we promise? | Time to 99% of traffic elsewhere |
| Backups and failover | Does 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.
| Tool | Acts at | Faults | Safety features | Notes |
|---|---|---|---|---|
| Chaos Monkey (Netflix) | VM instance | Terminate instance | Business hours, opt-in groups | The origin |
| Chaos Mesh (CNCF) | Kubernetes | PodChaos, NetworkChaos, StressChaos, IOChaos, TimeChaos, DNSChaos | Namespace scoping, schedules, workflows, dashboard | Open source; chaos-daemon runs privileged |
| LitmusChaos (CNCF) | Kubernetes | Pod, node, network, cloud faults via ChaosHub experiments | ChaosCenter, probes that check steady state | Open source, "cross-cloud support" |
| Gremlin | Hosts, containers, Kubernetes | Resource, network and state attacks | Reliability Score, scenarios (verify other safety features in vendor docs) | Commercial |
| AWS Fault Injection Service | AWS control plane | Stop or terminate EC2, throttle APIs, network disruption | Experiment templates with stop conditions, IAM role | Managed; "carries out real actions on real AWS resources" |
| Toxiproxy (Shopify) | TCP proxy | latency, down, bandwidth, slow_close, timeout, reset_peer, slicer, limit_data | Toxics added and removed over an HTTP API | Best for tests and staging |
| tc netem (Linux) | Kernel qdisc | delay, loss, corrupt, duplicate, reorder, rate | tc qdisc del to remove | Root needed; whole interface |
| Istio fault injection | Envoy sidecar | HTTP delay, HTTP abort | Per route, per header match, percentage | No app change |
| Envoy fault filter | Envoy | delay, abort, rate limit; header controlled | Percentages, header-driven overrides | x-envoy-fault-delay-request, x-envoy-fault-abort-request |
| Kubernetes pod deletion | API | Delete a pod | None built in; use --grace-period, namespaces | The 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.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.
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.
| Aspect | Istio fault | Envoy fault filter | App middleware |
|---|---|---|---|
| Needs code change | No | No (config) | Yes |
| Fault types | delay, abort | delay, abort, response rate limit | Anything |
| Per request control | Header match | Fault headers | Header with token |
| Fault inside the callee | No (caller side) | No | Yes |
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 property | Go implementation | Laravel implementation |
|---|---|---|
| Off by default | Injector zero value injects nothing | Pennant flag defined as false |
| Kill switch | Disable() | Feature::for('global')->deactivate(...) |
| Allowlist | AllowHosts, AllowPrefixes | config('chaos.allow'), deny list |
| Budget | MaxInjections | Cache::increment in a time window |
| Secret header | Token | hash_equals on the token |
| Cap on latency | 10 s in parseHeader | max_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?| Role | Duty |
|---|---|
| Facilitator (game master) | Runs the clock, injects, can pause or abort |
| Responders | The people on call, using normal tools and the runbook |
| Observer / scribe | Records timestamps: detected, diagnosed, mitigated |
| Safety officer | Owns the abort criteria and the kill switch |
| Communications | Plays customer support or status page owner |
| Form | What it tests | Cost | When |
|---|---|---|---|
| Tabletop exercise | Decisions, communication, runbook reading | Low (one hour, no systems) | First, and for scary scenarios |
| Live staging game day | Runbook commands, tooling, alerts | Medium | Quarterly |
| Live production game day | Real behaviour at real scale | High | After staging passes, announced |
| Surprise drill | Detection and escalation without warning | High; needs consent | Mature 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| Layer | Runs | Failure means |
|---|---|---|
| Unit fault test | Every commit | Fallback code removed or broken |
| Integration with Toxiproxy | Every merge or nightly | Timeout or retry config regressed |
| Staging pod or node kill | Nightly | Readiness, graceful shutdown, PDB wrong |
| Production canary | Scheduled, business hours | Real-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.
| Pattern | Claim | Experiment | Pass |
|---|---|---|---|
| Timeout (Timeouts, Retries & Jitter) | A slow call ends in N ms | +3 s latency on the dependency | p99 inside budget |
| Retry with jitter | Blips are absorbed, storms are not created | 20% errors for 5 min | Dependency load rises under 2x |
| Circuit breaker (Circuit Breaker) | Opens after repeated failure, recovers | 100% errors for 60 s, then healthy | Opens, then closes within the wait time |
| Bulkhead (Bulkheads) | One slow dependency cannot starve others | +10 s latency on A | Endpoint B unaffected |
| Load shedding (Load Shedding) | Overload degrades gracefully | 3x load | Goodput stable, low-priority dropped |
| Idempotency (API Idempotency) | Retries do not double-charge | Drop the response after the write | One charge |
| Cascading (Cascading Failures) | One failure stays contained | Kill the slowest dependency | No 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).
| Prerequisite | Why |
|---|---|
| SLI dashboard with a short window (1 min) | The abort condition needs fresh numbers |
| Metric split by cohort or version | Compare canary against baseline |
| Distributed traces with request ids | Find which hop produced the error |
| Event annotation on graphs ("fault on") | Correlate cause and effect |
| Alerts that page a human | Detection time is part of the result |
| Tested rollback path | The kill switch must work |
| On-call present and aware | A 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.
| Area | Practice |
|---|---|
| Blameless culture | Debrief about conditions and decisions, never individuals |
| Change management | Experiments registered like changes; freeze periods respected (the Laravel job checks chaos:paused) |
| Legal and compliance | Never 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 impact | Exclude paying-critical cohorts; define compensation if the SLO is breached |
| Error budget | Run chaos only while budget remains; pause when it is spent |
| Access | The chaos tool has narrow IAM roles; AWS FIS uses an IAM role, Chaos Mesh uses RBAC and namespace filters |
| Records | Keep 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.
| Measure | Formula | Use |
|---|---|---|
| Hypothesis hold rate | HELD runs / valid runs, per service | Where defences are weak |
| Time to detect | Alert time minus fault start | Alert quality |
| Time to mitigate (MTTR) | Steady-state time minus fault start | Compare to RTO |
| Recovery check | After-phase SLI inside bounds | The fix reverts cleanly |
| Experiment coverage | Services with a recent HELD experiment / services | Gaps |
| Findings closed | Closed actions / opened | Does learning turn into fixes |
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-pattern | Why it hurts | Fix |
|---|---|---|
| Random chaos without hypothesis | Nothing to learn; the result is "it broke" | Write the one-page experiment |
| Chaos in production without a kill switch | A mistake becomes an outage | Test the stop path first |
| Breaking things you cannot observe | You cannot tell harm from noise | Meet the observability prerequisites |
| Starting with the whole fleet | Maximum blast radius on the first run | Canary, then 1% |
| Injecting during a deploy or incident | Two changes at once | Check deploy and incident status first |
| Not removing the fault | A forgotten fault is a future outage | defer the stop; time box it |
| Experiments nobody reads | Findings rot | Owners and dates on action items |
| Chaos as a test of people | Fear, hidden problems | Blameless debrief |
| Testing only instance death | Misses slow and partial faults | Use the catalogue |
| Assuming a pass lasts | Systems change | Automate the experiment |
Mechanics
Knobs, in one place
| Knob | Product | Meaning |
|---|---|---|
fault.delay.fixedDelay, percentage.value | Istio VirtualService | Delay and share of requests |
fault.abort.httpStatus, percentage.value | Istio VirtualService | Status code returned and share |
x-envoy-fault-delay-request (ms), x-envoy-fault-abort-request (status 200 to 599) | Envoy fault filter | Per-request fault via headers |
latency, jitter attributes of the latency toxic | Toxiproxy | Added milliseconds and variation |
delay, loss, corrupt, duplicate, reorder, rate | tc netem | Kernel network emulation |
action: pod-kill, mode: one, selector.namespaces | Chaos Mesh PodChaos | What to kill and where |
| Stop conditions (CloudWatch alarm based) | AWS FIS experiment template | Automatic stop |
MaxInjections, AllowHosts, Token | The Go injector | Budget, scope, secret |
chaos.probability, chaos.budget, chaos.allow | The Laravel middleware | Same three ideas |
Error names and statuses you will see
| Message or code | Source | Meaning |
|---|---|---|
faultinject: injected connection error | The Go snippet | A deliberate connection failure |
HTTP 503 with X-Chaos-Injected | Go and Laravel snippets | An injected status |
fault filter abort | Envoy access log (response flag FI) | Envoy injected the failure |
context deadline exceeded | Go clients | Timeout fired: the expected result of latency injection |
Illuminate\Http\Client\ConnectionException | Laravel HTTP client | Connection failed or timed out |
Illuminate\Http\Client\RequestException | Laravel HTTP client | A 4xx or 5xx after throw() |
INVALID | The Go runner | The 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.
// 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.
// 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
}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)
}
}
}// 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
}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)
}
}// 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
// 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
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
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
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
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
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
// 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
// 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
| Symptom | Cause | Fix | Verify |
|---|---|---|---|
| Recommendations down, whole page 500 | Fallback code path never ran in production | Add the fallback; add a Http::fake rehearsal | Run the experiment; fallback rate rises, success holds |
Retries amplify the outage
| Symptom | Cause | Fix | Verify |
|---|---|---|---|
| Dependency at 3x load during blip | Three retries, no jitter, no budget | Bounded retries with jitter (Timeouts, Retries & Jitter) | Dependency load stays under 2x in the experiment |
One slow dependency starves the pool
| Symptom | Cause | Fix | Verify |
|---|---|---|---|
| Unrelated endpoints time out | Shared worker pool | Bulkhead per dependency | Latency injected on A, endpoint B unaffected |
The runbook is wrong
| Symptom | Cause | Fix | Verify |
|---|---|---|---|
| Responders stuck at step 4 | Command needs a permission or points to a retired host | Fix the runbook; test every step in a game day | Rerun the scenario in 30 days |
The failover takes five minutes, not thirty seconds
| Symptom | Cause | Fix | Verify |
|---|---|---|---|
| Measured MTTR far above RTO | Long DNS TTL, cold cache, connection pool pinned to old IP | Lower TTL, warm caches, refresh pools | Measure MTTR again |
The experiment itself caused harm
| Symptom | Cause | Fix | Verify |
|---|---|---|---|
| Customers affected beyond the cohort | Allowlist too wide or abort missing | Narrow scope; automate abort; tighten window | Abort test passes in staging |
Choosing
Which experiment next
| Situation | First experiment | Tool | Reason |
|---|---|---|---|
| New service, no tests | Fake returns 503 and +2 s | Http::fake or a Go fake RoundTripper | Cheapest proof the fallback exists |
| Timeouts changed | +latency in staging | Toxiproxy | Verifies the new numbers |
| Kubernetes deployment | Delete one pod under load | kubectl delete pod, Chaos Mesh PodChaos | Readiness and graceful shutdown |
| Mesh in place | Abort 503 for a header cohort | Istio fault.abort | No code change |
| AWS shop with budget | Stop instances in one AZ | AWS FIS with stop conditions | Managed guardrails |
| Team is new to this | Tabletop exercise | A meeting | Builds the habit |
| Mature team, tested runbooks | Production game day | Chosen tool plus announcement | Tests people at scale |
Tool selection
| Need | Pick |
|---|---|
| Open source on Kubernetes | Chaos Mesh or LitmusChaos |
| Commercial, many platforms, scoring | Gremlin |
| AWS-native with IAM and stop conditions | AWS Fault Injection Service |
| Test-time network faults | Toxiproxy |
| Kernel-level network faults on a host | tc netem |
| Faults inside your code | Feature-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 cohortDistributed 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
| Scale | Practice |
|---|---|
| 1x: one team, one service | Fake-based tests, one tabletop a quarter |
| 10x: tens of services | Toxiproxy or mesh faults in staging, nightly; weekly production canary |
| 100x: hundreds of services, several regions | Chaos 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=trueThis 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/faultinjectExperiment 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 pgExperiment 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 switchExperiment 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 fallbackExperiment 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
| Belief | Reality |
|---|---|
| Chaos engineering is random breaking in production | It is hypothesis-driven experimentation with scope and abort rules |
| You need production to start | Start with fakes, staging and tabletops; production comes later |
| A tool gives us chaos engineering | A tool injects; the discipline is the hypothesis and the measurement |
| Instance kill is the main test | Slow and partial failures are more damaging and more common |
| If it passes once we are resilient | It is evidence for that fault, at that load, on that day |
| Chaos replaces testing | It complements unit, integration and load tests |
| Game days are for ops only | Developers, support and product take part |
| A kill switch is optional if the abort rule is good | Abort rules miss things; keep both and test the switch |
| A resilience score is a measure of reliability | It is a to-do list; MTTR and customer impact are the measures |
| Findings are a failure of the team | They are the product; blameless debriefs depend on this |
Cheat sheet
| Topic | Remember |
|---|---|
| Definition | Experiment on a system to build confidence it withstands turbulence in production |
| Five principles | Steady-state hypothesis, real-world events, production, automate, minimise blast radius |
| Experiment page | SLI, hypothesis, one variable, scope, abort, kill switch, owner |
| Verdicts | HELD, REFUTED, ABORTED, INVALID |
| Blast radius ladder | Fake, staging, canary, 1%, AZ, region |
| Abort vs kill | Abort is automatic, kill is manual; test both |
| Faults to start | Latency, 503, dependency down, pod delete |
| Tools | Toxiproxy tests; mesh for no code; Chaos Mesh, Litmus, Gremlin, AWS FIS for platforms |
| Application-level | Flag, allowlist, token, budget, header, log it |
| Game day | Plan, roles, inject, respond, hot debrief, written debrief, action items |
| CI | Fake-based tests per commit; nightly staging; weekly canary |
| Prerequisite | Observability with cohort split and annotations |
| Measure | MTTR vs RTO, hold rate, findings closed |
| Never | Random chaos, no kill switch, unobserved systems |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Chaos engineering | Experimenting on a system to build confidence in its resilience |
| Steady state | Normal measurable behaviour of the system at its boundary |
| Hypothesis | The claim that steady state holds under a fault |
| SLI / SLO | Measured indicator / target for it |
| Blast radius | The set of users and resources an experiment can affect |
| Abort condition | Automatic rule that stops an experiment |
| Kill switch | Manual immediate stop |
| Canary experiment | Fault applied to a small comparable slice |
| Chaos Monkey | Netflix tool terminating instances in business hours |
| Simian Army | Netflix family of failure-injecting tools |
| Chaos Kong | Netflix exercise simulating region loss |
| FIT | Failure Injection Testing, request-scoped failure at Netflix |
| ChAP | Netflix Chaos Automation Platform |
| GameDay | Planned failure exercise (Amazon) |
| DiRT | Google's Disaster Recovery Testing |
| Game day | Rehearsal of an incident with people and runbooks |
| Tabletop exercise | Discussion-based game day without live faults |
| Runbook validation | Executing a runbook to prove each step works |
| Debrief | Blameless review with action items |
| Fault injection | Introducing a fault on purpose |
| Latency injection | Adding delay to calls |
| Error injection | Returning errors instead of real answers |
| Chaos Mesh | CNCF Kubernetes chaos platform |
| LitmusChaos | CNCF Kubernetes chaos project |
| Gremlin | Commercial chaos platform |
| AWS Fault Injection Service | AWS managed fault injection with stop conditions |
| Toxiproxy | Shopify TCP proxy with toxics |
| tc netem | Linux network emulation qdisc |
| Envoy fault filter | Envoy HTTP filter for delay and abort |
| Istio fault injection | VirtualService delay and abort |
| Feature flag | Runtime switch; here the chaos kill switch |
| Continuous verification | Experiments run automatically and repeatedly |
| MTTR | Mean time to recovery |
| RTO / RPO | Recovery time / point objective |
| Resilience score | Composite measure you define yourself |
| Blameless | Review culture that studies conditions, not people |
| Observability prerequisite | Metrics, traces, alerts needed before experiments |
References
- Principles of Chaos Engineering — https://principlesofchaos.org/
- Basiri et al., "Chaos Engineering", IEEE Software 33(3), 2016 — https://arxiv.org/abs/1702.05843
- AWS Fault Injection Service: What is AWS FIS — https://docs.aws.amazon.com/fis/latest/userguide/what-is.html
- AWS FIS actions reference — https://docs.aws.amazon.com/fis/latest/userguide/fis-actions-reference.html
- Chaos Mesh documentation — https://chaos-mesh.org/docs/
- LitmusChaos: What is Litmus — https://docs.litmuschaos.io/docs/introduction/what-is-litmus
- Gremlin: Chaos Engineering — https://www.gremlin.com/chaos-engineering
- Toxiproxy README — https://raw.githubusercontent.com/Shopify/toxiproxy/main/README.md
- Istio: Fault Injection — https://istio.io/latest/docs/tasks/traffic-management/fault-injection/
- Envoy HTTP fault filter — https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/fault_filter
- Google SRE Book, "Accelerating SREs to On-Call" (Wheel of Misfortune) — https://sre.google/sre-book/accelerating-sre-on-call/
- tc-netem(8) — https://man7.org/linux/man-pages/man8/tc-netem.8.html
- AWS GameDay (learning event) — https://aws.amazon.com/gameday/
- Laravel 13 HTTP client (faking, sequences) — https://laravel.com/docs/13.x/http-client
- Laravel 13 middleware — https://laravel.com/docs/13.x/middleware
- 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.