Circuit Breaker With Failure Threshold

Trip a circuit breaker after consecutive failures, short-circuiting calls during an open period and probing recovery with a half-open state.

GoResilience

Code

gosnippet
54 lines
package breaker

import (
	"errors"
	"sync"
	"time"
)

type State int

const (
	Closed State = iota
	Open
	HalfOpen
)

var ErrOpen = errors.New("circuit breaker is open")

type Breaker struct {
	mu           sync.Mutex
	state        State
	failures     int
	threshold    int
	openedAt     time.Time
	resetTimeout time.Duration
}

func (b *Breaker) Call(fn func() error) error {
	b.mu.Lock()
	if b.state == Open {
		if time.Since(b.openedAt) < b.resetTimeout {
			b.mu.Unlock()
			return ErrOpen
		}
		b.state = HalfOpen
	}
	b.mu.Unlock()

	err := fn()

	b.mu.Lock()
	defer b.mu.Unlock()
	if err != nil {
		b.failures++
		if b.failures >= b.threshold {
			b.state = Open
			b.openedAt = time.Now()
		}
		return err
	}
	b.failures = 0
	b.state = Closed
	return nil
}

What each part does

Structurally, expect the function Call and nothing else.

The Go idiom runs throughout — 1 if err != nil check, each handling the failure on the spot. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.

What to watch for

  • No package manager takes part — every call lands on a platform built-in.
  • The function reports failure by returning error — callers branch on it before touching other results.

Using it

Entry signature: func (b *Breaker) Call(fn func() error) error

Call is reached through its receiver type Breaker — call it on a value of that type rather than importing the name.

Key statements

if err != nil {
	b.failures++
	if b.failures >= b.threshold {
		b.state = Open
		b.openedAt = time.Now()
	}
	return err
}
var ErrOpen = errors.New("circuit breaker is open")
mu           sync.Mutex

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
Through `error` values, not panics — the snippet checks `err != nil` at 1 site.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `errors`, `sync`, `time`. The file defines `Call` at load time.