Chaos Testing
Validate resilience by injecting controlled failures to verify that fallbacks, retries, and circuit breakers work under real conditions
When to Use
- Validating that resilience patterns (circuit breakers, retries, fallbacks) actually work
- Preparing for production incidents by simulating them in controlled environments
- Building confidence that the system degrades gracefully under partial failure
- Discovering hidden dependencies and single points of failure
Instructions
- Start with a steady state hypothesis: "Users can still check out even when the recommendation service is down."
- Inject one failure at a time. Do not combine failures until individual effects are understood.
- Start in development/staging. Move to production only with tight blast radius controls.
- Types of failure injection: latency, errors, resource exhaustion, dependency unavailability, clock skew.
- Measure impact on user-facing metrics (error rate, latency p99, success rate), not just internal metrics.
- Build failure injection as middleware or wrappers that can be toggled on/off.
// chaos/fault-injector.ts
interface FaultConfig {
enabled: boolean;
latencyMs?: number; // Add artificial latency
errorRate?: number; // 0.0 to 1.0 probability of error
errorCode?: number; // HTTP status to return
timeoutRate?: number; // 0.0 to 1.0 probability of timeout
targetServices?: string[]; // Only affect specific services
}
export class FaultInjector {
private config: FaultConfig = { enabled: false };
configure(config: Partial<FaultConfig>) {
this.config = { ...this.config, ...config };
}
async maybeInjectFault(serviceName: string): Promise<void> {
if (!this.config.enabled) return;
if (this.config.targetServices && !this.config.targetServices.includes(serviceName)) return;
// Inject latency
if (this.config.latencyMs) {
await new Promise((r) => setTimeout(r, this.config.latencyMs));
}
// Inject timeout (never resolves until AbortController cancels)
if (this.config.timeoutRate && Math.random() < this.config.timeoutRate) {
await new Promise(() => {}); // Hang forever — caller's timeout should catch this
}
// Inject error
if (this.config.errorRate && Math.random() < this.config.errorRate) {
throw new ChaosError(`Injected fault for ${serviceName}`, this.config.errorCode ?? 500);
}
}
}
export class ChaosError extends Error {
constructor(
message: string,
public readonly statusCode: number
) {
super(message);
this.name = 'ChaosError';
}
}
// Integration with services
const faultInjector = new FaultInjector();
// Enable in test/staging via environment variable
if (process.env.CHAOS_ENABLED === 'true') {
faultInjector.configure({
enabled: true,
targetServices: ['payment-api'],
errorRate: 0.3, // 30% of payment API calls fail
latencyMs: 2000, // Add 2s latency to all calls
});
}
// Wrap service calls
export async function callPaymentAPI(orderId: string): Promise<PaymentResult> {
await faultInjector.maybeInjectFault('payment-api');
return fetch(`https://payment.example.com/charge/${orderId}`).then((r) => r.json());
}
// Chaos test scenario
describe('checkout resilience', () => {
it('completes checkout when payment service has 50% error rate', async () => {
faultInjector.configure({
enabled: true,
targetServices: ['payment-api'],
errorRate: 0.5,
});
// Circuit breaker + retry should handle transient failures
const result = await checkout(testOrder);
expect(result.status).toBe('completed');
faultInjector.configure({ enabled: false });
});
it('uses cached prices when pricing service is down', async () => {
faultInjector.configure({
enabled: true,
targetServices: ['pricing-api'],
errorRate: 1.0, // 100% failure
});
const result = await getProductPrice('sku-123');
expect(result.source).toBe('cache');
expect(result.price).toBeGreaterThan(0);
faultInjector.configure({ enabled: false });
});
});
Details
Chaos engineering principles (Netflix):
- Define steady state (what "normal" looks like in metrics)
- Hypothesize that steady state continues during failure
- Introduce real-world failures (network, disk, process)
- Try to disprove the hypothesis
- Fix weaknesses found
Failure types to test:
- Latency injection: Simulate slow responses (100ms, 1s, 5s, 30s)
- Error injection: Return 500, 503, connection refused
- Resource exhaustion: Fill disk, exhaust memory, saturate CPU
- Dependency death: Kill a database, cache, or downstream service entirely
- Clock skew: Jump time forward/backward (affects TTLs, JWT expiry)
- Network partition: Split services so they cannot communicate
Tools: toxiproxy (TCP proxy with configurable toxics), chaos-mesh (Kubernetes-native), litmus (Kubernetes chaos), gremlin (SaaS platform), pumba (Docker container chaos).
Production chaos safety:
- Always have a kill switch to stop the experiment immediately
- Limit blast radius (specific percentage of traffic, specific instances)
- Run during business hours when the team is available
- Start with the smallest possible impact and scale up
- Monitor user-facing metrics, not just infrastructure metrics
Source
https://principlesofchaos.org/
Process
- Read the instructions and examples in this document.
- Apply the patterns to your implementation, adapting to your specific context.
- Verify your implementation against the details and edge cases listed above.
Harness Integration
- Type: knowledge — this skill is a reference document, not a procedural workflow.
- No tools or state — consumed as context by other skills and agents.
Success Criteria
- The patterns described in this document are applied correctly in the implementation.
- Edge cases and anti-patterns listed in this document are avoided.
1---2name: resilience-chaos-testing3description: Chaos Testing4metadata:5 source: https://skillmd.com/skills/intense-visions/resilience-chaos-testing6---7# Chaos Testing89> Validate resilience by injecting controlled failures to verify that fallbacks, retries, and circuit breakers work under real conditions1011## When to Use1213- Validating that resilience patterns (circuit breakers, retries, fallbacks) actually work14- Preparing for production incidents by simulating them in controlled environments15- Building confidence that the system degrades gracefully under partial failure16- Discovering hidden dependencies and single points of failure1718## Instructions19201. Start with a steady state hypothesis: "Users can still check out even when the recommendation service is down."212. Inject one failure at a time. Do not combine failures until individual effects are understood.223. Start in development/staging. Move to production only with tight blast radius controls.234. Types of failure injection: latency, errors, resource exhaustion, dependency unavailability, clock skew.245. Measure impact on user-facing metrics (error rate, latency p99, success rate), not just internal metrics.256. Build failure injection as middleware or wrappers that can be toggled on/off.2627```typescript28// chaos/fault-injector.ts29interface FaultConfig {30 enabled: boolean;31 latencyMs?: number; // Add artificial latency32 errorRate?: number; // 0.0 to 1.0 probability of error33 errorCode?: number; // HTTP status to return34 timeoutRate?: number; // 0.0 to 1.0 probability of timeout35 targetServices?: string[]; // Only affect specific services36}3738export class FaultInjector {39 private config: FaultConfig = { enabled: false };4041 configure(config: Partial<FaultConfig>) {42 this.config = { ...this.config, ...config };43 }4445 async maybeInjectFault(serviceName: string): Promise<void> {46 if (!this.config.enabled) return;47 if (this.config.targetServices && !this.config.targetServices.includes(serviceName)) return;4849 // Inject latency50 if (this.config.latencyMs) {51 await new Promise((r) => setTimeout(r, this.config.latencyMs));52 }5354 // Inject timeout (never resolves until AbortController cancels)55 if (this.config.timeoutRate && Math.random() < this.config.timeoutRate) {56 await new Promise(() => {}); // Hang forever — caller's timeout should catch this57 }5859 // Inject error60 if (this.config.errorRate && Math.random() < this.config.errorRate) {61 throw new ChaosError(`Injected fault for ${serviceName}`, this.config.errorCode ?? 500);62 }63 }64}6566export class ChaosError extends Error {67 constructor(68 message: string,69 public readonly statusCode: number70 ) {71 super(message);72 this.name = 'ChaosError';73 }74}75```7677```typescript78// Integration with services79const faultInjector = new FaultInjector();8081// Enable in test/staging via environment variable82if (process.env.CHAOS_ENABLED === 'true') {83 faultInjector.configure({84 enabled: true,85 targetServices: ['payment-api'],86 errorRate: 0.3, // 30% of payment API calls fail87 latencyMs: 2000, // Add 2s latency to all calls88 });89}9091// Wrap service calls92export async function callPaymentAPI(orderId: string): Promise<PaymentResult> {93 await faultInjector.maybeInjectFault('payment-api');94 return fetch(`https://payment.example.com/charge/${orderId}`).then((r) => r.json());95}96```9798```typescript99// Chaos test scenario100describe('checkout resilience', () => {101 it('completes checkout when payment service has 50% error rate', async () => {102 faultInjector.configure({103 enabled: true,104 targetServices: ['payment-api'],105 errorRate: 0.5,106 });107108 // Circuit breaker + retry should handle transient failures109 const result = await checkout(testOrder);110 expect(result.status).toBe('completed');111112 faultInjector.configure({ enabled: false });113 });114115 it('uses cached prices when pricing service is down', async () => {116 faultInjector.configure({117 enabled: true,118 targetServices: ['pricing-api'],119 errorRate: 1.0, // 100% failure120 });121122 const result = await getProductPrice('sku-123');123 expect(result.source).toBe('cache');124 expect(result.price).toBeGreaterThan(0);125126 faultInjector.configure({ enabled: false });127 });128});129```130131## Details132133**Chaos engineering principles (Netflix):**1341351. Define steady state (what "normal" looks like in metrics)1362. Hypothesize that steady state continues during failure1373. Introduce real-world failures (network, disk, process)1384. Try to disprove the hypothesis1395. Fix weaknesses found140141**Failure types to test:**142143- **Latency injection:** Simulate slow responses (100ms, 1s, 5s, 30s)144- **Error injection:** Return 500, 503, connection refused145- **Resource exhaustion:** Fill disk, exhaust memory, saturate CPU146- **Dependency death:** Kill a database, cache, or downstream service entirely147- **Clock skew:** Jump time forward/backward (affects TTLs, JWT expiry)148- **Network partition:** Split services so they cannot communicate149150**Tools:** `toxiproxy` (TCP proxy with configurable toxics), `chaos-mesh` (Kubernetes-native), `litmus` (Kubernetes chaos), `gremlin` (SaaS platform), `pumba` (Docker container chaos).151152**Production chaos safety:**153154- Always have a kill switch to stop the experiment immediately155- Limit blast radius (specific percentage of traffic, specific instances)156- Run during business hours when the team is available157- Start with the smallest possible impact and scale up158- Monitor user-facing metrics, not just infrastructure metrics159160## Source161162https://principlesofchaos.org/163164## Process1651661. Read the instructions and examples in this document.1672. Apply the patterns to your implementation, adapting to your specific context.1683. Verify your implementation against the details and edge cases listed above.169170## Harness Integration171172- **Type:** knowledge — this skill is a reference document, not a procedural workflow.173- **No tools or state** — consumed as context by other skills and agents.174175## Success Criteria176177- The patterns described in this document are applied correctly in the implementation.178- Edge cases and anti-patterns listed in this document are avoided.