circuitbreaker
v9.24.1
Documentation
pkg.go.dev ↗Package circuitbreaker provides a circuit breaker implementation for fault tolerance.
Variables
ErrCircuitOpen
var ErrCircuitOpen = &CircuitOpenError{}
ErrCircuitOpen is returned when the circuit breaker is open.
Types
CircuitBreaker
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the circuit breaker pattern.
New
func New(config Config) *CircuitBreaker
New creates a new circuit breaker with the given configuration.
CircuitBreaker.Allow
func (cb *CircuitBreaker) Allow() (allowed, reserved bool)
Allow reports whether a request may proceed and whether the admission reserved a bounded half-open probe slot. Closed-state admissions reserve nothing, so callers whose operation may outlive a later open -> half-open transition (for example a WATCH transaction) must consult reserved before calling ReleaseHalfOpen — an unconditional release would free a slot a real recovery probe is holding.
CircuitBreaker.AllowReserve
func (cb *CircuitBreaker) AllowReserve() (allowed bool, r Reservation)
AllowReserve is Allow with an identity-bearing reservation. Prefer it over Allow when the admitted operation may outlive a later open -> half-open transition, or when several outcomes share one admission: the returned Reservation lets RecordSuccessFor / ReleaseFor settle the half-open slot exactly once and only within the episode the slot was reserved in.
CircuitBreaker.CheckState
func (cb *CircuitBreaker) CheckState() State
CheckState returns the current state and may trigger state transitions. Use this when you need to check if requests should be allowed.
CircuitBreaker.CurrentClosedReservation
func (cb *CircuitBreaker) CurrentClosedReservation() (Reservation, bool)
CurrentClosedReservation returns the slot-less reservation a closed-state AllowReserve would hand out now, and false when the circuit is not closed. It is for owners that admit work with AllowReserve but cannot carry the reservation to where the outcome lands (the MultiDB full-duplex router: the outcome comes from the engine's reader). Settling with it records the outcome in the current closed episode, and nothing while the circuit is open or half-open, so a late outcome cannot re-open or close a recovery episode it never probed.
The state and generation are read as a seqlock: generation, state, generation again. Every transition into a new episode (Reset, Open -> HalfOpen) bumps the generation before it publishes the new state, so an unchanged generation around a Closed read means the generation belongs to that closed episode. Without the re-check, a Closed read followed by a Closed -> Open -> HalfOpen cycle would pair the old Closed state with the new episode's generation. Lock-free: this runs once per reply.
CircuitBreaker.Execute
func (cb *CircuitBreaker) Execute(fn func() error) error
Execute runs the given function with circuit breaker protection. Returns ErrCircuitOpen if the circuit is open and not ready for testing.
CircuitBreaker.ForceOpen
func (cb *CircuitBreaker) ForceOpen()
ForceOpen transitions the breaker straight to Open, regardless of the current failure count. For callers that have already determined a member is down (for example a failed startup or health probe) and want to open the circuit without synthesizing FailureThreshold individual RecordFailure calls.
CircuitBreaker.IsAllowed
func (cb *CircuitBreaker) IsAllowed() bool
IsAllowed returns true if a request should be allowed through. This is a convenience method that combines CheckState with half-open request limiting.
CircuitBreaker.OnStateChange
func (cb *CircuitBreaker) OnStateChange(callback StateChangeCallback)
OnStateChange registers a callback to be called when the state changes.
CircuitBreaker.RecordExternalSuccess
func (cb *CircuitBreaker) RecordExternalSuccess()
RecordExternalSuccess records a successful operation that was NOT admitted through IsAllowed (e.g. an out-of-band health check). It counts toward closing a half-open circuit but never releases an admission slot it did not hold — releasing one would let more than MaxHalfOpenRequests requests reach a recovering service.
CircuitBreaker.RecordExternalSuccessForReset
func (cb *CircuitBreaker) RecordExternalSuccessForReset(gen uint64)
RecordExternalSuccessForReset records an out-of-band success (a health probe) unless a Reset has run since gen was sampled. Like RecordExternalSuccess it holds no admission slot. The generation check and the record run under transitionMu — the same lock Reset holds across its counter clear + generation bump — so a reselect cannot interleave between them.
CircuitBreaker.RecordFailure
func (cb *CircuitBreaker) RecordFailure()
RecordFailure records a failed operation.
CircuitBreaker.RecordFailureFor
func (cb *CircuitBreaker) RecordFailureFor(r Reservation)
RecordFailureFor records a failure for a reservation from AllowReserve. A half-open reservation records only while it is still the CURRENT half-open episode: a failure from an admission that outlived an open -> half-open cycle must not re-open (and abort the recovery of) the NEW episode — the symmetric guard to RecordSuccessFor. A closed-state reservation (held == false) records only while it is still the SAME closed episode it was admitted in: the generation must be unchanged AND the circuit still closed. If it has moved to open or half-open, or a Reset (reselect) bumped the generation and returned to closed, this failure predates the current episode and must not re-open it (a stale probe failure aborting a recovery, or reversing an operator reselect). Every Closed -> ... -> Closed round trip bumps the generation (Reset, and HalfOpen->Closed via maybeHalfOpenLocked's bump), so the generation check is what distinguishes "still the admission's closed episode" from "a new one". Unlike success/release this does not consume the once-only settle flag — a failure opens the circuit rather than freeing a slot, and the batch path records one failure per command.
CircuitBreaker.RecordFailureForReset
func (cb *CircuitBreaker) RecordFailureForReset(gen uint64)
RecordFailureForReset records an out-of-band failure (a health probe) unless a Reset has run since gen was sampled — the guard that stops a probe verdict sampled before an operator reselect from re-opening the freshly selected member (at FailureThreshold 1 a single stale failure would). The check and the record run under transitionMu, so they are atomic with Reset.
CircuitBreaker.RecordSuccess
func (cb *CircuitBreaker) RecordSuccess()
RecordSuccess records a successful operation that was admitted through IsAllowed. In half-open state the completed probe's admission slot is released when the circuit does not close.
CircuitBreaker.RecordSuccessFor
func (cb *CircuitBreaker) RecordSuccessFor(r Reservation)
RecordSuccessFor settles a successful outcome for a reservation from AllowReserve. A half-open reservation releases (or, at SuccessThreshold, closes on) its slot at most once, and only while it is still the current half-open episode; a stale reservation — the circuit cycled open -> half-open since it was taken — records nothing. A closed-state reservation (held == false) clears the failure count while the circuit is still closed and records nothing once it has moved on: its successes predate the failures that opened the circuit and are no evidence of recovery, and counting them would let one in-flight batch close a half-open episode it never probed. Out-of-band evidence goes through RecordExternalSuccess, which does count.
CircuitBreaker.ReleaseFor
func (cb *CircuitBreaker) ReleaseFor(r Reservation)
ReleaseFor returns a half-open reservation's slot when the outcome was neither a recordable success nor failure. Like RecordSuccessFor it settles at most once and only within the reservation's own half-open episode; a closed-state or already-settled reservation is a no-op.
CircuitBreaker.ReleaseHalfOpen
func (cb *CircuitBreaker) ReleaseHalfOpen()
ReleaseHalfOpen returns a half-open request slot previously reserved by a successful IsAllowed call when the operation produced neither a recordable success nor failure (for example, it was aborted for an unrelated reason). Without this, a reserved-but-never-completed probe could permanently starve half-open recovery once MaxHalfOpenRequests slots are exhausted. It only has an effect while the breaker is half-open.
CircuitBreaker.Reset
func (cb *CircuitBreaker) Reset()
Reset resets the circuit breaker to closed state. If the circuit was not already closed, callbacks are notified.
CircuitBreaker.ResetGeneration
func (cb *CircuitBreaker) ResetGeneration() uint64
ResetGeneration returns the current reset generation. A health probe samples it BEFORE running its checks and passes it to RecordExternalSuccessForReset / RecordFailureForReset, which drop the verdict if a Reset (an operator reselect) bumped the generation meanwhile. Unlike the reservation generation, this moves only on Reset, so a probe verdict still counts across a normal Open->HalfOpen.
CircuitBreaker.State
func (cb *CircuitBreaker) State() State
State returns the current state without triggering any transitions.
CircuitBreaker.Stats
func (cb *CircuitBreaker) Stats() Stats
Stats returns current statistics.
CircuitOpenError
type CircuitOpenError struct{}
CircuitOpenError indicates the circuit breaker is open.
CircuitOpenError.Error
func (e *CircuitOpenError) Error() string
Config
type Config struct {
// FailureThreshold is the number of failures before opening the circuit.
// Default: 5
FailureThreshold int
// SuccessThreshold is the number of successes in half-open state before closing.
// Default: 2
SuccessThreshold int
// MaxHalfOpenRequests is the maximum number of requests allowed in half-open state.
// If 0, uses SuccessThreshold as the limit.
// Default: 0 (uses SuccessThreshold)
MaxHalfOpenRequests int
// OpenTimeout is how long to wait before transitioning from open to half-open.
// This is the circuit "grace period" that gives a failed database time to
// self-heal before it is probed again.
// Default: 60 seconds
OpenTimeout time.Duration
}
Config holds configuration for a circuit breaker.
DefaultConfig
func DefaultConfig() Config
DefaultConfig returns the default circuit breaker configuration.
Reservation
type Reservation struct {
// contains filtered or unexported fields
}
Reservation identifies a single admission returned by AllowReserve. It carries the half-open episode (generation) the admission belongs to and a once-only settle guard, so that:
- a reservation taken in one half-open episode cannot settle against a later one (the admitted request outlived an open -> half-open cycle), and
- a reservation shared by several outcomes (e.g. a pipeline batch) settles the half-open slot exactly once, however many outcomes report success.
The zero Reservation (held == false) is what a closed-state admission returns: it holds no slot, and RecordSuccessFor treats it as an external success.
Reservation.Generation
func (r Reservation) Generation() uint64
Generation identifies the breaker episode in which the command was admitted.
Reservation.Held
func (r Reservation) Held() bool
Held reports whether the reservation holds a half-open probe slot (a half-open admission) rather than being a slot-less closed admission.
State
type State int32
State represents the state of a circuit breaker.
StateClosed (3 declarations)
const ( // StateClosed indicates the circuit is closed and requests are allowed. StateClosed State = iota // StateOpen indicates the circuit is open and requests are blocked. StateOpen // StateHalfOpen indicates the circuit is testing if the service has recovered. StateHalfOpen )
State.String
func (s State) String() string
String returns the string representation of the circuit state.
StateChangeCallback
type StateChangeCallback func(oldState, newState State, stats Stats)
StateChangeCallback is called when the circuit breaker state changes. stats is a snapshot taken at the transition, so it reflects the counters that triggered the change even though the callback runs asynchronously (see cbq): read it instead of calling Stats(), which by delivery time may show a later state.
Stats
type Stats struct {
State State
// Failures is the consecutive failure streak of admitted requests
// (RecordFailure, RecordFailureFor); a successful request ends it.
Failures int32
// ExternalFailures is the consecutive failure streak of out-of-band
// signals (RecordFailureForReset, e.g. a health check); an external
// success ends it. Either streak reaching FailureThreshold opens the
// circuit.
ExternalFailures int32
Successes int32
Requests int32
LastFailureTime time.Time
}
Stats returns current statistics for monitoring.