Apply circuit breakers and bulkheads
Apply circuit breakers and bulkheads
A circuit breaker stops sending calls to a failing dependency for a recovery interval. Closed allows calls; open rejects them; half-open permits limited probes before deciding whether to close again. A bulkhead limits the resources one dependency may occupy so its failure cannot consume every worker. These solve different problems and may be combined.
package main
import ( "fmt" "time")
type Breaker struct { failures int until time.Time}
func (b *Breaker) allow(now time.Time) bool { return b.failures < 2 || !now.Before(b.until) }func (b *Breaker) record(now time.Time, ok bool) { if ok { b.failures = 0 return } b.failures++ if b.failures >= 2 { b.until = now.Add(time.Second) }}func main() { b := Breaker{} now := time.Unix(100, 0) b.record(now, false) b.record(now, false) fmt.Println(b.allow(now)) fmt.Println(b.allow(now.Add(time.Second))) b.record(now.Add(time.Second), true) fmt.Println(b.allow(now.Add(time.Second)))}This sequential state model opens after two failures. After the interval, a probe may succeed and reset it. It is not a concurrent breaker: real implementations must serialize transitions, admit only a bounded number of half-open probes, classify failures and protect against late results from older states.
Expected output:
falsetruetrueLimit concurrent capacity
package main
import ( "fmt")
func acquire(slots chan struct{}) bool { select { case slots <- struct{}{}: return true default: return false }}func main() { a := make(chan struct{}, 1) b := make(chan struct{}, 1) fmt.Println(acquire(a), acquire(a), acquire(b)) <-a fmt.Println(acquire(a)) <-a <-b}A full A pool rejects work while B retains capacity. Always release a successfully acquired slot (usually defer after acquisition). This is admission control, not a queue or fairness guarantee. If waiting is required, use bounded waiting with context and monitor saturation.
Expected output:
true false truetrueTry it locally
Create a two-slot channel; attempt three nonblocking acquisitions and print the booleans. Release exactly the successful acquisitions.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distributed services 04: Apply circuit breakers and bulkheads
Check the lesson objective before moving on.
What should an open circuit normally do?
What does a bulkhead isolate?