Circuit Breaker States With Metrics

Implement a circuit breaker with state transitions and metrics for Go service protection.

GoResilience

Code

gosnippet
27 lines
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 }
}

What the code does

Count the functions Allow and Record as the entire surface area of Circuit Breaker States With Metrics.

Error handling is inline: 1 place test err != nil and branch immediately. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Applying it

Entry signature: func (b *Breaker) Allow() bool

Allow hangs off Breaker: obtain an instance and invoke the method on it.

Statements that matter

if time.Now().Before(b.resetAt) { return false }
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 }
}
mu sync.Mutex

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `Allow`, `Record` at load time.