Logarithm::Retry::CircuitBreaker
Circuit breaker implementation for preventing cascading failures.
This class monitors operation success/failure rates and automatically opens the circuit when failures exceed the threshold. After a timeout period, it enters half-open state to test if the service has recovered.
The circuit breaker prevents wasting resources on operations that are likely to fail, allowing the system to fail fast and recover gracefully.
Parameters:
- failure_threshold: Consecutive failures needed to open circuit (default: 5)
- timeout: Time to wait before attempting reset (default: 60s)
- success_threshold: Successes needed to close circuit from half-open (default: 3)
Example:
breaker = Logarithm::Retry::CircuitBreaker.new(
failure_threshold: 3,
timeout: 30.seconds
)
result = breaker.call { external_api_call() }
Constructors
Initializes a new circuit breaker with configurable thresholds.
Parameters:
- failure_threshold: Number of consecutive failures to open circuit
- timeout: Duration to wait in open state before attempting reset
- success_threshold: Number of successes needed to close from half-open
Instance methods
Executes an operation through the circuit breaker.
The method checks the current circuit state and either executes the operation or fails fast. Success/failure counts are updated based on the operation result.
Parameters:
- block: The operation to execute through the circuit breaker
Returns: The result of the successful operation
Raises:
RuntimeError: If circuit is open and not ready for reset- The original exception from the failed operation
State Transitions:
- CLOSED -> OPEN: After failure_threshold consecutive failures
- OPEN -> HALF_OPEN: After timeout period
- HALF_OPEN -> CLOSED: After success_threshold consecutive successes
- HALF_OPEN -> OPEN: After any failure in half-open state