TS·120
Chaos and Resilience Testing
Deliberately injecting failure to prove systems survive it: the principles of chaos engineering, steady-state hypotheses, blast radius and abort conditions, the failure modes to inject (dependency failure, latency, process kill, node failure, network partition, disk, CPU and memory pressure), fault injection at code, library, network, container, Kubernetes and cloud levels, tools (Chaos Mesh, LitmusChaos, Toxiproxy, AWS FIS, Azure Chaos Studio, Gremlin, Jepsen-style testing), game days, and testing resilience patterns in unit and integration tests.
Start here: breaking things on purpose, safely
Integration tests showed that one call handles one failure. Chaos experiments ask the system-level question: when a dependency misbehaves while real traffic is flowing, do customers still get served? You find out by injecting the failure deliberately, in a controlled way, and measuring.
An experiment has four parts
- Steady state: a measurable sign the system is healthy. Here: at 40 menu requests per second, at least 99% succeed and p95 latency is under 200 ms.
- Hypothesis: "if the database becomes slow (1 s extra latency), the steady state still holds".
- Fault injection: add the fault for a fixed window. Toxiproxy sits between the service and PostgreSQL and added 1,000 ms of latency from second 10 to second 20 of a 30-second run.
- Verify, and limit the damage: compare the steady-state measure before, during and after; stop early if harm exceeds an abort condition.
The naive service fails the hypothesis
The menu service queries PostgreSQL on every request, with no timeout:
before (0–10 s) n=399 success=100.0% p50= 2.1 ms p95= 4.4 ms
fault (10–20 s) n=113 success= 3.5% p50=5000.0 ms p95=5001.0 ms
after (20–30 s) n=553 success= 98.9% p50= 2.4 ms p95=4432.2 ms
dropped arrivals: 136
During the fault almost every request hit the load generator's 5-second timeout. Requests piled up on the 8 database connections; the backlog took time to clear after the fault ended (p95 4.4 s in the "after" window), and 136 arrivals couldn't even be sent. A one-second slowdown in one dependency became a ten-second outage, plus recovery.
The resilient service passes it
The same service with two changes: a 150 ms deadline on the database call, and a fallback to the last menu it read successfully:
before (0–10 s) n=399 success=100.0% p50= 2.3 ms p95= 4.3 ms
fault (10–20 s) n=402 success=100.0% p50=151.4 ms p95=153.2 ms
after (20–30 s) n=400 success=100.0% p50= 2.5 ms p95= 5.4 ms
Every request succeeded throughout. During the fault each one waited out the 150 ms deadline and got the cached menu (a few minutes old at most, which is fine for a menu, and would not be fine for a payment status). Recovery was instant because nothing had queued.
Limiting the blast radius
Running the naive experiment again, with an abort condition: probe the service every 0.5 s with a 2 s timeout, and remove the fault after three consecutive failed probes.
t=10.0 fault injected
t=17.1 ABORT: 3 consecutive failed probes, fault removed
fault window: success 84.0% (instead of 3.5%)
The guard cut the damage, but notice it took 7 seconds to decide: three probes, each allowed 2 seconds. Abort conditions need to be fast to detect, and you only run experiments where the worst case is acceptable, starting small (one instance, a fraction of traffic, a test environment) and widening as confidence grows.
How deep to go in chaos and resilience testing
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain chaos engineering's principles: steady state, hypothesis, blast radius, abort conditions |
| L2 | Inject dependency faults (latency, errors, resets) into a test environment and measure the effect |
| L3 | Explain which resilience patterns answer which faults (timeouts, retries with budgets, fallbacks, bulkheads, breakers) |
| L4 | Design and run experiments that reveal weaknesses, and verify the fixes under the same fault |
| L5 | Build a chaos practice for a system: experiment catalogue, game days, automation in CI and safe production experiments |
| L6 | Run resilience engineering across an organisation with guardrails, tooling and learning reviews |
Why break things on purpose
Distributed systems fail constantly: dependencies time out, nodes die, networks partition, disks fill, deployments go wrong (Vol. 5 ch. 78). Resilience mechanisms (timeouts, retries, circuit breakers, fallbacks, replication, autoscaling, failover) are code and configuration that only run during failures, so they're the least exercised paths in the system, and often broken: a timeout set longer than the caller's, a retry storm, a fallback that was never deployed, a failover that needs a manual step nobody remembers.
Chaos engineering (popularised by Netflix's Chaos Monkey, 2011) is "the discipline of experimenting on a system in order to build confidence in its capability to withstand turbulent conditions in production". It replaces hoping with evidence.
Principles
The Principles of Chaos Engineering:
- Define steady state as measurable output that indicates normal behaviour (business and SLI metrics: orders per minute, success rate, p99 latency), not internal details.
- Hypothesise that steady state will continue in both control and experimental conditions.
- Introduce real-world events: server crashes, latency, dependency failures, traffic spikes.
- Try to disprove the hypothesis by comparing steady state between control and experiment.
- Run in production eventually (realistic traffic and configuration), carefully.
- Automate experiments to run continuously.
- Minimise blast radius: start small, limit scope, have an abort plan.
Designing an experiment
A good experiment is a small, controlled scientific test, written down beforehand:
| Element | Example |
|---|---|
| Steady state | Checkout success rate ≥ 99.9%, p99 < 800 ms, orders/min within normal band |
| Hypothesis | "If one of three payment-service pods is killed every 2 minutes, steady state holds because the Deployment reschedules pods and the gateway retries idempotently" |
| Fault | Pod kill, 1 pod at a time, payments namespace, staging first |
| Blast radius | One service, one environment, 5% of traffic (via a canary or synthetic tenant), 15 minutes |
| Abort conditions | Success rate < 99.5% or p99 > 2 s for 1 minute → stop automatically and roll back the fault |
| Observability | Dashboards and traces ready; on-call informed; experiment annotated on graphs |
| Rollback | Fault auto-expires; runbook for manual cleanup |
| Outcome | Hypothesis held / disproved; findings → tickets; next experiment |
Progression: run on a developer machine or in CI (Toxiproxy, Testcontainers), then staging, then production with a small blast radius, then wider and automated.
Failure modes to inject
| Failure | What it tests | How to inject |
|---|---|---|
| Dependency failure (errors) | Error handling, fallbacks, circuit breakers, graceful degradation | Return 500/503 from a dependency (service mesh fault injection, Toxiproxy, WireMock, feature flag), block a port |
| Latency injection | Timeouts and deadlines, retry budgets, thread/connection pool exhaustion, cascading slowness | Add delay at the network (tc netem, Toxiproxy latency), mesh (fault.delay), or library |
| Process kill | Supervisors and restarts, in-flight work, idempotency of retried work, graceful shutdown | kill -9, pod deletion, container kill |
| Node / instance failure | Rescheduling, replica spread across zones, leader re-election, capacity headroom | Drain/terminate nodes, stop VMs, AWS FIS instance termination |
| Zone / region failure | Multi-AZ/region design, failover runbooks, DNS/traffic shifting | Block traffic to a zone's subnets, cloud fault-injection AZ scenarios, game days |
| Network partition | Split brain, consensus behaviour, quorum, stale reads, client retries | iptables rules, Chaos Mesh NetworkChaos partition, Jepsen nemesis |
| Packet loss, corruption, duplication, reordering | Protocol robustness, retries, idempotency | tc netem, Chaos Mesh |
| DNS failure | Caching, fallback resolution, startup dependencies | Chaos Mesh DNSChaos, blocking resolvers |
| Disk pressure / I/O faults | Behaviour when the disk is full or slow: logging, databases, temp files | Fill the disk, I/O latency/error injection (Chaos Mesh IOChaos, dm-flakey) |
| CPU pressure | Autoscaling triggers, throttling, latency under contention, noisy neighbours | stress-ng, Chaos Mesh StressChaos |
| Memory pressure | OOM kills, GC thrashing, cache eviction, memory limits | stress-ng --vm, memory hog containers |
| Clock skew | Token expiry, TTLs, ordering assumptions, certificate validity | Chaos Mesh TimeChaos, libfaketime |
| Expired certificates / credentials | Rotation automation, alerting | Short-lived test certificates, revoke a credential in staging |
| Traffic surge | Autoscaling, load shedding, rate limits | Spike tests (chapter 119) |
Fault injection levels and tools
In code and libraries
The cheapest place to test resilience logic is in unit and integration tests:
- Stub dependencies that fail or hang and assert on timeouts, retries, circuit-breaker state and fallbacks (with virtual time, chapter 115).
- Toxiproxy (Shopify): a TCP proxy between your service and a dependency (database, Redis, HTTP) with an API to add toxics: latency, bandwidth limits, timeouts, connection resets, slicing. Testcontainers has a Toxiproxy module.
// Java: Testcontainers Toxiproxy between the app and Postgres — verify the timeout and fallback
@Testcontainers
class InventoryTimeoutIT {
static Network net = Network.newNetwork();
@Container static PostgreSQLContainer pg = new PostgreSQLContainer("postgres:18-alpine")
.withNetwork(net).withNetworkAliases("pg");
@Container static ToxiproxyContainer toxi = new ToxiproxyContainer("ghcr.io/shopify/toxiproxy:2.5.0")
.withNetwork(net);
@Test
void fallsBackToCachedStockWhenDatabaseIsSlow() throws Exception {
var client = new ToxiproxyClient(toxi.getHost(), toxi.getControlPort());
Proxy proxy = client.createProxy("pg", "0.0.0.0:8666", "pg:5432");
var service = InventoryService.connect(toxi.getHost(), toxi.getMappedPort(8666), Duration.ofMillis(300));
proxy.toxics().latency("slow-db", ToxicDirection.DOWNSTREAM, 2_000); // 2 s added latency
var started = System.nanoTime();
var stock = service.stockFor("book-1");
assertThat(stock.source()).isEqualTo(Source.CACHE); // degraded, not failed
assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofMillis(500));
}
}
// Go: test a client's deadline and retry budget against a hanging server
func TestClientRespectsDeadline(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
select {
case <-time.After(5 * time.Second): // hang
case <-r.Context().Done():
}
}))
defer srv.Close()
c := NewClient(srv.URL, WithTimeout(200*time.Millisecond), WithMaxRetries(2))
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := time.Now()
_, err := c.Get(ctx, "/stock/book-1")
if !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, ErrTimeout) {
t.Fatalf("want timeout, got %v", err)
}
if elapsed := time.Since(start); elapsed > 900*time.Millisecond {
t.Fatalf("took %v: retries exceeded the caller's budget", elapsed)
}
if n := calls.Load(); n > 3 {
t.Fatalf("%d attempts: retry limit not enforced", n)
}
}
# Python: simulate a failing dependency and assert the circuit breaker opens (pybreaker)
import pybreaker, pytest
def test_breaker_opens_after_consecutive_failures():
breaker = pybreaker.CircuitBreaker(fail_max=3, reset_timeout=30)
client = PricingClient(transport=AlwaysFailingTransport(), breaker=breaker)
for _ in range(3):
with pytest.raises(UpstreamError):
client.price("book-1")
with pytest.raises(pybreaker.CircuitBreakerError): # fails fast without calling upstream
client.price("book-1")
assert client.transport.calls == 3
Network and service mesh
- Linux traffic control:
tc qdisc add dev eth0 root netem delay 200ms 50ms loss 1%adds latency with jitter and packet loss on a host or inside a container's network namespace. - Service mesh fault injection: Istio
VirtualServicefault(delay or abort a percentage of requests for a route), Linkerd via HTTPRoute filters or failure-injector services; precise and reversible, targeted by headers so only test traffic is affected.
# Istio: abort 10% of requests to ratings with 503 and delay 5% by 2s, only for test traffic
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata: { name: ratings, namespace: shop }
spec:
hosts: ["ratings"]
http:
- match: [{ headers: { x-chaos: { exact: "on" } } }]
fault:
abort: { percentage: { value: 10 }, httpStatus: 503 }
delay: { percentage: { value: 5 }, fixedDelay: 2s }
route: [{ destination: { host: ratings } }]
- route: [{ destination: { host: ratings } }]
Kubernetes
- Chaos Mesh (CNCF incubating): CRDs for
PodChaos(kill, failure),NetworkChaos(delay, loss, partition, bandwidth),StressChaos,IOChaos,TimeChaos,DNSChaos,HTTPChaos, kernel faults, plus Workflows to sequence experiments and schedules. - LitmusChaos (CNCF incubating): ChaosHub of experiments, probes that check steady-state hypotheses (HTTP, Prometheus queries, commands) during the experiment, and resilience scores.
- Simple:
kubectl delete pod,kubectl drain node, Chaos Monkey-style random pod killers (kube-monkey).
# Chaos Mesh: partition the payments pods from the ledger for 2 minutes in staging
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata: { name: payments-ledger-partition, namespace: chaos-testing }
spec:
action: partition
mode: all
selector:
namespaces: ["payments"]
labelSelectors: { app: payments-api }
direction: both
target:
mode: all
selector:
namespaces: ["ledger"]
labelSelectors: { app: ledger-api }
duration: "2m"
# Chaos Mesh: CPU and memory pressure on one pod of the search service
apiVersion: chaos-mesh.org/v1alpha1
kind: StressChaos
metadata: { name: search-pressure, namespace: chaos-testing }
spec:
mode: one
selector: { namespaces: ["search"], labelSelectors: { app: search-api } }
stressors:
cpu: { workers: 2, load: 90 }
memory: { workers: 1, size: "512MB" }
duration: "10m"
Cloud provider services
- AWS Fault Injection Service (FIS): templates that stop/terminate instances, inject API errors and throttling, disrupt network connectivity, pause volume I/O, run SSM stress commands, kill ECS tasks and EKS pods, and AZ power-interruption scenarios; stop conditions tied to CloudWatch alarms abort automatically.
- Azure Chaos Studio: service-direct and agent-based faults (VM shutdown, CPU pressure, NSG rules, AKS faults via Chaos Mesh) with experiment designer.
- Google Cloud: no single managed service; use Chaos Mesh/Litmus on GKE, and fault injection via load balancer/Traffic Director.
- Commercial platforms: Gremlin, Steadybit, Harness Chaos Engineering (built on Litmus) add safety controls, reliability scoring and scheduling.
Correctness under partitions: Jepsen
For databases and distributed systems that make consistency claims, Jepsen (Kyle Kingsbury) runs a cluster, issues concurrent operations, injects partitions, clock skew and crashes with a "nemesis", records a history of operations, and checks it against a consistency model (linearizability, serializability) with checkers such as Knossos and Elle. Jepsen analyses have found consistency violations in many well-known databases. The same approach (history-based checking under faults) applies to your own consensus or replication code (Vol. 5 ch. 72), alongside deterministic simulation testing (FoundationDB, TigerBeetle, Antithesis).
Game days
A game day is a planned exercise where a team injects a significant failure (losing a zone, a database failover, an expired certificate, a dependency outage) and practises detection and response, testing people and processes as well as technology:
- Do alerts fire? Are dashboards and runbooks adequate? Who's in charge (incident command, Vol. 9 ch. 103)?
- How long does failover actually take, compared with the documented RTO?
- Are backups restorable (restore drills: a backup that hasn't been restored isn't a backup)?
- Run as tabletop exercises first (talk through the scenario), then in staging, then production.
- Capture findings like a postmortem: action items with owners.
Making resilience testing routine
| Stage | Practice |
|---|---|
| Unit tests | Timeouts, retries with backoff and jitter, circuit breakers, fallbacks with virtual time |
| Integration tests (CI) | Toxiproxy/WireMock faults against real dependencies; kill and restart containers mid-test |
| Staging | Scheduled Chaos Mesh/Litmus experiments with probes; pod/node kills during load tests |
| Production | Small, automated, guarded experiments (single pod kills, latency on 1% of synthetic traffic); quarterly game days; AZ evacuation drills |
| Organisation | Resilience requirements in design reviews; findings tracked like incidents; reliability scores per service |
Prerequisites before production chaos: solid observability with SLO dashboards, tested rollback and abort mechanisms, clear ownership and communication (announce experiments, annotate dashboards), and a team culture where finding weaknesses is a success, not a blame event.
Lab: a chaos experiment with a hypothesis, a fix and an abort
Toxiproxy 2.12.0 (proxy pg: 127.0.0.1:25433 → PostgreSQL 16 on 5433), two versions of a Python menu service using a psycopg connection pool of 4–8 connections, and k6 1.3 sending 40 requests per second for 30 seconds with a 5 s client timeout. A script adds a 1,000 ms latency toxic at t=10 s and removes it at t=20 s; per-request results from k6's JSON output are split into three 10-second windows.
Experiment 1: the naive service
with pool.connection() as c: # waits up to 30 s for a connection
rows = c.execute("select name, price from menu order by name").fetchall()
before n=399 success=100.0% p50= 2.1 ms p95= 4.4 ms
fault n=113 success= 3.5% p50=5000.0 ms p95=5001.0 ms
after n=553 success= 98.9% p50= 2.4 ms p95=4432.2 ms
dropped_iterations: 136
Hypothesis rejected. Each query now took over a second (the toxic delays each chunk of data in both directions), so 8 connections could serve fewer than 8 requests per second against 40 arriving. The rest queued for a connection until the client gave up at 5 s. The windows count requests by when they finished, which is why the fault window shows only 113 and the after window 553: requests sent during the fault completed (or timed out) later.
Experiment 2: the resilient service
rows = executor.submit(query).result(timeout=0.15) # a 150 ms deadline
...
except Exception:
if cache["menu"] is not None:
return send(200, cache["menu"], [("X-Served-From", "cache")])
before n=399 success=100.0% p50= 2.3 ms p95= 4.3 ms
fault n=402 success=100.0% p50=151.4 ms p95=153.2 ms
after n=400 success=100.0% p50= 2.5 ms p95= 5.4 ms
Hypothesis held. One detail this simple version gets away with: a timed-out query keeps running in its worker thread and holds a pool connection until the slow response arrives, so the pool also has a short acquisition timeout (0.3 s) and every request still ends at the 150 ms deadline. A production version would also cancel the query server-side and add a circuit breaker, so that during a long outage it stops sending queries at all and serves the fallback immediately (see Volume 9, chapter 104). The response header X-Served-From: cache lets dashboards count degraded answers, so "100% success" can't hide a dependency that has been down for an hour.
Experiment 3: the abort condition
# probe every 0.5 s (curl -m 2); 3 consecutive failures → remove the toxic
t=10.0 fault injected
t=17.1 ABORT: 3 consecutive failed probes, fault removed
before success=100.0% fault window success=84.0% after success=100.0% p95=3.8 ms
The abort limited the damage (84% instead of 3.5% success in the window) but took 7.1 s to trigger, because each failing probe used its full 2 s timeout. Real chaos tools (Chaos Mesh, LitmusChaos, AWS Fault Injection Service, Gremlin) take abort conditions from monitoring: an alarm on error rate or latency over a short window stops the experiment and rolls back the fault automatically.
Experiment 4: a catalogue of faults to try next
Toxiproxy toxics map onto real failure modes:
| Toxic | Real-world failure | What it tests |
|---|---|---|
latency (+ jitter) |
slow dependency, overloaded network | deadlines, queueing, timeouts |
bandwidth |
congested link | large responses, streaming |
timeout |
connection hangs with no data | read timeouts, pool exhaustion |
reset_peer |
dependency crashes mid-request | retries, idempotency |
slicer |
packets split oddly | parser robustness |
limit_data |
connection closed after N bytes | partial responses |
Beyond the network: kill processes and pods, fill disks, exhaust memory, skew clocks, fail a whole availability zone, revoke a credential. Pick experiments from your incident history and your threat of the week, not at random.
Try it yourself
- Replace the latency toxic with
timeout(connection hangs). Does the resilient service still pass? What about the naive one? - Add
reset_peerand a retry with jitter and a retry budget to the service. Measure success rate and load on the database. - Rewrite the abort condition to read the error rate from k6's live output (or Prometheus) over a 2-second window, and measure the new detection time.
- Run the experiment at 120 requests per second. At what rate does even the resilient service start failing, and why?
Revision sheet: chaos and resilience testing
Key ideas
- Principles: define steady state in measurable terms; hypothesise it holds under a fault; inject realistic faults; minimise blast radius; automate; run continuously.
- Faults to inject: dependency latency, errors, hangs, resets; instance and pod loss; zone loss; resource exhaustion; clock skew; bad config; expired credentials.
- Patterns under test: timeouts and deadlines, retries with backoff, jitter and budgets, idempotency, fallbacks and graceful degradation, bulkheads, circuit breakers, load shedding.
- Safety: start in test, then a small slice of production; abort conditions from monitoring; rollback automated; people informed.
- Tools: Toxiproxy (network), Chaos Mesh and LitmusChaos (Kubernetes), AWS FIS and Azure Chaos Studio (cloud), Gremlin, and plain
kill,tc netemandstress-ng. - Game days: rehearsed experiments with the team watching, to test people and runbooks as well as software.
Numbers to remember
- Lab: 1 s of DB latency → naive service 3.5% success, p50 5 s; resilient service 100% success, p50 151 ms.
- Lab: naive service's backlog kept p95 at 4.4 s after the fault ended.
- Lab: probe-based abort took 7.1 s; a monitoring-based abort should take a couple of seconds.
Pitfalls
- Chaos without a hypothesis or steady-state metric ("let's see what happens").
- Starting in production at full scope; no abort or rollback.
- Fallbacks that serve stale data where staleness is harmful.
- Counting degraded responses as healthy without marking them.
- Retries without budgets amplifying the outage.
- Experiments chosen at random rather than from incidents and architecture.
Glossary
- Steady state: measurable normal behaviour.
- Blast radius: scope of potential impact.
- Abort condition: a limit that stops an experiment.
- Toxic: a Toxiproxy fault (latency, timeout, reset_peer…).
- Graceful degradation: reduced but useful service under failure.
- Game day: a planned, team-wide failure exercise.