Circuit Breaker Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Circuit Breaker runs in O(1) time and O(1) space, in Go as in every other language.
- ✓Nothing in the standard library. github.com/sony/gobreaker is the widely-used implementation: you configure Settings with MaxRequests (the half-open trial cap), Interval (the closed-state counter reset window), Timeout (how long to stay open), a ReadyToTrip function receiving the Counts, and an OnStateChange callback.
- ✓Construct one gobreaker.CircuitBreaker per dependency at package level and call breaker.Execute with a closure.
- ✓The Go trap: ReadyToTrip is called on every failure and the naive implementation returns counts.ConsecutiveFailures greater than some number, which ignores volume entirely, three failures at three in the morning open a circuit that nothing was wrong with.
- ✓gobreaker takes a mutex per call, so at extremely high request rates it can show up in a profile; for most services the network call dwarfs it entirely.
What Circuit Breaker actually is
Circuit Breaker in Go: what you actually reach for
Go implementation
package payments
import (
"context"
"errors"
"log"
"time"
"github.com/sony/gobreaker"
)
// ONE breaker per dependency, at package level.
var breaker = gobreaker.NewCircuitBreaker(gobreaker.Settings{
Name: "payments",
MaxRequests: 3, // HALF-OPEN trial cap: never the whole backlog
Interval: 60 * time.Second, // closed-state counter reset window
Timeout: 30 * time.Second, // time spent OPEN before HALF-OPEN
ReadyToTrip: func(c gobreaker.Counts) bool {
// Ratio WITH a volume floor. ConsecutiveFailures alone trips on
// three failures during a quiet night for no reason.
if c.Requests < 20 {
return false
}
return float64(c.TotalFailures)/float64(c.Requests) >= 0.5
},
OnStateChange: func(name string, from, to gobreaker.State) {
log.Printf("breaker %s: %s -> %s", name, from, to)
},
})
func Charge(ctx context.Context, amountCents int64) (string, error) {
out, err := breaker.Execute(func() (any, error) {
id, err := chargeUpstream(ctx, amountCents)
// A cancelled caller is NOT a dependency failure.
if errors.Is(err, context.Canceled) {
return nil, nil
}
return id, err
})
if errors.Is(err, gobreaker.ErrOpenState) {
return "", errors.New("payments temporarily unavailable")
}
if err != nil {
return "", err
}
id, _ := out.(string)
return id, nil
}
func chargeUpstream(ctx context.Context, cents int64) (string, error) { return "", nil }Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Circuit Breaker?
Nothing in the standard library. github.com/sony/gobreaker is the widely-used implementation: you configure Settings with MaxRequests (the half-open trial cap), Interval (the closed-state counter reset window), Timeout (how long to stay open), a ReadyToTrip function receiving the Counts, and an OnStateChange callback. afex/hystrix-go exists but tracks a project that has been in maintenance since 2018.
What is the most common Go mistake when implementing Circuit Breaker?
ReadyToTrip is called on every failure and the naive implementation returns counts.ConsecutiveFailures greater than some number, which ignores volume entirely, three failures at three in the morning open a circuit that nothing was wrong with. The larger deployment trap mirrors Python: state is per PROCESS, so fifty pods hold fifty independent breakers and the dependency absorbs the threshold multiplied by the pod count before any of them opens. That is usually acceptable and must be a deliberate decision rather than a surprise.
How does Circuit Breaker actually perform in Go?
gobreaker takes a mutex per call, so at extremely high request rates it can show up in a profile; for most services the network call dwarfs it entirely. The saving is large in the open state: returning ErrOpenState immediately frees the goroutine, the connection from the pool and the request context, which is exactly what prevents a slow dependency from consuming the connection pool that every other handler shares. Time complexity is O(1) and space is O(1).
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.