Overview
Thechaos middleware injects failures and latency into your application for chaos engineering and resilience testing. Use it to verify how your system handles errors and delays.
Installation
Quick Start
Configuration
Examples
Error Injection
Latency Injection
Combined Chaos
Selective Chaos (Path-based)
Selective Chaos (Method-based)
Header-triggered Chaos
Dynamic Control
Environment-Based
Custom Selector
Per-Route Chaos
Simulate Downstream Failures
Selectors
Controller Methods
API Reference
Safety
Always protect chaos endpoints:Technical Details
Architecture
The chaos middleware implements failure injection through a middleware chain pattern, supporting both static and dynamic configuration:- Static Configuration:
WithOptions(),Error(), andLatency()create middleware with fixed settings - Dynamic Configuration:
Controllerprovides thread-safe runtime configuration changes
Implementation Details
Random Number Generation:- Uses
math/randinstead ofcrypto/randfor performance (intentionally weak RNG) - Error injection: Generates random number 0-99 and compares against error rate percentage
- Latency injection: Calculates random duration between min and max using
rand.Int63n()
- Check if chaos is enabled
- Apply selector filter (if configured)
- Inject latency (if configured)
- Inject error based on probability (if configured)
- Pass to next handler (if no error injected)
PathSelector: Creates a map of paths for O(1) lookupMethodSelector: Creates a map of HTTP methods for O(1) lookupHeaderSelector: Checks header presence using standard library
- Options are read atomically during request processing
- Enable/Disable uses boolean flag
- Configuration methods update fields directly (suitable for controlled admin access)
Performance Considerations
- Selector maps provide constant-time path/method matching
- No mutex locking on hot path for static configuration
time.Sleep()blocks the handler goroutine (intentional for testing)- Random number generation is non-cryptographic for speed
Best Practices
- Never enable in production without safeguards
- Use selectors to limit scope
- Start with low error rates
- Monitor during chaos testing
- Use header-triggered chaos for CI/CD tests
- Implement circuit breakers in your clients
Testing
The chaos middleware includes comprehensive test coverage for all features:Related Middlewares
- timeout - Request timeout
- circuitbreaker - Circuit breaker
- recover - Panic recovery