Circuit Breaker States With Metrics
Implement a circuit breaker with state transitions and metrics for Go service protection.
Code
package main
import ("sync";"time";"errors")
type State int
const (Closed State = iota; Open; HalfOpen)
type Breaker struct {
mu sync.Mutex
state State
failures int
threshold int
resetAt time.Time
timeout time.Duration
}
func (b *Breaker) Allow() bool {
b.mu.Lock(); defer b.mu.Unlock()
if b.state == Open {
if time.Now().Before(b.resetAt) { return false }
b.state = HalfOpen
}
return true
}
func (b *Breaker) Record(err error) {
b.mu.Lock(); defer b.mu.Unlock()
if err != nil {
b.failures++
if b.failures >= b.threshold { b.state = Open; b.resetAt = time.Now().Add(b.timeout) }
} else if b.state == HalfOpen { b.state = Closed; b.failures = 0 }
}Report a problem with this exampleOpens a pre-filled issue on GitHub.