circuitbreaker

package module
v0.0.0-...-3271c1e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

🚦 Go Circuit Breaker

CI Go Reference License

Production‑ready, lightweight Circuit Breaker for Go. Protects your external calls (HTTP, DB, RPC) by monitoring failures in a sliding time window, opening on sustained errors, and probing recovery in half‑open before safely closing.

• Simple API • Sensible defaults • Powerful options • Observability built‑in


🔧 Install

go get github.com/anilonayy/circuitbreaker@latest

Requires Go 1.25 or newer. The library itself has no dependencies outside the standard library (testify is used by the tests only).

⚡ TL;DR (Quick Start)

package main

import (
    "context"
    "errors"
    "fmt"
    "time"

    circuitbreaker "github.com/anilonayy/circuitbreaker"
    "github.com/anilonayy/circuitbreaker/options"
)

func main() {
    // Start with a preset, then customize if needed
    opts := options.WithHTTPDefaults()
    opts = append(opts,
        options.WithFailureRateThreshold(0.5),      // open if 50%+ failures
        options.WithOpenTimeout(30*time.Second),    // stay open 30s
        options.WithRequestTimeout(5*time.Second),  // per-call timeout
    )
    cb := circuitbreaker.NewCircuitBreaker("payment-service", opts...)

    ctx := context.Background()
    err := cb.Execute(ctx, func(ctx context.Context) error {
        // Do your external call (respect ctx)
        // return an error to count as failure
        return nil
    })

    switch {
    case err == nil:
        fmt.Println("ok")
    case errors.Is(err, circuitbreaker.ErrCircuitBreakerOpen):
        fmt.Println("fast-fail: circuit open")
    case errors.Is(err, circuitbreaker.ErrCircuitBreakerTimeout):
        fmt.Println("breaker: request timeout")
    default:
        fmt.Printf("call error: %v\n", err)
    }
}

🚨 Todos

  • MVP
  • Add different framework examples (net/http, gin, echo): examples/
  • Unit tests (circuitbreaker_test.go, circuitbreaker_semantics_test.go, options/options_test.go)
  • Add benchmarks (circuitbreaker_bench_test.go, results)
  • Add documentation (package docs in doc.go, runnable examples in example_test.go)
  • Add regression tests (TestRegression* in circuitbreaker_concurrency_test.go)

🧭 How It Works

stateDiagram-v2
    [*] --> CLOSED
    CLOSED --> OPEN: failure rate ≥ threshold
    OPEN --> HALF_OPEN: after openTimeout
    HALF_OPEN --> CLOSED: probes success rate ≥ target
    HALF_OPEN --> OPEN: probes success rate < target
  • Closed: traffic flows; failures are tracked in a sliding time window. Once the window holds at least the minimum number of requests and the failure rate reaches the threshold, the breaker opens.
  • Open: fast‑fail; rejects immediately; waits openTimeout before probing. There is no background timer: the breaker turns Half‑Open when the first request arrives after openTimeout, so an idle breaker keeps reporting OPEN.
  • Half‑Open: lets through at most ThresholdRequestInHalfOpen probe requests per round, counting the ones still in flight, and rejects the rest with ErrCircuitBreakerOpen. Once all probes have completed it closes if their success rate ≥ target, otherwise re‑opens. A probe that times out counts as a failed probe. Closing starts a fresh window, so the probes of that round do not count towards opening again.

The full semantics (timeouts, panics, listeners, the registry) are written up in the package documentation.


✨ Features

  • Sliding window metrics with per‑second buckets
  • Configurable thresholds and timeouts
  • Half‑open probing with target success ratio
  • Custom error predicate (choose what counts as a failure)
  • Event hooks: state changes and request completion
  • Global registry to manage breakers by key
  • Detailed statistics for dashboards/logs

⚙️ Configuration

Import github.com/anilonayy/circuitbreaker/options and compose any of the options below. The default is what NewCircuitBreaker uses when the option is not passed.

