Skip to main content

Overview

The chaos 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(), and Latency() create middleware with fixed settings
  • Dynamic Configuration: Controller provides thread-safe runtime configuration changes

Implementation Details

Random Number Generation:
  • Uses math/rand instead of crypto/rand for 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()
Latency Calculation:
Request Flow:
  1. Check if chaos is enabled
  2. Apply selector filter (if configured)
  3. Inject latency (if configured)
  4. Inject error based on probability (if configured)
  5. Pass to next handler (if no error injected)
Selector Functions:
  • PathSelector: Creates a map of paths for O(1) lookup
  • MethodSelector: Creates a map of HTTP methods for O(1) lookup
  • HeaderSelector: Checks header presence using standard library
Controller Thread Safety:
  • 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: