Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Circuit Breaker Implementation in Go

14 min readintermediate
Website QA and SEO audits

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

A circuit breaker sits in front of a remote dependency and stops calling it once failures cross a threshold, failing fast instead of waiting for a timeout that is not going to succeed. It has three states: CLOSED, where calls pass through and failures are counted; OPEN, where calls are rejected immediately without touching the dependency; and HALF-OPEN, where a small number of trial calls are allowed through to discover whether recovery has happened. The reason it matters more than it first appears is that the failure it prevents is not the failed call, it is RESOURCE EXHAUSTION in the caller. Every request waiting on a five-second timeout occupies a thread, a connection and memory, so a slow dependency silently converts into a caller-side outage, and from there into a cascade through everything that depends on the caller. Failing in one millisecond instead of five seconds is what stops that chain.

Circuit Breaker in Go: what you actually reach for

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.

Go implementation

Construct one gobreaker.CircuitBreaker per dependency at package level and call breaker.Execute with a closure. Write ReadyToTrip against a failure RATIO with a minimum request count rather than a raw failure count, so a quiet period cannot trip it. Wire OnStateChange to your metrics. Do not count context cancellations as failures, the caller went away, the dependency did not.
go
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 Free

The Go-specific 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. 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.

Performance in Go, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Circuit Breaker between languages.

Real-World Applications

Circuit Breaker is used extensively in production software: web servers, database engines, operating system schedulers, and distributed systems use this pattern to coordinate work across threads and processes. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Circuit Breaker helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Circuit Breaker appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Circuit Breaker over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Circuit Breaker to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.