Circuit Breaker implementation for fault tolerance
Tracks failures and prevents requests to failing resources by:
- Counting consecutive failures
- Opening the circuit after threshold is reached
- Blocking requests while circuit is open
- Attempting recovery after timeout period
- Closing circuit on successful recovery
new
CircuitBreaker(options?: CircuitBreakerOptions)
Creates a new circuit breaker
private
failureCount: number
private
optional
lastFailureTime: Date
private
readonly
name: string
private
state: CircuitBreakerState
private
readonly
threshold: number
private
readonly
timeout: number
execute<T>(fn: () => Promise<T>): Promise<T>
Executes a function with circuit breaker protection
getFailureCount(): number
Gets the current failure count
getLastFailureTime(): Date | undefined
Gets the last failure time
Gets the current state of the circuit breaker
getStats(): CircuitBreakerStats
Gets circuit breaker statistics
private
getTimeUntilRecovery(): number
Gets time remaining until recovery attempt
private
onFailure(): void
Handles failed execution
private
onSuccess(): void
Handles successful execution
reset(): void
Manually resets the circuit breaker to CLOSED state Useful for testing or manual recovery
private
shouldAttemptRecovery(): boolean
Checks if enough time has passed to attempt recovery