Option Default What it does
WithTimeWindow(d time.Duration) 1 minute Length of the sliding window the failure rate is calculated over. Counted in whole seconds.
WithMinimumRequestThreshold(n int64) 10 Requests the window must hold before the failure rate can open the breaker.
WithFailureRateThreshold(p float64) 0.5 Failure rate (0–1) at or above which the Closed breaker opens.
WithOpenTimeout(d time.Duration) 30 seconds How long the breaker stays Open before it lets probes through.
WithRequestTimeout(d time.Duration) 5 seconds Deadline of the context passed to your function; a request that runs into it counts as a failure.
WithThresholdRequestInHalfOpen(n int64) 10 Probe requests admitted, and evaluated, per Half‑Open round.
WithTargetRateInHalfOpen(p float64) 0.6 Share of successful probes (0–1) required to close again.
WithCustomErrorPredicate(func(error) bool) every non‑nil error is a failure Decides which returned errors count as failures. Not asked about timeouts.
WithStateChangeListener(any) none Callback for every state transition. Must be a func(from, to circuitbreaker.State); any other type panics.
WithRequestCompleteListener(func(success bool, d time.Duration)) none Callback for every admitted request with its outcome and duration.

Options are applied in order, so a later one overrides an earlier one. An option with an out‑of‑range value (a duration or count that is not positive, a rate outside 0–1, a nil predicate) is silently skipped and the previous value stays; no error is reported. WithStateChangeListener skips nil the same way, but a value of the wrong type is a programming error and makes NewCircuitBreaker panic instead of leaving you with a listener that never fires. The Set* methods on a breaker follow the same rule: an out‑of‑range value leaves the setting as it was.

Mind the two ends of the rate options: WithFailureRateThreshold(0) opens the breaker as soon as the minimum number of requests is reached, failures or not, and WithTargetRateInHalfOpen(0) closes it after the probes whatever their outcome.

Presets

Each preset returns a []options.Option you can append overrides to. A dash means the preset leaves that setting at its default.

Preset Window Min. requests Failure rate Open timeout Request timeout Probes Target rate
WithDefaults() 1m 10 0.5 30s 5s 10 0.6
WithTestDefaults() 1m 5 0.5 30s 3s 10 0.6
WithAggressive() 30s 5 0.3 2m 3s 5 0.8
WithConservative() 2m 20 0.7 15s 10s 15 0.5
WithHTTPDefaults() 1m 10 0.5 30s 30s – –
WithDatabaseDefaults() 2m 15 0.6 45s 15s – –
WithMicroserviceDefaults() 1m 8 0.4 20s 8s – –

WithDefaults() spells out the values a breaker uses when it is given no options.

Builder
opts := options.NewConfigBuilder().
    TimeWindow(60).                     // seconds
    MinimumRequestThreshold(20).
    FailureRateThreshold(0.4).
    OpenTimeout(45).
    RequestTimeout(10).
    ThresholdRequestInHalfOpen(8).
    TargetRateInHalfOpen(0.7).
    Build()

cb := circuitbreaker.NewCircuitBreaker("svc", opts...)
Changing a live breaker

Every option has a matching setter on the breaker (SetOpenTimeout, SetFailureRateThreshold, …) that can be called while requests are in flight. The setters store what they are given: the range checks described above are done by the With… functions only.


🧪 Practical Examples

HTTP call with custom failure predicate
var errNotFound = errors.New("not found")

opts := append(options.WithHTTPDefaults(),
    options.WithCustomErrorPredicate(func(err error) bool {
        // A 404 says nothing about the health of the upstream:
        // return it to the caller, but do not count it as a failure
        return !errors.Is(err, errNotFound)
    }),
)
cb := circuitbreaker.NewCircuitBreaker("http-upstream", opts...)

err := cb.Execute(context.Background(), func(ctx context.Context) error {
    // net/http client call that respects ctx
    return nil
})
Event hooks for observability
cb := circuitbreaker.NewCircuitBreaker(
    "orders",
    options.WithStateChangeListener(func(from, to circuitbreaker.State) {
        fmt.Printf("state: %s -> %s\n", from, to)
    }),
    options.WithRequestCompleteListener(func(success bool, d time.Duration) {
        fmt.Printf("done: success=%v duration=%s\n", success, d)
    }),
)
Reading metrics
total, ok, fail, rate := cb.GetStatistics()
fmt.Printf("total=%d ok=%d fail=%d rate=%.2f\n", total, ok, fail, rate)

