Level: AdvancedGo Lang

Go Circuit Breaker Pattern Explained with Code

9 min read
Go Circuit Breaker featured image: closed, open and half-open state cards

A Go circuit breaker stops your program from calling a service that is already failing. In this post, you will learn the three states of a breaker and why it protects both sides. Then we will build one from scratch with a mutex and a replaceable clock.

This lesson builds on Go retry with backoff and jitter. We also use the Go sync package and Go error handling. So it helps to read those first.

What Is a Go Circuit Breaker?

In a house, a circuit breaker cuts the power when too much current flows. It protects the wires from a fire, because less current can flow. Then, after you fix the problem, you flip the switch back on. A Go circuit breaker works in a very similar way for function calls, so the idea is easy to remember.

Your program wraps a risky call, such as a payment API, inside the breaker. While the calls work, the breaker stays out of the way. When too many calls fail in a row, the breaker “opens”. From then on, new calls fail at once, and the payment API is not touched.

After a cooldown, the breaker lets one trial call through. When that call works, the breaker closes again. Otherwise, it opens for another cooldown. Because of this loop, a Go circuit breaker heals itself without any human help.

Why a Go Circuit Breaker Matters

Also, retries help with short problems. However, a service that is down for ten minutes needs a different answer. That answer is a Go circuit breaker. When every request waits for a timeout, your own service slows down and runs out of resources. Here is what a Go circuit breaker gives you.

  • Fast failures: callers get an answer in microseconds, not after a long timeout.
  • Protected resources: goroutines and connections are not stuck on a dead service.
  • Time to recover: the failing service gets quiet, so it can restart.
  • Clear signals: you can log and graph every time the breaker opens.

Without a breaker, one slow dependency can bring down a whole chain of services. This effect is called a cascading failure, and it is hard to stop later. As a result, many teams treat a breaker as basic equipment for any call across the network.

How a Go Circuit Breaker Works

A breaker is a small state machine with three states. Then it moves between them based on the results of calls.

Go Circuit Breaker diagram showing the closed, open and half-open states and how a call moves between them
The breaker starts closed. After enough failures it opens. After a cooldown it becomes half-open, and one trial call decides whether it closes or opens again.

The Closed State

While the breaker is closed, every call goes through. Meanwhile, the breaker counts failures in a row. Then a success resets the count to zero. When the count reaches the limit, the breaker moves to open.

The Open State

In the open state, calls fail at once with a special error, and the real function is not called. The breaker also remembers the time when it opened, so it knows when the cooldown is over.

The Half-Open State

After the cooldown, the next call becomes a trial. When it works, the breaker closes. When it fails, the breaker opens again, and then the cooldown restarts. So the half-open state is a careful test, not a full return to normal.

Go Circuit Breaker vs Retry

People often mix up these two tools, but they solve different problems. Still, they work well together. The table below compares them.

FeatureRetry with backoffCircuit breaker
GoalGet a success after a short glitchStop calling a service that is down
Acts onOne callMany calls over time
Helps whenFailure is briefFailure lasts a while
Risk if missingVisible errors from small glitchesSlow, stuck callers
MemoryNone between callsCounts failures and remembers state
Go Circuit Breaker diagram comparing a retry with a circuit breaker
A retry loop repeats one call with growing waits, while a breaker watches many calls and blocks them when the failure count is too high.

In practice, you put the retry inside the breaker or the breaker around the retry, depending on your needs. A common choice is to let the breaker see the final result of the retry helper. That way, one bad call counts as a single failure, so the count stays fair.

Go Circuit Breaker Hands-On: Build a Breaker

Now let’s write the code. We keep it small, so every line is easy to follow, and we use only the standard library.

Step 1: The State and the Struct

First, we define the three states with iota, which numbers them for us. Next, the Breaker struct holds a mutex, the current state, the failure count and a clock function. The clock is replaceable, so a test can move time forward without sleeping.

var ErrOpen = errors.New("circuit open")

type State int

const (
	Closed State = iota
	Open
	HalfOpen
)

func (s State) String() string { return [...]string{"closed", "open", "half-open"}[s] }

type Breaker struct {
	mu          sync.Mutex
	state       State
	failures    int
	maxFailures int
	cooldown    time.Duration
	openedAt    time.Time
	now         func() time.Time
}

func NewBreaker(maxFailures int, cooldown time.Duration) *Breaker {
	return &Breaker{maxFailures: maxFailures, cooldown: cooldown, now: time.Now}
}

Step 2: The Do Method

Then comes the main method. It checks the state under the lock and releases it while the real function runs. Then it takes the lock again to record the result. This order matters, because holding a lock during a slow call would block every other caller.

