The idea in one minute#
A circuit breaker wraps calls to a dependency and watches their outcomes. When failures cross a threshold it opens: further calls fail immediately, without touching the dependency, for a cool-down period. Then it goes half-open and lets a few trial calls through; if they succeed it closes again. This gives a struggling dependency room to recover and stops your service wasting time and resources on calls that will fail.
A bulkhead gives each dependency (or each class of work) its own limited pool of resources — goroutines, connections, threads — so one slow dependency can exhaust only its own pool, not the whole service. The name comes from ships: watertight compartments keep one breach from sinking the vessel.
An analogy#
The electrical fuse box in a house. A short circuit in the kitchen trips the kitchen’s breaker; the lights in the rest of the house stay on (bulkhead), and nobody keeps pushing current into a shorted wire (circuit breaker). After the fault is fixed, you reset it.
A picture#
stateDiagram-v2 [*] --> Closed Closed --> Open: failure rate > 50%<br/>over ≥ 20 calls Open --> HalfOpen: after cool-down (e.g. 10 s) HalfOpen --> Closed: trial calls succeed HalfOpen --> Open: a trial call fails note right of Closed: calls pass through,\noutcomes are counted note right of Open: calls fail immediately\n(or use a fallback) note right of HalfOpen: a few trial calls\nare allowed through
How it really works#
Circuit breaker settings#
| Setting | Typical value | Why |
|---|---|---|
| Window | Last 10–30 s or last 50–100 calls | Long enough to be meaningful, short enough to react |
| Minimum calls (or a full window) | 20 | Two failures out of three calls should not open it |
| Failure threshold | 50% failures (or slow calls > 1 s) | Count timeouts and slow calls, not only errors |
| Open duration | 5–30 s, ideally with jitter and growth | Long enough for recovery; jitter avoids synchronised trials |
| Half-open trials | 1–5 concurrent calls | Enough to judge, few enough not to overload |
What counts as a failure matters: timeouts and 5xx count; 4xx usually do not (the dependency is fine, the request was bad); 429 counts — the dependency is telling you to back off.
What to do when the breaker is open#
The breaker turns a slow failure into a fast one. You still need a decision (as with timeouts, 6.a):
- Return an error immediately (better than a 2-second timeout for every request).
- Use a fallback: cached data, a default, a degraded response (6.f).
- Queue the work for later (for asynchronous operations).
Where breakers live#
- In the client library (Go:
sony/gobreaker,failsafe-go; Java: Resilience4j; .NET: Polly). - In the service mesh or proxy: Envoy’s outlier detection ejects individual bad hosts from
the load-balancing pool (a per-host breaker), and Envoy’s circuit breakers cap connections,
pending requests and retries per upstream cluster (which is really a bulkhead). Istio exposes
both through
DestinationRule:
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
name: pricing
spec:
host: pricing.payments.svc.cluster.local
trafficPolicy:
connectionPool: # bulkhead
tcp: { maxConnections: 100 }
http: { http1MaxPendingRequests: 50, http2MaxRequests: 200 }
outlierDetection: # per-host circuit breaker
consecutive5xxErrors: 5
interval: 10s
baseEjectionTime: 30s
maxEjectionPercent: 50maxEjectionPercent is important: never eject every host, or the breaker becomes the outage.
Bulkheads#
Without bulkheads, all outbound calls share the same resources: the HTTP server’s goroutines, one connection pool, one worker pool. If one dependency becomes slow, requests to it pile up and consume everything (6.a), so requests that need only healthy dependencies fail too.
Bulkhead forms:
| Form | Example |
|---|---|
| Per-dependency concurrency limit | At most 20 concurrent calls to pricing, 50 to inventory (a semaphore) |
| Per-dependency connection pool | Separate http.Transport with MaxConnsPerHost per dependency |
| Per-traffic-class pools | Interactive requests and batch jobs use different worker pools or even different deployments |
| Per-tenant limits | One noisy customer cannot take all the capacity (with 7.c’s shuffle sharding) |
| Separate deployments | Critical checkout path on its own pods, separate from the admin API |
When a bulkhead is full, reject immediately (or wait only briefly) rather than queueing indefinitely.
A worked example#
A product page calls pricing (critical) and reviews (non-critical). One afternoon reviews starts timing out after 2 s.
- Without either pattern: each page request waits 2 s for reviews; 200 requests/s × 2 s = 400 goroutines stuck on reviews; the shared connection pool to everything fills; pricing calls queue behind them; the page fails entirely.
- With a bulkhead (reviews limited to 20 concurrent calls): at most 20 goroutines are stuck on reviews; the rest fail fast with “reviews unavailable”; pricing is unaffected.
- With a breaker on reviews: after 20 calls at > 50% failure it opens; for the next 10 s reviews calls cost nothing, the page renders without reviews, and every 10 s a trial call checks whether reviews is back.
Code#
A complete circuit breaker on a simulated clock, followed by a bulkhead demonstration with real goroutines.
// breaker.go — a circuit breaker (closed / open / half-open) and a bulkhead, both demonstrated.
package main
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
type state int
const (
closed state = iota
open
halfOpen
)
func (s state) String() string { return [...]string{"closed", "open", "half-open"}[s] }
var ErrOpen = errors.New("circuit open")
type Breaker struct {
Window int // judge the last Window calls
FailureRatio float64
OpenFor time.Duration
Trials int
OnChange func(from, to state)
mu sync.Mutex
st state
outcomes []bool // ring buffer of the last Window calls: true = failed
next, fails int
filled bool
openedAt time.Time
trialsInFlight int
trialsOK int
now func() time.Time
}
func (b *Breaker) set(to state) {
if b.OnChange != nil && to != b.st {
b.OnChange(b.st, to)
}
b.st = to
switch to {
case open:
b.openedAt = b.now()
case closed:
b.outcomes, b.next, b.fails, b.filled = make([]bool, b.Window), 0, 0, false
case halfOpen:
b.trialsInFlight, b.trialsOK = 0, 0
}
}
// Allow reports whether a call may proceed.
func (b *Breaker) Allow() error {
b.mu.Lock()
defer b.mu.Unlock()
switch b.st {
case open:
if b.now().Sub(b.openedAt) < b.OpenFor {
return ErrOpen
}
b.set(halfOpen)
fallthrough
case halfOpen:
if b.trialsInFlight >= b.Trials {
return ErrOpen
}
b.trialsInFlight++
}
return nil
}
// Record reports the outcome of an allowed call.
func (b *Breaker) Record(err error) {
b.mu.Lock()
defer b.mu.Unlock()
switch b.st {
case halfOpen:
if err != nil {
b.set(open)
return
}
b.trialsOK++
if b.trialsOK >= b.Trials {
b.set(closed)
}
case closed:
if b.outcomes == nil {
b.outcomes = make([]bool, b.Window)
}
if b.outcomes[b.next] {
b.fails-- // the outcome falling out of the window
}
b.outcomes[b.next] = err != nil
if err != nil {
b.fails++
}
b.next = (b.next + 1) % b.Window
if b.next == 0 {
b.filled = true
}
// Judge only a full window, so a couple of early failures cannot open it.
if b.filled && float64(b.fails)/float64(b.Window) >= b.FailureRatio {
b.set(open)
}
}
}
func breakerDemo() {
clock := time.Date(2026, 10, 24, 12, 0, 0, 0, time.UTC)
t := time.Duration(0)
b := &Breaker{Window: 20, FailureRatio: 0.5, OpenFor: 10 * time.Second, Trials: 3,
now: func() time.Time { return clock },
OnChange: func(from, to state) { fmt.Printf(" t=%5.1fs %-9s → %s\n", t.Seconds(), from, to) },
}
// The dependency fails from t=20 s to t=45 s.
dependency := func(t time.Duration) error {
if t >= 20*time.Second && t < 45*time.Second {
return errors.New("503")
}
return nil
}
var reachedDuringOutage, rejected int
fmt.Println("── circuit breaker: 10 calls/s, dependency down from 20 s to 45 s ──")
for ms := 0; ms < 70_000; ms += 100 {
t = time.Duration(ms) * time.Millisecond
clock = time.Date(2026, 10, 24, 12, 0, 0, 0, time.UTC).Add(t)
if err := b.Allow(); err != nil {
rejected++
continue
}
if t >= 20*time.Second && t < 45*time.Second {
reachedDuringOutage++
}
b.Record(dependency(t))
}
fmt.Printf(" during the 25 s outage (250 calls), %d reached the failing dependency;\n", reachedDuringOutage)
fmt.Printf(" %d failed fast without touching it\n\n", rejected)
}
func bulkheadDemo(withBulkhead bool) {
const shared = 30 // the service's total concurrent outbound calls
sharedPool := make(chan struct{}, shared)
reviewsPool := make(chan struct{}, 5) // the bulkhead: reviews may use at most 5
var pricingOK, pricingFail atomic.Int64
call := func(name string, d time.Duration) bool {
if withBulkhead && name == "reviews" {
select {
case reviewsPool <- struct{}{}:
defer func() { <-reviewsPool }()
default:
return false // bulkhead full: fail fast
}
}
select {
case sharedPool <- struct{}{}:
defer func() { <-sharedPool }()
case <-time.After(50 * time.Millisecond):
return false // could not get a slot in time
}
time.Sleep(d)
return true
}
var wg sync.WaitGroup
for i := 0; i < 300; i++ {
wg.Add(2)
go func() { defer wg.Done(); call("reviews", 500*time.Millisecond) }() // reviews is slow today
go func() {
defer wg.Done()
if call("pricing", 10*time.Millisecond) {
pricingOK.Add(1)
} else {
pricingFail.Add(1)
}
}()
time.Sleep(2 * time.Millisecond)
}
wg.Wait()
label := "no bulkhead "
if withBulkhead {
label = "with bulkhead"
}
fmt.Printf(" %s: pricing succeeded %3d, failed %3d (pricing itself was healthy)\n", label, pricingOK.Load(), pricingFail.Load())
}
func main() {
breakerDemo()
fmt.Println("── bulkhead: reviews is slow (500 ms) and shares a pool of 30 with pricing ──")
bulkheadDemo(false)
bulkheadDemo(true)
}The breaker opens one second into the outage (10 failures in a window of 20), lets a trial call through every 10 seconds — which fails and reopens it while the outage lasts — and closes on the first trial after recovery. Only a handful of the 250 calls made during the outage reach the failing dependency. The price is visible too: after the dependency recovers at 45 s, the breaker keeps failing calls until its next trial at about 51 s. A shorter open period recovers faster but probes a struggling dependency more often. In the bulkhead demo, pricing is healthy throughout, yet without a bulkhead the slow reviews calls take every shared slot and pricing fails; with the bulkhead, pricing is unaffected.
Remember this#
- A circuit breaker turns slow failures into fast ones and gives the dependency room to recover: closed → open → half-open → closed.
- Count timeouts, 5xx and 429 as failures; require a minimum number of calls; jitter the open time.
- Decide the open-state behaviour: fast error, fallback, or queue.
- Bulkheads cap the resources each dependency or traffic class can use; when full, reject fast.
- Meshes provide both (Envoy outlier detection and connection limits); never eject every host.
Try it#
- Run
breaker.go. SetWindowto 4. Would the breaker now open on noise from a healthy dependency? - Change the bulkhead size for reviews from 5 to 25. What happens to pricing, and why?
- Find a shared connection pool or worker pool in your service that serves more than one dependency. What would its bulkhead look like?
Check yourself#
- What is the half-open state for?
- Why should 4xx responses usually not count towards opening a breaker?
- Why must
maxEjectionPercentbe well below 100%? - A slow non-critical dependency is making critical requests fail. Which pattern fixes it?
Sources#
- Martin Fowler: CircuitBreaker
- Michael Nygard, Release It!, 2nd edition (Pragmatic Bookshelf, 2018) — circuit breakers and bulkheads as stability patterns
- Envoy: circuit breaking and outlier detection
- Istio: Circuit breaking task