AlgoViz

Circuit breaker

medium 30 min

A circuit breaker watches the calls to one dependency.

Video lesson · Chapter 1 of 6

Closed, open and half-open

0:00 / 4:26

Circuit breaker

1:10Reel

Theory

Read or listen first. About 2 min.

What it is

A circuit breaker is a small guard around calls to one dependency. It remembers recent results and is in one of three states: closed (calls pass), open (calls are refused at once) and half-open (a few test calls decide).

The name comes from the switch in a house that cuts the current when something is wrong. Closed means that current flows, so closed is the good state.

Why it exists

A timeout limits how long one call waits. If every call waits for its timeout, a service with 100 calls a second and a limit of 1 second still has 100 threads waiting for nothing. A breaker learns from the first failures and spares the rest the wait.

It also protects the other side. A service that is trying to start again under full load, plus retries, may never manage it. An open breaker gives it quiet, and the half-open state brings the load back carefully.

A short history

  1. 1879

    Thomas Edison describes an early form of electrical circuit breaker in a patent application.

  2. 1924

    Brown, Boveri and Cie patent a miniature circuit breaker much like those in today's houses. Hugo Stotz is named as inventor.

  3. 2012

    Hystrix, Netflix's library with a breaker around each command, matures and spreads through Netflix's teams. Its later README says it is in maintenance mode and points to Resilience4j.

  4. 2014

    Martin Fowler publishes CircuitBreaker, and credits Michael Nygard's book Release It! with making the pattern popular.

  5. 2018

    The second edition of Release It! appears.

  6. 2022

    Marc Brooker writes about breakers and sharded systems: a breaker that sees only one whole can turn a partial failure into a full one.

Words to know

Closed
Normal. Calls pass and results are recorded.
Open
Calls are refused without being sent.
Half-open
A limited number of test calls decides what comes next.
Failure threshold
How many failures, or which share, open it.
Minimum calls
How many results are needed before the share is trusted.
Open time
How long it stays open before testing. Often also called timeout, sleep window or wait duration.
Success threshold
How many test calls must succeed to close it.
Fail fast
An error now instead of the same error after a wait.
Flapping
Opening and closing again and again.

How it works

Step through the idea, or press Play.

Step 1 of 3

Closed: count. Calls pass, recent results are remembered

Understand it

Start here

The switch in the hall

Think of a house. If a toaster is faulty, a switch in the fuse box cuts the kitchen's current before the wire gets hot. The rest of the house keeps its light. The software pattern took its name and its idea from there.

Max, Noor and the toaster
FUSE BOXKITCHENHALL

In a house a person pushes the switch up. A software breaker tests by itself, and that is what the half-open state is for.

What it gives you

  • Failures do not spread by waiting
  • Threads, connections and time are spared
  • Trouble becomes visible quickly
  • A moment for a fallback
  • Recovery without a person

What it costs

  • Some calls that would have worked are refused
  • More states to test
  • Thresholds to tune
  • A wrong breaker can cause an outage by itself

States

Closed, open, half-open

Transitions

StateCallsIt remembersLeaves when
ClosedAll passRecent results. With a simple counter a success sets it to 0The threshold is reached
OpenAll refused, at onceWhen it openedThe open time has passed
Half-openA limited number pass, the rest are refusedTest resultsEnough successes, or one failure
Memory help, COH: Closed is normal, Open is fast-fail, Half-open is testing.

What callers see

Value

What it saves

Threads waiting for nothing

100 calls/s×1 s=100 threadswith an open breaker≈0100 \text{ calls/s} \times 1 \text{ s} = 100 \text{ threads} \qquad \text{with an open breaker} \approx 0
The timeout alone holds 100 threads for the whole outage. The breaker needs a handful of failures to learn, and then holds only the test calls.

One breaker per dependency

One orders machine holds three breakers, for payments, stock and reviews. The reviews breaker is open and no calls leave through it. Calls to payments and stock flow normally.
Reviews is failing. Orders does not call it, and payments and stock do not notice.

Where it helps

  • External APIs

    Payment, shipping, maps: you cannot repair them.

  • Service to service

    Between microservices, often in a shared client or a mesh.

  • Databases

    Connections that hang. Careful: for the main database there is rarely a fallback.

  • Third-party integrations

    E-mail, analytics, anything optional.

  • Expensive operations

    Reports or model calls that are slow when they fail.

Opening

How much evidence is enough

KindRuleGoodBad
Count-basedfailures in a row >= thresholdSimple, quick, no window to keepBlind to 50% failures: a success in between resets it. With many calls a chance run opens it
Sliding windowfailures / calls >= 50% in the last 60 s or 100 callsSees partial failureWith 2 calls, 1 failure is 50%. Needs a minimum
Hybridfailures > 10 and rate > 40%Robust at low and high trafficMore values to tune
Slow-call rateshare of calls slower than 2 s >= 50%Opens before the timeouts beginNeeds a good idea of slow
Most libraries use a window with a minimum number of calls.

Five in a row, by chance

