Circuit breaker
Fail fast while a dependency keeps failing, and confirm recovery with one probe after a cooldown.
The three states
| State | Calls | Moves to |
|---|---|---|
Closed | run and counted | Open, when the failure threshold is reached |
Open | rejected with ErrOpen | HalfOpen, once BreakerConfig.Cooldown has passed |
HalfOpen | one probe runs, the rest are rejected | Closed if the probe succeeds, Open if it fails |
The move from Open to HalfOpen happens lazily, on the next call or Breaker.State, so no background goroutine is needed.
Watch it open and recover
In the example, the dependency is down at first. After three failures in a row the breaker opens, and later calls fail fast. Once the dependency recovers and the cooldown has passed, the probe succeeds and the breaker closes. BreakerConfig.OnStateChange is called after every state change.
breaker, err := resil.NewBreaker(resil.BreakerConfig{
Failures: 3,
Cooldown: 200 * time.Millisecond,
OnStateChange: func(from, to resil.State) {
fmt.Printf(" breaker %s → %s\n", from, to)
},
})
if err != nil {
panic(err)
}
fmt.Println("payments is down:")
for i := range 5 {
err := breaker.Do(ctx, payments)
fmt.Printf("call %d: %v\n", i+1, err)
}
fmt.Println("payments recovers; waiting for the cooldown...")
healthy = true
time.Sleep(200 * time.Millisecond)
err = breaker.Do(ctx, payments) // the half-open probe
fmt.Printf("probe: err=%v, state=%s\n", err, breaker.State())breaker, _ := resil.NewBreaker(resil.BreakerConfig{
Failures: 2,
OnStateChange: func(from, to resil.State) {
fmt.Println("breaker:", from, "→", to)
},
})
down := func(context.Context) error { return errors.New("connection refused") }
for range 3 {
err := breaker.Do(context.Background(), down)
fmt.Println(err)
}connection refused
breaker: closed → open
connection refused
resil: breaker is openChoose how it trips
The zero value of BreakerConfig is valid: the breaker opens after 5 consecutive failures and cools down for 30 seconds. Set BreakerConfig.Failures to trip on consecutive failures. Under heavier traffic, set BreakerConfig.FailureRate, BreakerConfig.Window, and BreakerConfig.MinRequests to trip on the failure rate over a sliding window, so a few unlucky calls do not open the breaker. Choose one or the other; NewBreaker returns an error if both are set. The failure rate is measured over ten buckets that expire one at a time, so memory use is fixed.
Which calls are counted
By default every error counts as a failure, and BreakerConfig.IsFailure can change that. A call whose own context was cancelled or timed out is never counted, because the caller giving up says nothing about the dependency. To have slow calls count as failures, wrap the operation in a Timeout. Every state change starts a new generation, and calls from an earlier generation are not counted when they finish, so a slow call from before the breaker opened cannot reopen it after it has recovered. A panic in the operation counts as a failure and keeps propagating.