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
| Option | Type | Default | Description |
|---|---|---|---|
Enabled | bool | false | Enable chaos injection |
ErrorRate | int | 0 | Percentage of requests to fail (0-100) |
ErrorCode | int | 500 | HTTP status code for errors |
LatencyMin | time.Duration | 0 | Minimum latency to inject |
LatencyMax | time.Duration | 0 | Maximum latency to inject |
Selector | func(*mizu.Ctx) bool | - | Filter which requests to affect |
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
| Selector | Description |
|---|---|
PathSelector(paths...) | Match specific URL paths |
MethodSelector(methods...) | Match HTTP methods |
HeaderSelector(header) | Match requests with header |
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:| Test Case | Description | Expected Behavior |
|---|---|---|
TestNew | Default middleware creation | Returns 200 OK (chaos disabled by default) |
TestError | Error injection with 100% rate | Returns 503 Service Unavailable |
TestLatency | Latency injection (50-100ms) | Request takes >= 50ms to complete |
TestWithOptions_Disabled | Disabled chaos with 100% error rate | Returns 200 OK (no error injection) |
TestWithOptions_Selector | Custom selector for specific path | Injects error on /chaos, allows /normal |
TestController | Controller enable/disable | Correctly toggles enabled state |
TestController_Middleware | Controller middleware integration | Injects errors only when enabled |
TestController_SetErrorCode | Custom error code via controller | Returns 502 Bad Gateway |
TestPathSelector | Path-based selector | Matches /api/chaos, ignores /api/normal |
TestHeaderSelector | Header presence selector | Selects requests with X-Chaos header |
TestMethodSelector | HTTP method selector | Matches POST, ignores GET |
Related Middlewares
- timeout - Request timeout
- circuitbreaker - Circuit breaker
- recover - Panic recovery