Overview
Thecircuitbreaker middleware implements the circuit breaker pattern to prevent cascading failures. When errors exceed a threshold, it βopensβ the circuit, immediately failing requests without calling the handler, giving the system time to recover.
Use it when you need:
- Protection against cascading failures
- Graceful degradation
- System resilience
- External service call protection
Installation
Quick Start
Configuration
Options
States
Examples
Basic Circuit Breaker
Custom Threshold
Custom Failure Detection
State Change Monitoring
Custom Error Response
Per-Route Circuit Breakers
Recovery Testing
With Metrics
Fallback Response
State Machine
API Reference
Functions
State Type
Technical Details
State Machine Implementation
The circuit breaker implements a thread-safe state machine with three states:- Closed State: Normal operation where all requests are allowed through. Failures are counted, and when the failure count reaches the
Threshold, the circuit transitions to Open. - Open State: Protective state where all requests are immediately rejected without calling the handler. After the
Timeoutperiod, the circuit automatically transitions to Half-Open. - Half-Open State: Recovery testing state where a limited number of requests (controlled by
MaxRequests) are allowed through. If all test requests succeed, the circuit closes. If any request fails, the circuit immediately reopens.
Threshold Mechanism
The failure threshold works differently in each state:- In Closed State: Consecutive failures are counted. Once the count reaches
Threshold, the circuit opens. Successful requests reset the failure counter to zero. - In Open State: No requests are processed, so failures are not counted. The circuit waits for the
Timeoutperiod before transitioning to Half-Open. - In Half-Open State: Successes are counted. The circuit requires
MaxRequestsconsecutive successes to close. A single failure immediately reopens the circuit.
Thread Safety
The circuit breaker uses a mutex (sync.Mutex) to protect concurrent access to:
- Current state
- Failure and success counters
- Last failure timestamp
Failure Detection
TheIsFailure function determines what constitutes a failure:
- Default behavior: Any non-nil error is considered a failure
- Custom behavior: Can be configured to filter specific errors (e.g., ignore 4xx client errors, only count 5xx server errors)
Best Practices
- Set thresholds based on normal error rates
- Use meaningful timeout values
- Monitor state changes for alerting
- Consider different breakers for different dependencies
- Implement fallback responses when possible