details := cb.GetDetailedStatistics()
fmt.Println(details.State, details.Key)
// includes Open/Half‑Open timestamps, counters, and thresholds;
// marshals to JSON for a status endpoint

Durations come twice: the ...Seconds fields are whole seconds, rounded down, and the ...Millis fields (open_timeout_ms, request_timeout_ms, time_until_half_open_ms in JSON) carry the exact value, so a timeout below one second does not read as 0.

Registry utilities
_ = circuitbreaker.NewCircuitBreaker("billing")
if got, ok := circuitbreaker.GetCircuitBreaker("billing"); ok { _ = got }
for _, k := range circuitbreaker.ListCircuitBreakers() { _ = k }
circuitbreaker.RemoveCircuitBreaker("billing")

More examples, each verified by go test, are in example_test.go and show up on pkg.go.dev.


🌐 Framework Examples

examples/ has a runnable middleware for each of:

Framework Example Run
net/http examples/nethttp go run ./nethttp
Gin examples/gin go run ./gin
Echo (v5) examples/echo go run ./echo

Each one puts the breaker in front of a downstream HTTP call, passes the breaker's context on to that call so it is canceled at the request timeout, and maps the result to a response:

Result of Execute Response
nil whatever the handler wrote
ErrCircuitBreakerOpen 503 Service Unavailable, the downstream is not called
ErrCircuitBreakerTimeout 504 Gateway Timeout
any other error 502 Bad Gateway

The examples start a pretend downstream themselves, so they run as they are:

cd examples
go run ./nethttp                              # or ./gin, ./echo
curl -i 'localhost:8080/quote'                # 200
curl -i 'localhost:8080/quote?mode=error'     # 502, repeat a few times …
curl -i 'localhost:8080/quote?mode=slow'      # 504
curl -i 'localhost:8080/quote'                # … and now 503 until the open timeout has passed

examples/ is a separate Go module, so Gin and Echo are not dependencies of the library.


🚨 Errors

Error Meaning Was your function called? Counted as failure?
ErrCircuitBreakerOpen Request rejected (fast‑fail): the circuit is Open, or it is Half‑Open and all probe slots are taken No No, rejected requests are not counted
ErrCircuitBreakerTimeout The request ran into a deadline: your function returned an error wrapping context.DeadlineExceeded, or ExecuteWithTimeout stopped waiting for it Yes Yes, always
any other error Returned by your function and passed through unchanged Yes If the error predicate says so (default: yes)

Compare with errors.Is. Two details worth knowing:

  • A timeout is recognized by the error, not by the breaker's clock. A deadline your function set itself, or one on the caller's context, is reported as ErrCircuitBreakerTimeout too.
  • A caller that cancels its context is not a timeout: both Execute and ExecuteWithTimeout return context.Canceled, and the error predicate decides whether it counts (the default predicate says yes).

🔒 Concurrency Guarantees

  • All methods of a breaker and all registry functions are safe for concurrent use. The suite passes under go test -race.
  • A single internal lock per breaker protects state, configuration and metrics. Admitting a request and recording its result are each atomic, so concurrent callers see one consistent state machine: callers racing through an expired open timeout cause a single OPEN → HALF_OPEN transition and share one set of probe slots.
  • At most ThresholdRequestInHalfOpen probes are in flight in Half‑Open, however many callers arrive at once.
  • A request that was admitted while the breaker was Closed and finishes during a later Half‑Open round is not counted as a probe.
  • Your function, the error predicate and the event hooks run outside the lock. Hooks run asynchronously, each call in its own goroutine: they may call back into the breaker, and calls for successive events are not ordered.
  • The setters may be called while requests are in flight; a request keeps the request timeout and error predicate it was admitted with.
  • GetDetailedStatistics returns a snapshot that later requests do not change.

