Documentation
¶
Overview ¶
Package circuitbreaker provides a per-host circuit breaker as HTTP middleware.
The circuit breaker monitors request failures and temporarily blocks requests to unhealthy hosts, allowing them time to recover before retrying.
State machine ¶
- Closed — normal operation, requests pass through
- Open — too many failures, requests are rejected with ErrCircuitOpen
- HalfOpen — after a cooldown period, one probe request is allowed through
Usage ¶
mw := circuitbreaker.Transport(
circuitbreaker.WithThreshold(5),
circuitbreaker.WithTimeout(30 * time.Second),
)
transport := mw(http.DefaultTransport)
The circuit breaker is per-host: each unique request host gets its own independent breaker state machine stored in a sync.Map.
Sentinel errors ¶
ErrCircuitOpen is returned when a request is rejected because the circuit is in the Open state.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrCircuitOpen = errors.New("httpx: circuit breaker is open")
ErrCircuitOpen is returned by Allow when the breaker is in the Open state.
Functions ¶
func Transport ¶
func Transport(opts ...Option) middleware.Middleware
Transport returns a middleware that applies per-host circuit breaking. It maintains an internal map of host → *Breaker so each target host is tracked independently.
Types ¶
type Breaker ¶
type Breaker struct {
// contains filtered or unexported fields
}
Breaker implements a per-endpoint circuit breaker state machine.
State transitions:
Closed → Open: after failureThreshold consecutive failures Open → HalfOpen: after openDuration passes HalfOpen → Closed: on success HalfOpen → Open: on failure (timer resets)
func NewBreaker ¶
NewBreaker creates a Breaker with the given options.
type Option ¶
type Option func(*options)
Option configures a Breaker.
func WithFailureThreshold ¶
WithFailureThreshold sets the number of consecutive failures required to trip the breaker from Closed to Open. Default is 5.
func WithHalfOpenMax ¶
WithHalfOpenMax sets the maximum number of concurrent probe requests allowed while the breaker is in the HalfOpen state. Default is 1.
func WithOpenDuration ¶
WithOpenDuration sets how long the breaker stays in the Open state before transitioning to HalfOpen. Default is 30s.