func (b *Breaker) Do(fn func() error) error {
	b.mu.Lock()
	if b.state == Open {
		if b.now().Sub(b.openedAt) < b.cooldown {
			b.mu.Unlock()
			return ErrOpen
		}
		b.state = HalfOpen
	}
	b.mu.Unlock()

	err := fn()

	b.mu.Lock()
	defer b.mu.Unlock()
	if err != nil {
		b.failures++
		if b.state == HalfOpen || b.failures >= b.maxFailures {
			b.state = Open
			b.openedAt = b.now()
		}
		return err
	}
	b.failures = 0
	b.state = Closed
	return nil
}

Let’s look at the key lines. When the state is open and the cooldown has not passed, we return ErrOpen and never call fn. After the cooldown, we switch to half-open and let the call run. On a failure in half-open, the breaker opens again at once. Also, on a success, it resets the count and closes.

Step 3: Try It with a Fake Clock

Finally, we replace the clock with a variable, because a real wait would slow the demo. We call a failing function five times, because the limit is three. Then we move the clock forward by 11 seconds and call a working function.

clock := time.Date(2026, 5, 31, 9, 0, 0, 0, time.UTC)
br := NewBreaker(3, 10*time.Second)
br.now = func() time.Time { return clock }

for i := 1; i <= 5; i++ {
	err := br.Do(func() error { return errors.New("payment API down") })
	fmt.Printf("call %d: err=%v state=%s\n", i, err, br.State())
}

clock = clock.Add(11 * time.Second)
err := br.Do(func() error { return nil })
fmt.Printf("after cooldown: err=%v state=%s\n", err, br.State())

Here is the real output from our run.

call 1: err=payment API down state=closed
call 2: err=payment API down state=closed
call 3: err=payment API down state=open
call 4: err=circuit open state=open
call 5: err=circuit open state=open
after cooldown: err=<nil> state=closed

As you can see, the first two failures keep the breaker closed, because the limit is three. Then the third failure opens it. Calls 4 and 5 fail at once with circuit open. Meanwhile, the payment function is never run. Finally, after the cooldown, one working call closes the breaker. This is the full life cycle of a Go circuit breaker.

Go Circuit Breaker Settings

A breaker has only a few settings, yet each one changes how it behaves. The table below explains them and gives a starting value.

SettingWhat it controlsStarting value
Failure limitFailures in a row before it opens5
CooldownHow long it stays open10 to 30 seconds
Trial callsCalls allowed in half-open1
Counted errorsWhich errors count as failuresTimeouts and 5xx only

Start with these values, then adjust them from real data. A short cooldown makes the breaker test the service often, while a long cooldown keeps users waiting for recovery. Likewise, a low failure limit reacts fast but may open on a short glitch. So watch your metrics for a week and tune from there.

What Callers Should Do When the Breaker Is Open

Returning ErrOpen is only half of the job, because users never read error codes. The caller must also decide what the user sees. For example, a product page can show cached prices with a small note. A checkout page, on the other hand, may show a clear message and ask the user to try again soon. In both cases, the page loads fast, because no one waits for a dead service.

Common Mistakes with a Go Circuit Breaker

  • Holding the lock during the call: every caller then waits in line. So release the mutex before you run fn.
  • Counting all errors: a 404 is not a sign of a sick service. Therefore, count only errors that mean the service is unhealthy.
  • No cooldown: a breaker that reopens at once never lets the service rest. Instead, wait for a real pause.
  • One breaker for everything: a failure in one service should not block another. So make one breaker for each dependency.
  • Hiding the open state: users need a clear message. For that reason, return a distinct error such as ErrOpen and handle it.

Best Practices for a Go Circuit Breaker

  • Use one breaker for each dependency, because each service fails on its own schedule.
  • Pick a small failure limit, usually between three and ten.
  • Allow only one trial call in half-open, since many trials can overload a service that is just waking up.
  • Log every state change, which makes outages easy to trace.
  • Offer a fallback, such as a cached value or a friendly message.
  • Test with a fake clock, because sleeping in tests is slow.

Practice Task

To practise the Go circuit breaker, add a successThreshold field. The breaker should need two good calls in half-open before it closes.

Hint: add a counter for successes in the half-open state. Then reset it when the breaker opens again. After that, run the demo and check the state after each call.

Official Resources

These pages describe the packages and ideas used in this lesson.

Quick Recap

  • A Go circuit breaker blocks calls to a service that keeps failing.
  • It has three states: closed, open and half-open.
  • Open means calls fail at once, and half-open allows one trial.
  • A mutex protects the state, but the lock is released during the real call.
  • Use one breaker for each dependency, and count only real service errors.
  • A fake clock makes the breaker easy to test.

What’s Next?

By now, you can protect your service from a failing dependency. However, APIs also need to return long lists without sending everything at once. So next, we will cover pagination for REST APIs.

Next up: Go pagination for REST APIs