Documentation
¶
Overview ¶
Package circuitbreaker implements a circuit breaker for calls to things that can fail or hang: HTTP services, databases, RPC peers.
A breaker wraps each call. While the calls succeed it stays out of the way. When too many of them fail it stops making them for a while and fails fast instead, then lets a limited number of probe requests through to find out whether the dependency has recovered.
cb := circuitbreaker.NewCircuitBreaker("payments",
options.WithFailureRateThreshold(0.5),
options.WithOpenTimeout(30*time.Second),
)
err := cb.Execute(ctx, func(ctx context.Context) error {
return callPayments(ctx)
})
Configuration lives in the options subpackage. A breaker built without options uses a 1 minute time window, a minimum of 10 requests, a failure rate threshold of 0.5, an open timeout of 30 seconds, a request timeout of 5 seconds, 10 half-open probes and a half-open target rate of 0.6.
States ¶
A breaker is in one of three states.
StateClosed is the normal state. Every request is admitted. Outcomes are counted in one-second buckets over a sliding time window. As soon as the window holds at least the minimum number of requests and the share of failures among them reaches the failure rate threshold, the breaker opens. The check runs when a request completes.
StateOpen rejects every request with ErrCircuitBreakerOpen without calling the wrapped function. It lasts for the open timeout. The breaker has no timer of its own: it moves on when the first request arrives after the open timeout has passed, so a breaker nobody calls keeps reporting OPEN.
StateHalfOpen is the trial. Entering it clears the statistics. The breaker admits a fixed number of probe requests (see below) and, once all of them have completed, closes if the share of successful probes reaches the target rate and opens again otherwise. Closing clears the statistics as well: the closed breaker starts with an empty window, so the probes that closed it, failed ones included, do not count towards opening it again.
Half-open probe limit ¶
In half-open at most ThresholdRequestInHalfOpen requests are admitted per round. A probe takes its slot when it is admitted, not when it completes, so the limit holds for requests in flight: if a hundred callers arrive at the moment the open timeout expires, the configured number get through and the rest receive ErrCircuitBreakerOpen. Callers therefore see that error in two states, and it means the same in both: the function was not called.
The round is decided only when every admitted probe has completed. Nothing is decided early, however the first probes go.
Only probes are counted. A request that was admitted while the breaker was still closed and finishes during a later half-open round is recorded in the statistics, but it is not a probe result and cannot close or reopen the breaker.
Timeouts ¶
The function passed to CircuitBreaker.Execute receives a context that is canceled when the request timeout expires. Execute itself waits until the function returns, so the function has to honor that context; one that ignores it and returns nil late is a success.
CircuitBreaker.ExecuteWithTimeout does not depend on that cooperation. It runs the function in a separate goroutine and returns when the context is done, leaving the function to finish in the background with its result discarded.
A timeout is a failed request. It is counted in the statistics, reported to the request complete listener with success=false and, in half-open, counted as a failed probe, so a round of probes that all hang ends in OPEN. The caller receives ErrCircuitBreakerTimeout.
The breaker recognizes a timeout by the error, not by its own clock: any error that wraps context.DeadlineExceeded is turned into ErrCircuitBreakerTimeout and counted as a failure without asking the error predicate. That includes a deadline the function set up itself and a deadline on the caller's context. A caller that cancels its context is not a timeout: both methods return context.Canceled and let the error predicate judge it. Execute gets there by returning the function's error, so it depends on the function honoring its context; ExecuteWithTimeout stops waiting as soon as the context is canceled and reports the cancellation itself.
Errors and the error predicate ¶
Any other error the function returns is passed back to the caller unchanged. Whether it counts as a failure is up to the error predicate, which by default says yes to every non-nil error. Use options.WithCustomErrorPredicate to keep errors that say nothing about the health of the dependency, such as a "not found", from opening the breaker.
Panics ¶
If the function or the error predicate panics, the request is recorded as a failure exactly like a returned error: in the statistics, as a failed probe in half-open, and in the request complete listener. The breaker does not recover the panic on the caller's behalf; it reaches the caller with its original value. With ExecuteWithTimeout the panic happens in the function's goroutine and is raised again in the caller's. If the caller has already left because of a timeout, there is nobody to hand it to, and it terminates the program like any unrecovered panic in a goroutine.
Listeners ¶
Two callbacks can be registered: a state change listener, called with the old and the new state on every transition, and a request complete listener, called with the outcome and duration of every admitted request. Rejected requests are not reported.
Each call runs in a goroutine of its own, outside the breaker's lock. A listener may therefore call back into the breaker, and a slow listener does not hold up requests. The price is that calls are not ordered: two transitions in quick succession can reach the listener in either order, and a listener may still be running after the request that triggered it has returned. A listener that needs the current state should ask for it with CircuitBreaker.GetState rather than keep track of the transitions it saw. A panic in a listener is not recovered and terminates the program.
The state change listener is passed as any, because the options package cannot name State. It must be a func(from, to State), or a value of a defined type with that signature. A nil value is ignored and keeps the listener set earlier; a value of any other type panics when it is set, so a mistyped listener shows up when the breaker is created, not as a callback that never fires.
The registry: one breaker per key ¶
Breakers are registered by key in a process-wide registry, so that every part of a program that names the same dependency shares one breaker. NewCircuitBreaker with a key that is already registered returns the existing breaker and ignores the options of that call, without an error and even if they differ. To change a registered breaker, call its Set methods; to start over, call RemoveCircuitBreaker first. Removing a breaker only takes it out of the registry; code that still holds the pointer keeps using it.
Entries are never removed automatically. Keys should name dependencies, not requests: a key built from a user ID or a URL with parameters grows the registry without bound.
Concurrency ¶
All methods of a CircuitBreaker and all package functions are safe for concurrent use. One mutex per breaker guards its state, configuration and statistics. Admitting a request and recording its outcome are one critical section each, so concurrent callers observe a single consistent state machine: one transition per cause and one shared set of probe slots. The wrapped function, the error predicate and the listeners run outside the lock.
The Set methods may be called while requests are in flight. A request keeps the request timeout and the error predicate it was admitted with.
The Set methods store what they are given. The range checks (a positive duration, a rate between 0 and 1, a non-nil predicate) are done by the functions in the options package, which skip a value that fails them.
Example ¶
A breaker wraps a call. As long as the call succeeds it stays closed and passes the result through.
package main
import (
"context"
"fmt"
circuitbreaker "github.com/anilonayy/circuitbreaker"
)
func main() {
cb := circuitbreaker.NewCircuitBreaker("inventory")
defer circuitbreaker.RemoveCircuitBreaker("inventory")
err := cb.Execute(context.Background(), func(ctx context.Context) error {
// Call the dependency here and pass ctx on: it carries the breaker's
// request timeout.
return nil
})
fmt.Println("error:", err)
fmt.Println("state:", cb.GetState())
}
Output: error: <nil> state: CLOSED
Example (ErrorMapping) ¶
The two sentinel errors tell a rejected request from a slow one; everything else is the dependency's own error. Compare with errors.Is.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"time"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
var errUnavailable = errors.New("inventory: connection refused")
// statusFor maps the result of Execute to an HTTP status for the client of a
// service that sits in front of the protected dependency.
func statusFor(err error) int {
switch {
case err == nil:
return http.StatusOK
case errors.Is(err, circuitbreaker.ErrCircuitBreakerOpen):
return http.StatusServiceUnavailable
case errors.Is(err, circuitbreaker.ErrCircuitBreakerTimeout):
return http.StatusGatewayTimeout
default:
return http.StatusBadGateway
}
}
func main() {
cb := circuitbreaker.NewCircuitBreaker("pricing",
options.WithMinimumRequestThreshold(3),
options.WithRequestTimeout(20*time.Millisecond),
)
defer circuitbreaker.RemoveCircuitBreaker("pricing")
ctx := context.Background()
ok := func(context.Context) error { return nil }
broken := func(context.Context) error { return errUnavailable }
slow := func(ctx context.Context) error {
<-ctx.Done() // gives up when the request timeout expires
return ctx.Err()
}
// One success, one error, one timeout: two failures out of three requests
// open the breaker, and the fourth request is rejected.
for _, call := range []func(context.Context) error{ok, broken, slow, ok} {
err := cb.Execute(ctx, call)
fmt.Printf("%d %v\n", statusFor(err), err)
}
}
Output: 200 <nil> 502 inventory: connection refused 504 circuit breaker request timeout 503 circuit breaker is open
Example (ErrorPredicate) ¶
An error predicate keeps errors that say nothing about the health of the dependency out of the failure rate. The caller still gets the error.
package main
import (
"context"
"errors"
"fmt"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
var errNotFound = errors.New("user not found")
func main() {
cb := circuitbreaker.NewCircuitBreaker("users",
options.WithMinimumRequestThreshold(2),
options.WithCustomErrorPredicate(func(err error) bool {
return !errors.Is(err, errNotFound)
}),
)
defer circuitbreaker.RemoveCircuitBreaker("users")
var err error
for range 5 {
err = cb.Execute(context.Background(), func(context.Context) error { return errNotFound })
}
total, successes, failures, _ := cb.GetStatistics()
fmt.Println("error:", err)
fmt.Printf("total=%d successes=%d failures=%d\n", total, successes, failures)
fmt.Println("state:", cb.GetState())
}
Output: error: user not found total=5 successes=5 failures=0 state: CLOSED
Example (Options) ¶
Start from a preset and append overrides; later options win.
package main
import (
"fmt"
"time"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
func main() {
opts := append(options.WithHTTPDefaults(),
options.WithFailureRateThreshold(0.3),
options.WithRequestTimeout(2*time.Second),
options.WithThresholdRequestInHalfOpen(3),
)
cb := circuitbreaker.NewCircuitBreaker("catalog", opts...)
defer circuitbreaker.RemoveCircuitBreaker("catalog")
cfg := cb.GetDetailedStatistics()
fmt.Println("time window (s):", cfg.TimeWindowSeconds)
fmt.Println("minimum requests:", cfg.MinimumRequestThreshold)
fmt.Println("failure rate threshold:", cfg.FailureRateThreshold)
fmt.Println("open timeout (s):", cfg.OpenTimeoutSeconds)
fmt.Println("request timeout (s):", cfg.RequestTimeoutSeconds)
fmt.Println("half-open probes:", cfg.ThresholdRequestInHalfOpen)
fmt.Println("half-open target rate:", cfg.TargetRateInHalfOpen)
}
Output: time window (s): 60 minimum requests: 10 failure rate threshold: 0.3 open timeout (s): 30 request timeout (s): 2 half-open probes: 3 half-open target rate: 0.6
Example (Recovery) ¶
After the open timeout the breaker lets a fixed number of probes through and closes again if enough of them succeed.
package main
import (
"context"
"errors"
"fmt"
"time"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
var errUnavailable = errors.New("inventory: connection refused")
func main() {
cb := circuitbreaker.NewCircuitBreaker("shipping",
options.WithMinimumRequestThreshold(1),
options.WithOpenTimeout(20*time.Millisecond),
options.WithThresholdRequestInHalfOpen(2), // two probes per round
options.WithTargetRateInHalfOpen(1.0), // both must succeed
)
defer circuitbreaker.RemoveCircuitBreaker("shipping")
ctx := context.Background()
ok := func(context.Context) error { return nil }
_ = cb.Execute(ctx, func(context.Context) error { return errUnavailable })
fmt.Println("after a failure:", cb.GetState())
time.Sleep(40 * time.Millisecond) // wait out the open timeout
_ = cb.Execute(ctx, ok)
fmt.Println("after the first probe:", cb.GetState())
_ = cb.Execute(ctx, ok)
fmt.Println("after the second probe:", cb.GetState())
}
Output: after a failure: OPEN after the first probe: HALF_OPEN after the second probe: CLOSED
Example (StateChangeListener) ¶
Listeners are called asynchronously, each call in its own goroutine. This example waits for the call before it prints.
package main
import (
"context"
"errors"
"fmt"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
var errUnavailable = errors.New("inventory: connection refused")
func main() {
changes := make(chan string, 1)
cb := circuitbreaker.NewCircuitBreaker("billing",
options.WithMinimumRequestThreshold(1),
// The listener must have exactly this signature.
options.WithStateChangeListener(func(from, to circuitbreaker.State) {
changes <- fmt.Sprintf("%s -> %s", from, to)
}),
)
defer circuitbreaker.RemoveCircuitBreaker("billing")
_ = cb.Execute(context.Background(), func(context.Context) error { return errUnavailable })
fmt.Println(<-changes)
}
Output: CLOSED -> OPEN
Index ¶
- Variables
- func ListCircuitBreakers() []string
- func RemoveCircuitBreaker(key string)
- type CircuitBreaker
- func (cb *CircuitBreaker) Execute(ctx context.Context, fn func(context.Context) error) error
- func (cb *CircuitBreaker) ExecuteWithTimeout(ctx context.Context, fn func(context.Context) error) error
- func (cb *CircuitBreaker) GetDetailedStatistics() DetailedStatistics
- func (cb *CircuitBreaker) GetKey() string
- func (cb *CircuitBreaker) GetState() State
- func (cb *CircuitBreaker) GetStatistics() (totalRequests, successCount, failureCount int64, failureRate float64)
- func (cb *CircuitBreaker) SetCustomErrorPredicate(predicate func(error) bool)
- func (cb *CircuitBreaker) SetFailureRateThreshold(threshold float64)
- func (cb *CircuitBreaker) SetMinimumRequestThreshold(threshold int64)
- func (cb *CircuitBreaker) SetOpenTimeout(timeout time.Duration)
- func (cb *CircuitBreaker) SetRequestCompleteListener(listener func(success bool, duration time.Duration))
- func (cb *CircuitBreaker) SetRequestTimeout(timeout time.Duration)
- func (cb *CircuitBreaker) SetStateChangeListener(listener any)
- func (cb *CircuitBreaker) SetTargetRateInHalfOpen(rate float64)
- func (cb *CircuitBreaker) SetThresholdRequestInHalfOpen(threshold int64)
- func (cb *CircuitBreaker) SetTimeWindow(duration time.Duration)
- func (cb *CircuitBreaker) String() string
- type DetailedStatistics
- type RequestStats
- type State
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCircuitBreakerOpen is returned by Execute and ExecuteWithTimeout when // the request was rejected and the wrapped function was not called: the // breaker is open, or it is half-open and all probe slots are taken. ErrCircuitBreakerOpen = errors.New("circuit breaker is open") // ErrCircuitBreakerTimeout is returned by Execute and ExecuteWithTimeout // when the request ended in a deadline: the wrapped function returned an // error wrapping context.DeadlineExceeded, or ExecuteWithTimeout stopped // waiting for it. The request counts as a failure. ErrCircuitBreakerTimeout = errors.New("circuit breaker request timeout") )
Functions ¶
func ListCircuitBreakers ¶
func ListCircuitBreakers() []string
ListCircuitBreakers returns the keys of all registered circuit breakers, in no particular order.
func RemoveCircuitBreaker ¶
func RemoveCircuitBreaker(key string)
RemoveCircuitBreaker removes the breaker registered under key from the registry, if there is one. The breaker itself keeps working for whoever still holds it; the next NewCircuitBreaker call with key creates a new one.
Types ¶
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker is a circuit breaker for one dependency. Create it with NewCircuitBreaker; the zero value is not usable.
All methods are safe for concurrent use. Every field below except key is guarded by mu. Unexported methods documented as "mu must be held" rely on the caller for locking; everything else takes the lock itself. User supplied callbacks (the request function, the error predicate and both listeners) are never invoked while mu is held, so they may call back into the breaker.
func GetCircuitBreaker ¶
func GetCircuitBreaker(key string) (*CircuitBreaker, bool)
GetCircuitBreaker returns the breaker registered under key. The second result reports whether there is one; unlike NewCircuitBreaker it never creates it.
func NewCircuitBreaker ¶
func NewCircuitBreaker(key string, opts ...options.Option) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker instance with the given key and options and registers it under key.
Breakers are shared by key: if a breaker is already registered under key, that instance is returned as is and opts are ignored. This holds even when opts differ from the options the breaker was created with, and no error is reported. To reconfigure a registered breaker use its Set* methods, or call RemoveCircuitBreaker first to start over with a fresh instance.
Example ¶
Breakers are shared by key. A second NewCircuitBreaker call with the same key returns the first breaker and does not apply its options.
package main
import (
"fmt"
"time"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
func main() {
first := circuitbreaker.NewCircuitBreaker("search", options.WithOpenTimeout(10*time.Second))
defer circuitbreaker.RemoveCircuitBreaker("search")
second := circuitbreaker.NewCircuitBreaker("search", options.WithOpenTimeout(99*time.Second))
fmt.Println("same breaker:", first == second)
fmt.Println("open timeout:", second.GetDetailedStatistics().OpenTimeoutSeconds)
// To reconfigure a registered breaker, use its setters.
second.SetOpenTimeout(99 * time.Second)
fmt.Println("open timeout:", first.GetDetailedStatistics().OpenTimeoutSeconds)
}
Output: same breaker: true open timeout: 10 open timeout: 99
func (*CircuitBreaker) Execute ¶
Execute runs fn if the breaker admits the request and records its outcome.
It returns ErrCircuitBreakerOpen without calling fn when the breaker is open, or when it is half-open and all probe slots are taken. fn receives a context that is canceled after the request timeout; Execute itself waits for fn to return, so fn has to honor that context. If fn returns an error wrapping context.DeadlineExceeded the request counts as a failure and Execute returns ErrCircuitBreakerTimeout. Any other error is passed to the error predicate and returned unchanged.
If fn or the error predicate panics, the request is recorded as a failure, exactly like a returned error, and the panic continues to the caller with its original value.
Example ¶
Once the failure rate in the time window reaches the threshold, the breaker opens and rejects requests without calling the function.
package main
import (
"context"
"errors"
"fmt"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
var errUnavailable = errors.New("inventory: connection refused")
func main() {
cb := circuitbreaker.NewCircuitBreaker("inventory-execute",
options.WithMinimumRequestThreshold(4), // judge after 4 requests
options.WithFailureRateThreshold(0.5), // open at 50% failures
)
defer circuitbreaker.RemoveCircuitBreaker("inventory-execute")
ctx := context.Background()
failing := func(context.Context) error { return errUnavailable }
for i := 1; i <= 4; i++ {
err := cb.Execute(ctx, failing)
fmt.Printf("request %d: %v (%s)\n", i, err, cb.GetState())
}
called := false
err := cb.Execute(ctx, func(context.Context) error {
called = true
return nil
})
fmt.Printf("request 5: %v (function called: %t)\n", err, called)
}
Output: request 1: inventory: connection refused (CLOSED) request 2: inventory: connection refused (CLOSED) request 3: inventory: connection refused (CLOSED) request 4: inventory: connection refused (OPEN) request 5: circuit breaker is open (function called: false)
func (*CircuitBreaker) ExecuteWithTimeout ¶
func (cb *CircuitBreaker) ExecuteWithTimeout(ctx context.Context, fn func(context.Context) error) error
ExecuteWithTimeout is like Execute, but does not rely on fn to honor its context: fn runs in its own goroutine and ExecuteWithTimeout returns ErrCircuitBreakerTimeout as soon as the request timeout expires, recording a failure. In that case fn keeps running in the background until it returns and its result is discarded.
If fn or the error predicate panics, the request is recorded as a failure and the panic is raised again in the caller's goroutine with its original value. A panic in fn after ExecuteWithTimeout has already returned on timeout has no caller left to go to; it is not swallowed and terminates the program like any other unrecovered panic.
Example ¶
ExecuteWithTimeout returns when the request timeout expires even if the function does not watch its context.
package main
import (
"context"
"errors"
"fmt"
"time"
circuitbreaker "github.com/anilonayy/circuitbreaker"
"github.com/anilonayy/circuitbreaker/options"
)
func main() {
cb := circuitbreaker.NewCircuitBreaker("inventory-timeout",
options.WithRequestTimeout(20*time.Millisecond),
)
defer circuitbreaker.RemoveCircuitBreaker("inventory-timeout")
done := make(chan struct{})
defer close(done)
err := cb.ExecuteWithTimeout(context.Background(), func(context.Context) error {
<-done // a call that hangs and ignores its context
return nil
})
fmt.Println(err)
fmt.Println(errors.Is(err, circuitbreaker.ErrCircuitBreakerTimeout))
_, _, failures, _ := cb.GetStatistics()
fmt.Println("failures:", failures)
}
Output: circuit breaker request timeout true failures: 1
func (*CircuitBreaker) GetDetailedStatistics ¶
func (cb *CircuitBreaker) GetDetailedStatistics() DetailedStatistics
GetDetailedStatistics returns a snapshot of the breaker's state, configuration and counters. See DetailedStatistics for the fields.
Example ¶
GetDetailedStatistics returns a snapshot that marshals to JSON, for a status endpoint or a log line.
package main
import (
"context"
"errors"
"fmt"
circuitbreaker "github.com/anilonayy/circuitbreaker"
)
var errUnavailable = errors.New("inventory: connection refused")
func main() {
cb := circuitbreaker.NewCircuitBreaker("ledger")
defer circuitbreaker.RemoveCircuitBreaker("ledger")
ctx := context.Background()
for i := range 4 {
_ = cb.Execute(ctx, func(context.Context) error {
if i == 0 {
return errUnavailable
}
return nil
})
}
stats := cb.GetDetailedStatistics()
fmt.Println(stats.Key, stats.State)
fmt.Printf("total=%d successes=%d failures=%d rate=%.2f\n",
stats.TotalRequests, stats.SuccessCount, stats.FailureCount, stats.FailureRate)
fmt.Println(cb)
}
Output: ledger CLOSED total=4 successes=3 failures=1 rate=0.25 CircuitBreaker{key=ledger, state=CLOSED, requests=4, failures=1, failureRate=25.00%}
func (*CircuitBreaker) GetKey ¶
func (cb *CircuitBreaker) GetKey() string
GetKey returns the key this circuit breaker was created with.
func (*CircuitBreaker) GetState ¶
func (cb *CircuitBreaker) GetState() State
GetState returns the current state of the circuit breaker.
The breaker leaves StateOpen when a request arrives after the open timeout, not when the timeout expires, so GetState keeps returning StateOpen for an idle breaker.
func (*CircuitBreaker) GetStatistics ¶
func (cb *CircuitBreaker) GetStatistics() (totalRequests, successCount, failureCount int64, failureRate float64)
GetStatistics returns the request counters of the current time window: completed requests, how many of them succeeded and failed, and the failure rate between 0 and 1. Rejected requests are not counted. The window starts empty every time the breaker turns half-open.
func (*CircuitBreaker) SetCustomErrorPredicate ¶
func (cb *CircuitBreaker) SetCustomErrorPredicate(predicate func(error) bool)
SetCustomErrorPredicate sets the function that decides whether an error returned by the wrapped function counts as a failure. It is not asked about nil errors or timeouts. A nil predicate is ignored.
func (*CircuitBreaker) SetFailureRateThreshold ¶
func (cb *CircuitBreaker) SetFailureRateThreshold(threshold float64)
SetFailureRateThreshold sets the failure rate, between 0 and 1, at which the closed breaker opens. A rate outside that range is ignored.
func (*CircuitBreaker) SetMinimumRequestThreshold ¶
func (cb *CircuitBreaker) SetMinimumRequestThreshold(threshold int64)
SetMinimumRequestThreshold sets the number of requests the time window must hold before the failure rate can open the breaker. A threshold that is not positive is ignored.
func (*CircuitBreaker) SetOpenTimeout ¶
func (cb *CircuitBreaker) SetOpenTimeout(timeout time.Duration)
SetOpenTimeout sets how long the circuit breaker stays open before it lets probes through. It applies to a breaker that is open right now as well. A timeout that is not positive is ignored.
func (*CircuitBreaker) SetRequestCompleteListener ¶
func (cb *CircuitBreaker) SetRequestCompleteListener(listener func(success bool, duration time.Duration))
SetRequestCompleteListener sets a callback for request completion. The callback runs in its own goroutine for every completed request; a request that timed out or panicked is reported with success=false.
func (*CircuitBreaker) SetRequestTimeout ¶
func (cb *CircuitBreaker) SetRequestTimeout(timeout time.Duration)
SetRequestTimeout sets the maximum duration for individual requests. It applies to requests admitted from now on. A timeout that is not positive is ignored.
func (*CircuitBreaker) SetStateChangeListener ¶
func (cb *CircuitBreaker) SetStateChangeListener(listener any)
SetStateChangeListener sets a callback for state changes. The callback runs in its own goroutine for every transition.
listener must be a func(from, to State), or a value of a defined type with that signature. A nil interface value is ignored and keeps the listener set earlier. Any other value is a programming error and panics, because a listener that is dropped without a word leaves a breaker running without the listener its owner thinks it has.
func (*CircuitBreaker) SetTargetRateInHalfOpen ¶
func (cb *CircuitBreaker) SetTargetRateInHalfOpen(rate float64)
SetTargetRateInHalfOpen sets the share of successful probes, between 0 and 1, required to close the circuit after a half-open round. A rate outside that range is ignored.
func (*CircuitBreaker) SetThresholdRequestInHalfOpen ¶
func (cb *CircuitBreaker) SetThresholdRequestInHalfOpen(threshold int64)
SetThresholdRequestInHalfOpen sets the number of probe requests admitted and evaluated per half-open round. A threshold that is not positive is ignored.
func (*CircuitBreaker) SetTimeWindow ¶
func (cb *CircuitBreaker) SetTimeWindow(duration time.Duration)
SetTimeWindow sets the time window for failure analysis. The window is counted in whole seconds. A duration that is not positive is ignored.
func (*CircuitBreaker) String ¶
func (cb *CircuitBreaker) String() string
String returns a one-line summary of the breaker for logs: key, state and the counters of the current time window.
type DetailedStatistics ¶
type DetailedStatistics struct {
// OpenedAt is when the breaker opened, in RFC 3339 format.
OpenedAt *string `json:"opened_at,omitempty"`
// HalfOpenSuccessRate is the share of successful probes among the completed
// probes of the current round. It is nil until a probe has completed.
HalfOpenSuccessRate *float64 `json:"half_open_success_rate,omitempty"`
// HalfOpenFailureCount is the number of completed probes that failed.
HalfOpenFailureCount *int64 `json:"half_open_failure_count,omitempty"`
// HalfOpenSuccessCount is the number of completed probes that succeeded.
HalfOpenSuccessCount *int64 `json:"half_open_success_count,omitempty"`
// RemainingTestRequests is the number of probe slots still free in the
// current round.
RemainingTestRequests *int64 `json:"remaining_test_requests,omitempty"`
// HalfOpenRequestCount is the number of probes admitted in the current
// round, in flight or completed.
HalfOpenRequestCount *int64 `json:"half_open_request_count,omitempty"`
// TimeUntilHalfOpenSeconds is the time left until the open timeout has
// passed, in whole seconds, rounded down. It is nil once it has: the
// breaker then turns half-open with the next request.
TimeUntilHalfOpenSeconds *int64 `json:"time_until_half_open_seconds,omitempty"`
// TimeUntilHalfOpenMillis is the same time in milliseconds, for timeouts
// that whole seconds cannot express. It is nil when
// TimeUntilHalfOpenSeconds is.
TimeUntilHalfOpenMillis *int64 `json:"time_until_half_open_ms,omitempty"`
// NextHalfOpenAt is OpenedAt plus the open timeout, in RFC 3339 format.
NextHalfOpenAt *string `json:"next_half_open_at,omitempty"`
// State is the state's name as returned by State.String.
State string `json:"state"`
// Key is the key the breaker is registered under.
Key string `json:"key"`
// FailureRate is FailureCount divided by TotalRequests, 0 without requests.
FailureRate float64 `json:"failure_rate"`
// ThresholdRequestInHalfOpen is the number of probes per half-open round.
ThresholdRequestInHalfOpen int64 `json:"threshold_request_in_half_open"`
// TargetRateInHalfOpen is the share of successful probes needed to close.
TargetRateInHalfOpen float64 `json:"target_rate_in_half_open"`
// RequestTimeoutSeconds is the request timeout in whole seconds, rounded
// down: 0 for a timeout below one second.
RequestTimeoutSeconds int64 `json:"request_timeout_seconds"`
// RequestTimeoutMillis is the request timeout in milliseconds.
RequestTimeoutMillis int64 `json:"request_timeout_ms"`
// OpenTimeoutSeconds is how long the breaker stays open, in whole seconds,
// rounded down: 0 for a timeout below one second.
OpenTimeoutSeconds int64 `json:"open_timeout_seconds"`
// OpenTimeoutMillis is how long the breaker stays open, in milliseconds.
OpenTimeoutMillis int64 `json:"open_timeout_ms"`
// FailureRateThreshold is the failure rate at which the breaker opens.
FailureRateThreshold float64 `json:"failure_rate_threshold"`
// MinimumRequestThreshold is the number of requests the window must hold
// before the failure rate is acted on.
MinimumRequestThreshold int64 `json:"minimum_request_threshold"`
// TimeWindowSeconds is the length of the sliding window.
TimeWindowSeconds int64 `json:"time_window_seconds"`
// FailureCount is the number of failed requests in the window.
FailureCount int64 `json:"failure_count"`
// SuccessCount is the number of successful requests in the window.
SuccessCount int64 `json:"success_count"`
// TotalRequests is the number of completed requests in the window.
TotalRequests int64 `json:"total_requests"`
}
DetailedStatistics describes a circuit breaker at one moment: its state, its configuration and the counters of the current time window. It marshals to JSON, so it can be served from a status endpoint as it is.
It is a snapshot: the values, including the ones behind pointers, do not change after GetDetailedStatistics returns.
The pointer fields depend on the state and are nil (omitted from JSON) in the states they do not apply to: OpenedAt, NextHalfOpenAt and TimeUntilHalfOpenSeconds are set while the breaker is open, the HalfOpen fields and RemainingTestRequests while it is half-open.
The fields ending in Seconds are whole seconds; a shorter duration, such as a request timeout of 500ms, is reported as 0.
type RequestStats ¶
type RequestStats struct {
RequestCount int64 // Total number of requests in that second
SuccessCount int64 // Number of successful requests in that second
FailureCount int64 // Number of failed requests in that second
}
RequestStats holds the request counters of one second of the sliding window.
type State ¶
type State int
State is the state of a circuit breaker. The package documentation describes what each state does and how a breaker moves between them.
const ( // StateClosed is the normal operating state: requests pass through and // their outcomes are tracked. It is the state a new breaker starts in. StateClosed State = iota // StateOpen means the circuit is open: every request is rejected with // ErrCircuitBreakerOpen until the open timeout has passed. StateOpen // StateHalfOpen means a limited number of probe requests is let through to // find out whether the dependency has recovered; all others are rejected. StateHalfOpen )