0.055=3.125×10−78,640,000×3.125×10−7×0.95≈2.6 a day0.05^5 = 3.125 \times 10^{-7} \qquad 8{,}640{,}000 \times 3.125 \times 10^{-7} \times 0.95 \approx 2.6 \text{ a day}
A service with 5% random errors and 100 calls a second (8.64 million a day) produces about 2.6 runs of five failures a day. Each would open a count-based breaker although 95% of calls work.

Settings

Four numbers to set

SettingTypicalThink about
Failure threshold5 to 10 failuresOr a rate of 50% over at least 10 to 20 calls. How noisy is the service normally?
Success threshold3 to 5 successesOne lucky call is weak evidence
Open time30 to 60 sLong enough to restart, short enough for users. Grow it after each failed test, with jitter
Test calls at once1 to 5 callsMust allow enough successes, or it can never close

Defaults you meet

LibraryOpens whenOpen timeHalf-open
Hystrix50% errors with at least 20 requests in the rolling window5 sOne test request
Resilience4j50% of the last 100 calls, with at least 100 calls known. Slow calls can count too60 s10 calls, then the same rate rule
A simple breaker5 failures in a row30 sUp to 3 calls, 3 successes close it
From the projects' documentation on the day of writing. Check your version. With a minimum of 100 calls a breaker on a quiet route may never open.

Failures

What counts

Counts as a failure

  • Timeouts
  • Connection refused or reset
  • 5xx answers
  • Calls slower than a limit
  • 429, if you want to back off as a whole

Does not count

  • 400, 404, 409, 422: the service is alive and answers
  • A business answer such as card declined
  • Your own cancelled calls
  • A refusal by this breaker or by a bulkhead
  • A bug in your own code around the call

One result arrives

A slow call from the time before may come back during half-open. It says nothing about now, so it must not open or close anything.

Scope

How big is the thing behind it?

A breaker sees one number. If behind it are ten shards and one is down, about 10% of calls fail. With a low threshold it opens and takes nine healthy shards away. With a high one it never helps the users of the tenth.

Scope of one breakerGoodRisk
All dependencies togetherNothingReviews fail, payments are refused
One per serviceThe usual startHides a broken shard or host
One per endpointA slow report does not block simple readsLess traffic per breaker, slower to learn
One per host or shardFits partial failureMany breakers. Load balancers call this outlier ejection
One per customerOne customer's bad data blocks only themVery many, with little traffic each

Every instance learns by itself

Users reach a balancer and three shop machines. Each machine has its own breaker for payments, which is outside our system. The breaker of shop 3 is already open, so no arrow leaves it. The others are still closed.
Each has its own breaker and opens a little earlier or later. That is normal, and needs no shared state.

The price of learning separately

40 instances×5 failures=200 failed calls until all are open40 \text{ instances} \times 5 \text{ failures} = 200 \text{ failed calls until all are open}
And in half-open up to 40 x 3 = 120 test calls. A shared breaker would need fewer, but it adds a network call and a new dependency to each call. Local is usually better.

Together

With timeouts, retries and fallbacks

  1. 1

    Timeout inside

    Without a timeout a hanging call never becomes a failure, and the breaker never learns.

  2. 2

    Breaker around each attempt

    Retries ask the breaker each time, and stop at once when it refuses.

  3. 3

    Fallback outside

    A refusal needs an answer: cached data, a default, a queue, an honest error. See fallbacks.

  4. 4

    Bulkhead beside it

    Until the breaker opens, a separate pool limits the damage. See resilience.

Do I need a breaker here?

A breaker without a fallback still saves threads. But if every request needs the call anyway, the user sees an error either way.

Operate

Best practices

  1. 1

    Combine with fallbacks

    Decide what is returned while it is open.

  2. 2

    Monitor the state

    Count changes of state, time open, refused calls. Alert when it opens, and when it flaps.

  3. 3

    Tune thresholds

    From real error rates, traffic and the service's targets. Begin in an observe-only mode: record when it would have opened.

  4. 4

    Separate circuits

    One per service or smaller. Never one for several services.

  5. 5

    A manual switch

    Force it open before planned maintenance, or closed if it is wrong. Show who did it.

  6. 6

    Test it

    Make the dependency fail in a drill and watch all three states.

When it does not behave

You seeLikely causeTry
Never opens in an outageNo timeout, or the minimum of calls is never reachedTimeout, lower minimum, longer window
Opens on ordinary daysCounts 4xx, or a run by chanceFix what counts, use a rate
FlapsOpen time too short, one test call is enoughMore successes, growing open time
Never closesTests allowed < successes needed, or no traffic to test withFix the numbers, send a health probe
Everything refused, service is fineScope too bigSplit per endpoint, host or shard

Summary

The whole topic in one minute.

Closed, open, half-open. Open on enough evidence, refuse at once, test with a few calls, close on success, open again on the first failed test.

One breaker per thing that fails by itself. Count timeouts, connection errors and 5xx, not the caller's own mistakes. Pair it with a fallback, a timeout and an alert. Try it out before you need it.

  • Closed is good: current flows.
  • Open on a failure rate with a minimum of calls. Refuse at once.
  • Half-open: a few tests, one failure opens again.
  • Count the service's faults, not the caller's, and ignore results from an older state.
  • Small scope, a timeout inside, a fallback outside, an alert beside it.

Sources