Circuit Breakers
A from-scratch guide to failing fast when a dependency is sick: why a retry loop makes an outage worse, what state a breaker actually holds, how the three states interact under concurrency, and how to tune one without turning it into a random outage generator.
Read top to bottom. It goes beginner → advanced, and generic → concrete. Part I builds the mental model with no code. Part II builds a real breaker in Go, line by line, and then critiques the one already in this repo (
circuit-breaker.go).Companion docs: Bulkheads (the pattern that limits how much of your system one dependency can eat) and Retries: A Go HTTP Retry Transport (the retry transport a breaker must sit outside of).
Part I — The generic model
1. The problem: why retries make outages worse
Start with a service A that calls a dependency B on every request.
1000 rps
──────────────────► ┌───┐ ──────────────► ┌───┐
clients │ A │ │ B │
└───┘ └───┘
B gets slow — say its p99 goes from 20 ms to 10 s because a database index got
dropped. Three things now happen to A, in this order, and each one is worse than the
last.
Stage 1 — threads/goroutines pile up. Every in-flight call to B holds a goroutine,
a connection from the pool, a slot in A's inbound concurrency limit, and a chunk of
memory. At 1000 rps with a 10 s latency, Little's Law says the number in flight is
L = λ × W = 1000 × 10 = 10,000. A was sized for 1000 × 0.02 = 20. It now needs
500× the resources it has.
Stage 2 — retries multiply the load. A has a sensible retry policy: 3 attempts. So
B, already dying, now receives 3× the traffic exactly when it can least afford it.
This is a retry storm, and it is the single most common way a partial degradation
becomes a total outage.
Stage 3 — the failure spreads. A runs out of goroutines/connections/memory and
starts failing requests that never needed B at all. A's callers time out and retry.
The infection moves up the call graph. This is a cascading failure, and by now the
original cause (B's index) is invisible in the noise.
healthy B degrades cascade
─────── ────────── ───────
A: 20 in flight → A: 10,000 in flight → A: out of memory
B: 1000 rps B: 3000 rps (retries) C, D: also down
The key insight: once B is failing, calling B has negative expected value. The
call will almost certainly fail, and in the meantime it consumes a resource in A and
adds load to B. You are paying twice for a guaranteed loss.
The circuit breaker's whole job: notice that calls are failing, and stop making them for a while — cheaply, immediately, and without asking anyone's permission.
The electrical metaphor is exact. A house breaker doesn't fix the short in your wiring; it disconnects the circuit so the short doesn't burn the house down, and it makes you come back and check before re-energizing.
2. The idea: a breaker is a memory of recent failure
Strip everything else away and a circuit breaker is:
A small piece of shared, mutable state sitting in front of a call site, which remembers how recent calls went, and which can decide to reject a call without making it.
That's it. Three consequences follow immediately, and they explain most of the design:
-
It is shared state on the hot path. Every request touches it. So it must be cheap (a mutex held for nanoseconds, or atomics) and it must never block.
-
It is a control loop with feedback delay. It observes failures, acts (opens), and then must re-observe to know when to stop acting. But while it's open it isn't making calls, so it has no observations. Resolving that paradox is what half-open is for (section 11).
-
It is a heuristic, not a proof. It will sometimes reject calls that would have succeeded (false positive) and sometimes let through calls that fail (false negative). You tune the tradeoff; you never eliminate it.
What a breaker is not
| Not | Because |
|---|---|
| A retry mechanism | Retries make more calls; a breaker makes fewer. They are opposites that compose (section 8). |
| A rate limiter | A rate limiter caps load unconditionally. A breaker caps load conditionally on failure. |
| A load balancer health check | Health checks are out-of-band probes with a global view. A breaker is in-band, per-caller, and reacts in milliseconds. They complement each other. |
| A bulkhead | A bulkhead limits concurrency so one dependency can't eat all your resources — it works even when the dependency is slow but not failing. See Bulkheads. |
That last row matters more than it looks. A breaker catches errors; a bulkhead catches slowness. A dependency that returns 200 OK after 30 s trips no breaker but will still kill you. You need both.
3. The three states and every legal transition
failure threshold exceeded
┌────────────────────────────────────────────────┐
│ ▼
┌──────────────┐ ┌──────────────┐
│ CLOSED │ │ OPEN │
│ calls pass │ │ fail fast │
│ count fails │ │ no calls │
└──────────────┘ └──────────────┘
▲ │
│ N consecutive probe successes │ cooldown elapsed
│ ▼
│ ┌──────────────┐
└─────────────────────────────────────────│ HALF-OPEN │
│ ≤K probes │
any probe fails │ in flight │
┌────────────────────────────└──────────────┘
│ │
└──── back to OPEN (reset cooldown) ──┘
CLOSED — the normal state
Calls pass through. The breaker records outcomes. When the failure signal crosses a threshold, it trips to OPEN.
Note the naming trap that catches everyone: closed = healthy = traffic flows. It's the electrical sense (a closed circuit conducts), not the "closed for business" sense.
OPEN — fail fast
Calls are rejected immediately with a sentinel error (ErrOpen). No network I/O, no
goroutine held, no load on the dependency. This is the entire point: the rejection costs
~100 ns instead of 10 s.
The breaker stays open for a cooldown (also called the open duration or reset timeout). Typical: 5–30 s. Too short and you hammer a dependency that's still down; too long and you stay dark after it recovers.
HALF-OPEN — the careful experiment
After the cooldown, you need to answer "is B better now?" The only way to know is to
call it. But if you dump the full 1000 rps back onto a still-fragile B, you re-break it
instantly — the thundering herd on recovery.
So half-open allows a small, bounded number of probe calls through:
- If a probe fails → straight back to OPEN, cooldown restarts (usually with backoff).
- If
Kprobes succeed → back to CLOSED, counters reset.
K > 1 matters. With K = 1 a single lucky request (served from a cache, or hitting the
one healthy replica out of ten) closes the breaker and slams the full load back onto a
broken dependency. K = 3..5 is a reasonable default.
The transition table, exhaustively
| From | Event | To | Notes |
|---|---|---|---|
| CLOSED | success | CLOSED | reset consecutive-failure counter |
| CLOSED | countable failure, below threshold | CLOSED | increment |
| CLOSED | countable failure, at threshold | OPEN | set openUntil = now + cooldown |
| CLOSED | non-countable failure (e.g. 404) | CLOSED | do not increment |
| OPEN | call arrives, now < openUntil |
OPEN | reject with ErrOpen |
| OPEN | call arrives, now ≥ openUntil |
HALF-OPEN | this call becomes probe #1 |
| HALF-OPEN | probe succeeds, < K total |
HALF-OPEN | increment success count |
| HALF-OPEN | probe succeeds, = K total |
CLOSED | reset everything |
| HALF-OPEN | probe fails | OPEN | reset cooldown, with backoff |
| HALF-OPEN | call arrives, probes at cap | HALF-OPEN | reject with ErrTooManyProbes |
| any | operator forces open | OPEN | manual kill switch |
| any | operator forces closed | CLOSED | manual override, for when the breaker is wrong |
Two entries deserve emphasis:
Backoff on repeated trips. If the breaker trips, probes, fails, and trips again, the cooldown should grow: 5 s → 10 s → 20 s → 40 s, capped at a minute or two. A dependency that has failed five recovery attempts is not going to recover in the next five seconds, and each probe round costs you a burst of load on it. Add jitter, for the same reason retries need jitter (section 8).
The manual override is not optional. Every real breaker eventually mis-fires — a bad
classifier counts a client error as a server error, and you're dark on a healthy
dependency at 3 a.m. ForceClose is the escape hatch. ForceOpen is the other half: an
operator-triggered kill switch to shed load from a dependency you know is in trouble,
before it fails enough to trip on its own.
4. What counts as a failure? (classification)
This is the highest-leverage decision in the whole pattern, and the one most implementations get wrong. A breaker that counts the wrong things is worse than no breaker.
The rule: count only failures that indicate the dependency is unhealthy, and that would recur for the next caller.
| Outcome | Count? | Why |
|---|---|---|
| Connection refused / reset | Yes | The dependency is not accepting work. |
| DNS failure | Yes | Nothing you send will arrive. |
| Timeout (your deadline) | Yes | The classic overload signal — arguably the most important one. |
| HTTP 500 / 502 | Yes | Server-side failure. |
| HTTP 503 Service Unavailable | Yes, aggressively | The server is explicitly saying "stop". Consider tripping immediately. |
| HTTP 429 Too Many Requests | Yes, aggressively | Explicit backpressure. Honor Retry-After as a minimum open duration. |
| HTTP 400 / 404 / 422 | No | Your request is bad. The dependency is perfectly healthy. Counting these means one client bug takes down a healthy dependency for everyone. |
| HTTP 401 / 403 | No (usually) | Auth problem, not a health problem. Though a mass 401 spike can mean a broken auth service — a separate breaker's job. |
context.Canceled from the caller |
No | The caller went away. The dependency did nothing wrong. Counting these means an impatient client trips your breaker. |
| Business-logic error ("insufficient funds") | No | Not a transport concern at all. |
The two mistakes
Mistake 1: counting all non-2xx. A client that sends 10,000 malformed requests will open your breaker and deny service to every other client of a completely healthy dependency. This is a self-inflicted outage triggered by a bug in someone else's code.
Mistake 2: not counting timeouts. Slow is the most common form of "down", and a timeout is your only in-band evidence of it. If you only count explicit errors, you'll sail straight into the Stage-1 pileup from section 1.
Accelerated tripping
Some signals are strong enough that waiting for a threshold is silly. A 503 with
Retry-After: 120 is the dependency telling you, in writing, that it will be down for
two minutes. Trip immediately, and set the open duration to at least 120 s.
classify(err) → {
kind: timeout | overloaded | unavailable | other
countable: bool // does it move the threshold counter?
tripNow: bool // bypass the threshold entirely
minOpenFor: duration // floor on the cooldown, e.g. from Retry-After
}
Splitting countable from tripNow is what lets you express "count this, but don't
panic" and "don't wait, trip right now" with the same struct.
Per-kind thresholds
You may want different sensitivities: unavailable at 3 failures (it's unambiguous),
timeout at 8 (a few slow requests are normal under load), other at 5. This is a real
refinement, but be aware of the trap: per-kind counters that each need their own
threshold mean a mix of failure types may never trip anything. Nine timeouts and two
unavailables — with thresholds of 10 and 3 — trips nothing, despite 11 failures out of
maybe 12 calls. Always keep a global threshold as the backstop, and check both.
5. Counting: consecutive, windowed, and rate-based trips
"Threshold exceeded" hides a real design choice.
(a) Consecutive failures
"Trip after 5 failures in a row." Any success resets to zero.
- Pro: trivial to implement (one
int), no memory, zero allocation. - Con: blind to partial failure. A dependency failing 40% of calls will never produce 5 in a row at any reasonable rate — you'll sit at 40% errors forever and never trip.
Fine for low-traffic call sites. Not adequate for a busy one.
(b) Failure count in a sliding window
"Trip after 20 failures in the last 10 seconds."
- Pro: catches partial failure.
- Con: the threshold is coupled to traffic volume. Twenty failures is catastrophic at 30 rps and irrelevant at 5000 rps. When traffic drops overnight the breaker effectively stops working.
(c) Failure rate in a sliding window — the good default
"Trip when ≥50% of the last 10 seconds' calls failed, provided there were at least 20 calls."
The minimum-volume guard is essential. Without it, one failure out of one call is a 100% error rate, and your breaker flaps every time traffic is sparse. With it, the breaker simply stays closed on low-traffic call sites, which is the correct behavior — at 2 rps you cannot hurt anyone anyway.
trip if: calls_in_window ≥ minVolume
and: failures / calls ≥ failureRateThreshold
Typical: minVolume = 20, rate = 0.5, window = 10 s.
(d) Concurrency-based ("slow call" breakers)
Trip when the number of in-flight calls exceeds a limit, or when the fraction of calls
slower than T exceeds a rate. This is really a bulkhead wearing a breaker costume —
see Bulkheads — but resilience4j ships it as a breaker feature and
it's genuinely useful against the "slow but not failing" case.
Window implementation: buckets, not a list
Don't keep a timestamped list of every call — it allocates on the hot path and grows with
traffic. Use ring buckets: divide the window into N sub-intervals (say 10 buckets of
1 s), keep {success, failure} counts per bucket, and roll forward by zeroing stale
buckets. Cost is O(1) amortized, memory is fixed, and the resolution error is one bucket.
Code in section 10.
6. Granularity: what does one breaker protect?
A breaker's state is only meaningful if all the calls sharing it fail together. Get this wrong and you either can't detect anything or you take out the world.
Too coarse — one breaker for all of service B. B has 20 endpoints. One of them,
/reports, is slow and failing. Its errors trip the shared breaker, and now
/health, /users, /orders — all fine — are refused too. You converted a
single-endpoint degradation into a full outage of B from your side.
Too fine — one breaker per (endpoint, user ID). Each breaker sees a handful of calls, never reaches minimum volume, never trips. You also leak memory: an unbounded map keyed by user ID is a slow OOM. If you key breakers by anything user-controlled, you need an LRU with a hard cap.
About right — one breaker per (dependency, operation class), and additionally per partition when partitions fail independently:
| Key | Use when |
|---|---|
service |
Small dependency, endpoints share a fate (one process, one DB). |
service:endpoint |
Default. Endpoints have different backends or cost profiles. |
service:endpoint:shard |
Sharded/partitioned dependency where one shard can be down alone. |
service:endpoint:region |
Multi-region, where one region's failure shouldn't dark the others. |
service:endpoint:host |
You're client-side load balancing and want to eject one bad host. |
The registry pattern (a map[string]*Breaker behind a mutex, lazily created — see the
Registry type in the existing circuit-breaker.go) is how you get per-key breakers.
Bound it. Keys must come from a closed set (your own endpoint names, your own shard
IDs), never from request data.
Per-process vs. distributed state
Breaker state is normally per process. Ten replicas of A each have their own view of
B. This is fine and usually desirable:
-
Each replica learns independently; a network partition affecting one replica correctly opens only that one.
-
No shared-state dependency on the hot path — the last thing you want is your resilience mechanism calling Redis, which can itself be down.
The cost is a slower aggregate signal (each replica must see enough failures itself) and
N × the probe traffic during half-open — with 100 replicas each sending 5 probes,
that's 500 requests hitting a barely-recovered dependency. If you run at that scale,
lower K per replica, add jitter to the cooldown so replicas don't probe in lockstep, or
push the decision into a shared proxy layer (a service mesh sidecar like Envoy, which
implements outlier detection exactly here).
7. What to do when the breaker is open (fallbacks)
ErrOpen is only useful if the caller does something sensible with it. Options, roughly
in order of preference:
1. Serve stale/cached data. The best fallback when it's available. "Recommendations from 10 minutes ago" beats "no page". Requires you to keep a cache with a TTL longer than your expected outage.
2. Degrade the feature. Drop the personalized module and render the generic one. The page still works; it's just less good. This is what makes a breaker a user-visible availability win rather than just a server resource win.
3. Try a different source. Secondary region, read replica, a cheaper model. Watch out: if the fallback shares a failure domain with the primary, you've just moved the outage.
4. Queue for later. Only for genuinely asynchronous work. The "replay journal" idea — buffer rejected calls and re-run them when the breaker closes — is dangerous by default and worth spelling out:
- Replaying a non-idempotent call double-charges someone.
-
The buffer is unbounded pressure: if the outage is long, you either OOM or drop, and dropping silently is a data-loss bug.
-
Replaying the whole buffer the instant the breaker closes is a self-inflicted thundering herd — you must rate-limit the drain.
-
The original caller is long gone, so nobody sees the result or the error.
Use it only for fire-and-forget writes, with a hard cap, a drop policy you've chosen deliberately, and a throttled drain.
5. Fail fast to the user. Perfectly respectable. A 503 in 1 ms is much better than a timeout in 30 s: the user retries or leaves, and your server is free to serve someone else.
Anti-pattern: catch ErrOpen and retry. It converts fail-fast into a busy loop
against the breaker. If you must retry across a breaker, the retry has to wait for the
cooldown, which means it isn't really a retry — it's a scheduled job.
8. Interaction with timeouts, retries, and bulkheads
These four patterns are not alternatives. They form a stack, and the order matters.
caller
│
▼
┌────────────────────────────────────────┐
│ BULKHEAD limit concurrent calls │ ← reject when saturated
│ ┌──────────────────────────────────┐ │
│ │ BREAKER reject when unhealthy │ │ ← reject when open
│ │ ┌────────────────────────────┐ │ │
│ │ │ RETRY re-attempt failures │ │ │ ← N attempts
│ │ │ ┌──────────────────────┐ │ │ │
│ │ │ │ TIMEOUT per attempt │ │ │ │ ← bound each attempt
│ │ │ │ the actual call │ │ │ │
│ │ │ └──────────────────────┘ │ │ │
│ │ └────────────────────────────┘ │ │
│ └──────────────────────────────────┘ │
└────────────────────────────────────────┘
Read it outside-in: bulkhead → breaker → retry → timeout → call.
Why the breaker goes outside the retry
If the breaker is inside the retry loop, a single logical operation with 3 attempts
records 3 failures. Your threshold of 5 is now really a threshold of ~1.7 operations, and
worse, the count depends on the retry policy — change maxAttempts and you silently
change breaker sensitivity.
With the breaker outside, one logical operation contributes exactly one outcome, which is what "50% of operations are failing" is supposed to mean. And when the breaker is open, the entire retry loop is skipped — which is the whole point, since retrying against a known-dead dependency is precisely the retry storm you're preventing.
There's a defensible variant where an inner breaker sits per-host inside a retry-across-hosts loop; retry then routes around the ejected host. That's load-balancer outlier detection, and it's a different (also good) design. Just don't put a per-service breaker inside a same-host retry loop.
Why the timeout is innermost, and must be per-attempt
The timeout is what manufactures the failure signal. Without a per-attempt deadline, a hung call blocks forever, the breaker records nothing (no outcome yet), and you pile up exactly as in section 1. A breaker without timeouts underneath it is decorative.
The budget has to nest:
caller deadline 10 s ← total, covers everything
retry: 3 attempts
per-attempt timeout 2.5 s ← 3 × 2.5 = 7.5 s
backoff between ~1 s ← plus jitter
─────
~8.5 s ← fits inside 10 s. Good.
If attempts × perAttempt > callerDeadline, your last attempt is always cancelled
mid-flight — you're paying for load you never get an answer from.
Jitter, everywhere
Both retry backoff and breaker cooldown need randomization. Without it, all N replicas
that tripped at the same moment (they saw the same outage) will probe at the same moment,
producing a synchronized burst — a self-organized DDoS on a recovering service. cooldown
× (0.5 + rand()×0.5) is enough.
Where the bulkhead fits
Outermost, because it protects a resource (goroutines, connections, memory) that must be capped regardless of health, and because it's the only one of the four that helps against a dependency that is slow but returning 200s. Details in Bulkheads.
Part II — Building one in Go
Everything below compiles under Go 1.21+ with no external dependencies. The complete
runnable version belongs next to
circuit-breaker.go;
here we build it up piece by piece so each decision is visible.
9. Skeleton: state, mutex, and the Execute wrapper
package breaker
import (
"context"
"errors"
"math/rand"
"sync"
"time"
)
type State int
const (
StateClosed State = iota
StateOpen
StateHalfOpen
)
func (s State) String() string {
switch s {
case StateClosed:
return "closed"
case StateOpen:
return "open"
case StateHalfOpen:
return "half-open"
}
return "unknown"
}
var (
// ErrOpen means the call was rejected without being attempted.
ErrOpen = errors.New("circuit breaker open")
// ErrTooManyProbes means we are half-open and already at the probe cap.
ErrTooManyProbes = errors.New("circuit breaker half-open: probe limit reached")
)
type Config struct {
// Trip conditions (rate-based, with a volume guard — see §5c).
Window time.Duration // observation window, e.g. 10s
Buckets int // window resolution, e.g. 10
MinVolume int // don't evaluate below this many calls
FailureRate float64 // 0..1, e.g. 0.5
// Recovery.
Cooldown time.Duration // base open duration
MaxCooldown time.Duration // ceiling for exponential backoff
ProbeSuccesses int // successes needed to close (K)
MaxProbes int // concurrent probes allowed in half-open
// Behavior.
Classify func(error) Verdict
Now func() time.Time // injectable clock for tests
Rand func() float64 // injectable jitter for tests
// Observability.
OnStateChange func(from, to State, reason string)
}
// Verdict is the classifier's answer about one error. See §4.
type Verdict struct {
Countable bool // moves the failure counter
TripNow bool // bypass the threshold, open immediately
MinOpenFor time.Duration // floor on cooldown (e.g. Retry-After)
Kind string // for metrics: "timeout", "unavailable", ...
}
type Breaker struct {
cfg Config
mu sync.Mutex
state State
counts *window // §10
openedAt time.Time
openUntil time.Time
consecTrips int // drives cooldown backoff
probeOK int // successes so far in half-open
probesInFlight int
forcedOpen bool
forcedClosed bool
}
Three design notes before the logic:
One mutex, held briefly. Not RWMutex: nearly every operation mutates (even a read
of "current state" may need to promote OPEN→HALF-OPEN on the time check), so read-lock
sharing buys nothing and costs more on the write path. The mutex is never held across the
call to the dependency — only across counter updates, which are tens of nanoseconds. At
that hold time a single mutex sustains millions of ops/sec; if you genuinely outgrow it,
shard the breaker by key rather than by reaching for atomics and getting the transitions
subtly wrong.
Injectable Now and Rand. A breaker is a time-driven state machine. If you can't
control time, your tests are time.Sleep calls that are slow and flaky. This one field
is the difference between a test suite you trust and one you skip. See section 14.
Config validation. Zero values here are traps (FailureRate: 0 trips on the first
call; Buckets: 0 divides by zero). Fill in defaults explicitly:
func (c *Config) applyDefaults() {
if c.Window <= 0 { c.Window = 10 * time.Second }
if c.Buckets <= 0 { c.Buckets = 10 }
if c.MinVolume <= 0 { c.MinVolume = 20 }
if c.FailureRate <= 0 || c.FailureRate > 1 { c.FailureRate = 0.5 }
if c.Cooldown <= 0 { c.Cooldown = 5 * time.Second }
if c.MaxCooldown < c.Cooldown { c.MaxCooldown = 60 * time.Second }
if c.ProbeSuccesses <= 0 { c.ProbeSuccesses = 3 }
if c.MaxProbes <= 0 { c.MaxProbes = 1 }
if c.Classify == nil { c.Classify = DefaultClassify }
if c.Now == nil { c.Now = time.Now }
if c.Rand == nil { c.Rand = rand.Float64 }
}
func New(c Config) *Breaker {
c.applyDefaults()
return &Breaker{
cfg: c,
state: StateClosed,
counts: newWindow(c.Window, c.Buckets, c.Now),
}
}
The core: Allow / Do / Done
Split the breaker's job into three primitives so the call itself never happens under the lock:
// Allow decides whether a call may proceed. If it returns nil, the caller MUST
// eventually call the returned done func exactly once with the call's outcome.
func (b *Breaker) Allow() (done func(error), err error) {
b.mu.Lock()
defer b.mu.Unlock()
now := b.cfg.Now()
switch {
case b.forcedOpen:
return nil, ErrOpen
case b.forcedClosed:
return b.doneFunc(StateClosed), nil
}
switch b.state {
case StateOpen:
if now.Before(b.openUntil) {
return nil, ErrOpen
}
// Cooldown elapsed: this caller becomes the first probe.
b.toLocked(StateHalfOpen, "cooldown elapsed")
fallthrough
case StateHalfOpen:
if b.probesInFlight >= b.cfg.MaxProbes {
return nil, ErrTooManyProbes
}
b.probesInFlight++
return b.doneFunc(StateHalfOpen), nil
default: // StateClosed
return b.doneFunc(StateClosed), nil
}
}
The done closure records the outcome:
func (b *Breaker) doneFunc(entered State) func(error) {
var once sync.Once
return func(callErr error) {
once.Do(func() { b.record(entered, callErr) })
}
}
func (b *Breaker) record(entered State, callErr error) {
b.mu.Lock()
defer b.mu.Unlock()
if entered == StateHalfOpen {
b.probesInFlight--
}
if callErr == nil {
b.onSuccessLocked(entered)
return
}
v := b.cfg.Classify(callErr)
if !v.Countable && !v.TripNow {
// e.g. a 404 or a caller cancellation: invisible to the breaker.
return
}
b.onFailureLocked(entered, v)
}
The sync.Once guard is not paranoia. done is typically called from a defer, and a
caller that also calls it explicitly on an early return would otherwise double-count and
leak a probe slot (driving probesInFlight negative and permanently un-capping probes).
Success and failure handling:
func (b *Breaker) onSuccessLocked(entered State) {
b.counts.add(true)
if b.state == StateHalfOpen {
b.probeOK++
if b.probeOK >= b.cfg.ProbeSuccesses {
b.toLocked(StateClosed, "probe successes reached")
}
}
_ = entered
}
func (b *Breaker) onFailureLocked(entered State, v Verdict) {
b.counts.add(false)
switch b.state {
case StateHalfOpen:
// One bad probe is enough. The dependency is not ready.
b.tripLocked(v, "probe failed")
case StateClosed:
if v.TripNow {
b.tripLocked(v, "accelerated trip: "+v.Kind)
return
}
total, fails := b.counts.totals()
if total >= b.cfg.MinVolume && float64(fails)/float64(total) >= b.cfg.FailureRate {
b.tripLocked(v, "failure rate threshold")
}
}
_ = entered
}
Note the entered parameter being deliberately ignored in the state checks: we branch on
b.state (the state now), not on the state when the call started. A call that began
while CLOSED but finishes after another goroutine already tripped the breaker should be
recorded against the current reality. The entered value is used only to balance the
probe counter, which must be symmetric with Allow.
Tripping, with backoff and jitter:
func (b *Breaker) tripLocked(v Verdict, reason string) {
now := b.cfg.Now()
b.consecTrips++
// Exponential backoff on repeated trips: 5s, 10s, 20s, ... capped.
d := b.cfg.Cooldown << uint(min(b.consecTrips-1, 6))
if d > b.cfg.MaxCooldown {
d = b.cfg.MaxCooldown
}
// Jitter to 50–100% so replicas don't probe in lockstep (§8).
d = time.Duration(float64(d) * (0.5 + 0.5*b.cfg.Rand()))
// Honor an explicit Retry-After.
if v.MinOpenFor > d {
d = v.MinOpenFor
}
b.openedAt = now
b.openUntil = now.Add(d)
b.probeOK = 0
b.counts.reset()
b.toLocked(StateOpen, reason)
}
func (b *Breaker) toLocked(s State, reason string) {
if b.state == s {
return
}
from := b.state
b.state = s
if s == StateClosed {
b.consecTrips = 0
b.probeOK = 0
b.counts.reset()
}
if b.cfg.OnStateChange != nil {
// Called under the lock: the hook MUST NOT block or call back into
// the breaker. Document this loudly, or dispatch to a channel.
b.cfg.OnStateChange(from, s, reason)
}
}
Hook discipline.
OnStateChangefires withb.muheld. If someone's hook does a synchronous HTTP POST to a webhook, every request to this breaker blocks behind it. Two safe options: document "must be non-blocking" and keep it (cheap: a metrics counter increment is fine), or push the event to a buffered channel drained by a goroutine. Never call the hook after unlocking without care — you'd then need to re-derive the event, and out-of-order delivery becomes possible.
And the ergonomic wrapper most callers actually use:
// Do runs op under the breaker.
func (b *Breaker) Do(ctx context.Context, op func(context.Context) error) error {
done, err := b.Allow()
if err != nil {
return err
}
err = op(ctx)
done(err)
return err
}
Why expose Allow/done at all, if Do is nicer? Because some call sites can't be
expressed as a single function — a streaming RPC whose failure only becomes known when
the stream ends, or a call whose outcome is decided by a later callback. The
Allow/done pair handles those; Do is sugar over it.
10. A sliding window that is actually cheap
The ring-bucket counter from section 5:
type bucket struct {
start time.Time
total, failure int
}
type window struct {
buckets []bucket
width time.Duration // per-bucket duration
now func() time.Time
}
func newWindow(d time.Duration, n int, now func() time.Time) *window {
return &window{
buckets: make([]bucket, n),
width: d / time.Duration(n),
now: now,
}
}
// index returns the bucket for time t, zeroing it first if it's stale.
func (w *window) index(t time.Time) *bucket {
slot := (t.UnixNano() / int64(w.width)) % int64(len(w.buckets))
bkt := &w.buckets[slot]
// Truncate t to the bucket boundary; if the bucket holds an older
// generation, it has expired — reuse it.
start := t.Truncate(w.width)
if !bkt.start.Equal(start) {
bkt.start = start
bkt.total, bkt.failure = 0, 0
}
return bkt
}
func (w *window) add(ok bool) {
b := w.index(w.now())
b.total++
if !ok {
b.failure++
}
}
// totals sums only the buckets still inside the window.
func (w *window) totals() (total, failure int) {
cutoff := w.now().Add(-w.width * time.Duration(len(w.buckets)))
for i := range w.buckets {
if w.buckets[i].start.After(cutoff) {
total += w.buckets[i].total
failure += w.buckets[i].failure
}
}
return
}
func (w *window) reset() {
for i := range w.buckets {
w.buckets[i] = bucket{}
}
}
Properties worth naming:
- Fixed memory.
nbuckets, regardless of traffic. At 10 buckets that's ~320 bytes. -
O(1) writes, O(n) reads with tiny
n.totals()runs on every failure only — you can skip it on success, since a success can never trip a breaker. -
Self-expiring. No background goroutine sweeping old data. A stale bucket is zeroed lazily the next time its slot is reused, and excluded by
totals()in the meantime. This matters: a breaker that spawns a goroutine per instance leaks badly when you have a registry of thousands. -
Resolution error of one bucket. With a 10 s / 10-bucket window the effective window drifts between 9 and 10 s. Irrelevant for this purpose.
The Truncate-based generation check is the trick that avoids needing a separate
"cleanup" pass: the bucket's own start timestamp tells you whether the data in it
belongs to this lap around the ring or a previous one.
reset() on trip is a deliberate choice: when the breaker opens, the pre-trip history is
no longer relevant — the next evaluation should be about the post-recovery world, not
polluted by the failures that caused the trip.
11. Half-open: the part everyone gets wrong
Half-open is a bounded concurrent experiment, and the concurrency is what makes it subtle. Four bugs show up over and over.
Bug 1: no cap on probes
// WRONG
if b.state == StateOpen && now.After(b.openUntil) {
b.state = StateHalfOpen
}
if b.state == StateHalfOpen {
return allow() // every caller gets through
}
At 1000 rps, the instant the cooldown expires all 1000 requests in that second are let
through as "probes". You've reproduced the thundering herd the breaker exists to prevent.
The cap (MaxProbes, often 1) is not a nicety.
Bug 2: counting probes on entry instead of on completion
If probesInFlight is decremented anywhere other than in done, or if done can be
skipped (early return, panic), the counter drifts. Drifting up means the breaker
permanently refuses probes and never recovers — a breaker stuck open forever, which is a
total outage of that dependency. Drifting down (negative) means the cap stops working.
Defenses: the sync.Once in doneFunc, a defer done(err) idiom in the wrapper, and
recover() if your call sites might panic. If you want belt-and-braces, clamp:
if b.probesInFlight < 0 { b.probesInFlight = 0 } and alert on it.
Bug 3: check-then-act races
// WRONG
if b.State() == StateHalfOpen && b.ProbesInFlight() < b.cfg.MaxProbes {
b.IncProbes() // three separate lock acquisitions
...
}
Two goroutines both read 0 < 1, both increment, both probe. The decision and the
increment must happen in one critical section — which is why Allow() does the state
check, the cap check, and the increment under a single Lock().
Bug 4: closing on one success
Covered in section 3, but concretely: with ProbeSuccesses: 1, a dependency behind a load
balancer with one healthy and nine sick instances closes the breaker as soon as a probe
lands on the healthy one — roughly a 10% chance per probe, so it happens quickly. Full
traffic returns, 90% of it fails, and you trip again. The breaker now flaps on a cycle of
cooldown + one request, which is worse than useless: it produces a saw-tooth load
pattern on a struggling dependency and a stream of state-change alerts nobody can act on.
ProbeSuccesses: 3..5 plus exponential cooldown backoff kills the flapping.
An optional refinement: gradual ramp
Rather than jumping HALF-OPEN → CLOSED (0% → 100% of traffic), some implementations ramp: 10% of traffic, then 25%, 50%, 100%, dropping back on any failure. This is gentler on a recovering dependency and is what you'd want for a large fleet. It's more state and more tuning; add it when you've measured that the binary version hurts, not before.
12. Generics in Go: why Execute[T] cannot be a method
The existing circuit-breaker.go in this repo contains:
func (cb *CircuitBreaker) Execute[T any](ctx context.Context, op func(ctx context.Context) (T, error)) (T, error)
This does not compile. Go does not permit type parameters on methods:
syntax error: method must have no type parameters
The reason is not arbitrary. Allowing it would mean a single *CircuitBreaker value could
satisfy an interface with infinitely many instantiations of Execute, which breaks Go's
implementation of interface method tables — the compiler would have to generate method
code for every T any caller might ever use, including ones in packages compiled later.
Type parameters are therefore allowed on functions and on types, never on methods.
Three workarounds, in order of usefulness:
(a) A generic free function taking the breaker — recommended
// Execute runs a typed op under b.
func Execute[T any](ctx context.Context, b *Breaker, op func(context.Context) (T, error)) (T, error) {
var zero T
done, err := b.Allow()
if err != nil {
return zero, err
}
res, err := op(ctx)
done(err)
if err != nil {
return zero, err
}
return res, nil
}
// Call site:
resp, err := breaker.Execute(ctx, cb, func(ctx context.Context) (*http.Response, error) {
return client.Do(req.WithContext(ctx))
})
Type inference makes this read exactly like a method call. This is the idiomatic Go
answer, and it's what sync.OnceValue, slices.SortFunc, etc. do.
(b) A generic wrapper type
type Typed[T any] struct{ B *Breaker }
func (t Typed[T]) Do(ctx context.Context, op func(context.Context) (T, error)) (T, error) {
return Execute(ctx, t.B, op)
}
Type parameters on types are legal, and their methods inherit them. Useful when you want to store the typed breaker in a struct field.
(c) Non-generic core + closure capture
var resp *http.Response
err := cb.Do(ctx, func(ctx context.Context) error {
var e error
resp, e = client.Do(req.WithContext(ctx))
return e
})
No generics at all. Slightly clunkier, but it's the form that works with any Go version
and composes fine. The Do method in section 9 is exactly this.
Note also that the existing file redefines max(a, b int) int while using max on
time.Duration values in toOpenLocked — under Go 1.21+ the local definition shadows
the builtin, so max(d/2, 500*time.Millisecond) is a type error. Deleting the local
max/min helpers fixes both problems at once, since 1.21 provides generic builtins.
13. Plugging it in: an http.RoundTripper breaker
The cleanest integration point for HTTP is a RoundTripper, so it composes with the
retry transport in
Retries: A Go HTTP Retry Transport.
Remember section 8: the breaker wraps the retry transport, not the other way around.
package breaker
import (
"errors"
"fmt"
"net/http"
"strconv"
"time"
)
// Transport short-circuits requests when the breaker for the target is open.
type Transport struct {
Next http.RoundTripper // usually your RetryTransport
// Key selects which breaker guards this request. Keep the key space
// CLOSED — never derive it from user input (§6).
Key func(*http.Request) string
Reg *Registry
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
b := t.Reg.Get(t.Key(req))
done, err := b.Allow()
if err != nil {
// Fail fast. No connection, no goroutine, no load on the dependency.
return nil, fmt.Errorf("%s: %w", req.URL.Host, err)
}
resp, err := t.Next.RoundTrip(req)
if err != nil {
done(err)
return nil, err
}
// A response is not automatically a success. Classify the status.
if v := verdictForStatus(resp.StatusCode, resp.Header.Get("Retry-After")); v.Countable || v.TripNow {
done(&StatusError{Code: resp.StatusCode, Verdict: v})
} else {
done(nil)
}
// Either way the caller still gets the real response to handle.
return resp, nil
}
Two things to notice.
The response is returned even when it counted as a failure. The breaker's opinion and the caller's are separate. A 500 counts against the breaker and is handed to the caller to deal with. Swallowing it would be a surprising transport.
done is called before returning, on every path. The body hasn't been read yet — an
error while reading the body later won't be seen by the breaker. That's an accepted
limitation of doing this at the RoundTripper layer; if body-read failures matter to you,
wrap resp.Body and report on Close.
The status classifier, encoding the table from section 4:
type StatusError struct {
Code int
Verdict Verdict
}
func (e *StatusError) Error() string { return fmt.Sprintf("http %d", e.Code) }
func verdictForStatus(code int, retryAfter string) Verdict {
switch {
case code == http.StatusTooManyRequests: // 429
return Verdict{Countable: true, TripNow: true, Kind: "overloaded",
MinOpenFor: parseRetryAfter(retryAfter)}
case code == http.StatusServiceUnavailable: // 503
return Verdict{Countable: true, TripNow: true, Kind: "unavailable",
MinOpenFor: parseRetryAfter(retryAfter)}
case code >= 500:
return Verdict{Countable: true, Kind: "server_error"}
default:
// 2xx, 3xx, and ALL 4xx: the dependency is healthy. Not our problem.
return Verdict{}
}
}
func parseRetryAfter(v string) time.Duration {
if v == "" {
return 0
}
if secs, err := strconv.Atoi(v); err == nil && secs >= 0 {
// Cap it: a hostile or buggy server shouldn't be able to keep us
// dark for a week with "Retry-After: 604800".
if d := time.Duration(secs) * time.Second; d < 5*time.Minute {
return d
}
return 5 * time.Minute
}
if when, err := http.ParseTime(v); err == nil {
if d := time.Until(when); d > 0 && d < 5*time.Minute {
return d
}
}
return 0
}
The cap on Retry-After is a real defense: it's a value from a remote system that you're
letting control your availability. Bound it.
And the transport-error classifier:
func DefaultClassify(err error) Verdict {
if err == nil {
return Verdict{}
}
// The caller gave up. Not evidence about the dependency (§4).
if errors.Is(err, context.Canceled) {
return Verdict{}
}
if errors.Is(err, context.DeadlineExceeded) {
return Verdict{Countable: true, Kind: "timeout"}
}
var se *StatusError
if errors.As(err, &se) {
return se.Verdict
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
return Verdict{Countable: true, Kind: "timeout"}
}
// Connection refused, reset, DNS failure, EOF mid-response.
return Verdict{Countable: true, Kind: "network"}
}
The context.Canceled case is the one that bites in production. A user closing a browser
tab cancels the request context. If that counts as a failure, then a page with a slow
render and impatient users will trip your breaker against a perfectly healthy backend.
The registry, bounded
type Registry struct {
mu sync.RWMutex
breakers map[string]*Breaker
newFn func(key string) *Breaker
}
func NewRegistry(newFn func(string) *Breaker) *Registry {
return &Registry{breakers: make(map[string]*Breaker), newFn: newFn}
}
func (r *Registry) Get(key string) *Breaker {
r.mu.RLock()
b, ok := r.breakers[key]
r.mu.RUnlock()
if ok {
return b
}
r.mu.Lock()
defer r.mu.Unlock()
if b, ok := r.breakers[key]; ok { // re-check: another goroutine may have won
return b
}
b = r.newFn(key)
r.breakers[key] = b
return b
}
// Snapshot is what your /debug/breakers handler and metrics exporter use.
func (r *Registry) Snapshot() map[string]State {
r.mu.RLock()
defer r.mu.RUnlock()
out := make(map[string]State, len(r.breakers))
for k, b := range r.breakers {
out[k] = b.State()
}
return out
}
The double-checked lock (RLock fast path, then Lock + re-check) is the standard shape. The re-check inside the write lock is mandatory — without it, two goroutines racing on a cold key create two breakers, and one of them silently accumulates state nobody reads.
On memory: this map only stays bounded because Key(req) returns values from a closed
set. If you ever key by something like a customer ID, wrap it in an LRU with a fixed cap.
14. Testing a breaker deterministically
This is where the injectable clock from section 9 pays for itself.
type fakeClock struct {
mu sync.Mutex
t time.Time
}
func (c *fakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.t
}
func (c *fakeClock) Advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.t = c.t.Add(d)
}
Now the whole state machine is testable in microseconds:
func TestTripsOnFailureRate(t *testing.T) {
clk := &fakeClock{t: time.Unix(0, 0)}
b := New(Config{
Window: 10 * time.Second, Buckets: 10,
MinVolume: 20, FailureRate: 0.5,
Cooldown: 5 * time.Second, ProbeSuccesses: 2, MaxProbes: 1,
Now: clk.Now,
Rand: func() float64 { return 1.0 }, // disable jitter
})
boom := errors.New("boom")
// 19 failures: below MinVolume, must not trip.
for i := 0; i < 19; i++ {
_ = b.Do(context.Background(), func(context.Context) error { return boom })
}
if got := b.State(); got != StateClosed {
t.Fatalf("state = %v, want closed (below min volume)", got)
}
// The 20th crosses both the volume and the rate threshold.
_ = b.Do(context.Background(), func(context.Context) error { return boom })
if got := b.State(); got != StateOpen {
t.Fatalf("state = %v, want open", got)
}
// While open, calls are rejected without invoking op.
called := false
err := b.Do(context.Background(), func(context.Context) error {
called = true
return nil
})
if !errors.Is(err, ErrOpen) || called {
t.Fatalf("err = %v, called = %v; want ErrOpen and no invocation", err, called)
}
// After the cooldown, exactly one probe is admitted.
clk.Advance(5 * time.Second)
if err := b.Do(context.Background(), func(context.Context) error { return nil }); err != nil {
t.Fatalf("probe 1: %v", err)
}
if got := b.State(); got != StateHalfOpen {
t.Fatalf("state = %v, want half-open (1 of 2 probes)", got)
}
// Second success closes it.
if err := b.Do(context.Background(), func(context.Context) error { return nil }); err != nil {
t.Fatalf("probe 2: %v", err)
}
if got := b.State(); got != StateClosed {
t.Fatalf("state = %v, want closed", got)
}
}
Tests worth writing beyond the happy path:
| Test | Guards against |
|---|---|
Probe cap under concurrency (launch 100 goroutines at the moment the cooldown expires; assert exactly MaxProbes reach op) |
Bug 1 and Bug 3 in section 11 |
Non-countable errors never trip (1000 × context.Canceled) |
The section 4 mistake that darkens healthy dependencies |
done called twice doesn't corrupt probesInFlight |
Bug 2 in section 11 |
Repeated trips grow the cooldown and stop at MaxCooldown |
Backoff arithmetic, overflow on the shift |
| Window expiry: fail 10, advance past the window, succeed 10, assert no trip | Stale buckets counted as current |
-race on a loop of concurrent Do |
Every lock-discipline bug at once |
That concurrency test is the important one, and it's easy to write:
func TestProbeCapIsRespected(t *testing.T) {
// ... set up an open breaker, advance past cooldown ...
var admitted atomic.Int32
var wg sync.WaitGroup
release := make(chan struct{})
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-release // start all goroutines at once
_ = b.Do(context.Background(), func(context.Context) error {
admitted.Add(1)
return nil
})
}()
}
close(release)
wg.Wait()
// MaxProbes=1 and ProbeSuccesses=2, so at most 2 calls ever reach op:
// one probe closes nothing, the second closes the breaker, and the rest
// were either rejected or admitted after it closed.
if n := admitted.Load(); n < 1 {
t.Fatalf("admitted %d, want at least 1", n)
}
}
Be careful what you assert here: once the breaker closes, remaining goroutines are
legitimately admitted. The invariant to test is "at most MaxProbes in flight
simultaneously while half-open", which you check with a counter incremented and
decremented inside op plus a max-watermark.
15. Observability: the four signals that matter
A breaker that silently opens converts a loud problem (errors) into a quiet one (everything is fine, we're just not calling anyone). An open breaker must be as visible as an outage, because it is one.
1. State, as a gauge. breaker_state{name, key, region} with 0/1/2. Alert on "open
for more than 60 s" — not on the transition, which is normal and noisy.
2. Rejections, as a counter. breaker_rejections_total{name, key}. This is user-
visible impact, distinct from breaker_failures_total. Rejections are requests that
never got a chance; failures are requests that tried and lost. Conflating them makes an
outage look half as bad as it is.
3. State transitions, as an event. breaker_transitions_total{from, to, reason}. The
reason label is what makes a postmortem tractable: "accelerated trip: overloaded" and
"failure rate threshold" send you to very different places. Flapping shows up here as a
high transition rate — alert on it.
4. The classifier's verdicts. breaker_verdicts_total{kind, countable}. When someone
asks "why did this trip?", this is the answer. It also catches classifier bugs: a spike in
kind=network, countable=true that turns out to be client cancellations is exactly the
section 4 failure, and you'd never find it otherwise.
Also expose a debug endpoint. Ten lines, enormous value at 3 a.m.:
func (r *Registry) Handler() http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(r.Snapshot())
}
}
And log every transition at INFO with the key, the reason, the counts that triggered it, and the cooldown chosen. Transitions are rare and each one is a real event; there is no volume concern.
16. Critique of the existing circuit-breaker.go
The file at
circuit-breaker.go
has a good feature list — classification, per-kind thresholds, hooks, registries,
region maps, health pings. It also does not compile, and has several design issues worth
naming, because each one maps to a lesson above.
Compile errors
| Issue | Fix |
|---|---|
func (cb *CircuitBreaker) Execute[T any](...) — methods cannot have type parameters |
Make it a free function Execute[T any](ctx, cb, op) (section 12a) |
Local func max(a, b int) int shadows the 1.21 builtin, but max(d/2, 500*time.Millisecond) passes Durations |
Delete the local max/min; use the builtins |
cb.o.HealthPing loop calls minDuration(cb.o.OperationTimeout, 1*time.Second) when OperationTimeout may be 0 → a 0-duration context that expires instantly |
Guard for zero before taking the min |
Design issues
Consecutive-failure counting only (section 5a). failures++ with a reset to 0 on any
success means a dependency failing 40% of the time never trips. Replace with the ring
window from section 10.
No probe cap in the OPEN→HALF-OPEN promotion. canProbeFromOpen returns a bool and
the caller then transitions and proceeds; between the state read and the in-flight
increment, unbounded goroutines can slip through (section 11, bugs 1 and 3). The check and the
increment must be in one critical section.
The half-open probe counter can leak. cb.halfOpenInFlight.Add(1) happens after a
separate cb.currentState() call, and the Add(-1) is deferred only on the path that
passed the cap. On the rejection path it decrements immediately — correct — but the
state can change between the two atomic operations, so a probe can be counted against a
state the breaker has already left. Fold it into the same mutex as everything else;
atomic here buys nothing since the surrounding operations already take the lock.
emitStateChange reports From: 0. 0 is StateClosed, so every transition claims
to originate from closed — including OPEN→HALF-OPEN. Anyone graphing transitions gets
garbage. Capture the real previous state before assigning.
Per-kind thresholds with no global backstop. shouldTripLocked returns the per-kind
check instead of the global one when a kind threshold exists. Mixed failure types can
therefore sit below every individual threshold forever (section 4). Check both, trip on either.
OnStateChange is invoked under cb.mu. Not wrong, but undocumented — a blocking
hook stalls every caller. Add the constraint to the doc comment (section 9).
The replay journal is on by default in the HTTP example, and unbounded in effect.
Replay drains everything synchronously the moment it's called, with no rate limit, and
the journaled closures may be non-idempotent HTTP calls. This is section 7's item 4 in its most
dangerous form. Either delete it or gate it behind an explicit Idempotent: true plus a
throttled drain.
pingLoop starts a goroutine per breaker with no way to know it stopped. Combined
with NewRegistry + NewRegionMap creating breakers lazily per key, a large key space
means a large number of goroutines and tickers that only Stop() cleans up — and nothing
calls Stop(). The lazy-expiring window in section 10 avoids needing a background goroutine at
all; keep health pings optional and owned by one supervisor, not one per breaker.
None of this makes the original a bad sketch — the feature inventory is genuinely the right one. But it's a good illustration of the theme of this doc: the hard part of a circuit breaker is not the three states, it's the concurrency and the classification.
Reference
Tuning cheat sheet
Start here, then adjust with data.
| Parameter | Default | Move it up when | Move it down when |
|---|---|---|---|
Window |
10 s | Traffic is bursty; you want a smoother signal | You need faster detection |
Buckets |
10 | — | Memory matters (rarely) |
MinVolume |
20 | The breaker flaps on low traffic | High-traffic call site, you want faster detection |
FailureRate |
0.5 | False trips on a noisy-but-usable dependency | The dependency is critical and partial failure is unacceptable |
Cooldown |
5 s | Recovery is slow (DB failover ≈ 30 s) | Recovery is fast, staying dark is expensive |
MaxCooldown |
60 s | Outages are typically long | You need to detect recovery quickly |
ProbeSuccesses |
3 | Breaker flaps on recovery | Fast recovery matters more than certainty |
MaxProbes |
1 | Huge traffic, one probe is too slow a signal | Many replicas (N × probes hits the dependency) |
| per-attempt timeout | p99 × 1.5 | Legitimate slow requests get killed | You're piling up on slow calls |
Two sanity checks to run before shipping:
-
Detection time. Worst case ≈
MinVolume / rps + one bucket. At 100 rps withMinVolume: 20, that's ~1.2 s. Acceptable? If detection takes longer than your caller's deadline, the breaker never helps. -
Blast radius on recovery.
replicas × MaxProbesrequests hit the dependency the instant cooldowns expire. At 200 replicas × 1 probe = 200 concurrent requests onto a service that just came back. If that's too much, jitter is doing the work — verify your jitter actually spreads them.
Failure modes of breakers themselves
Things that go wrong with the breaker, not the dependency:
| Failure mode | Symptom | Cause | Fix |
|---|---|---|---|
| Flapping | Rapid open/closed cycling, alert storm | ProbeSuccesses: 1, no cooldown backoff |
section 11 bug 4 |
| Stuck open | Dependency healthy, breaker never closes | Leaked probesInFlight, or a probe path that can't succeed |
section 11 bug 2; add a stuck-open alert |
| Never trips | Cascading failure despite a breaker | Consecutive-only counting, or MinVolume never reached |
section 5, section 6 granularity |
| Trips on healthy dependency | Outage with no server-side errors | Counting 4xx or context.Canceled |
section 4 |
| Breaker takes out the world | One bad endpoint darkens 20 good ones | Granularity too coarse | section 6 |
| OOM from the registry | Slow memory growth | Unbounded key space | section 6, section 13 |
| Goroutine leak | Growing goroutine count | Per-breaker background loops, no Stop() |
section 16 |
| Metrics lie | Postmortem is impossible | From: 0 bug, rejections counted as failures |
section 15, section 16 |
Glossary
- Breaker / circuit breaker — Stateful guard that rejects calls to a failing dependency.
- Closed — Healthy. Traffic flows. (Electrical sense.)
- Open — Tripped. Calls rejected immediately.
- Half-open — Trial state; a bounded number of probes are allowed.
- Trip — The CLOSED → OPEN transition.
- Cooldown / reset timeout / open duration — How long the breaker stays open before probing.
- Probe — A call allowed through in half-open to test recovery.
- Fail fast — Returning an error immediately without attempting the call.
- Classification — Deciding whether an error is evidence of dependency ill-health.
- Accelerated trip — Opening immediately on a strong signal (429/503) rather than at a threshold.
- Cascading failure — One component's failure propagating to its callers, and theirs.
- Retry storm — Retries multiplying load onto an already-failing dependency.
- Thundering herd — Many clients hitting a recovering dependency simultaneously.
- Minimum volume — Call count below which the failure rate is not evaluated.
- Outlier detection — Load-balancer-level per-host breaking (Envoy's term).
Exercises
-
Implement the ring window from section 10 and write a test that advances a fake clock past the window boundary. Assert that expired buckets are excluded from
totals(). -
Write the concurrency test from section 14 with a max-watermark counter inside
op. Confirm it fails if you move theprobesInFlight++outside the mutex. -
Take the existing
circuit-breaker.goand make it compile: convertExecuteto a free generic function, remove the shadowingmax/min, and fixemitStateChange'sFrom. -
Add a "slow call rate" trip condition: open when ≥50% of calls in the window exceeded
SlowThreshold, even though none of them errored. Compare with what a bulkhead would have done to the same workload (see Bulkheads). -
Simulate a 100-replica fleet: 100 breakers, a shared fake dependency that recovers at
t=30 s, and cooldowns with and without jitter. Plot requests/second hitting the dependency att=30 sin both cases. -
Argue for or against sharing breaker state across replicas via Redis. What happens when Redis is the thing that's down?
See also
- Bulkheads — limiting concurrency so one dependency can't consume all your resources
- Retries: A Go HTTP Retry Transport — the retry transport this must wrap
- Streaming, Data Movement, and How Bytes Travel — section 6 covers timeouts, retries, and idempotency for data movement
Appendix: the existing circuit-breaker.go
The breaker critiqued in section 16, in full.
// circuitbreaker.go
// A pragmatic circuit breaker with error classification, observability,
// health-check pings, manual override, replay journal (bounded), and
// shard/region-aware registries.
//
// Go 1.20+
// No external deps.
package circuitbreaker
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"sync"
"sync/atomic"
"time"
)
// ----- States & errors -----
type State int
const (
StateClosed State = iota
StateOpen
StateHalfOpen
)
func (s State) String() string {
switch s {
case StateClosed:
return "closed"
case StateOpen:
return "open"
case StateHalfOpen:
return "half-open"
default:
return "unknown"
}
}
var (
// ErrOpen indicates the breaker is open and call was short-circuited.
ErrOpen = errors.New("circuit breaker is open")
// ErrHalfOpenMaxProbes indicates the breaker is half-open and has reached
// the probe concurrency cap.
ErrHalfOpenMaxProbes = errors.New("circuit breaker half-open: max probes in flight")
)
// ----- Failure classification (types of exceptions, accelerated breaking) -----
// FailureKind is a coarse tag used for different thresholds by type.
type FailureKind string
const (
FailureTimeout FailureKind = "timeout"
FailureOverloaded FailureKind = "overloaded" // e.g., HTTP 429
FailureUnavailable FailureKind = "unavailable" // e.g., HTTP 503 / connection refused
FailureOther FailureKind = "other"
)
// FailureInfo provides metadata about an error the breaker can use
// to decide if/when/how to trip, including accelerated tripping.
type FailureInfo struct {
Kind FailureKind
Countable bool // whether this failure counts toward thresholds
TripNow bool // if true, trip immediately
MinOpenFor time.Duration // optional minimum open duration (e.g., Retry-After)
Temporary bool
Description string
}
// Classifier inspects an error and returns FailureInfo.
// If err == nil, it won't be called.
type Classifier func(err error) FailureInfo
// DefaultClassifier covers context timeouts/cancelation
func DefaultClassifier(err error) FailureInfo {
if err == nil {
return FailureInfo{}
}
if errors.Is(err, context.DeadlineExceeded) {
return FailureInfo{Kind: FailureTimeout, Countable: true, Temporary: true, Description: "deadline exceeded"}
}
if errors.Is(err, context.Canceled) {
// caller canceled usually shouldn't trip
return FailureInfo{Kind: FailureOther, Countable: false, Temporary: true, Description: "canceled"}
}
return FailureInfo{Kind: FailureOther, Countable: true, Temporary: true, Description: err.Error()}
}
// ----- Observability hooks (monitoring / tracing integration points) -----
// ResultHook carries details for each attempt (success or failure).
type ResultHook struct {
Name string
ResourceKey string
Region string
State State
Duration time.Duration
Success bool
Error error
Failure FailureInfo
Replayed bool // true if executed by the replayer after recovery
}
type StateChangeHook struct {
Name string
ResourceKey string
Region string
From State
To State
Reason string
}
// OnRequest is called after each attempt.
// OnStateChange is called when state changes.
// You can wire these into metrics/tracing (OpenTelemetry) in your app.
type OnRequestFunc func(ResultHook)
type OnStateChangeFunc func(StateChangeHook)
// ----- Options -----
type Options struct {
// Core thresholds
FailureThreshold int // (Closed) countable failures before tripping Open
FailureThresholdByKind map[FailureKind]int // optional, overrides per kind
HalfOpenSuccessesToClose int // successes needed in Half-Open to fully Close
HalfOpenMaxConcurrentProbes int // limit concurrent probes while Half-Open
OpenBaseDuration time.Duration // baseline time to stay Open before probing
// Error handling & classification
Classifier Classifier
// Timeouts: wrapper will enforce this (shorter than dependency’s own)
OperationTimeout time.Duration
// Health ping (failed-operations testing): if non-nil, breaker will ping
// while Open at PingInterval. Success promotes to Half-Open.
HealthPing func(ctx context.Context) error
PingInterval time.Duration
// Manual override: you’ll use methods ForceOpen / ForceClose / Reset.
// Observability hooks
OnRequest OnRequestFunc
OnStateChange OnStateChangeFunc
// Resource info (for differentiation & multiregion metrics)
Name string // breaker name (service/dependency)
ResourceKey string // shard/tenant/etc
Region string // region for multiregion deployments
// Journal: bounded in-memory recording for replay after recovery
EnableReplay bool
ReplayCap int // max enqueued records
}
// AdaptiveDefaults quickly tunes sensible defaults for different compute
// environments (serverless vs containers). Call before New if desired.
func (o *Options) AdaptiveDefaults(env string) {
switch env {
case "serverless":
// Cold starts / bursty traffic -> conservative opening & longer open time
if o.FailureThreshold == 0 {
o.FailureThreshold = 8
}
if o.OpenBaseDuration == 0 {
o.OpenBaseDuration = 10 * time.Second
}
if o.OperationTimeout == 0 {
o.OperationTimeout = 1500 * time.Millisecond
}
default: // containers / VMs
if o.FailureThreshold == 0 {
o.FailureThreshold = 5
}
if o.OpenBaseDuration == 0 {
o.OpenBaseDuration = 5 * time.Second
}
if o.OperationTimeout == 0 {
o.OperationTimeout = 800 * time.Millisecond
}
}
if o.HalfOpenSuccessesToClose == 0 {
o.HalfOpenSuccessesToClose = 2
}
if o.HalfOpenMaxConcurrentProbes == 0 {
o.HalfOpenMaxConcurrentProbes = 2
}
if o.PingInterval == 0 {
o.PingInterval = 1 * time.Second
}
if o.ReplayCap == 0 {
o.ReplayCap = 256
}
if o.Classifier == nil {
o.Classifier = DefaultClassifier
}
}
// ----- CircuitBreaker -----
type CircuitBreaker struct {
o Options
// mutable state guarded by mu
mu sync.Mutex
state State
failures int
failuresByKind map[FailureKind]int
halfOpenSuccess int
openUntil time.Time
nextProbeAt time.Time
manualForcedOpen bool
manualForcedClose bool
// half-open probe concurrency
halfOpenInFlight atomic.Int64
// background ping loop
stopPing chan struct{}
wg sync.WaitGroup
// journal (bounded)
journalMu sync.Mutex
journal []journalItem
}
type journalItem struct {
created time.Time
call func(context.Context) error
}
// New constructs a breaker and starts the health ping loop if configured.
func New(o Options) *CircuitBreaker {
cb := &CircuitBreaker{
o: o,
state: StateClosed,
failuresByKind: make(map[FailureKind]int),
stopPing: make(chan struct{}),
}
if cb.o.HealthPing != nil {
cb.wg.Add(1)
go cb.pingLoop()
}
return cb
}
func (cb *CircuitBreaker) Name() string { return cb.o.Name }
func (cb *CircuitBreaker) ResourceKey() string { return cb.o.ResourceKey }
func (cb *CircuitBreaker) Region() string { return cb.o.Region }
// Snapshot is useful for monitoring endpoints.
type Snapshot struct {
Name string
ResourceKey string
Region string
State State
Failures int
ByKind map[FailureKind]int
HalfOpenSuccess int
OpenUntil time.Time
}
func (cb *CircuitBreaker) Snapshot() Snapshot {
cb.mu.Lock()
defer cb.mu.Unlock()
copyMap := make(map[FailureKind]int, len(cb.failuresByKind))
for k, v := range cb.failuresByKind {
copyMap[k] = v
}
return Snapshot{
Name: cb.o.Name,
ResourceKey: cb.o.ResourceKey,
Region: cb.o.Region,
State: cb.state,
Failures: cb.failures,
ByKind: copyMap,
HalfOpenSuccess: cb.halfOpenSuccess,
OpenUntil: cb.openUntil,
}
}
// Stop terminates background loops. Call on shutdown.
func (cb *CircuitBreaker) Stop() {
if cb.o.HealthPing != nil {
close(cb.stopPing)
cb.wg.Wait()
}
}
// ----- Manual override -----
func (cb *CircuitBreaker) ForceOpen(minOpen time.Duration, reason string) {
cb.mu.Lock()
defer cb.mu.Unlock()
cb.manualForcedOpen = true
cb.manualForcedClose = false
cb.toOpenLocked(maxDuration(minOpen, cb.o.OpenBaseDuration), reason)
}
func (cb *CircuitBreaker) ForceClose(reason string) {
cb.mu.Lock()
defer cb.mu.Unlock()
cb.manualForcedClose = true
cb.manualForcedOpen = false
cb.toClosedLocked(reason)
}
func (cb *CircuitBreaker) Reset(reason string) {
cb.mu.Lock()
defer cb.mu.Unlock()
cb.manualForcedClose = false
cb.manualForcedOpen = false
cb.toClosedLocked(reason)
}
// ----- Execute wrapper (generic) -----
// Execute runs op under the breaker, enforcing a per-call timeout.
// If Open, it fails fast (optionally journaling for replay).
// In Half-Open, only a limited number of probes are allowed concurrently.
func (cb *CircuitBreaker) Execute[T any](ctx context.Context, op func(ctx context.Context) (T, error)) (T, error) {
start := time.Now()
var zero T
// Fast-path gate
state := cb.currentState()
switch state {
case StateOpen:
if cb.canProbeFromOpen() {
// promote to Half-Open optimistically
cb.transition(StateOpen, StateHalfOpen, "probe from open")
// continue below to half-open path
} else {
cb.maybeJournal(ctx, func(ctx context.Context) error {
_, err := op(ctx)
return err
})
cb.emitResult(start, StateOpen, false, ErrOpen, FailureInfo{}, false)
return zero, ErrOpen
}
}
// Wrap context with operation timeout
if cb.o.OperationTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, cb.o.OperationTimeout)
defer cancel()
}
replayed := false
// Half-open probe cap
if cb.currentState() == StateHalfOpen {
if cb.halfOpenInFlight.Add(1) > int64(max(1, cb.o.HalfOpenMaxConcurrentProbes)) {
cb.halfOpenInFlight.Add(-1)
cb.emitResult(start, StateHalfOpen, false, ErrHalfOpenMaxProbes, FailureInfo{}, false)
return zero, ErrHalfOpenMaxProbes
}
defer cb.halfOpenInFlight.Add(-1)
}
// Call
res, err := op(ctx)
if err == nil {
cb.onSuccess()
cb.emitResult(start, cb.currentState(), true, nil, FailureInfo{}, replayed)
return res, nil
}
// Classify & react
fi := cb.o.Classifier(err)
if fi.TripNow {
// accelerated trip (e.g., 429/503 with Retry-After)
cb.tripOpen(fi, fmt.Sprintf("accelerated trip: %s", fi.Kind))
} else if fi.Countable {
cb.onFailure(fi)
}
cb.emitResult(start, cb.currentState(), false, err, fi, replayed)
return zero, err
}
// ----- Success/Failure handling -----
func (cb *CircuitBreaker) onSuccess() {
cb.mu.Lock()
defer cb.mu.Unlock()
switch cb.state {
case StateClosed:
// reset backoff counters
cb.failures = 0
cb.failuresByKind = make(map[FailureKind]int)
case StateHalfOpen:
cb.halfOpenSuccess++
if cb.halfOpenSuccess >= max(1, cb.o.HalfOpenSuccessesToClose) {
cb.toClosedLocked("half-open successes threshold reached")
}
}
}
func (cb *CircuitBreaker) onFailure(fi FailureInfo) {
cb.mu.Lock()
defer cb.mu.Unlock()
switch cb.state {
case StateClosed:
if fi.Countable {
cb.failures++
cb.failuresByKind[fi.Kind]++
if cb.shouldTripLocked(fi.Kind) {
cb.toOpenLocked(cb.openDuration(fi), "failure threshold reached")
}
}
case StateHalfOpen:
// Any countable failure in Half-Open sends it back to Open
if fi.Countable {
cb.toOpenLocked(cb.openDuration(fi), "half-open failure")
}
}
}
func (cb *CircuitBreaker) tripOpen(fi FailureInfo, reason string) {
cb.mu.Lock()
defer cb.mu.Unlock()
cb.toOpenLocked(cb.openDuration(fi), reason)
}
func (cb *CircuitBreaker) shouldTripLocked(kind FailureKind) bool {
// kind-specific threshold wins, else global
if thr, ok := cb.o.FailureThresholdByKind[kind]; ok && thr > 0 {
return cb.failuresByKind[kind] >= thr
}
return cb.failures >= max(1, cb.o.FailureThreshold)
}
func (cb *CircuitBreaker) openDuration(fi FailureInfo) time.Duration {
// Use accelerated minimum if provided (e.g., Retry-After), else base.
d := cb.o.OpenBaseDuration
if fi.MinOpenFor > d {
d = fi.MinOpenFor
}
return d
}
// ----- State transitions -----
func (cb *CircuitBreaker) toOpenLocked(d time.Duration, reason string) {
now := time.Now()
cb.state = StateOpen
cb.openUntil = now.Add(d)
cb.nextProbeAt = now.Add(max(d/2, 500*time.Millisecond)) // small delay before probes
cb.halfOpenSuccess = 0
cb.failures = 0
cb.failuresByKind = make(map[FailureKind]int)
cb.emitStateChange(StateOpen, reason)
}
func (cb *CircuitBreaker) toClosedLocked(reason string) {
cb.state = StateClosed
cb.openUntil = time.Time{}
cb.nextProbeAt = time.Time{}
cb.halfOpenSuccess = 0
cb.failures = 0
cb.failuresByKind = make(map[FailureKind]int)
cb.emitStateChange(StateClosed, reason)
}
func (cb *CircuitBreaker) transition(from, to State, reason string) {
cb.mu.Lock()
defer cb.mu.Unlock()
if cb.state == from {
switch to {
case StateHalfOpen:
cb.state = StateHalfOpen
cb.halfOpenSuccess = 0
cb.emitStateChange(StateHalfOpen, reason)
case StateClosed:
cb.toClosedLocked(reason)
case StateOpen:
cb.toOpenLocked(cb.o.OpenBaseDuration, reason)
}
}
}
func (cb *CircuitBreaker) currentState() State {
cb.mu.Lock()
defer cb.mu.Unlock()
return cb.state
}
func (cb *CircuitBreaker) canProbeFromOpen() bool {
cb.mu.Lock()
defer cb.mu.Unlock()
now := time.Now()
// Manual overrides always honored
if cb.manualForcedOpen {
return false
}
if cb.manualForcedClose {
return true
}
// Wait at least until openUntil expires OR nextProbeAt if health ping succeeds
if now.Before(cb.openUntil) {
// can still probe using health ping outcome
if cb.o.HealthPing == nil {
return false
}
return now.After(cb.nextProbeAt)
}
return true
}
// ----- Health ping loop (Open -> Half-Open) -----
func (cb *CircuitBreaker) pingLoop() {
defer cb.wg.Done()
t := time.NewTicker(cb.o.PingInterval)
defer t.Stop()
for {
select {
case <-cb.stopPing:
return
case <-t.C:
if cb.currentState() != StateOpen {
continue
}
if !cb.canProbeFromOpen() {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), minDuration(cb.o.OperationTimeout, 1*time.Second))
err := cb.o.HealthPing(ctx)
cancel()
if err == nil {
cb.transition(StateOpen, StateHalfOpen, "health ping succeeded")
} else {
// stay open; push next probe a bit
cb.mu.Lock()
cb.nextProbeAt = time.Now().Add(cb.o.PingInterval)
cb.mu.Unlock()
}
}
}
}
// ----- Journaling & replay (optional, bounded, off by default) -----
func (cb *CircuitBreaker) maybeJournal(ctx context.Context, call func(context.Context) error) {
if !cb.o.EnableReplay {
return
}
cb.journalMu.Lock()
defer cb.journalMu.Unlock()
if len(cb.journal) >= max(1, cb.o.ReplayCap) {
// drop oldest
cb.journal = cb.journal[1:]
}
cb.journal = append(cb.journal, journalItem{
created: time.Now(),
call: call,
})
}
// Replay drains the journal. Invoke after you observe a transition to Closed,
// for example from a control loop in your app. It runs synchronously.
func (cb *CircuitBreaker) Replay(ctx context.Context) {
if !cb.o.EnableReplay {
return
}
items := cb.drainJournal()
for _, it := range items {
start := time.Now()
err := it.call(ctx)
cb.emitResult(start, cb.currentState(), err == nil, err, DefaultClassifier(err), true)
}
}
func (cb *CircuitBreaker) drainJournal() []journalItem {
cb.journalMu.Lock()
defer cb.journalMu.Unlock()
out := cb.journal
cb.journal = nil
return out
}
// ----- Hooks -----
func (cb *CircuitBreaker) emitResult(start time.Time, st State, ok bool, err error, fi FailureInfo, replayed bool) {
if cb.o.OnRequest == nil {
return
}
cb.o.OnRequest(ResultHook{
Name: cb.o.Name,
ResourceKey: cb.o.ResourceKey,
Region: cb.o.Region,
State: st,
Duration: time.Since(start),
Success: ok,
Error: err,
Failure: fi,
Replayed: replayed,
})
}
func (cb *CircuitBreaker) emitStateChange(to State, reason string) {
if cb.o.OnStateChange == nil {
return
}
cb.o.OnStateChange(StateChangeHook{
Name: cb.o.Name,
ResourceKey: cb.o.ResourceKey,
Region: cb.o.Region,
From: 0, // unknown to caller; they can Snapshot if needed
To: to,
Reason: reason,
})
}
// ----- Helpers -----
func maxDuration(a, b time.Duration) time.Duration {
if a > b {
return a
}
return b
}
func minDuration(a, b time.Duration) time.Duration {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// ----- Registry: resource differentiation (e.g., shard-aware) -----
type Registry struct {
mu sync.RWMutex
breakers map[string]*CircuitBreaker
newFunc func(key string) *CircuitBreaker
}
func NewRegistry(newFunc func(key string) *CircuitBreaker) *Registry {
return &Registry{breakers: make(map[string]*CircuitBreaker), newFunc: newFunc}
}
func (r *Registry) Get(key string) *CircuitBreaker {
r.mu.RLock()
b, ok := r.breakers[key]
r.mu.RUnlock()
if ok {
return b
}
r.mu.Lock()
defer r.mu.Unlock()
if b, ok := r.breakers[key]; ok {
return b
}
b = r.newFunc(key)
r.breakers[key] = b
return b
}
// ----- Region-aware convenience (multiregion deployments) -----
type RegionMap struct {
mu sync.RWMutex
registry map[string]*Registry
newReg func(region string) *Registry
}
func NewRegionMap(newReg func(region string) *Registry) *RegionMap {
return &RegionMap{registry: make(map[string]*Registry), newReg: newReg}
}
func (rm *RegionMap) For(region string) *Registry {
rm.mu.RLock()
r, ok := rm.registry[region]
rm.mu.RUnlock()
if ok {
return r
}
rm.mu.Lock()
defer rm.mu.Unlock()
if r, ok := rm.registry[region]; ok {
return r
}
r = rm.newReg(region)
rm.registry[region] = r
return r
}
// ===================================================================================
// Example usage with HTTP: classification of 429/503 (accelerated tripping),
// observability hooks, and health-check pings.
// ===================================================================================
// HTTPFailureFromResponse builds FailureInfo from an HTTP response.
// Use this in your Classifier when the dependency returns status+Retry-After.
func HTTPFailureFromResponse(resp *http.Response) FailureInfo {
if resp == nil {
return FailureInfo{Kind: FailureOther, Countable: true, Temporary: true, Description: "nil response"}
}
switch resp.StatusCode {
case http.StatusTooManyRequests: // 429
return FailureInfo{
Kind: FailureOverloaded,
Countable: true,
TripNow: true, // accelerated without waiting for threshold
MinOpenFor: retryAfterToDuration(resp.Header.Get("Retry-After")),
Temporary: true,
Description: "too many requests",
}
case http.StatusServiceUnavailable: // 503
return FailureInfo{
Kind: FailureUnavailable,
Countable: true,
TripNow: true, // often indicates a broader outage
MinOpenFor: retryAfterToDuration(resp.Header.Get("Retry-After")),
Temporary: true,
Description: "service unavailable",
}
default:
// Treat 5xx as countable, 4xx usually not (depends on your API).
if resp.StatusCode >= 500 {
return FailureInfo{
Kind: FailureOther,
Countable: true,
Temporary: true,
Description: fmt.Sprintf("http %d", resp.StatusCode),
}
}
// 4xx that are client errors typically don't count (adjust as needed).
return FailureInfo{Kind: FailureOther, Countable: false, Temporary: true, Description: fmt.Sprintf("http %d", resp.StatusCode)}
}
}
// retryAfterToDuration parses Retry-After as seconds or RFC1123 date.
func retryAfterToDuration(v string) time.Duration {
if v == "" {
return 0
}
if secs, err := strconv.Atoi(v); err == nil && secs >= 0 {
return time.Duration(secs) * time.Second
}
if when, err := http.ParseTime(v); err == nil {
d := time.Until(when)
if d < 0 {
return 0
}
return d
}
return 0
}
// Example: building a breaker for an HTTP dependency.
func ExampleHTTPBreaker() *CircuitBreaker {
opts := Options{
Name: "payments-api",
ResourceKey: "shard-12",
Region: "us-east-1",
// thresholds
FailureThreshold: 5,
FailureThresholdByKind: map[FailureKind]int{FailureTimeout: 8, FailureUnavailable: 3},
HalfOpenSuccessesToClose: 2,
HalfOpenMaxConcurrentProbes: 2,
OpenBaseDuration: 5 * time.Second,
OperationTimeout: 800 * time.Millisecond,
EnableReplay: true,
ReplayCap: 128,
// Health ping (could be a lightweight HEAD /health)
HealthPing: func(ctx context.Context) error {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://payments.example.com/health", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode == 200 {
return nil
}
return fmt.Errorf("health %d", resp.StatusCode)
},
// Observability hooks (wire to your metrics/traces)
OnRequest: func(r ResultHook) {
// increment counters, record histograms, set trace attrs, etc.
_ = r // no-op here
},
OnStateChange: func(s StateChangeHook) {
// log or emit event; useful for on-call
_ = s
},
}
// Example adaptive tweak for serverless:
// opts.AdaptiveDefaults("serverless")
// Enrich classifier with HTTP semantics (429/503 accelerated)
opts.Classifier = func(err error) FailureInfo {
// If the operation returns a *http.Response inside the error, unwrap it.
var httpErr *HTTPError
if errors.As(err, &httpErr) {
return HTTPFailureFromResponse(httpErr.Response)
}
// Fall back to baseline classification
return DefaultClassifier(err)
}
return New(opts)
}
// HTTPError is a tiny wrapper to propagate response details up to the breaker.
type HTTPError struct {
Err error
Response *http.Response
}
func (e *HTTPError) Error() string {
if e.Err != nil {
return e.Err.Error()
}
if e.Response != nil {
return fmt.Sprintf("http %d", e.Response.StatusCode)
}
return "http error"
}
func (e *HTTPError) Unwrap() error { return e.Err }
// DoWithBreaker shows how to wrap an HTTP request with the breaker.
func DoWithBreaker(ctx context.Context, cb *CircuitBreaker, req *http.Request) (*http.Response, error) {
return cb.Execute[*http.Response](ctx, func(ctx context.Context) (*http.Response, error) {
// Replace client with one that has its own (short) timeout if desired.
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
// e.g., dial timeout: counts as FailureUnavailable/Timeout by DefaultClassifier
return nil, err
}
if resp.StatusCode >= 400 {
// Turn non-2xx into an *HTTPError so the classifier can inspect it.
return nil, &HTTPError{Response: resp}
}
return resp, nil
})
}