Notes

  • Context‑aware: your function receives a context that is canceled at the request timeout. Execute waits for the function to return, so the function has to honor that context; one that ignores it and returns nil late is a success.
  • ExecuteWithTimeout does not rely on that: it runs the function in its own goroutine and returns as soon as the context is done: ErrCircuitBreakerTimeout at a deadline, context.Canceled if the caller canceled. The function keeps running in the background and its result is discarded, so use it for calls that cannot be canceled.
  • Panics: if the wrapped function (or the error predicate) panics, the request is recorded as a failure, exactly like a returned error (statistics, Half‑Open probe result, request‑complete hook with success=false), and the panic reaches the caller with its original value. The breaker never swallows a panic.
  • NewCircuitBreaker(key, ...) registers the breaker under key; calling it again with an existing key returns the already-registered breaker and ignores the new options. Breakers are never removed from the registry on their own, so use keys that name a dependency, not a request.
  • Stringer: cb.String() prints a compact summary for logs.

📈 Benchmarks

Overhead of the breaker around a function that does nothing. Measured on this machine: AMD Ryzen 7 7800X3D (8 cores, 16 threads), Linux amd64, Go 1.27.2. Each value is the median of 5 runs, rounded to three significant digits.

go test -run '^$' -bench . -benchmem -count=5
Benchmark What it measures ns/op B/op allocs/op
ExecuteClosed Execute, Closed, call succeeds 487 272 4
ExecuteClosedParallel same, from 16 goroutines 579 272 4
ExecuteClosedFailure Execute, Closed, call fails 490 272 4
ExecuteOpen Execute, Open (rejected) 25.4 0 0
ExecuteOpenParallel same, from 16 goroutines 54.5 0 0
ExecuteHalfOpenProbe Execute, Half‑Open, admitted probe 421 272 4
ExecuteHalfOpenProbeParallel same, from 16 goroutines 460 272 4
ExecuteHalfOpenRejected Execute, Half‑Open, probe slots taken (rejected) 10.9 0 0
ExecuteWithTimeoutClosed ExecuteWithTimeout, Closed 1380 912 11
ExecuteWithTimeoutClosedParallel same, from 16 goroutines 813 912 11
ExecuteWithTimeoutOpen ExecuteWithTimeout, Open (rejected) 25.4 0 0
ExecuteClosedListeners/none Execute, Closed, no hooks 485 272 4
ExecuteClosedListeners/state-change same, with a state‑change hook 489 272 4
ExecuteClosedListeners/request-complete same, with a request‑complete hook 636 304 5
ExecuteClosedListeners/both same, with both hooks 631 304 5
GetState GetState 3.76 0 0
GetDetailedStatistics GetDetailedStatistics 79.7 0 0
  • A healthy call through a Closed breaker costs about half a microsecond and 4 allocations.
  • A rejected call costs between about 10 and 55 nanoseconds and allocates nothing, which is the point of failing fast.
  • A breaker is guarded by one lock, so Execute through the same breaker does not get faster with more cores: under contention from 16 goroutines a call takes somewhat longer than a sequential one (the "from 16 goroutines" rows).
  • ExecuteWithTimeout pays for the extra goroutine, and a request‑complete hook for the goroutine it is delivered in.

Numbers depend on hardware and Go version; run the command above to get yours.


🧷 Tests

go test -race ./...

Tests that wait for the open timeout or the request timeout run on a virtual clock (testing/synctest), so they take no real time and do not depend on scheduling. Every concurrency and panic-handling bug fixed so far is pinned by a regression test named after it (go test -race -run Regression -v .); each of them fails against the code from before the fixes.

CI runs gofmt, go vet and the race tests, for the library and the examples, on the oldest supported Go (see go.mod) and on the current release.


License

MIT — see LICENSE.

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

Examples

Constants

This section is empty.

Variables

View Source
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

func (cb *CircuitBreaker) Execute(ctx context.Context, fn func(context.Context) error) error

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
)

func (State) String

func (s State) String() string

String returns the name of the state: "CLOSED", "OPEN" or "HALF_OPEN", and "UNKNOWN" for any other value.

Directories

Path Synopsis
Package options holds the functional options that configure a circuit breaker from github.com/anilonayy/circuitbreaker.
Package options holds the functional options that configure a circuit breaker from github.com/anilonayy/circuitbreaker.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL