Performance#

Measured 2026-11-05 on an Intel Core i5-8257U @ 1.40GHz (darwin/amd64) with Go 1.27.3, running the suite five times:

1
go test -run '^$' -bench . -benchmem ./internal/breaker/

Each figure is the median of the five passes; the range shows the fastest and slowest pass. On this laptop the same benchmark varied by up to 2x between passes (CPU frequency scaling), so compare rows rather than reading the numbers as exact. Run make bench on your own hardware.

Execute, per state#

StateBenchmarkns/op (median)rangeB/opallocs/op
ClosedExecute_Closed61.149.5–82.000
Closed (ExecuteContext)ExecuteContext_Closed63.155.0–81.900
Closed, failing requestExecuteFailure76.766.5–137.400
Closed, 8 goroutines (b.RunParallel)ConcurrentExecute164.4136.5–181.800
Open (request rejected)Execute_Open112.291.6–148.700
HalfOpen: trip, probe, closeExecute_HalfOpen624.3521.1–958.900

A HalfOpen probe always changes state (one success closes the breaker), so the HalfOpen row times a full cycle on one breaker: a failing request that trips it, the move to HalfOpen, and the probe that closes it.

The function being wrapped costs 1.0 ns when called directly (CompareBaseline).

Other operations#

OperationBenchmarkns/op (median)rangeB/opallocs/op
State()State0.30.3–0.400
Counts()Counts0.90.8–1.200
Metrics()Metrics18.216.0–26.500
Diagnostics()Diagnostics40.436.5–56.400
UpdateSettings()UpdateSettings12.911.8–20.200
New()New215.9166.4–292.41441

Allocations#

Execute() does not allocate in Closed, Open or HalfOpen state, including the call that changes state (trip, probe success, probe failure); TestExecuteDoesNotAllocate checks this with testing.AllocsPerRun. The exception is the log line written when a callback panics or a counter saturates. New() allocates once. Callbacks you supply run inside Execute(), so any allocation they make is added to the calls that run them.

Lock-Free Design#

1
2
3
4
5
6
7
type CircuitBreaker struct {
    state atomic.Int32  // 0=Closed, 1=Open, 2=HalfOpen
    requests atomic.Uint32
    totalSuccesses atomic.Uint32
    totalFailures atomic.Uint32
    // ... other atomic fields
}

The request path uses atomic loads, adds and compare-and-swap. The only mutex serializes the log lines written when a callback panics or a counter saturates. There is no background goroutine.

Keep Callbacks Fast#

ReadyToTrip, OnStateChange and IsSuccessful run synchronously inside Execute().

1
2
3
4
5
6
7
8
9
// Good: Async logging
OnStateChange: func(name string, from, to State) {
    go metrics.Record(name, from, to) // Async, non-blocking
}

// Bad: Blocking I/O in callback
OnStateChange: func(name string, from, to State) {
    db.SaveStateChange(name, from, to) // Blocks!
}