Circuit Breaker
"Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all." — Martin Fowler, CircuitBreaker, martinfowler.com bliki (6 March 2014)
Summary: A circuit breaker watches the outcomes of calls to one dependency and, when too many fail or crawl, stops making the call for a while: it fails fast, answers from a fallback, and sends only a few probes until the dependency looks healthy again. Focus: The three states (closed, open, half-open), count-based and time-based sliding windows, failure-rate and slow-call-rate thresholds and the minimum number of calls, open (wait) duration and probes, what counts as a failure, fallbacks, per-dependency granularity, how it composes with timeouts, retries and bulkheads, metrics and alerts, local vs shared (Redis) state, breakers in Envoy, Istio, NGINX and HAProxy, libraries (Resilience4j, Hystrix, Polly, gobreaker, failsafe-go), anti-patterns, and testing with fake clocks and fault injection. Learning goal: For any outbound dependency, decide whether a breaker belongs there, choose its window, thresholds, open duration and fallback with numbers, wire it into the timeout and retry stack in the right order, make its state changes visible, and prove it with a fake-clock test and a fault-injection run.
This chapter sits in the Resilience group, after Cascading Failures (why one slow service takes down its callers) and Timeouts, Retries & Jitter (the two tools the breaker wraps), and before Bulkheads & Graceful Degradation (the isolation that keeps a failing dependency from using every thread) and Load Shedding (what a server does for itself when it is overloaded). The service-level view of the same toolkit is in Service Communication. Proxy-level health checking is in Load Balancing and Service Mesh & the Sidecar Pattern. This page owns the breaker itself: the state machine, the windows, the numbers, the placement, the products and the code.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why a failing dependency needs a switch | Why it exists |
| Nygard, Fowler, Hystrix, Resilience4j | Where it comes from |
| Closed, open, half-open | States |
| Count-based vs time-based windows | Sliding windows |
| Failure rate, slow-call rate, minimum number of calls | Thresholds |
| Open duration, probes, trial requests | Open duration and probes |
| What should trip it and what should not | What counts as a failure |
| Static default, cached value, degraded response, fail fast | Fallbacks |
| One breaker per dependency or per endpoint | Granularity |
| Order of breaker, retry, timeout, bulkhead | Composition |
| Alerts and dashboards | Metrics and alerting |
| Shared state in Redis vs one breaker per instance | Distributed breakers |
| Envoy, Istio, NGINX, HAProxy | Breakers at the proxy and the mesh |
| Resilience4j, Hystrix, Polly, gobreaker, failsafe-go | Libraries |
| What goes wrong | Anti-patterns |
| Fake clocks and fault injection | Testing |
| Exact knobs and error names | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Which settings for which dependency | Choosing |
| Monolith to distributed system | In architecture |
| Numbers from a replayed outage | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three states.
| State | What happens to a call | What the breaker records | How it leaves the state |
|---|---|---|---|
| Closed | Runs normally | Every outcome goes into the sliding window | Failure rate or slow-call rate reaches its threshold once the minimum number of calls is recorded: closed to open |
| Open | Rejected at once, the dependency is not called | Rejections are counted, nothing else | The open (wait) duration elapses: open to half-open |
| Half-open | A small number of probe (trial) calls run, the rest are rejected | Only the probes | Probes succeed: back to closed with an empty window. Probes fail: back to open and the wait restarts |
The knobs, with the defaults of the products you will meet.
| Knob | Resilience4j | Hystrix | Polly (.NET) | sony/gobreaker v2 | failsafe-go |
|---|---|---|---|---|---|
| Window type | slidingWindowType COUNT_BASED (default) or TIME_BASED | Rolling stats window | SamplingDuration (time) | Interval (+ BucketPeriod for a rolling window) | Count based or time based |
| Window size | slidingWindowSize 100 | Rolling window | SamplingDuration | Interval | WithFailureThresholdRatio(3, 5), WithFailureRateThreshold(.2, 5, time.Minute) |
| Minimum calls | minimumNumberOfCalls 100 | circuitBreakerRequestVolumeThreshold | MinimumThroughput | Inside your ReadyToTrip | Second argument of WithFailureRateThreshold |
| Failure threshold | failureRateThreshold 50 (%) | circuitBreakerErrorThresholdPercentage | FailureRatio | ReadyToTrip(Counts) bool; default: more than 5 consecutive failures | WithFailureThreshold(5) |
| Slow-call rate | slowCallRateThreshold 100 (%), slowCallDurationThreshold 60000 ms | Via timeout counting as failure | Via a timeout strategy | Not built in | Not built in |
| Open duration | waitDurationInOpenState 60000 ms | circuitBreakerSleepWindowInMilliseconds | BreakDuration (or BreakDurationGenerator) | Timeout (0 means 60 s) | WithDelay (default 1 minute) |
| Probes | permittedNumberOfCallsInHalfOpenState 10 | The next single request | The next execution after BreakDuration | MaxRequests (0 means 1) | Trial executions; WithSuccessThreshold |
| State-change hook | onStateTransition | HystrixCommand metrics stream | OnOpened, OnClosed, OnHalfOpened | OnStateChange | OnStateChanged |
The order of the policy stack (outside to inside), as this chapter recommends it.
| Layer | Question it answers | Why this position |
|---|---|---|
| Fallback | What does the user get if everything below failed or was rejected? | It sees both real failures and breaker rejections |
| Circuit breaker | Should we even try this dependency right now? | It counts one outcome per logical call, after retries gave up |
| Retry with backoff, jitter and a budget | Is this failure transient? | It must stop on a breaker rejection and never retry it |
| Timeout / deadline | How long may one attempt take? | A call that never returns never reaches the breaker as a failure |
| Bulkhead | How many calls may be in flight to this dependency? | It keeps a slow dependency from consuming every thread |
Numbers worth remembering.
| Number | Meaning |
|---|---|
| 9 of 9 failed, 10 required | Resilience4j: "If only 9 calls have been evaluated the CircuitBreaker will not trip open even if all 9 calls have failed." The minimum number of calls prevents a verdict from a tiny sample |
| 100 calls, 100 rps, 1 s | The default Resilience4j window fills in about one second at 100 requests per second |
| 100 calls, 2 rps, 50 s | The same defaults need about 50 seconds to judge a low-traffic endpoint: size the window to the traffic |
| 100 rps x 3 attempts x 2 s | An unprotected caller can hold about 600 threads busy (rate x time, Little's law; our arithmetic) |
| 1 failure, 10 s | NGINX max_fails and fail_timeout defaults are 1 and 10 s: the load-balancer cousin of a breaker |
The picture is the state machine. Everything else on this page is a decision about one arrow: what makes it fire, how long it waits, and what the caller gets while it is waiting.
Why it exists
When a dependency slows down, its callers do not fail quickly: they wait. Every waiting request holds a thread, a connection, memory and a place in a queue. Retries make it worse because each user request now becomes several slow attempts. Fowler describes exactly this: "if you have many callers on a unresponsive supplier, then you can run out of critical resources leading to cascading failures across multiple systems". The breaker is the switch that turns a slow failure (every call waits for the full timeout) into a fast one (every call returns in microseconds) and, at the same time, gives the struggling dependency room to recover.
| Without a breaker | With a breaker |
|---|---|
| Every call waits for the full timeout, then retries | After the trip, calls fail in microseconds |
| Threads and connections fill with doomed calls | Resources stay free for work that can succeed |
| The dependency receives the full load while it is down | The dependency receives almost nothing, then a few probes |
| Recovery is slow: a backlog of retries arrives with the first healthy second | Recovery is staged: probes first, then traffic |
| The caller fails whenever the dependency fails | The caller can answer from a fallback |
| Nobody is told until users complain | Every state change is an event you can alert on |
The analogy we reuse on this page: the fuse box and the restaurant that is out of an ingredient. A fuse trips when current is too high so the wire does not burn; you do not keep switching the kettle on. A restaurant that learns the fish supplier is not delivering takes fish off the menu and offers something else instead of letting every table wait forty minutes for a dish that will not come; once an hour the waiter asks the kitchen "any fish yet?" (the probe), and puts it back on the menu when the answer is yes. The trip is the fuse; the menu card is the fallback; the hourly question is half-open.
Three common misunderstandings, up front
- "A circuit breaker retries for me." It does not. Polly's documentation says the strategy "rethrows all exceptions" and "does not manage retries". It decides whether a call may start; retries are a different policy placed next to it.
- "A breaker protects my service from overload." It protects the caller from a failing dependency. Protecting a server from its own callers is Load Shedding and Rate Limiting.
- "Open means the dependency is down." Open means this caller decided to stop trying. The dependency may have recovered a second ago, or may be healthy for other callers or other endpoints. The breaker is an opinion held by one process (or one shared state), not a health fact.
Where it comes from
Nygard, Release It!. Fowler credits the pattern's popularity to Michael Nygard: "In his excellent book Release It, Michael Nygard popularized the Circuit Breaker pattern to prevent this kind of catastrophic cascade." The Pragmatic Bookshelf page for the second edition (January 2018) lists Circuit Breaker among the "Stability Patterns", next to Timeouts, Bulkheads, Steady State, Fail Fast, Let It Crash, Handshaking, Shed Load and Create Back Pressure. The first edition appeared in 2007 (inference from the "second edition" label; the publisher page we saved does not give the year).
Fowler's bliki, 2014. Fowler's post (6 March 2014) is the canonical short description: wrap a protected call in an object that monitors failures; once failures reach a threshold the breaker trips; add a reset timeout and a "half open" state "ready to make a real call as trial to see if the problem is fixed"; log every state change; let operations trip and reset by hand; and not all errors should trip the circuit.
Hystrix, then retirement. Netflix open-sourced Hystrix (command pattern, rolling-window circuit breaker, per-dependency thread pools or semaphores, fallbacks). Its README now says: "Hystrix is no longer in active development, and is currently in maintenance mode." Netflix's reasons: "our focus has shifted towards more adaptive implementations that react to an application's real time performance rather than pre-configured settings", and "to leverage open and active projects like resilience4j for new internal projects". The version at that point is 1.5.18.
Resilience4j. The JVM successor: a state machine with CLOSED, OPEN and HALF_OPEN plus the special states METRICS_ONLY, DISABLED and FORCED_OPEN; a count-based or time-based sliding window; a slow-call rate beside the failure rate. Its documentation (v2.2.0) compares itself with Hystrix in a dedicated page.
The cloud and mesh era. Envoy enforces circuit-breaking limits "at the network level as opposed to having to configure and code each application independently", and adds outlier detection that ejects individual hosts. Istio exposes both through DestinationRule. Polly (.NET) rebuilt its breaker around failure ratio, sampling duration and minimum throughput.
A dissent worth knowing. The Amazon Builders' Library (Marc Brooker, Timeouts, retries and backoff with jitter): circuit breakers "introduce modal behavior into systems that can be difficult to test, and can introduce significant addition time to recovery"; AWS prefers "limiting retries locally using a token bucket". That is a trade-off statement, not a ban: a breaker is a second mode your system can be in, and every mode needs a test.
Year Idea What changed in practice
1 2007 Release It! (Nygard), first edition Circuit Breaker named as a stability pattern (inference on the year)
2 - Hystrix open-sourced by Netflix Breaker + bulkhead + fallback as a library, per-dependency pools
3 2014 Fowler bliki CircuitBreaker Three states, monitor state changes, trip/reset by hand
4 2018 Release It! second edition Stability patterns for microservices and cloud
5 - Hystrix enters maintenance mode Netflix recommends resilience4j; adaptive limits preferred
6 - Resilience4j Sliding windows, slow-call rate, functional decorators
7 - Envoy / Istio outlier detection Breaking moves out of the app into the proxy
8 - Polly v8 resilience strategies FailureRatio, SamplingDuration, MinimumThroughputThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products provide it, and the fix.
The three states Must-know
In plain words: closed means "calls flow", open means "calls are refused without trying", half-open means "a few calls are allowed through to test the water".
Common misunderstanding: "Half-open means the breaker is half way between the two." It is a distinct state with its own rule: only a bounded number of probe calls are admitted and the rest are rejected exactly as in open. Fowler: the half-open state means "the circuit is ready to make a real call as trial to see if the problem is fixed".
Definition: a finite state machine with transitions closed to open (threshold reached), open to half-open (wait elapsed), half-open to closed (probes succeeded) and half-open to open (a probe failed). Resilience4j adds METRICS_ONLY (record everything, never open), DISABLED (always allow) and FORCED_OPEN (always deny) for operators and experiments.
t Event State Caller sees
1 0 s 50 calls, 29 failed in the window closed>open last call fails normally
2 0-30 s every call rejected locally open ErrOpen in microseconds, fallback runs
3 30 s first call after the wait arrives half-open this call is probe 1 of 3
4 30 s probes 2 and 3 are admitted, call 4 is rejected half-open probes run, extra callers rejected
5 31 s three probes succeeded half-open>closed window is empty, traffic flowsReal scenarios: a payment provider returns 503 for ten minutes (open, fallback "pay on delivery"); a recommendation service answers in 6 s instead of 80 ms (slow-call rate opens the breaker before anything errors); a deploy of the dependency restarts it (open, then half-open succeeds a minute later); an operator trips the breaker by hand before a database failover (Fowler: "Operations staff should be able to trip or reset breakers").
| Product | States | Special states |
|---|---|---|
| Resilience4j | CLOSED, OPEN, HALF_OPEN | METRICS_ONLY, DISABLED, FORCED_OPEN |
| Hystrix | CLOSED, OPEN, HALF-OPEN (one request) | None documented on the "How it Works" page |
| Polly | Closed, Open, HalfOpen | Isolated (manual hold-open via CircuitBreakerManualControl) |
| sony/gobreaker | StateClosed, StateOpen, StateHalfOpen | None |
| failsafe-go | Closed, Open, HalfOpen | breaker.Open(), HalfOpen(), Close() for manual use |
Fix / how to use it: keep the state machine tiny and the transition code under one lock; never run the protected call inside that lock (Resilience4j does the same: "the function call itself is not part of the critical section"). Go code is in Go, Laravel code in Laravel.
Sliding windows: count-based and time-based Must-know
In plain words: the breaker needs a memory of recent calls to judge "too many failed". A count-based window remembers the last N calls; a time-based window remembers the last N seconds.
Common misunderstanding: "A bigger window is always safer." A big count-based window on a quiet endpoint can take minutes to fill (100 calls at 2 rps is 50 s), and a big time-based window keeps reacting to failures that are long over. Windows trade detection speed against noise.
Definition: Resilience4j implements the count-based window as "a circular array of N measurements" and the time-based window as "a circular array of N partial aggregations (buckets)", one per epoch second. Both keep a running total and use "Subtract-on-Evict": when the oldest measurement leaves, its values are subtracted, so reading a snapshot is O(1) whatever the window size and memory is O(N). A partial aggregation is three integers (failed, slow, total) plus the total duration. gobreaker's rolling window (BucketPeriod) and failsafe-go's time-based breaker (ten time slices per period) use the same idea.
Window Holds Judged when Weak spot
1 count-based, N = 100 the last 100 outcomes 100 calls are recorded slow to fill on quiet traffic
2 time-based, N = 30 s 30 one-second buckets minimum calls fall in 30 s a quiet period leaves almost no sample
3 fixed interval (gobreaker Interval) counters reset every Interval, a cliff edge a burst can straddle the resetReal scenarios: a checkout endpoint at 300 rps fits a 30-second time window (9000 calls); an admin report endpoint at 1 rps is better served by a count window of 20 with a minimum of 10, or by not having a breaker at all; a batch job that calls a dependency in bursts every hour needs a window that does not forget between bursts (count-based).
| Choice | Detection speed | Noise | Memory | Best for |
|---|---|---|---|---|
| Count-based, small N | Fast under load, slow when quiet | High (a few unlucky calls trip it) | O(N) | Steady, moderate traffic |
| Count-based, large N | Slow | Low | O(N) | Very high traffic where each call is cheap |
| Time-based, short | Fast under load | Medium | O(seconds) | Bursty traffic, spikes of errors |
| Time-based, long | Slow to forget | Low | O(seconds) | Smooth traffic, protecting against slow degradation |
| Fixed interval (gobreaker default) | Simple | Cliff at the reset | O(1) | Small services, simple needs |
Fix / how to use it: pick the window from the traffic, not from a blog post: window seconds times requests per second should be several times the minimum number of calls. The Go implementation in breaker/window.go has both windows behind one interface.
Thresholds: failure rate, slow-call rate, minimum number of calls Must-know
In plain words: the breaker opens when the share of failed calls, or the share of slow calls, in the window reaches a limit, but only once enough calls have been seen to make the share meaningful.
Common misunderstanding: "Fifty percent failures means half my users are affected, so 50 is a conservative threshold." It is a statement about one window of calls to one dependency. A dependency failing 20% of the time can still ruin a request that makes ten calls to it (1 - 0.8^10 is about 89% of those requests hitting at least one failure, our arithmetic). The right threshold depends on how many calls one user request makes.
Definition: failure rate = failed calls / recorded calls in the window. Slow-call rate = calls slower than slowCallDurationThreshold / recorded calls; Resilience4j explains it "helps to reduce the load on an external system before it is actually unresponsive". Minimum number of calls = the smallest window population for which any rate is evaluated. Comparison is "equal or greater": exactly 50% trips a 50% breaker. Consecutive-failure counting (gobreaker's default ReadyToTrip: more than 5 consecutive failures; failsafe-go's WithFailureThreshold(5)) is a simpler alternative that ignores traffic volume.
Calls in window Failed Minimum 10 Rate Verdict
1 9 9 not met - stay closed (9 of 9 failed, still not judged)
2 10 10 met 100% open
3 10 5 met 50% open (equal or greater)
4 40 7 met 17.5% stay closedReal scenarios: a flaky downstream with a 3% background error rate must not trip a 50% breaker; a dependency whose p99 rises from 100 ms to 8 s should trip on slow calls before it returns a single error; a low-traffic admin API must not trip because its 3 calls last night failed.
| Mode | Opens when | Strength | Weakness |
|---|---|---|---|
| Consecutive failures (gobreaker default, Fowler's example, failsafe-go count) | N failures in a row | Dead simple, instant for hard-down | One success resets it; blind to 60% failure that interleaves successes |
| Failure rate with a minimum number of calls | rate >= threshold | Handles partial failure | Needs traffic to be meaningful |
| Slow-call rate | share of calls slower than a duration >= threshold | Trips before errors appear | Needs a sensible duration per endpoint |
| Per-error thresholds (Fowler) | e.g. 10 timeouts but 3 connection failures | Different errors, different urgency | More knobs to tune |
Fix / how to use it: start from the dependency's SLO: if its error budget is 0.1% and one user request makes ~5 calls, a breaker threshold of 50% is a last resort, not an SLO tool. Then set the minimum number of calls to roughly 10 to 20 seconds of traffic. Both rates are implemented in breaker.go (evaluate).
Open duration, probes and half-open Must-know
In plain words: after tripping, the breaker waits for a set time (the open duration, Resilience4j calls it the wait duration), then lets a few real calls through as probes (trial requests). If the probes work, it closes; if they fail, it waits again.
Common misunderstanding: "After the wait, the breaker closes and traffic resumes." It first goes half-open; if it closed straight away, the whole queued-up traffic would hit a dependency that has not been proven healthy. Hystrix's rule is the strictest: "the next single request is let through (this is the HALF-OPEN state). If the request fails, the circuit-breaker returns to the OPEN state for the duration of the sleep window".
Definition: waitDurationInOpenState (Resilience4j, default 60 s), circuitBreakerSleepWindowInMilliseconds (Hystrix), BreakDuration (Polly), Timeout (gobreaker, 0 means 60 s), WithDelay (failsafe-go, 1 minute). A probe is a real call, so it costs real work and can fail for the user: choose a probe that is cheap and idempotent (a read, a health endpoint) when you can. Resilience4j lets automaticTransitionFromOpenToHalfOpenEnabled move to half-open on a timer; by default the transition happens only when a call arrives. maxWaitDurationInHalfOpenState stops a breaker from waiting forever in half-open. Polly can compute the wait from the failure count with BreakDurationGenerator, and its exceptions expose RetryAfter. Envoy's analogue is ejection time growing as base_ejection_time times the number of consecutive ejections, capped by max_ejection_time.
t Event State Note
1 0 s breaker trips open wait = 30 s
2 30 s probes 1..3 allowed, 2 of 3 fail half-open>open failure rate 67% >= 50%, closing impossible
3 30 s wait restarts open another 30 s
4 60 s probes 1..3 succeed half-open>closedReal scenarios: a dependency restarts in 20 s but the open duration is 60 s (the caller serves fallbacks for 40 s of healthy time: the cost of a long wait); a database primary fails over in 8 s but a 10-second open duration means probes land right as it recovers; a thundering herd of 3000 instances each sending 10 probes (30,000 probes at one recovering service, the argument for small probe counts or shared state).
| Setting | Too short | Too long |
|---|---|---|
| Open duration | Hammers a dependency that is still down; the breaker flaps | Serves fallbacks long after recovery |
| Probe count | One unlucky probe decides everything | Many instances multiply the probes into real load |
| Probe type | A write probe can have side effects | A health-only probe can pass while real calls fail |
Fix / how to use it: start with an open duration of two to three times the dependency's typical recovery time, 3 to 10 probes per instance for chatty services or 1 for fragile ones, and add jitter to the open duration when thousands of instances share one dependency so they do not all probe in the same second.
What counts as a failure Important
In plain words: not every error means the dependency is sick. A 404 is a correct answer; a connection reset is not; a caller cancelling the request says nothing about the dependency.
Common misunderstanding: "Any exception should count." Fowler: "Not all errors should trip the circuit, some should reflect normal failures and be dealt with as part of regular logic."
Definition: a classifier with three outcomes: failure (counts against the dependency), success (including normal business answers) and ignored (neither: the request was cancelled by the caller, rejected by a bulkhead or a rate limiter). Resilience4j: recordExceptions, ignoreExceptions, recordFailurePredicate, ignoreExceptionPredicate; gobreaker v2: IsSuccessful and IsExcluded; Polly: ShouldHandle; failsafe-go: HandleErrors, HandleResult. failsafe-go also advises: "it's recommended to not have a circuit breaker handle errors from other policies, such as bulkhead.ErrFull or ratelimiter.ErrExceeded".
| Outcome | Examples | Counts as |
|---|---|---|
| Connection refused, reset, DNS failure | ECONNREFUSED, TLS handshake failure | Failure |
| Timeout of the call itself | context.DeadlineExceeded from the per-attempt timeout | Failure |
| HTTP 500, 502, 503, 504 | Server error | Failure |
| HTTP 429 | The dependency is shedding load | Failure (it asks you to back off) |
| HTTP 400, 404, 409, 422 | Correct answer to a bad question | Success |
context.Canceled | The user closed the tab | Ignored |
| Local bulkhead or rate-limiter rejection | Your own limit, not the dependency | Ignored |
| Slow success | 200 after 7 s | Success and slow (slow-call rate) |
Real scenarios: a search service returning 404 for an unknown SKU must not trip the product breaker; a client disconnecting during a page render must not push the recommendations breaker toward open; a 429 from a partner API must open the breaker and also honour Retry-After.
Fix / how to use it: Go: IsFailure and IsIgnored in breaker.Config; the HTTP transport in httpguard/guard.go counts 5xx and 429 and passes 4xx. Laravel: GuardedHttp::isFailure counts ConnectionException, 5xx and 429 RequestExceptions.
Fallbacks Must-know
In plain words: a breaker without a fallback just turns slow errors into fast errors. A fallback is the plan for what the caller returns when the call is rejected or fails.
Common misunderstanding: "The fallback can call a backup service over the network." Hystrix: "Write your fallback to provide a generic response, without any network dependency, from an in-memory cache or by means of other static logic." A fallback that can fail the same way fails the same way.
Definition: a ladder of answers from best to worst: (1) the cached last-good value, (2) a static default, (3) a degraded response (a smaller page, no recommendations, "check availability in store"), (4) fail fast with a clear error and a Retry-After. Fowler: "A credit card authorization could be put on a queue to deal with later, failure to get some data may be mitigated by showing some stale data that's good enough to display." The product team, not the engineer, decides which rung is acceptable.
Request Breaker Rung used Response
1 GET /product/42 closed live call price from pricing service
2 GET /product/42 open cached last-good price from 4 minutes ago, flagged stale
3 GET /product/42 open, none static default "price on request"
4 POST /checkout (payment) open fail fast 503 + Retry-After: 20, cart kept
5 POST /checkout (receipt) open queue for later 202 Accepted, receipt emailed laterReal scenarios: product page with recommendations (rung 3: render without the carousel); exchange rate (rung 1 with a 15-minute maximum age); loyalty points (rung 5: apply later via a queue); payment authorisation (rung 4: never invent an answer).
| Rung | Good for | Risk |
|---|---|---|
| Cached value (stale-while-error) | Reads that change slowly | Serving wrong money values; always bound the age |
| Static default | Feature flags, config, recommendation lists | Hides a long outage if nobody alerts on the fallback rate |
| Degraded response | Pages with optional parts | Needs the UI to cope with missing parts |
| Fail fast | Writes, payments, anything that must not be invented | Users see an error, but a fast and honest one |
| Queue for later | Work that can be done asynchronously (see Message Acknowledgment, Outbox) | Needs idempotency (API Idempotency) |
Fix / how to use it: Go: DoFallback, Static and LastGood in breaker.go. Laravel: the fallback closure of GuardedHttp::send and the degraded ladder in InventoryClient. Count fallbacks as a metric: a fallback that serves 100% of traffic for days is an incident that looks like success.
Granularity: per dependency, per endpoint, never global Must-know
In plain words: one breaker per thing that can fail independently.
Common misunderstanding: "One breaker for the whole HTTP client is simpler and safer." One slow endpoint (reports) then opens the breaker for healthy ones (login). The failsafe-go docs state the other half of the rule: a breaker "can and should be shared across code that accesses common dependencies", because all callers of one failing server should stop together.
Definition: the unit is the failure domain. Usually that is one downstream service. Split further when endpoints have very different latency or failure profiles (a search endpoint at 800 ms normal and a lookup at 20 ms cannot share a slow-call threshold), or when one host serves several tenants with isolated capacity. Per-instance granularity inside a cluster is the job of outlier detection (Proxy), not an application breaker.
| Granularity | Example | When |
|---|---|---|
| Global (one breaker for everything) | Single http.Client breaker | Almost never: it couples unrelated failures |
| Per downstream service | inventory, payments | Default |
| Per endpoint or operation | payments.authorize vs payments.refund | Different SLOs, latency or idempotency |
| Per host/pod | Envoy outlier detection ejects one pod | A cluster where one instance is bad |
| Per tenant or shard | db-shard-7 | Shard-per-failure-domain data stores |
Fix / how to use it: a registry keyed by name (Resilience4j CircuitBreakerRegistry; Go: the httpguard.Transport keeps one breaker per req.URL.Host; Laravel: app('breaker')($name) from config/breakers.php). Name the breaker after the dependency, not the library.
Composition: timeouts, retries, bulkheads Must-know
In plain words: a breaker only works if calls end. A timeout makes a stuck call end as a failure; retries absorb blips; a bulkhead caps concurrency. The order matters.
Common misunderstanding: "Retries and breakers are alternatives." They are layers: retries for transient errors, a breaker for sustained ones. And the order is a decision, not a law: Resilience4j's Spring aspect order is Retry ( CircuitBreaker ( RateLimiter ( TimeLimiter ( Bulkhead ( Function ) ) ) ) ), which puts the breaker inside the retry; this chapter's default puts it outside, for the reasons below. Pick one per system and write it down.
Definition: with the breaker outside the retries, it records one outcome per logical call, after the retries gave up: a transient blip that a retry hid never counts, and one outage counts once per user request, not three times. With the breaker inside, it records every attempt: it trips sooner (three times faster on three attempts), and the retry loop must treat the breaker's rejection as non-retryable or it will spin on ErrOpen. In both orders: the timeout is innermost (per attempt), the retry never retries a rejection, and the retry volume is capped by a budget (Timeouts, Retries & Jitter).
Order One outage, 3 attempts per request Effect
1 breaker outside retries records 1 failure per request after 3 attempts trips after minimum calls = 20 requests (60 attempts)
2 breaker inside retries records 3 failures per request trips after 20 attempts (about 7 requests)
3 breaker inside, retry stops attempt 1 rejected, retry sees ErrOpen, stops one rejection per request, no spinning
4 breaker inside, retry blind every attempt rejected, retried 3 times 3 pointless rejections per requestReal scenarios: an e-commerce backend with ~2% transient timeouts (breaker outside: the blips never reach the breaker); a fully dead dependency (breaker inside opens three times faster); a bulkhead in front of both (its rejections are ignored by the breaker, per failsafe-go advice).
| Policy | Per attempt or per call | Owns | Link |
|---|---|---|---|
| Timeout / deadline | Per attempt, bounded by the caller's deadline | "How long may it take" | Latency Budgets |
| Retry | Wraps attempts | "Is this transient" | Timeouts, Retries & Jitter |
| Circuit breaker | Per call (outside) or per attempt (inside) | "Should we try at all" | this page |
| Bulkhead | Per call, concurrency | "How many at once" | Bulkheads |
| Rate limiter | Per call, rate | "How fast" | Rate Limiting |
| Fallback | Outermost | "What to say instead" | Fallbacks |
Fix / how to use it: the Lab measures both orders. Retrying non-idempotent writes under either order needs idempotency keys (API Idempotency).
Bulkheads next to breakers Important
In plain words: the breaker reacts after a dependency has been failing; the bulkhead limits the damage while it is failing, by giving each dependency a separate pool of threads or permits.
Common misunderstanding: "A sliding window of 15 means at most 15 calls run at once." Resilience4j: "The sliding window does not mean that only 15 calls are allowed to run concurrently. If you want to restrict the number of concurrent threads, please use a Bulkhead."
Definition: Hystrix paired every breaker with isolation: "Hystrix uses separate, per-dependency thread pools as a way of constraining any given dependency so latency on the underlying executions will saturate the available threads only in that pool", or semaphores for very low-latency calls. Envoy's cluster-level limits (max connections, max pending requests, max requests, max retries) are bulkheads enforced in the proxy. Details and Go/Laravel patterns are in Bulkheads & Graceful Degradation.
| Tool | Reacts to | Speed | Typical limit |
|---|---|---|---|
| Bulkhead | Concurrency right now | Immediate | N in flight per dependency |
| Circuit breaker | Failure/slowness over a window | After the window fills | Rate over time |
| Timeout | One slow call | Per call | Seconds |
Fix / how to use it: semaphore bulkhead of roughly (peak rps x p99 latency x 1.5) per dependency; breaker above it; ignore bulkhead rejections in the breaker's statistics.
Metrics and alerting on state changes Must-know
In plain words: an open breaker is the system telling you that a dependency is unhealthy; if nobody hears it, you have hidden an outage behind a fallback.
Common misunderstanding: "If the breaker works, nobody needs to be paged." Fowler: "Any change in breaker state should be logged and breakers should reveal details of their state for deeper monitoring. Breaker behavior is often a good source of warnings about deeper troubles in the environment."
Definition: emit one event per state change (name, from, to, reason, window snapshot, time) and keep counters per dependency: successes, failures, slow calls, ignored, rejected (not permitted), fallbacks served, transitions, plus the current state as a gauge. Resilience4j publishes onStateTransition, onSuccess, onError, onIgnoredError, onReset; failsafe-go has OnStateChanged and metrics for the current state; gobreaker has OnStateChange. Envoy exposes counters such as upstream_cx_overflow, upstream_rq_pending_overflow, upstream_rq_active_overflow and upstream_rq_retry_overflow.
| Signal | Type | Alert when |
|---|---|---|
breaker_state | Gauge 0/1/2 | State is open for longer than 2 minutes (page), flapping more than 4 transitions in 10 minutes (ticket) |
breaker_rejected_total | Counter | Rate above zero on a critical dependency for more than 1 minute |
breaker_fallback_total | Counter | Fallback share of calls above 5% for 10 minutes |
breaker_failure_ratio | Gauge from the window | Above half the threshold: early warning |
breaker_transitions_total | Counter by from, to, reason | Any closed>open on a tier-1 dependency |
Event Log line (structured)
1 closed>open level=warn breaker=inventory from=closed to=open reason="failure rate 60% >= 50%" window_total=40
2 open>half-open level=info breaker=inventory from=open to=half-open reason="open duration elapsed"
3 half-open>closed level=info breaker=inventory from=half-open to=closed reason="probes succeeded"Real scenarios: a dashboard row per dependency with state, rejection rate and fallback share; a page on "tier-1 breaker open > 2 min"; a Grafana annotation for each transition so graphs show why latency fell (see Alerting That Actually Works and Observability).
Fix / how to use it: Go: OnStateChange, OnCall and Stats() in breaker.go. Laravel: the CircuitBreakerStateChanged event, a log listener, Pulse::record('circuit_breaker', ...) and a custom Pulse card (Breakers).
Distributed breakers: local state or shared state Important
In plain words: with fifty instances, you have fifty breakers unless you do something about it.
Common misunderstanding: "A shared breaker is strictly better." It is a different trade-off: it adds a network hop to every call, a new dependency (the store) and a failure mode (the store is down or slow), in exchange for a single, faster and consistent verdict.
Definition: local-per-instance state keeps counters in process memory; every instance learns of the outage by itself, which costs about one window of failures per instance, but there is no extra hop and no shared failure. Shared state keeps the state, the window counters and the probe tickets in Redis: one verdict, probes are limited fleet-wide, new instances inherit the open state. In Laravel the building blocks are Cache::add plus Cache::increment for atomic counters (Laravel: "The add method is an atomic operation") and Cache::lock for transitions.
Step Instance A Redis Instance B
1 1 call fails -> INCR breaker:inv:g3:t:41 total/failed
2 2 evaluate: 21 calls, 12 failed -> LOCK transition
3 3 state = open, generation 3 -> 4 breaker:inv:state = open@gen4
4 4 call: GET state -> open, rejected locally
5 5 (a late result from generation 3 is ignored: keys include the generation)| Aspect | Local (in-process) | Shared (Redis) |
|---|---|---|
| Detection | Each instance needs its own failures | Fleet-wide counters: faster with many instances |
| Probes | N per instance, so fleet load multiplies | N in total via an atomic counter |
| Latency overhead | Nanoseconds | One Redis round trip (about a millisecond within a region) per call |
| Failure mode | None new | Redis down: you must decide to fail open (use local state) |
| New instance | Starts closed, learns by failing | Inherits the open state |
| Cross-region | Natural | Redis per region, or pay cross-region latency |
| Consistency | Each instance's view | Races on counters and transitions need a lock and generation numbers |
Real scenarios: 3000 containers calling one provider (local breakers send up to 3000 x probes at it; shared state sends a fixed number); a PHP-FPM fleet where processes live only for one request (a local in-memory breaker is useless, shared state is the only choice); a Go service with 4 pods (local is enough).
Fix / how to use it: Laravel (shared, Redis-backed) in Laravel. In Go keep local state and let the mesh do the fleet-level part; a Redis-backed variant would keep the same state machine and replace the window with INCR on per-second keys under a Lua script. Always fail open when the store is unavailable: a breaker must not become the reason calls fail.
Breakers at the proxy and the mesh Important
In plain words: the proxy in front of a dependency can break the circuit for every caller without any code, but it cannot give the application a fallback.
Common misunderstanding: "Envoy's circuit breaking is the same as a Hystrix-style breaker." Envoy's "circuit breakers" are limits (connections, pending requests, requests, retries, connection pools): the docs call them "fully distributed (not coordinated)". The state machine with half-open probes is Envoy's outlier detection, which ejects hosts.
Definition: Envoy circuit breaking: "It's nearly always better to fail quickly and apply back pressure downstream as soon as possible." Limits are per upstream cluster and per priority; defaults are modest ("1024 connections per cluster"); overflow increments upstream_cx_overflow and friends and sets the x-envoy-overloaded header. Envoy outlier detection: "Outlier detection is a form of passive health checking"; types are consecutive 5xx, consecutive gateway failure (502, 503, 504), consecutive local-origin failure, success rate (statistical) and failure percentage; ejection time is base_ejection_time times the number of times the host was ejected in a row, capped by max_ejection_time; max_ejection_percent keeps the proxy from ejecting the whole cluster. Istio: a DestinationRule with trafficPolicy.connectionPool (tcp.maxConnections, http.http1MaxPendingRequests, http.maxRequestsPerConnection) and trafficPolicy.outlierDetection (consecutive5xxErrors, interval, baseEjectionTime, maxEjectionPercent). NGINX: max_fails (default 1) failures within fail_timeout (default 10 s) mark a server unavailable for fail_timeout; "if there is only a single server in a group, max_fails, fail_timeout and slow_start parameters are ignored, and such a server will never be considered unavailable". HAProxy: observe layer7 verifies responses ("Valid status codes include 100 to 499, 501 and 505") and combined with on-error and error-limit it adjusts server health.
| Product | Mechanism | Unit | Half-open equivalent | App fallback |
|---|---|---|---|---|
| Envoy circuit breaking | Limits: connections, pending, requests, retries, pools | Cluster + priority | None (limit, not state) | No (503 + x-envoy-overloaded) |
| Envoy outlier detection | Passive ejection of hosts | Host | Un-eject after the ejection time | No |
Istio DestinationRule | Configures Envoy: connectionPool, outlierDetection | Service host | Same as Envoy | No |
NGINX max_fails / fail_timeout | Passive failure counting | Server in an upstream | Next request after fail_timeout | No |
HAProxy observe + error-limit | Passive health from live traffic | Server | Health-check recovery | No |
| Application library | Window + state machine | Dependency or endpoint | Yes, probes | Yes |
Layer Sees Can do Cannot do
1 app breaker logical calls, business errors fallback, per-endpoint policy nothing for other languages
2 mesh sidecar every request of every service eject a bad pod, cap connections choose a fallback value
3 load balancer requests to a pool remove a server from rotation know what the call meantReal scenarios: a Kubernetes service with one bad pod (outlier detection ejects it in seconds; an app breaker would just open for the whole service); a polyglot fleet (the mesh gives one baseline behaviour); an NGINX upstream of two PHP-FPM servers (max_fails=3 fail_timeout=30s). See Service Mesh & the Sidecar Pattern and Load Balancing for the mechanics of the proxy itself.
Fix / how to use it: use the mesh for host ejection and connection limits, and the application for per-endpoint thresholds and fallbacks; do not configure the same retry and breaker semantics in both layers without knowing that two breakers stack.
Libraries and where each one stands Good to know
In plain words: do not write your own unless you must; know what the library gives you.
Common misunderstanding: "Hystrix is the standard." Hystrix is in maintenance mode; Netflix itself recommends resilience4j for new work.
Definition: a comparison of what you get.
| Library | Language | Status | Window | Half-open | Fallback | Notes |
|---|---|---|---|---|---|---|
| Resilience4j | JVM | Active (docs v2.2.0) | Count or time based, subtract-on-evict | Configurable number of permitted calls, optional max wait | Via decorators | Registry, Micrometer metrics, Spring Boot starter |
| Hystrix | JVM | Maintenance mode (1.5.18) | Rolling counters | One request | getFallback(), resumeWithFallback() | Command pattern, thread pools, request cache, dashboard |
| Polly | .NET | Active (v8 strategies) | Sampling duration, failure ratio, minimum throughput | Next execution after BreakDuration | Fallback strategy | BrokenCircuitException, IsolatedCircuitException, manual control |
| sony/gobreaker v2 | Go | Active (v2.4.0 in our module) | Fixed Interval or rolling via BucketPeriod | MaxRequests probes | You write it | Generics, ReadyToTrip, IsExcluded, OnStateChange; DistributedCircuitBreaker with a SharedDataStore |
| failsafe-go | Go | Active | Count or time based, 10 slices | Trial executions, WithSuccessThreshold | fallback policy | Composable policies, RemainingDelay(), ErrOpen |
| Envoy / Istio | Proxy | Active | Per-host counters, outlier types | Ejection time then un-eject | No | No app changes |
| Laravel packages | PHP | Community | Cache counters | Varies | You write it | Laravel has no first-party breaker; this chapter builds one on Cache |
Real scenarios: a Spring Boot service picks Resilience4j; a .NET service uses Polly's resilience pipeline; a Go service starts with gobreaker (simple) or failsafe-go (composition) and writes its own only when it needs a time-based rate, slow-call rate or per-call context rules; a PHP service uses the Redis-backed breaker in this chapter or lets the mesh handle it.
Fix / how to use it: the Go comparison in cmd/gobreakercmp/main.go maps our Config onto gobreaker's Settings. What gobreaker does not give you out of the box: a slow-call rate, a minimum-number-of-calls (you encode it in ReadyToTrip), and a failure-rate-based close from half-open.
Anti-patterns Important
In plain words: the common ways a breaker makes things worse.
Common misunderstanding: "More breakers means more resilience." Every breaker is a mode: Brooker's warning about "modal behavior" applies; each needs a test and an owner.
Definition: a table of failure modes.
| Anti-pattern | What happens | Fix |
|---|---|---|
| Breaker on a non-idempotent write with retries and no idempotency key | A timed-out charge is retried, the first one went through: double charge | Idempotency key (API Idempotency); fail fast on writes |
| One global breaker | A slow report endpoint opens it for login | One per dependency or endpoint |
| Too-sensitive thresholds | 3 of 5 calls fail on a blip, flapping all day | Minimum number of calls, 50%+ rate, time-based window |
| No half-open | Needs a human to reset; or reopens the floodgates all at once | Probes with a bounded count |
| No fallback | Slow errors become fast errors; users still see failure | Agree on a ladder with the product team |
| Fallback calls the same dependency | The fallback fails the same way | Local data only |
| Counting 4xx as failures | A bad client trips the breaker for everyone | Classify errors |
| Breaker without a timeout | A hung call never completes, so never counts | Per-attempt timeout innermost |
| Counting your own bulkhead rejection | Self-inflicted open | Ignore rejections from other policies |
| Silent state changes | An outage hidden behind a fallback | Event, log, metric, alert |
| Breaker and retry both unbounded | 3 x 3 x 3 attempt multiplication across layers | One retry layer, a budget |
| Open duration of 5 minutes for a 10-second blip | Long fake outage | Open duration near recovery time, with jitter |
Real scenarios: each row is a postmortem somewhere; the retry-storm lab shows the first and last in numbers.
Fix / how to use it: run through this table as a review checklist before a breaker ships.
Testing breakers: fake clocks and fault injection Must-know
In plain words: a breaker is time-dependent state; test it by controlling time and by breaking the dependency on purpose.
Common misunderstanding: "I can test it with sleep." Sleep-based tests are slow and flaky; the open duration is 30 seconds and the window is time-based. Inject a clock.
Definition: unit tests with a fake clock (advance time by hand): minimum calls hold the breaker closed, threshold is inclusive, window expires, wait elapses, half-open admits exactly N probes, a failed probe restarts the wait, stale results are not recorded, ignored errors are ignored, fallbacks run. Integration tests with fault injection: Envoy/Istio fault (delay, abort), Toxiproxy, Http::fake with sequences and Http::failedConnection() in Laravel, httptest.Server returning 503 in Go. Production: chaos experiments and game days (Chaos Engineering).
| Level | Tool | Verifies |
|---|---|---|
| Unit | Fake clock (clock.Fake, Laravel travel()) | State machine, windows, boundaries |
| Concurrency | go test -race, many goroutines | One state, exactly N probes |
| HTTP integration | httptest.Server, Http::fake | 5xx counted, 4xx not, host isolation |
| Staging | Toxiproxy, Istio fault injection (delay, abort) | Real timeouts, real fallbacks |
| Production | Chaos experiments, game days | Alerts fire, fallbacks acceptable, recovery works |
Test Setup Assert
1 minimum calls 9 failures, minimum 10 still closed; 10th failure opens
2 window forgets 4 failures, advance 11 s, 5 calls closed, snapshot total 5
3 probe limit trip, advance 30 s, 8 concurrent 3 admitted, 5 rejected
4 failed probe 2 of 3 probes fail open, wait restartsReal scenarios: the Go tests in breaker_test.go cover these; the Laravel feature tests use Http::fake and travel.
Fix / how to use it: Go and Laravel code below; chaos in Chaos Engineering.
Mechanics
What each knob does, in one place
| Question | Setting | Typical start | Effect of raising it |
|---|---|---|---|
| How many recent calls matter? | Window size | 20 to 100 calls, or 10 to 60 s | Slower to open, less noise |
| How sure must we be? | Minimum number of calls | 10 to 20 s of traffic | Fewer false trips, slower on quiet traffic |
| How bad is too bad? | Failure rate | 50% | Tolerates more failure |
| How slow is too slow? | Slow-call duration and rate | p99 x 2 to 3, rate 50 to 80% | Tolerates more slow calls |
| How long to stay away? | Open (wait) duration | 10 to 60 s | Longer fallback time, gentler on the dependency |
| How careful are the probes? | Half-open probes | 3 to 10 | More evidence, more load |
| What is a failure? | Classifier | Connection, timeout, 5xx, 429 | Broader = more trips |
Time to trip: arithmetic
With a count-based window of N, minimum M, failure threshold f and a dependency that fails every call: the breaker opens after M calls (taking M <= N), because the rate is 100% from the first failure and the minimum is the only gate. For Resilience4j defaults (N = 100, M = 100) that is 100 calls. With only half the calls failing it opens when failures reach f x N inside the window, never before M. At r requests per second, time to trip = calls / r. For 100 calls: 1 s at 100 rps, 10 s at 10 rps, 50 s at 2 rps. A time-based window of W seconds trips when the calls in the window reach M with enough failures, so the time to trip is about M / r once the window contains failures only. Rule of thumb: choose M near 10 seconds of traffic, window of 30 to 60 s, and accept that endpoints below 1 rps need a small count window or no breaker.
Time to recover = remaining open duration + probe time. If the dependency recovers at a random moment during the open period, the expected wasted time is open duration / 2. With a 30 s open duration that is about 15 s of fallbacks while the dependency is healthy (our arithmetic); the Lab measures it (5.28 s in that run).
Error names you will see
| Where | Error / signal | Meaning |
|---|---|---|
| Resilience4j | CallNotPermittedException | The breaker is OPEN (or HALF_OPEN with all permitted calls used) |
| Hystrix | Fallback invoked; with no fallback (or a failing one) the Observable "immediately terminates with an onError notification" | Short-circuited, rejected or failed |
| Polly | BrokenCircuitException, IsolatedCircuitException | Circuit open; manually isolated. Both carry RetryAfter |
| sony/gobreaker | gobreaker.ErrOpenState, gobreaker.ErrTooManyRequests | Open; half-open probe slots are used up |
| failsafe-go | circuitbreaker.ErrOpen | Breaker open; breaker.RemainingDelay() says how long |
| Envoy | HTTP 503 with x-envoy-overloaded; counters upstream_rq_pending_overflow, upstream_cx_overflow | A circuit-breaking limit overflowed |
| Istio sample | Code 503 : 3 (15.0 %) from fortio | Connection or pending-request limits tripped |
| NGINX | no live upstreams while connecting to upstream (error log) | All servers in the upstream are marked unavailable |
| This chapter's Go code | *breaker.RejectedError, errors.Is(err, breaker.ErrOpen) | Rejected, with RetryAfter |
| This chapter's Laravel code | App\Resilience\CircuitOpenException | Rejected, with retryAfterSeconds |
What the response to the user should look like
| Situation | HTTP | Headers | Body |
|---|---|---|---|
| Breaker open, no fallback, safe to retry later | 503 Service Unavailable | Retry-After: 20 | Problem Details with type = dependency unavailable |
| Breaker open, fallback served | 200 | Warning or an X-Data-Source: stale marker | Data plus a source field |
| Breaker open, deferred work | 202 Accepted | Location of the status resource | Receipt id |
| Bad request (not a breaker case) | 4xx | - | Normal validation error |
Go
Before
The first version has no memory. Every request retries three times, so during an outage the dependency receives three times the traffic and every user waits for every timeout. Run it: 20 user requests against a dead dependency cost 60 dependency calls (the program waits 50 ms per attempt instead of 2 s, so it finishes in 3.1 s here; with the real 2 s timeout it would be 120 s of waiting).
// Before: a client that retries every failure and has no memory.
// During an outage every user request still pays the full timeout, times
// the number of attempts, and the struggling dependency gets all of it.
package main
import (
"context"
"errors"
"fmt"
"time"
)
var errTimeout = errors.New("inventory: timeout")
// inventory is a dependency that has been down since t0.
type inventory struct{ calls int }
func (d *inventory) stock(ctx context.Context, sku string) (int, error) {
d.calls++
select {
case <-time.After(50 * time.Millisecond): // pretend the 2 s timeout fired
return 0, errTimeout
case <-ctx.Done():
return 0, ctx.Err()
}
}
func stockWithRetries(ctx context.Context, d *inventory, sku string) (int, error) {
var err error
for attempt := 1; attempt <= 3; attempt++ {
var n int
if n, err = d.stock(ctx, sku); err == nil {
return n, nil
}
}
return 0, err
}
func main() {
d := &inventory{}
start := time.Now()
for i := 0; i < 20; i++ { // 20 user requests during the outage
_, _ = stockWithRetries(context.Background(), d, "sku-1")
}
fmt.Printf("dependency calls: %d, time spent waiting: %s\n", d.calls, time.Since(start).Round(100*time.Millisecond))
}After
The breaker is built from small parts. A Clock interface (real and fake), two sliding windows behind one interface, a state machine under one mutex that never holds the lock while the protected call runs, a permit that carries a generation number so a result that arrives after a state change is ignored, and hooks for state changes and for every call.
// Package clock is the only source of time for the breaker, so tests can
// move time by hand instead of sleeping.
package clock
import (
"sync"
"time"
)
// Clock returns the current time.
type Clock interface {
Now() time.Time
}
// Real reads the wall clock.
type Real struct{}
// Now implements Clock.
func (Real) Now() time.Time { return time.Now() }
// Fake is a clock that only moves when Advance is called.
type Fake struct {
mu sync.Mutex
now time.Time
}
// NewFake starts a fake clock at a fixed instant.
func NewFake() *Fake {
return &Fake{now: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)}
}
// Now implements Clock.
func (f *Fake) Now() time.Time {
f.mu.Lock()
defer f.mu.Unlock()
return f.now
}
// Advance moves the clock forward.
func (f *Fake) Advance(d time.Duration) {
f.mu.Lock()
f.now = f.now.Add(d)
f.mu.Unlock()
}package breaker
import "time"
// Outcome is what one finished call is recorded as.
type Outcome struct {
Failure bool
Slow bool
}
// Snapshot is the aggregate of everything inside the window.
type Snapshot struct {
Total int
Failures int
Slow int
}
// FailureRate is failures / total, or 0 for an empty window.
func (s Snapshot) FailureRate() float64 {
if s.Total == 0 {
return 0
}
return float64(s.Failures) / float64(s.Total)
}
// SlowRate is slow calls / total, or 0 for an empty window.
func (s Snapshot) SlowRate() float64 {
if s.Total == 0 {
return 0
}
return float64(s.Slow) / float64(s.Total)
}
// window stores recent outcomes and keeps a pre-aggregated total, so
// snapshot is O(1) whatever the window size (subtract-on-evict).
type window interface {
record(now time.Time, o Outcome)
snapshot(now time.Time) Snapshot
reset()
}
// countWindow keeps the last n outcomes in a ring buffer.
type countWindow struct {
ring []Outcome
next int
count int
total Snapshot
}
func newCountWindow(n int) *countWindow {
return &countWindow{ring: make([]Outcome, n)}
}
func (w *countWindow) record(_ time.Time, o Outcome) {
if w.count == len(w.ring) {
old := w.ring[w.next]
w.total.Total--
if old.Failure {
w.total.Failures--
}
if old.Slow {
w.total.Slow--
}
} else {
w.count++
}
w.ring[w.next] = o
w.next = (w.next + 1) % len(w.ring)
w.total.Total++
if o.Failure {
w.total.Failures++
}
if o.Slow {
w.total.Slow++
}
}
func (w *countWindow) snapshot(time.Time) Snapshot { return w.total }
func (w *countWindow) reset() {
w.next, w.count, w.total = 0, 0, Snapshot{}
for i := range w.ring {
w.ring[i] = Outcome{}
}
}
// timeWindow keeps one bucket per second for the last n seconds.
type timeWindow struct {
buckets []Snapshot
epochs []int64 // epoch second each bucket currently holds
total Snapshot
}
func newTimeWindow(seconds int) *timeWindow {
return &timeWindow{buckets: make([]Snapshot, seconds), epochs: make([]int64, seconds)}
}
// expire drops every bucket that is older than the window.
func (w *timeWindow) expire(now time.Time) {
sec := now.Unix()
for i := range w.buckets {
if w.buckets[i].Total > 0 && sec-w.epochs[i] >= int64(len(w.buckets)) {
w.total.Total -= w.buckets[i].Total
w.total.Failures -= w.buckets[i].Failures
w.total.Slow -= w.buckets[i].Slow
w.buckets[i] = Snapshot{}
}
}
}
func (w *timeWindow) record(now time.Time, o Outcome) {
w.expire(now)
sec := now.Unix()
i := int(sec % int64(len(w.buckets)))
if w.epochs[i] != sec {
w.epochs[i] = sec
}
w.buckets[i].Total++
w.total.Total++
if o.Failure {
w.buckets[i].Failures++
w.total.Failures++
}
if o.Slow {
w.buckets[i].Slow++
w.total.Slow++
}
}
func (w *timeWindow) snapshot(now time.Time) Snapshot {
w.expire(now)
return w.total
}
func (w *timeWindow) reset() {
for i := range w.buckets {
w.buckets[i] = Snapshot{}
w.epochs[i] = 0
}
w.total = Snapshot{}
}// Package breaker is a circuit breaker with a count-based or time-based
// sliding window, failure-rate and slow-call-rate thresholds, a minimum
// number of calls, half-open probes, fallbacks and metrics hooks.
package breaker
import (
"context"
"errors"
"fmt"
"sync"
"time"
"academy/circuit-breaker/clock"
)
// State is one of the three normal states of the state machine.
type State int
const (
Closed State = iota
Open
HalfOpen
)
func (s State) String() string {
switch s {
case Closed:
return "closed"
case Open:
return "open"
case HalfOpen:
return "half-open"
}
return "unknown"
}
// ErrOpen is returned without calling the dependency. Use errors.Is.
var ErrOpen = errors.New("circuit breaker is open")
// RejectedError carries how long the caller should stay away.
type RejectedError struct {
Name string
State State
RetryAfter time.Duration
}
func (e *RejectedError) Error() string {
return fmt.Sprintf("breaker %q rejected the call (%s, retry after %s)", e.Name, e.State, e.RetryAfter)
}
// Is makes errors.Is(err, ErrOpen) true for every rejection.
func (e *RejectedError) Is(target error) bool { return target == ErrOpen }
// WindowKind selects how outcomes are aggregated.
type WindowKind int
const (
CountBased WindowKind = iota // the last WindowSize calls
TimeBased // the calls of the last WindowSize seconds
)
// Config holds every knob. Zero values are replaced by defaults.
type Config struct {
Name string
Window WindowKind
WindowSize int // calls (CountBased) or seconds (TimeBased)
MinimumCalls int // no rate is evaluated below this many recorded calls
FailureRate float64 // open at or above this fraction (0.5 = 50%)
SlowCallDuration time.Duration // a call slower than this counts as slow; 0 disables
SlowCallRate float64 // open at or above this fraction of slow calls
OpenDuration time.Duration // how long to reject before probing
HalfOpenProbes int // trial calls allowed in half-open
// IsFailure decides whether an error counts as a failure. The default
// counts every error except context.Canceled.
IsFailure func(err error) bool
// IsIgnored removes a call from the statistics entirely (neither
// success nor failure). The default ignores context.Canceled.
IsIgnored func(err error) bool
Clock clock.Clock
OnStateChange func(StateChange)
OnCall func(CallEvent)
}
// StateChange is delivered to OnStateChange after the lock is released.
type StateChange struct {
Name string
From, To State
At time.Time
Snapshot Snapshot // the window that caused the change (zero for open to half-open)
Reason string
}
// Result classifies one call for the OnCall hook and the counters.
type Result string
const (
ResultSuccess Result = "success"
ResultFailure Result = "failure"
ResultSlow Result = "slow"
ResultIgnored Result = "ignored"
ResultRejected Result = "rejected"
)
// CallEvent is delivered to OnCall for every call, including rejections.
type CallEvent struct {
Name string
Result Result
State State
Duration time.Duration
}
// Stats is a copy of the counters, safe to scrape.
type Stats struct {
State State
Successes uint64
Failures uint64
SlowCalls uint64
Ignored uint64
Rejected uint64
Transitions uint64
}
// Breaker is safe for concurrent use. The protected call is never run
// inside the lock.
type Breaker struct {
cfg Config
mu sync.Mutex
state State
generation uint64
win window
openedAt time.Time
probesStart int // probes handed out in this half-open period
probesDone int
probesFailed int
stats Stats
}
// New applies defaults and returns a closed breaker.
func New(cfg Config) *Breaker {
if cfg.Name == "" {
cfg.Name = "default"
}
if cfg.WindowSize <= 0 {
cfg.WindowSize = 20
}
if cfg.MinimumCalls <= 0 {
cfg.MinimumCalls = 10
}
if cfg.FailureRate <= 0 {
cfg.FailureRate = 0.5
}
if cfg.SlowCallRate <= 0 {
cfg.SlowCallRate = 1.0
}
if cfg.OpenDuration <= 0 {
cfg.OpenDuration = 30 * time.Second
}
if cfg.HalfOpenProbes <= 0 {
cfg.HalfOpenProbes = 3
}
if cfg.Clock == nil {
cfg.Clock = clock.Real{}
}
if cfg.IsFailure == nil {
cfg.IsFailure = func(err error) bool { return !errors.Is(err, context.Canceled) }
}
if cfg.IsIgnored == nil {
cfg.IsIgnored = func(err error) bool { return errors.Is(err, context.Canceled) }
}
b := &Breaker{cfg: cfg}
if cfg.Window == TimeBased {
b.win = newTimeWindow(cfg.WindowSize)
} else {
b.win = newCountWindow(cfg.WindowSize)
}
return b
}
// Name returns the dependency name used in metrics and logs.
func (b *Breaker) Name() string { return b.cfg.Name }
// State returns the current state (an open breaker whose wait elapsed
// still reports open until the next call moves it to half-open).
func (b *Breaker) State() State {
b.mu.Lock()
defer b.mu.Unlock()
return b.state
}
// Stats returns a copy of the counters.
func (b *Breaker) Stats() Stats {
b.mu.Lock()
defer b.mu.Unlock()
s := b.stats
s.State = b.state
return s
}
// Snapshot returns the current window aggregate.
func (b *Breaker) Snapshot() Snapshot {
b.mu.Lock()
defer b.mu.Unlock()
return b.win.snapshot(b.cfg.Clock.Now())
}
// Trip forces the breaker open, for an operator or a deploy script.
func (b *Breaker) Trip() {
b.mu.Lock()
ch := b.setState(Open, Snapshot{}, "manual trip")
b.mu.Unlock()
b.emit(ch)
}
// Reset forces the breaker closed with an empty window.
func (b *Breaker) Reset() {
b.mu.Lock()
ch := b.setState(Closed, Snapshot{}, "manual reset")
b.mu.Unlock()
b.emit(ch)
}
// permit is the ticket handed out by allow. It remembers the generation
// so a result that arrives after a state change is not recorded.
type permit struct {
gen uint64
state State
}
func (b *Breaker) allow() (permit, error) {
b.mu.Lock()
var ch *StateChange
now := b.cfg.Clock.Now()
if b.state == Open && now.Sub(b.openedAt) >= b.cfg.OpenDuration {
ch = b.setState(HalfOpen, Snapshot{}, "open duration elapsed")
}
var (
p permit
err error
)
switch b.state {
case Closed:
p = permit{gen: b.generation, state: Closed}
case HalfOpen:
if b.probesStart < b.cfg.HalfOpenProbes {
b.probesStart++
p = permit{gen: b.generation, state: HalfOpen}
} else {
err = &RejectedError{Name: b.cfg.Name, State: HalfOpen, RetryAfter: b.cfg.OpenDuration}
}
default:
err = &RejectedError{Name: b.cfg.Name, State: Open, RetryAfter: b.cfg.OpenDuration - now.Sub(b.openedAt)}
}
if err != nil {
b.stats.Rejected++
}
state := b.state
b.mu.Unlock()
b.emit(ch)
if err != nil && b.cfg.OnCall != nil {
b.cfg.OnCall(CallEvent{Name: b.cfg.Name, Result: ResultRejected, State: state})
}
return p, err
}
func (b *Breaker) done(p permit, d time.Duration, err error) {
ignored := err != nil && b.cfg.IsIgnored(err)
failed := err != nil && !ignored && b.cfg.IsFailure(err)
slow := !ignored && b.cfg.SlowCallDuration > 0 && d >= b.cfg.SlowCallDuration
result := ResultSuccess
switch {
case ignored:
result = ResultIgnored
case failed:
result = ResultFailure
case slow:
result = ResultSlow
}
b.mu.Lock()
var ch *StateChange
if p.gen == b.generation {
now := b.cfg.Clock.Now()
switch result {
case ResultIgnored:
b.stats.Ignored++
if p.state == HalfOpen {
b.probesStart-- // give the probe slot back
}
default:
b.count(result)
if p.state == Closed {
b.win.record(now, Outcome{Failure: failed, Slow: slow})
ch = b.evaluate(now)
} else {
ch = b.finishProbe(failed || slow)
}
}
} else if result != ResultIgnored {
b.count(result) // still a real call, but it must not move the state
}
state := b.state
b.mu.Unlock()
b.emit(ch)
if b.cfg.OnCall != nil {
b.cfg.OnCall(CallEvent{Name: b.cfg.Name, Result: result, State: state, Duration: d})
}
}
func (b *Breaker) count(r Result) {
switch r {
case ResultSuccess:
b.stats.Successes++
case ResultFailure:
b.stats.Failures++
case ResultSlow:
b.stats.SlowCalls++
}
}
// evaluate runs after every closed-state call.
func (b *Breaker) evaluate(now time.Time) *StateChange {
s := b.win.snapshot(now)
if s.Total < b.cfg.MinimumCalls {
return nil
}
if s.FailureRate() >= b.cfg.FailureRate {
return b.setState(Open, s, fmt.Sprintf("failure rate %.0f%% >= %.0f%%", 100*s.FailureRate(), 100*b.cfg.FailureRate))
}
if b.cfg.SlowCallDuration > 0 && s.SlowRate() >= b.cfg.SlowCallRate {
return b.setState(Open, s, fmt.Sprintf("slow call rate %.0f%% >= %.0f%%", 100*s.SlowRate(), 100*b.cfg.SlowCallRate))
}
return nil
}
// finishProbe decides half-open: reopen as soon as the probe failures
// make closing impossible, close when every probe has succeeded enough.
func (b *Breaker) finishProbe(bad bool) *StateChange {
b.probesDone++
if bad {
b.probesFailed++
}
rate := float64(b.probesFailed) / float64(b.cfg.HalfOpenProbes)
if rate >= b.cfg.FailureRate {
return b.setState(Open, Snapshot{Total: b.probesDone, Failures: b.probesFailed}, "probe failed")
}
if b.probesDone >= b.cfg.HalfOpenProbes {
return b.setState(Closed, Snapshot{Total: b.probesDone, Failures: b.probesFailed}, "probes succeeded")
}
return nil
}
// setState must be called with the lock held. It returns the event so
// the caller can deliver it after unlocking.
func (b *Breaker) setState(to State, s Snapshot, reason string) *StateChange {
from := b.state
if from == to {
return nil
}
now := b.cfg.Clock.Now()
b.state = to
b.generation++
b.stats.Transitions++
b.probesStart, b.probesDone, b.probesFailed = 0, 0, 0
b.win.reset()
if to == Open {
b.openedAt = now
}
return &StateChange{Name: b.cfg.Name, From: from, To: to, At: now, Snapshot: s, Reason: reason}
}
func (b *Breaker) emit(ch *StateChange) {
if ch != nil && b.cfg.OnStateChange != nil {
b.cfg.OnStateChange(*ch)
}
}
// Do runs call through the breaker. When the breaker rejects the call,
// call is not executed and the error satisfies errors.Is(err, ErrOpen).
func Do[T any](ctx context.Context, b *Breaker, call func(context.Context) (T, error)) (T, error) {
var zero T
p, err := b.allow()
if err != nil {
return zero, err
}
start := b.cfg.Clock.Now()
v, err := call(ctx)
b.done(p, b.cfg.Clock.Now().Sub(start), err)
return v, err
}
// DoFallback runs call and, if it was rejected or failed, returns the
// fallback's answer. The fallback sees the original error and must be
// cheap and local: no network call that can fail the same way.
func DoFallback[T any](ctx context.Context, b *Breaker, call func(context.Context) (T, error), fallback func(context.Context, error) (T, error)) (T, error) {
v, err := Do(ctx, b, call)
if err == nil {
return v, nil
}
return fallback(ctx, err)
}
// Static returns a fallback that always answers with v.
func Static[T any](v T) func(context.Context, error) (T, error) {
return func(context.Context, error) (T, error) { return v, nil }
}
// LastGood remembers the last successful value for a stale-but-useful
// fallback. Its Wrap returns the call that records, and Fallback serves it.
type LastGood[T any] struct {
mu sync.Mutex
value T
at time.Time
ok bool
clk clock.Clock
maxAge time.Duration
}
// NewLastGood creates the cache; values older than maxAge are not served.
func NewLastGood[T any](clk clock.Clock, maxAge time.Duration) *LastGood[T] {
return &LastGood[T]{clk: clk, maxAge: maxAge}
}
// Wrap records every successful result.
func (l *LastGood[T]) Wrap(call func(context.Context) (T, error)) func(context.Context) (T, error) {
return func(ctx context.Context) (T, error) {
v, err := call(ctx)
if err == nil {
l.mu.Lock()
l.value, l.at, l.ok = v, l.clk.Now(), true
l.mu.Unlock()
}
return v, err
}
}
// Fallback serves the remembered value, or the original error if there
// is none or it is too old.
func (l *LastGood[T]) Fallback(_ context.Context, cause error) (T, error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.ok && l.clk.Now().Sub(l.at) <= l.maxAge {
return l.value, nil
}
var zero T
return zero, cause
}The tests run on the fake clock; none of them sleeps. They cover the minimum number of calls (9 of 9 failures stays closed), the inclusive threshold, rejection without calling, probe limits under concurrency (3 admitted, 5 rejected), a failed probe restarting the wait, the time-based window forgetting old failures, count-window eviction, slow-call opening, ignored and business errors, fallbacks (last good value and static), a stale result from an older generation, hooks and counters, and a race test.
package breaker_test
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"academy/circuit-breaker/breaker"
"academy/circuit-breaker/clock"
)
var errBoom = errors.New("boom")
type rig struct {
b *breaker.Breaker
clk *clock.Fake
changes []breaker.StateChange
calls int
}
func newRig(t *testing.T, mod func(*breaker.Config)) *rig {
t.Helper()
r := &rig{clk: clock.NewFake()}
cfg := breaker.Config{
Name: "inventory",
Window: breaker.CountBased,
WindowSize: 10,
MinimumCalls: 10,
FailureRate: 0.5,
OpenDuration: 30 * time.Second,
HalfOpenProbes: 3,
Clock: r.clk,
OnStateChange: func(c breaker.StateChange) { r.changes = append(r.changes, c) },
}
if mod != nil {
mod(&cfg)
}
r.b = breaker.New(cfg)
return r
}
// call runs one protected call that fails when fail is true.
func (r *rig) call(fail bool, took time.Duration) error {
_, err := breaker.Do(context.Background(), r.b, func(context.Context) (string, error) {
r.calls++
r.clk.Advance(took)
if fail {
return "", errBoom
}
return "ok", nil
})
return err
}
func (r *rig) states() []string {
var out []string
for _, c := range r.changes {
out = append(out, c.From.String()+">"+c.To.String())
}
return out
}
func TestMinimumNumberOfCallsHoldsTheBreakerClosed(t *testing.T) {
r := newRig(t, nil)
for i := 0; i < 9; i++ {
_ = r.call(true, time.Millisecond)
}
if r.b.State() != breaker.Closed {
t.Fatalf("9 failures with minimum 10 must not trip, got %s", r.b.State())
}
_ = r.call(true, time.Millisecond) // the 10th recorded call reaches the minimum
if r.b.State() != breaker.Open {
t.Fatalf("10 failures of 10 must trip, got %s", r.b.State())
}
}
func TestFailureRateThresholdIsInclusive(t *testing.T) {
r := newRig(t, nil)
for i := 0; i < 10; i++ {
_ = r.call(i%2 == 0, time.Millisecond) // exactly 50% failures
}
if r.b.State() != breaker.Open {
t.Fatalf("50%% >= 50%% must open, got %s", r.b.State())
}
}
func TestOpenRejectsWithoutCallingTheDependency(t *testing.T) {
r := newRig(t, nil)
r.b.Trip()
before := r.calls
err := r.call(false, 0)
var rej *breaker.RejectedError
if !errors.Is(err, breaker.ErrOpen) || !errors.As(err, &rej) {
t.Fatalf("want ErrOpen with RejectedError, got %v", err)
}
if r.calls != before {
t.Fatal("the dependency must not be called while open")
}
if rej.RetryAfter != 30*time.Second {
t.Fatalf("RetryAfter = %s", rej.RetryAfter)
}
r.clk.Advance(10 * time.Second)
err = r.call(false, 0)
if !errors.As(err, &rej) || rej.RetryAfter != 20*time.Second {
t.Fatalf("RetryAfter must shrink to 20s, got %v", err)
}
}
func TestHalfOpenLimitsProbesAndCloses(t *testing.T) {
r := newRig(t, nil)
r.b.Trip()
r.clk.Advance(30 * time.Second)
release := make(chan struct{})
var wg sync.WaitGroup
var admitted, rejected atomic.Int32
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, err := breaker.Do(context.Background(), r.b, func(context.Context) (int, error) {
admitted.Add(1)
<-release
return 1, nil
})
if errors.Is(err, breaker.ErrOpen) {
rejected.Add(1)
}
}()
}
deadline := time.Now().Add(2 * time.Second)
for rejected.Load() < 5 && time.Now().Before(deadline) {
time.Sleep(time.Millisecond)
}
close(release)
wg.Wait()
if admitted.Load() != 3 || rejected.Load() != 5 {
t.Fatalf("want 3 probes and 5 rejections, got %d and %d", admitted.Load(), rejected.Load())
}
if r.b.State() != breaker.Closed {
t.Fatalf("3 successful probes must close, got %s", r.b.State())
}
if got := r.states(); len(got) != 3 || got[0] != "closed>open" || got[1] != "open>half-open" || got[2] != "half-open>closed" {
t.Fatalf("unexpected transitions %v", got)
}
}
func TestFailedProbeReopensAndRestartsTheWait(t *testing.T) {
r := newRig(t, nil)
r.b.Trip()
r.clk.Advance(30 * time.Second)
_ = r.call(true, 0) // 1 of 3 probes failed: 33% < 50%, still half-open
if r.b.State() != breaker.HalfOpen {
t.Fatalf("want half-open, got %s", r.b.State())
}
_ = r.call(true, 0) // 2 of 3 failed: closing is now impossible
if r.b.State() != breaker.Open {
t.Fatalf("want open, got %s", r.b.State())
}
r.clk.Advance(29 * time.Second)
if err := r.call(false, 0); !errors.Is(err, breaker.ErrOpen) {
t.Fatalf("the wait must restart after the failed probe, got %v", err)
}
}
func TestTimeBasedWindowForgetsOldFailures(t *testing.T) {
r := newRig(t, func(c *breaker.Config) {
c.Window = breaker.TimeBased
c.WindowSize = 10 // seconds
c.MinimumCalls = 5
})
for i := 0; i < 4; i++ {
_ = r.call(true, 0)
}
r.clk.Advance(11 * time.Second) // the four failures leave the window
for i := 0; i < 4; i++ {
_ = r.call(false, 0)
}
_ = r.call(true, 0) // 1 failure of 5 recent calls
if r.b.State() != breaker.Closed {
t.Fatalf("old failures must have expired, got %s", r.b.State())
}
s := r.b.Snapshot()
if s.Total != 5 || s.Failures != 1 {
t.Fatalf("snapshot %+v", s)
}
}
func TestCountWindowEvictsTheOldestCall(t *testing.T) {
r := newRig(t, func(c *breaker.Config) { c.WindowSize = 4; c.MinimumCalls = 4; c.FailureRate = 0.75 })
for _, fail := range []bool{true, true, false, false, false, false} {
_ = r.call(fail, 0)
}
if s := r.b.Snapshot(); s.Total != 4 || s.Failures != 0 {
t.Fatalf("the two failures must have been evicted, got %+v", s)
}
}
func TestSlowCallRateOpensBeforeAnythingFails(t *testing.T) {
r := newRig(t, func(c *breaker.Config) {
c.SlowCallDuration = 2 * time.Second
c.SlowCallRate = 0.5
})
for i := 0; i < 10; i++ {
if err := r.call(false, 3*time.Second); err != nil && !errors.Is(err, breaker.ErrOpen) {
t.Fatal(err)
}
}
if r.b.State() != breaker.Open {
t.Fatalf("10 slow successes must open the breaker, got %s", r.b.State())
}
if got := r.changes[0].Reason; got == "" {
t.Fatal("state change must carry a reason")
}
}
func TestIgnoredErrorsAreNeitherSuccessNorFailure(t *testing.T) {
r := newRig(t, nil)
for i := 0; i < 20; i++ {
_, _ = breaker.Do(context.Background(), r.b, func(context.Context) (int, error) {
return 0, context.Canceled // the caller gave up; the dependency is not to blame
})
}
if r.b.State() != breaker.Closed || r.b.Snapshot().Total != 0 {
t.Fatalf("cancellations must not be recorded: %s %+v", r.b.State(), r.b.Snapshot())
}
if r.b.Stats().Ignored != 20 {
t.Fatalf("ignored = %d", r.b.Stats().Ignored)
}
}
func TestBusinessErrorsCanBeExcludedFromFailures(t *testing.T) {
errNotFound := errors.New("404")
r := newRig(t, func(c *breaker.Config) {
c.IsFailure = func(err error) bool { return !errors.Is(err, errNotFound) }
})
for i := 0; i < 20; i++ {
_, _ = breaker.Do(context.Background(), r.b, func(context.Context) (int, error) { return 0, errNotFound })
}
if r.b.State() != breaker.Closed {
t.Fatalf("a 404 is a normal answer, got %s", r.b.State())
}
}
func TestFallbackForRejectionAndFailure(t *testing.T) {
r := newRig(t, nil)
lg := breaker.NewLastGood[string](r.clk, time.Minute)
good := lg.Wrap(func(context.Context) (string, error) { return "fresh", nil })
bad := func(context.Context) (string, error) { return "", errBoom }
v, _ := breaker.DoFallback(context.Background(), r.b, good, lg.Fallback)
if v != "fresh" {
t.Fatal(v)
}
v, err := breaker.DoFallback(context.Background(), r.b, bad, lg.Fallback)
if v != "fresh" || err != nil {
t.Fatalf("a failure must be answered from the last good value, got %q %v", v, err)
}
r.b.Trip()
v, err = breaker.DoFallback(context.Background(), r.b, bad, lg.Fallback)
if v != "fresh" || err != nil {
t.Fatalf("a rejection must be answered from the last good value, got %q %v", v, err)
}
r.clk.Advance(2 * time.Minute)
if _, err = breaker.DoFallback(context.Background(), r.b, bad, lg.Fallback); err == nil {
t.Fatal("a value older than maxAge must not be served")
}
v, _ = breaker.DoFallback(context.Background(), r.b, bad, breaker.Static("default"))
if v != "default" {
t.Fatal(v)
}
}
func TestResultFromBeforeAStateChangeIsNotRecorded(t *testing.T) {
r := newRig(t, nil)
started := make(chan struct{})
finish := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
_, _ = breaker.Do(context.Background(), r.b, func(context.Context) (int, error) {
close(started)
<-finish
return 0, errBoom
})
}()
<-started
r.b.Trip()
r.b.Reset()
close(finish)
<-done
if s := r.b.Snapshot(); s.Total != 0 {
t.Fatalf("a slow straggler from the old generation must not pollute the new window: %+v", s)
}
}
func TestMetricsAndHooks(t *testing.T) {
var events []breaker.Result
r := newRig(t, func(c *breaker.Config) {
c.OnCall = func(e breaker.CallEvent) { events = append(events, e.Result) }
})
_ = r.call(false, 0)
_ = r.call(true, 0)
r.b.Trip()
_ = r.call(false, 0)
st := r.b.Stats()
if st.Successes != 1 || st.Failures != 1 || st.Rejected != 1 || st.Transitions != 1 || st.State != breaker.Open {
t.Fatalf("stats %+v", st)
}
want := []breaker.Result{breaker.ResultSuccess, breaker.ResultFailure, breaker.ResultRejected}
for i, w := range want {
if events[i] != w {
t.Fatalf("event %d = %s want %s", i, events[i], w)
}
}
}
func TestConcurrentCallsAreRaceFree(t *testing.T) {
r := newRig(t, func(c *breaker.Config) { c.WindowSize = 50; c.MinimumCalls = 20 })
var wg sync.WaitGroup
for g := 0; g < 16; g++ {
wg.Add(1)
go func(g int) {
defer wg.Done()
for i := 0; i < 200; i++ {
_, _ = breaker.Do(context.Background(), r.b, func(context.Context) (int, error) {
if (g+i)%3 == 0 {
return 0, errBoom
}
return 1, nil
})
if i%50 == 0 {
r.clk.Advance(time.Second)
}
}
}(g)
}
wg.Wait()
st := r.b.Stats()
if st.Successes+st.Failures+st.Rejected == 0 {
t.Fatal("no calls recorded")
}
}The HTTP integration is a RoundTripper: one breaker per host (per-dependency granularity), 5xx and 429 counted, 4xx treated as an answer, and the caller still receives the real 503 body while the breaker counts it.
// Package httpguard puts one breaker per upstream host in front of an
// http.RoundTripper, so the standard http.Client gets circuit breaking.
package httpguard
import (
"context"
"net/http"
"sync"
"academy/circuit-breaker/breaker"
)
// Transport is a RoundTripper that routes each request through the
// breaker of its host (per-dependency granularity).
type Transport struct {
Next http.RoundTripper
// New builds the breaker for a host the first time it is seen.
New func(host string) *breaker.Breaker
mu sync.Mutex
breakers map[string]*breaker.Breaker
}
func (t *Transport) forHost(host string) *breaker.Breaker {
t.mu.Lock()
defer t.mu.Unlock()
if t.breakers == nil {
t.breakers = map[string]*breaker.Breaker{}
}
b, ok := t.breakers[host]
if !ok {
b = t.New(host)
t.breakers[host] = b
}
return b
}
// Breaker exposes the breaker of a host for metrics and operators.
func (t *Transport) Breaker(host string) *breaker.Breaker { return t.forHost(host) }
// statusError turns a bad status into an error the breaker can count,
// while the original response still reaches the caller.
type statusError struct{ code int }
func (e statusError) Error() string { return http.StatusText(e.code) }
// IsServerFault says which statuses are the dependency's fault: 5xx and
// 429. A 404 or 400 is a correct answer to a bad question, not a failure.
func IsServerFault(code int) bool { return code >= 500 || code == http.StatusTooManyRequests }
// RoundTrip implements http.RoundTripper.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
b := t.forHost(req.URL.Host)
var resp *http.Response
_, err := breaker.Do(req.Context(), b, func(context.Context) (struct{}, error) {
var err error
resp, err = t.Next.RoundTrip(req)
if err != nil {
return struct{}{}, err
}
if IsServerFault(resp.StatusCode) {
return struct{}{}, statusError{resp.StatusCode}
}
return struct{}{}, nil
})
if err != nil && resp != nil {
return resp, nil // hand the real 5xx to the caller; the breaker has already counted it
}
return resp, err
}package httpguard_test
import (
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"academy/circuit-breaker/breaker"
"academy/circuit-breaker/clock"
"academy/circuit-breaker/httpguard"
)
func TestPerHostBreakersAndFiveHundredCounting(t *testing.T) {
var badHits, goodHits atomic.Int32
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
badHits.Add(1)
w.WriteHeader(http.StatusServiceUnavailable)
}))
defer bad.Close()
good := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
goodHits.Add(1)
if r.URL.Path == "/missing" {
w.WriteHeader(http.StatusNotFound)
return
}
_, _ = w.Write([]byte("ok"))
}))
defer good.Close()
clk := clock.NewFake()
tr := &httpguard.Transport{
Next: http.DefaultTransport,
New: func(host string) *breaker.Breaker {
return breaker.New(breaker.Config{Name: host, WindowSize: 4, MinimumCalls: 4, FailureRate: 0.5,
OpenDuration: 10 * time.Second, Clock: clk})
},
}
c := &http.Client{Transport: tr}
for i := 0; i < 4; i++ {
resp, err := c.Get(bad.URL)
if err != nil || resp.StatusCode != 503 {
t.Fatalf("the caller must still see the real 503: %v %v", resp, err)
}
resp.Body.Close()
}
if _, err := c.Get(bad.URL); !errors.Is(err, breaker.ErrOpen) {
t.Fatalf("5th call must be rejected locally, got %v", err)
}
if badHits.Load() != 4 {
t.Fatalf("the open breaker must not reach the server, hits=%d", badHits.Load())
}
// A different host has its own breaker, and a 404 is not a failure.
for i := 0; i < 8; i++ {
resp, err := c.Get(good.URL + "/missing")
if err != nil || resp.StatusCode != 404 {
t.Fatalf("good host must stay reachable: %v %v", resp, err)
}
resp.Body.Close()
}
if tr.Breaker(good.Listener.Addr().String()).State() != breaker.Closed {
t.Fatal("404 must not trip the breaker")
}
}The command replays the outage from the Lab in virtual time: 100 requests per second for 120 s, dependency down from second 20 to second 75, three attempts per request, three client designs.
// Command outage replays a 55 second dependency outage in virtual time and
// compares three clients: retries only, breaker around the retries, and
// breaker inside the retries. No sleeping: a fake clock moves 10 ms per
// request, so the run is instant and the numbers are reproducible.
package main
import (
"context"
"errors"
"fmt"
"time"
"academy/circuit-breaker/breaker"
"academy/circuit-breaker/clock"
)
const (
step = 10 * time.Millisecond // 100 requests per second
total = 120 * time.Second
outageStart = 20 * time.Second
outageEnd = 75 * time.Second
timeout = 2 * time.Second // what one failed attempt costs the user
attempts = 3
)
var errTimeout = errors.New("timeout")
type world struct {
clk *clock.Fake
depCalls int
outageHit int
}
// call is one attempt against the dependency.
func (w *world) call(context.Context) (int, error) {
w.depCalls++
at := w.clk.Now().Sub(clock.NewFake().Now())
if at >= outageStart && at < outageEnd {
w.outageHit++
return 0, errTimeout
}
return 1, nil
}
type result struct {
name string
depCalls int
outageHit int
rejected int
userWait time.Duration // total time users spent waiting on timeouts
firstOK time.Duration // first success after the outage ended
stateTrail string
}
func newBreaker(w *world, trail *string) *breaker.Breaker {
return breaker.New(breaker.Config{
Name: "inventory", Window: breaker.CountBased, WindowSize: 50, MinimumCalls: 20,
FailureRate: 0.5, OpenDuration: 10 * time.Second, HalfOpenProbes: 3, Clock: w.clk,
OnStateChange: func(c breaker.StateChange) {
*trail += fmt.Sprintf(" %s@%ds", c.To, int(c.At.Sub(clock.NewFake().Now()).Seconds()))
},
})
}
func run(name string, mk func(w *world, trail *string) func(ctx context.Context) (time.Duration, error)) result {
w := &world{clk: clock.NewFake()}
r := result{name: name}
do := mk(w, &r.stateTrail)
for at := time.Duration(0); at < total; at += step {
w.clk.Advance(step)
wait, err := do(context.Background())
r.userWait += wait
if errors.Is(err, breaker.ErrOpen) {
r.rejected++
}
if err == nil && at >= outageEnd && r.firstOK == 0 {
r.firstOK = at
}
}
r.depCalls, r.outageHit = w.depCalls, w.outageHit
return r
}
// retry calls fn up to attempts times and never retries a rejection.
func retry(ctx context.Context, fn func(context.Context) (int, error)) (time.Duration, error) {
var wait time.Duration
var err error
for i := 0; i < attempts; i++ {
if _, err = fn(ctx); err == nil {
return wait, nil
}
if errors.Is(err, breaker.ErrOpen) {
return wait, err
}
wait += timeout
}
return wait, err
}
func main() {
results := []result{
run("A retries only", func(w *world, _ *string) func(context.Context) (time.Duration, error) {
return func(ctx context.Context) (time.Duration, error) { return retry(ctx, w.call) }
}),
run("B breaker around retries", func(w *world, trail *string) func(context.Context) (time.Duration, error) {
b := newBreaker(w, trail)
return func(ctx context.Context) (time.Duration, error) {
var wait time.Duration
_, err := breaker.Do(ctx, b, func(ctx context.Context) (int, error) {
var err error
wait, err = retry(ctx, w.call)
return 0, err
})
return wait, err
}
}),
run("C breaker inside retries", func(w *world, trail *string) func(context.Context) (time.Duration, error) {
b := newBreaker(w, trail)
return func(ctx context.Context) (time.Duration, error) {
return retry(ctx, func(ctx context.Context) (int, error) { return breaker.Do(ctx, b, w.call) })
}
}),
}
fmt.Printf("%-26s %10s %12s %10s %12s %10s\n", "client", "dep calls", "in outage", "rejected", "user wait", "recovered")
for _, r := range results {
fmt.Printf("%-26s %10d %12d %10d %12s %10s\n", r.name, r.depCalls, r.outageHit, r.rejected,
r.userWait.Round(time.Second), r.firstOK-outageEnd)
}
for _, r := range results[1:] {
fmt.Printf("%s transitions:%s\n", r.name, r.stateTrail)
}
}Finally, the same configuration expressed with sony/gobreaker v2, to see the API difference side by side.
// Command gobreakercmp configures sony/gobreaker v2 to behave as close as
// it can to our breaker, and shows where the two differ.
package main
import (
"errors"
"fmt"
"time"
"github.com/sony/gobreaker/v2"
)
func main() {
var trail []string
cb := gobreaker.NewCircuitBreaker[string](gobreaker.Settings{
Name: "inventory",
MaxRequests: 3, // our HalfOpenProbes
Interval: 10 * time.Second, // closed-state counting period
BucketPeriod: time.Second, // rolling window of 10 one-second buckets (our TimeBased window)
Timeout: 30 * time.Second, // our OpenDuration
ReadyToTrip: func(c gobreaker.Counts) bool {
// our FailureRate 0.5 with MinimumCalls 10 has to be written by hand
return c.Requests >= 10 && float64(c.TotalFailures)/float64(c.Requests) >= 0.5
},
OnStateChange: func(name string, from, to gobreaker.State) {
trail = append(trail, fmt.Sprintf("%s: %s -> %s", name, from, to))
},
IsExcluded: func(err error) bool { return errors.Is(err, errCanceled) }, // our IsIgnored
})
boom := errors.New("boom")
for i := 0; i < 10; i++ {
_, _ = cb.Execute(func() (string, error) { return "", boom })
}
_, err := cb.Execute(func() (string, error) { return "never runs", nil })
fmt.Println("after 10 failures:", cb.State(), "|", err, "|", errors.Is(err, gobreaker.ErrOpenState))
for _, line := range trail {
fmt.Println(line)
}
}
var errCanceled = errors.New("canceled")Our breaker.Config | gobreaker.Settings | Difference |
|---|---|---|
WindowSize, Window | Interval, BucketPeriod | gobreaker: fixed interval by default, rolling when BucketPeriod is set |
MinimumCalls, FailureRate | ReadyToTrip(Counts) bool | gobreaker has no built-in rate; you write the formula |
SlowCallDuration, SlowCallRate | none | Slow calls are not tracked by gobreaker |
OpenDuration | Timeout | Same meaning; 0 means 60 s in gobreaker |
HalfOpenProbes | MaxRequests | gobreaker admits MaxRequests probes in half-open; ours also reopens early once closing is impossible |
IsFailure, IsIgnored | IsSuccessful, IsExcluded | Same idea, inverted naming |
OnStateChange, OnCall, Stats() | OnStateChange, Counts() | We add a per-call hook and a reason string |
Do[T], DoFallback[T] | Execute(func() (T, error)) | Both are generic; ours takes a context.Context and a fallback |
*RejectedError with RetryAfter | ErrOpenState, ErrTooManyRequests | We say how long to wait |
Trip(), Reset() | none | Manual operator control |
| Local only | DistributedCircuitBreaker with a SharedDataStore | gobreaker v2 ships a shared-state variant (from its Go documentation) |
The Go angle
Go's standard library has no breaker, but its pieces fit one well. context.Context carries the deadline that makes a hung call a failure and the cancellation that must not count as one (context.Canceled is ignored by default in our code). http.RoundTripper is the natural middleware point: one breaker per host, every http.Client user gets it. Generics (since Go 1.18) let Do[T] return a typed result without interface{}. The race detector is the test that matters most, because the state machine is shared by every goroutine. Two Go-specific rules: never run the protected call under the mutex, and treat a panic in the call as a failure and re-panic (gobreaker does exactly this; our code does not handle panics, which is a limit to know). Libraries: sony/gobreaker for simplicity, failsafe-go for composing retry, timeout, bulkhead, hedge, fallback and breaker with one executor. The unit for tuning is a Config literal per dependency, kept in the service's own configuration.
Laravel
Before
The Laravel client retries three times with a 2-second timeout. During an outage a PHP-FPM worker is occupied for up to 6 seconds per request, so with 20 workers about 3 requests per second saturate the pool (20 workers / 6 s, our arithmetic).
<?php
namespace App\Before;
use Illuminate\Support\Facades\Http;
// Before: retry everything, remember nothing. During an outage every web
// request waits timeout x attempts, and the dependency receives all of it.
final class InventoryClient
{
public function stock(string $sku): int
{
$response = Http::baseUrl(config('services.inventory.url'))
->timeout(2)
->retry(3, 100)
->get("/stock/{$sku}");
return (int) $response->json('available');
}
}After
Laravel 13 has no first-party circuit breaker, but its HTTP client, cache, events and Pulse give every part. PHP-FPM processes live for one request, so in-process memory cannot hold breaker state: it has to live in a shared store, and the Laravel Cache (Redis in production) provides one. Counters use Cache::add (atomic, creates the key with a TTL) followed by Cache::increment; transitions use Cache::lock; counter keys include the breaker generation so late results from before a transition are ignored; the state changes dispatch an event.
<?php
// One entry per dependency, not one global breaker.
return [
'store' => env('BREAKER_STORE', 'redis'),
'defaults' => [
'window_seconds' => 30, // time-based window
'minimum_calls' => 20, // no rate is evaluated below this
'failure_rate' => 0.5, // open at or above 50% failures
'slow_call_ms' => 0, // 0 disables the slow-call rate
'slow_call_rate' => 1.0,
'open_seconds' => 30, // wait before probing
'half_open_probes' => 3,
],
'dependencies' => [
'inventory' => ['failure_rate' => 0.5, 'open_seconds' => 20],
'payments' => ['minimum_calls' => 10, 'failure_rate' => 0.3, 'open_seconds' => 60],
],
];<?php
namespace App\Resilience;
final readonly class BreakerConfig
{
public function __construct(
public int $windowSeconds = 30,
public int $minimumCalls = 20,
public float $failureRate = 0.5,
public int $slowCallMs = 0,
public float $slowCallRate = 1.0,
public int $openSeconds = 30,
public int $halfOpenProbes = 3,
) {
}
/** @param array<string, int|float> $values */
public static function fromArray(array $values): self
{
return new self(
windowSeconds: (int) ($values['window_seconds'] ?? 30),
minimumCalls: (int) ($values['minimum_calls'] ?? 20),
failureRate: (float) ($values['failure_rate'] ?? 0.5),
slowCallMs: (int) ($values['slow_call_ms'] ?? 0),
slowCallRate: (float) ($values['slow_call_rate'] ?? 1.0),
openSeconds: (int) ($values['open_seconds'] ?? 30),
halfOpenProbes: (int) ($values['half_open_probes'] ?? 3),
);
}
}<?php
namespace App\Resilience;
use RuntimeException;
final class CircuitOpenException extends RuntimeException
{
public function __construct(public readonly string $dependency, public readonly int $retryAfterSeconds)
{
parent::__construct("Circuit for [{$dependency}] is open; retry after {$retryAfterSeconds}s.");
}
}<?php
namespace App\Events;
final readonly class CircuitBreakerStateChanged
{
public function __construct(
public string $dependency,
public string $from,
public string $to,
public string $reason,
public int $at,
) {
}
}<?php
namespace App\Resilience;
use App\Events\CircuitBreakerStateChanged;
use Closure;
use Illuminate\Cache\Repository;
use Illuminate\Contracts\Events\Dispatcher;
use Throwable;
/**
* A circuit breaker whose state lives in the Laravel cache (Redis in
* production), so every web and queue worker shares one view of a
* dependency. Counters are per generation and per second, written with
* Cache::add + Cache::increment; state transitions run under Cache::lock.
*/
final class CircuitBreaker
{
private const CLOSED = 'closed';
private const OPEN = 'open';
private const HALF_OPEN = 'half_open';
public function __construct(
private readonly Repository $cache,
private readonly Dispatcher $events,
private readonly string $name,
private readonly BreakerConfig $config,
private readonly ?Closure $isFailure = null,
) {
}
/**
* @template T
* @param Closure(): T $call
* @param Closure(Throwable): T|null $fallback
* @return T
*/
public function call(Closure $call, ?Closure $fallback = null): mixed
{
try {
$permit = $this->acquire();
} catch (CircuitOpenException $e) {
if ($fallback === null) {
throw $e;
}
return $fallback($e);
}
$started = hrtime(true);
try {
$result = $call();
} catch (Throwable $e) {
$failed = $this->isFailure === null || ($this->isFailure)($e);
$this->record($permit, $failed, $this->elapsedMs($started));
if (! $failed) {
throw $e; // a normal business answer such as a 404
}
return $fallback !== null ? $fallback($e) : throw $e;
}
$this->record($permit, false, $this->elapsedMs($started));
return $result;
}
/** @return array{state: string, generation: int, opened_at: int} */
public function snapshot(): array
{
return $this->state();
}
public function trip(): void
{
$this->transition(self::OPEN, 'manual trip', fromAny: true);
}
public function reset(): void
{
$this->transition(self::CLOSED, 'manual reset', fromAny: true);
}
/** @return array{generation: int, state: string} */
private function acquire(): array
{
$state = $this->state();
if ($state['state'] === self::OPEN) {
$waited = $this->now() - $state['opened_at'];
if ($waited < $this->config->openSeconds) {
throw new CircuitOpenException($this->name, $this->config->openSeconds - $waited);
}
$this->transition(self::HALF_OPEN, 'open duration elapsed');
$state = $this->state();
}
if ($state['state'] === self::HALF_OPEN) {
// Cache::add makes the counter exist; increment is atomic, so
// exactly halfOpenProbes callers get a ticket across all workers.
$key = $this->key($state['generation'], 'probes');
$this->cache->add($key, 0, $this->config->openSeconds * 2);
if ($this->cache->increment($key) > $this->config->halfOpenProbes) {
throw new CircuitOpenException($this->name, $this->config->openSeconds);
}
}
return ['generation' => $state['generation'], 'state' => $state['state']];
}
/** @param array{generation: int, state: string} $permit */
private function record(array $permit, bool $failed, int $elapsedMs): void
{
$slow = $this->config->slowCallMs > 0 && $elapsedMs >= $this->config->slowCallMs;
$current = $this->state();
if ($current['generation'] !== $permit['generation']) {
return; // the state changed while this call was in flight
}
if ($permit['state'] === self::HALF_OPEN) {
$this->recordProbe($current['generation'], $failed || $slow);
return;
}
$second = $this->now();
$ttl = $this->config->windowSeconds + 5;
foreach (['total' => true, 'failed' => $failed, 'slow' => $slow] as $field => $count) {
if (! $count) {
continue;
}
$key = $this->key($current['generation'], "{$second}:{$field}");
$this->cache->add($key, 0, $ttl);
$this->cache->increment($key);
}
$this->evaluate($current['generation']);
}
private function evaluate(int $generation): void
{
$total = $failed = $slow = 0;
$now = $this->now();
for ($i = 0; $i < $this->config->windowSeconds; $i++) {
$second = $now - $i;
$total += (int) $this->cache->get($this->key($generation, "{$second}:total"), 0);
$failed += (int) $this->cache->get($this->key($generation, "{$second}:failed"), 0);
$slow += (int) $this->cache->get($this->key($generation, "{$second}:slow"), 0);
}
if ($total < $this->config->minimumCalls) {
return;
}
if ($failed / $total >= $this->config->failureRate) {
$this->transition(self::OPEN, sprintf('failure rate %d/%d', $failed, $total));
} elseif ($this->config->slowCallMs > 0 && $slow / $total >= $this->config->slowCallRate) {
$this->transition(self::OPEN, sprintf('slow call rate %d/%d', $slow, $total));
}
}
private function recordProbe(int $generation, bool $bad): void
{
$done = $this->key($generation, 'probes_done');
$bads = $this->key($generation, 'probes_bad');
$this->cache->add($done, 0, $this->config->openSeconds * 2);
$this->cache->add($bads, 0, $this->config->openSeconds * 2);
$completed = $this->cache->increment($done);
$failures = $bad ? $this->cache->increment($bads) : (int) $this->cache->get($bads, 0);
if ($failures / $this->config->halfOpenProbes >= $this->config->failureRate) {
$this->transition(self::OPEN, 'probe failed');
} elseif ($completed >= $this->config->halfOpenProbes) {
$this->transition(self::CLOSED, 'probes succeeded');
}
}
/**
* One writer at a time moves the state; the lock keeps two workers from
* both opening the circuit and bumping the generation twice.
*/
private function transition(string $to, string $reason, bool $fromAny = false): void
{
$lock = $this->cache->lock($this->key(0, 'transition'), 5);
if (! $lock->get()) {
return; // another worker is already transitioning
}
try {
$state = $this->state();
$from = $state['state'];
$legal = match ($to) {
self::OPEN => in_array($from, [self::CLOSED, self::HALF_OPEN], true),
self::HALF_OPEN => $from === self::OPEN,
self::CLOSED => $from === self::HALF_OPEN,
default => false,
};
if ($from === $to || (! $legal && ! $fromAny)) {
return;
}
$this->cache->forever($this->key(0, 'state'), [
'state' => $to,
'generation' => $state['generation'] + 1,
'opened_at' => $to === self::OPEN ? $this->now() : 0,
]);
$this->events->dispatch(new CircuitBreakerStateChanged($this->name, $from, $to, $reason, $this->now()));
} finally {
$lock->release();
}
}
/** @return array{state: string, generation: int, opened_at: int} */
private function state(): array
{
return $this->cache->get($this->key(0, 'state'))
?? ['state' => self::CLOSED, 'generation' => 0, 'opened_at' => 0];
}
private function key(int $generation, string $suffix): string
{
return "breaker:{$this->name}:{$generation}:{$suffix}";
}
private function now(): int
{
return now()->getTimestamp();
}
private function elapsedMs(int|float $started): int
{
return (int) ((hrtime(true) - $started) / 1_000_000);
}
}Guzzle middleware registered with withRequestMiddleware and withResponseMiddleware can inspect or modify the request and response but cannot return a fallback from inside the handler stack, so the guard wraps the call instead, and Http::macro makes it available as Http::guarded('inventory', ...). The service provider also registers the listener that logs state changes and feeds Pulse.
<?php
namespace App\Resilience;
use Closure;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Throwable;
/**
* Wraps one pending HTTP request in a breaker. Guzzle middleware cannot
* answer with a fallback from inside the handler stack, so the guard sits
* around the call instead: the breaker is outside the retries.
*/
final class GuardedHttp
{
public function __construct(
private readonly CircuitBreaker $breaker,
private readonly PendingRequest $request,
) {
}
/**
* The callback must call ->throw() so 4xx/5xx become exceptions the
* breaker can classify. The fallback runs for rejections and failures,
* never for a normal 404.
*
* @template T
* @param Closure(PendingRequest): T $send
* @param Closure(Throwable): T|null $fallback
* @return T
*/
public function send(Closure $send, ?Closure $fallback = null): mixed
{
return $this->breaker->call(fn (): mixed => $send($this->request), $fallback);
}
/** What the breaker counts: connection problems, 5xx and 429. A 404 is an answer. */
public static function isFailure(Throwable $e): bool
{
if ($e instanceof ConnectionException) {
return true;
}
if ($e instanceof RequestException) {
$status = $e->response->status();
return $status >= 500 || $status === 429;
}
return false;
}
}<?php
namespace App\Providers;
use App\Events\CircuitBreakerStateChanged;
use App\Resilience\BreakerConfig;
use App\Resilience\CircuitBreaker;
use App\Resilience\GuardedHttp;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Laravel\Pulse\Facades\Pulse;
final class ResilienceServiceProvider extends ServiceProvider
{
public function register(): void
{
// One breaker per dependency, resolved by name.
$this->app->bind('breaker', fn ($app) => fn (string $name): CircuitBreaker => new CircuitBreaker(
cache: Cache::store(config('breakers.store')),
events: $app->make(Dispatcher::class),
name: $name,
config: BreakerConfig::fromArray(
(config("breakers.dependencies.{$name}") ?? []) + config('breakers.defaults'),
),
isFailure: GuardedHttp::isFailure(...),
));
}
public function boot(): void
{
// Http::guarded('inventory', fn ($http) => $http->timeout(2))
Http::macro('guarded', function (string $dependency, ?callable $configure = null): GuardedHttp {
$request = Http::asJson()->acceptJson();
if ($configure !== null) {
$request = $configure($request) ?? $request;
}
return new GuardedHttp(app('breaker')($dependency), $request);
});
// A state change is the alert-worthy event: log it, count it for Pulse.
Event::listen(function (CircuitBreakerStateChanged $e): void {
Log::warning('circuit breaker state changed', [
'dependency' => $e->dependency, 'from' => $e->from, 'to' => $e->to, 'reason' => $e->reason,
]);
Pulse::record('circuit_breaker', "{$e->dependency}:{$e->to}")->count();
});
}
}The service uses the guard with the retries inside the breaker call, a cached last-good value as the first fallback rung and an honest "unknown" as the last.
<?php
namespace App\Services;
use App\Resilience\GuardedHttp;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;
// After: a per-dependency breaker around the retries, with a fallback ladder.
final class InventoryClient
{
/** @return array{available: int|null, source: string} */
public function stock(string $sku): array
{
$guard = Http::guarded('inventory', fn (PendingRequest $http) => $http
->baseUrl(config('services.inventory.url'))
->timeout(2)
->retry(2, 100, throw: false)); // the retries stay INSIDE the breaker call
return $guard->send(
send: function (PendingRequest $http) use ($sku): array {
$available = (int) $http->get("/stock/{$sku}")->throw()->json('available');
$stock = ['available' => $available, 'source' => 'live'];
Cache::put("stock:last-good:{$sku}", $stock, 600); // feeds the cached-value rung
return $stock;
},
fallback: fn (Throwable $e): array => $this->degraded($sku),
);
}
/** Ladder: last good value, then an honest "unknown". */
private function degraded(string $sku): array
{
$last = Cache::get("stock:last-good:{$sku}");
return $last !== null
? ['source' => 'stale'] + $last
: ['available' => null, 'source' => 'degraded']; // the UI shows "check in store"
}
}Pulse has no breaker card, but a custom card is a Livewire component extending Laravel\Pulse\Livewire\Card, reading what Pulse::record wrote with aggregate.
<?php
namespace App\Livewire\Pulse;
use Laravel\Pulse\Livewire\Card;
use Livewire\Attributes\Lazy;
#[Lazy]
final class Breakers extends Card
{
public function render()
{
// Transition counts per "dependency:new_state" for the period shown.
$transitions = $this->aggregate('circuit_breaker', ['count']);
return view('livewire.pulse.breakers', [
'transitions' => $transitions,
]);
}
}<x-pulse::card :cols="$cols" :rows="$rows" :class="$class" wire:poll.5s="">
<x-pulse::card-header name="Circuit breakers" />
<x-pulse::scroll :expand="$expand">
@if ($transitions->isEmpty())
<x-pulse::no-results />
@else
<x-pulse::table>
<x-pulse::thead>
<tr>
<x-pulse::th>Dependency : new state</x-pulse::th>
<x-pulse::th class="text-right">Transitions</x-pulse::th>
</tr>
</x-pulse::thead>
<tbody>
@foreach ($transitions as $row)
<tr wire:key="{{ $row->key }}">
<x-pulse::td>{{ $row->key }}</x-pulse::td>
<x-pulse::td numeric>{{ number_format($row->count) }}</x-pulse::td>
</tr>
@endforeach
</tbody>
</x-pulse::table>
@endif
</x-pulse::scroll>
</x-pulse::card>An audit table makes state changes queryable after the cache entries are gone.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
// An audit trail of state changes: who opened what, when, and why.
public function up(): void
{
Schema::create('breaker_events', function (Blueprint $table): void {
$table->id();
$table->string('dependency', 64)->index();
$table->string('from_state', 16);
$table->string('to_state', 16);
$table->string('reason', 255);
$table->timestamp('occurred_at')->index();
});
}
public function down(): void
{
Schema::dropIfExists('breaker_events');
}
};-- Which dependencies flapped in the last day, and how often?
SELECT dependency,
COUNT(*) FILTER (WHERE to_state = 'open') AS opened,
COUNT(*) FILTER (WHERE to_state = 'closed') AS closed,
MIN(occurred_at) FILTER (WHERE to_state = 'open') AS first_open
FROM breaker_events
WHERE occurred_at >= now() - interval '1 day'
GROUP BY dependency
HAVING COUNT(*) FILTER (WHERE to_state = 'open') >= 3
ORDER BY opened DESC;The feature tests use Http::fake with a closure (a later fake() call does not replace an earlier stub), travel() to move time, and Event::fake to assert the transitions.
<?php
namespace Tests\Feature;
use App\Events\CircuitBreakerStateChanged;
use App\Services\InventoryClient;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
final class CircuitBreakerTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config(['breakers.store' => 'array', 'services.inventory.url' => 'https://inventory.test']);
Cache::store('array')->flush();
}
public function test_it_opens_after_the_minimum_number_of_failing_calls_and_stops_calling(): void
{
Event::fake([CircuitBreakerStateChanged::class]);
Http::fake(['inventory.test/*' => Http::response([], 503)]);
for ($i = 0; $i < 30; $i++) {
$result = app(InventoryClient::class)->stock('sku-1');
$this->assertSame('degraded', $result['source']);
}
// 20 recorded calls x 2 attempts each, then the breaker rejects locally.
Http::assertSentCount(40);
Event::assertDispatched(
CircuitBreakerStateChanged::class,
fn ($e) => $e->dependency === 'inventory' && $e->to === 'open',
);
}
public function test_it_probes_after_the_open_duration_and_closes_on_success(): void
{
Event::fake([CircuitBreakerStateChanged::class]);
$up = false; // later fake() calls do not override earlier stubs, so flip a flag instead
Http::fake(function () use (&$up) {
return $up ? Http::response(['available' => 7]) : Http::response([], 503);
});
for ($i = 0; $i < 25; $i++) {
app(InventoryClient::class)->stock('sku-1');
}
$this->travel(21)->seconds(); // open_seconds for inventory is 20
$up = true;
for ($i = 0; $i < 3; $i++) {
$this->assertSame('live', app(InventoryClient::class)->stock('sku-1')['source']);
}
Event::assertDispatched(CircuitBreakerStateChanged::class, fn ($e) => $e->to === 'half_open');
Event::assertDispatched(CircuitBreakerStateChanged::class, fn ($e) => $e->to === 'closed');
}
public function test_it_serves_the_last_good_value_while_open(): void
{
$up = true;
Http::fake(function () use (&$up) {
return $up ? Http::response(['available' => 7]) : Http::response([], 503);
});
$this->assertSame('live', app(InventoryClient::class)->stock('sku-1')['source']);
$up = false;
app('breaker')('inventory')->trip();
$stale = app(InventoryClient::class)->stock('sku-1');
$this->assertSame(['source' => 'stale', 'available' => 7], $stale);
}
public function test_a_404_is_an_answer_not_a_failure(): void
{
Http::fake(['inventory.test/*' => Http::response([], 404)]);
for ($i = 0; $i < 30; $i++) {
try {
app(InventoryClient::class)->stock('missing');
} catch (\Illuminate\Http\Client\RequestException) {
// the caller handles "not found"; the breaker must not count it
}
}
$this->assertSame('closed', app('breaker')('inventory')->snapshot()['state']);
}
}The Laravel angle
Four Laravel features carry the design. The HTTP client's timeout, connectTimeout and retry supply the inner layers; ConnectionException is what a timeout or refused connection becomes, and throw() turns 4xx and 5xx into RequestException, which is where the breaker classifies. The Cache facade, with Redis as the store, supplies shared state: Cache::add ("The add method is an atomic operation"), Cache::increment, Cache::forever and Cache::lock(...)->get(). Http::macro gives a fluent entry point. Pulse's Pulse::record(...)->count() and a custom Card give a dashboard row. Limits to state plainly: the counters are approximate under heavy contention; a Redis outage should fail open (as written it would throw: wrap acquire() accordingly in production); reading the window sums up to window_seconds keys per call (use a Lua script or a bucketed hash if that matters); and Pulse aggregates transitions, it does not show the live state (read the state key from the cache for that). For Octane, keep the breaker stateless in the process (this one is) and resolve it per call. Queue workers share the same Redis state, which is what you want: a job that fails because the dependency is open can release() itself with a delay rather than burn retries.
Solving the classic problems
A slow dependency exhausts the worker pool
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Per-attempt timeout | Http::timeout(2), context.WithTimeout | Bounds the damage of each call | Does not stop new calls |
| Slow-call rate | Open at 50% slower than 2 s | Trips before errors appear | Needs a duration per endpoint |
| Bulkhead | Semaphore per dependency | Caps concurrency immediately | Rejections need a fallback |
| Breaker | Open after the window shows the problem | Stops all calls for a while | Takes a window to react |
Use all four: timeout innermost, bulkhead, breaker, fallback outermost. Code: SlowCallDuration in the Go config, slow_call_ms in config/breakers.php.
Retry storm during an outage
The unprotected client in the Lab makes 23,000 dependency calls over the 120-second run, 16,500 of them while the dependency is down. A breaker around the retries makes 105 calls during the outage; one inside makes 35. See the Lab for the full table and the cost: about 5 seconds of extra fallbacks after recovery.
A dependency that flaps
| Symptom | Cause | Fix |
|---|---|---|
| Opens and closes every 30 seconds | One probe batch fails, the wait restarts | Longer open duration; more probes; check the dependency's real recovery time |
| Opens on every deploy of the dependency | A short blip trips a tiny window | Larger minimum number of calls and a longer window; tolerate the deploy |
| Opens at night | Low traffic, tiny samples | Time-based window plus a minimum; or disable the breaker below a traffic floor |
Thundering herd of probes
3000 instances with 10 probes each send 30,000 trial calls at a dependency that has just restarted. Fixes: jitter the open duration per instance; probe count 1 to 3; shared state with one probe ticket pool (the Laravel version: Cache::add + Cache::increment); or let the mesh eject and re-admit hosts gradually (Envoy's ejection time grows with repeated ejections).
Double charge after a timeout
A payment call times out, the breaker counts a failure, the client retries and the first charge had succeeded. The breaker is not the fix: send an idempotency key with the request (API Idempotency), treat a payment timeout as "unknown", and reconcile. With the breaker open, fail fast rather than invent an answer.
The breaker hides an outage
The fallback serves stale data for two days and nobody noticed. Fix: alert on the fallback share and on "open for more than N minutes", bound the age of cached fallbacks, and show the staleness to the user.
Probes are real calls and have side effects
A half-open probe that is a POST /orders is a real order. Fixes: probe with a read or a dedicated lightweight endpoint, or run active health checks beside the breaker (Envoy active health checking next to outlier detection; the Envoy docs say they can be used together or independently).
Choosing
Which dependency needs a breaker
| Dependency | Breaker? | Why |
|---|---|---|
| Third-party API (payments, SMS, maps) | Yes | Outside your control, shared failure |
| Another internal service with its own SLO | Yes, per service | Isolates cascades |
| Your primary database | Usually no (use pool limits, timeouts, read replicas) | A breaker cannot give a useful fallback for core data |
| Cache (Redis) | Yes, fail open to the source | The cache must never be the outage |
| Message broker publish | Yes, with local buffering or the outbox | See Outbox |
| In-process call | No | No network, no partial failure |
| Rarely called admin endpoint | Probably no | Too little traffic to judge |
Starting settings by dependency type
| Dependency type | Window | Minimum calls | Failure rate | Slow call | Open duration | Probes | Fallback |
|---|---|---|---|---|---|---|---|
| High-traffic read (catalogue) | Time 30 s | 50 | 50% | 2 x p99 at 50% | 15 s | 5 | Cached value |
| Payment provider | Count 20 | 10 | 30% | 5 s at 50% | 60 s | 1 to 3 | Fail fast + queue |
| Recommendations (optional) | Time 30 s | 20 | 50% | 500 ms at 50% | 30 s | 3 | Empty or static list |
| Search | Time 30 s | 30 | 50% | 1 s at 60% | 20 s | 3 | Degraded results |
| Internal auth service | Time 10 s | 20 | 20% | 200 ms at 30% | 10 s | 3 | Cached token validation |
| Email/SMS gateway | Count 50 | 20 | 50% | 3 s at 80% | 120 s | 1 | Queue for later |
These are starting points to be replaced by your own p99 and traffic numbers; they are our judgement, not vendor defaults.
Breaker, mesh or both
| Situation | Use |
|---|---|
| One language, per-endpoint rules, real fallbacks | Library breaker |
| Many languages, no code changes, bad pod ejection | Mesh outlier detection + connection limits |
| Plain NGINX/HAProxy in front of an upstream pool | max_fails / fail_timeout, observe layer7 |
| Serverless or PHP-FPM | Shared-state breaker (Redis) or mesh/edge |
| Very high throughput hot path | Adaptive concurrency limits or load shedding instead of thresholds |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A single Laravel or Go process calling one payment provider and one email provider is the simplest correct place for a breaker. Put one breaker per outbound dependency in a small wrapper, count only what is the dependency's fault, give each a fallback (email goes to a queue; payments fail fast with a clear message) and log every transition. In PHP-FPM the state must be in Redis; in a Go monolith it can live in memory. There is no breaker for the database: pool limits, timeouts and statement timeouts do that job.
Modular monolith: boundaries without the network
Inside one process there is nothing to break, but the module boundary is where a later network hop will go. Put the breaker behind the module's interface (an InventoryGateway), so replacing an in-process implementation with an HTTP client changes one class and a configuration entry, not every caller. Shared database schemas do not need breakers; shared external integrations do, and they should be owned by one module.
Microservices: every arrow is a decision
Checkout calls Inventory, Pricing, Payments and Recommendations. Each arrow gets its own breaker with its own fallback ladder: Recommendations (empty list), Pricing (cached price within 15 minutes), Inventory (optimistic "in stock" with reservation checked later, if the business accepts oversell risk), Payments (fail fast, never invent). A request that touches all four needs the failure probabilities multiplied, which is why thresholds that look generous per dependency are tight per request. Deadlines propagate (Service Communication); the breaker sits beside the timeout, not instead of it. In a mesh, add outlier detection for bad pods and connection limits per cluster; keep the application breaker for fallbacks.
Step Checkout Breaker state Result
1 1 GET pricing closed live price
2 2 GET recommendations open empty list (degraded)
3 3 POST payments authorize closed charged with Idempotency-Key
4 4 POST receipt open 202, queued for laterDistributed data: replicas, caches, regions
Breakers meet distributed data in three places. A read replica that lags or is down: a breaker per replica (or per pool) lets reads fall back to the primary within a limit, with the lag shown to the user (Replication Topologies). A cache: when Redis fails, fail open to the source but bound the load with a bulkhead or the source collapses (Caching). Multi-region: each region needs its own breakers per remote region, so a regional failure does not open the global circuit; shared-state breakers are per region, because cross-region round trips cost tens of milliseconds and would defeat the point. Failure detection by gossip (Gossip Protocols) is a cousin: both decide "is this node unhealthy" from observations; a breaker decides per caller, gossip decides cluster-wide.
Scaling path: 1x, 10x, 100x
| Scale | Setup | What to watch |
|---|---|---|
| 1x (a few instances, tens of rps) | Library breaker per dependency, local or Redis state, fallbacks, alerts on open | Windows too big for the traffic; no alert on fallbacks |
| 10x (tens of instances, hundreds of rps) | Mesh outlier detection and connection limits; shared state where processes are short-lived; per-endpoint breakers | Probe multiplication; mode bugs; config drift between services |
| 100x (hundreds of instances, thousands of rps) | Mesh as baseline; app breakers only for fallbacks; adaptive concurrency limits and load shedding beside thresholds | Hot keys in Redis state; probe herds; static thresholds no longer fit variable load (Netflix's own move toward "adaptive" mechanisms) |
Lab: an outage, with numbers
Experiment 1: replay a 55-second outage in virtual time (run)
cd docs/snippets/system-design/circuit-breaker/go
go run ./before
go run ./cmd/outageOutput as run on this machine (Go 1.27.4, a fake clock, so it is deterministic):
dependency calls: 60, time spent waiting: 3.1s
client dep calls in outage rejected user wait recovered
A retries only 23000 16500 0 9h10m0s 0s
B breaker around retries 6076 105 5994 3m30s 5.28s
C breaker inside retries 6027 35 6000 1m10s 5.07s
B breaker around retries transitions: open@20s half-open@30s open@30s half-open@40s open@40s half-open@50s open@50s half-open@60s open@60s half-open@70s open@70s half-open@80s closed@80s
C breaker inside retries transitions: open@20s half-open@30s open@30s half-open@40s open@40s half-open@50s open@50s half-open@60s open@60s half-open@70s open@70s half-open@80s closed@80sHow to read it. The simulation runs 12,000 requests at 100 per second; the dependency is down from second 20 to second 75, every failed attempt costs the user a 2-second timeout, and each request makes up to 3 attempts. Client A calls the dependency 16,500 times during the outage; B only 105; C only 35 (its minimum of 20 is counted in attempts, not requests, which is why it trips about three times sooner). The recovered column is the cost: the breaker needs up to one open duration to notice the dependency is back, so users got fallbacks for 5.28 s (B) and 5.07 s (C) after the dependency was healthy. The transitions show the half-open probes at 30, 40, 50, 60 and 70 s failing, and the probe at 80 s succeeding. user wait is the sum of simulated timeout time across all requests, not a latency percentile.
Experiment 2: the Go tests with the race detector (run)
cd docs/snippets/system-design/circuit-breaker/go
gofmt -l . && go vet ./... && go test -race ./...Expected: ok for breaker and httpguard, no output from gofmt -l.
Experiment 3: compare with gobreaker (run)
go run ./cmd/gobreakercmpOutput as run:
after 10 failures: open | circuit breaker is open | true
inventory: closed -> openExperiment 4: the Laravel breaker against a failing fake (expected, not run)
php artisan test --filter=CircuitBreakerTestExpected: four tests pass. After 30 calls against a fake that always returns 503, Http::assertSentCount(40) holds (20 recorded calls x 2 attempts, then local rejection) and the inventory breaker has dispatched one closed>open event. Status: expected, not run.
Experiment 5: Istio circuit breaking (expected, not run)
Following the Istio task, apply a DestinationRule with connectionPool.tcp.maxConnections: 1, connectionPool.http.http1MaxPendingRequests: 1, maxRequestsPerConnection: 1 and outlierDetection (consecutive5xxErrors: 1, interval: 1s, baseEjectionTime: 3m, maxEjectionPercent: 100), then send 20 requests with two connections using fortio: some return 503. The Istio page shows output such as Code 503 : 3 (15.0 %) (their run; your counts will vary). Status: expected, not run.
Common misconceptions
| Belief | Reality |
|---|---|
| A circuit breaker retries failed calls | It decides whether a call may start; retries are a separate policy (Polly: "does not manage retries") |
| Open means the dependency is down | Open means this caller stopped trying; the dependency may be fine or fine for others |
| One breaker per application is enough | One per dependency (or endpoint); a global one couples unrelated failures |
| 50% failure rate is a safe threshold | It is relative to the window and to how many calls one user request makes |
| A bigger window is safer | It is slower to react and can take minutes to fill on quiet endpoints |
| Half-open closes the breaker after the wait | It admits a few probes first; only success closes it |
| The sliding window limits concurrency | It does not: "If you want to restrict the number of concurrent threads, please use a Bulkhead" |
| Every error should trip the breaker | A 404 or a cancelled request is not the dependency's fault |
| Envoy circuit breaking is a Hystrix-style breaker | Envoy's circuit breakers are limits; the state machine with ejection is outlier detection |
| Hystrix is the standard library | Hystrix is in maintenance mode; Netflix points to resilience4j |
| A breaker fixes retry storms | A budgeted retry fixes storms; AWS prefers a local token bucket and warns about breaker "modal behavior" |
| With a fallback nobody needs to be paged | A fallback can hide an outage for days; alert on state and on fallback share |
Cheat sheet
| Topic | What to remember |
|---|---|
| States | Closed (count), open (reject), half-open (probe) |
| Trip rule | Rate >= threshold AND calls >= minimum; equal counts |
| Window | Count-based for steady or sparse traffic, time-based for smooth high traffic |
| Slow calls | A slow-call rate opens the breaker before errors appear |
| Open duration | 2 to 3 times the typical recovery time, with jitter for big fleets |
| Probes | 1 to 10, real calls, so make them safe |
| Failures | Connection, timeout, 5xx, 429; not 4xx, not cancellations, not your own bulkhead |
| Fallback | Cached, static, degraded, fail fast, queue; no network in the fallback |
| Granularity | Per dependency or endpoint; never one global breaker |
| Order | Fallback, breaker, retry (with budget), timeout, bulkhead; retries never retry a rejection |
| Observability | Event per transition, gauge for state, counters for rejected and fallback, alert on open duration |
| Shared state | Redis counters with Cache::add + increment, lock for transitions, generations, fail open |
| Proxy | Envoy outlier detection, Istio DestinationRule, NGINX max_fails, HAProxy observe layer7 |
| Libraries | Resilience4j (JVM), Polly (.NET), gobreaker or failsafe-go (Go); Hystrix is retired |
| Testing | Fake clock, race test, fault injection, game day |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A breaker has minimumNumberOfCalls = 10 and the first nine calls all fail. What state is it in, and why? Important
Answer
Answer: Closed. The rate is not evaluated below the minimum; Resilience4j says it "will not trip open even if all 9 calls have failed". The tenth recorded call lets the verdict run.
2 — Why does a count-based window of 100 behave badly on an endpoint receiving 2 requests per second? Important
Answer
Answer: It needs 100 recorded calls before it can judge, which is about 50 seconds. Use a smaller count window or a time-based window with a minimum matched to the traffic.
3 — Name the three outcomes a failure classifier should produce and one example of each. Must-know
Answer
Answer: Failure (connection reset, 503), success (404, a normal business answer) and ignored (context cancelled, a local bulkhead rejection).
4 — What is the difference between Envoy circuit breaking and Envoy outlier detection? Important
Answer
Answer: Circuit breaking is a set of limits per cluster (connections, pending requests, requests, retries, pools) that cause fast 503s on overflow. Outlier detection is passive health checking that ejects individual hosts for a time based on consecutive errors or statistics.
5 — With a breaker outside the retries, how many failures does one failed user request record, and what if the breaker is inside? Important
Answer
Answer: One outside (after the retries gave up); one per attempt inside (three for three attempts). Inside trips sooner but the retry must not retry a rejection.
6 — Why is the half-open state limited to a few probes instead of letting all traffic through? Must-know
Answer
Answer: A dependency that has just restarted may fail again under full load; probes give evidence cheaply, and the cap stops the breaker from turning into the next thundering herd.
7 — Give two reasons a PHP-FPM application cannot keep breaker state in process memory. Important
Answer
Answer: A process serves one request and exits (or is one of many workers), so counters are lost or never reach the threshold; and each worker would learn of the outage alone. State must live in a shared store such as Redis through the Laravel Cache.
8 — What does the generation number in the Go and Laravel implementations protect against? Good to know
Answer
Answer: A slow call that started before a state change and finishes after it: its result belongs to the old state's window and must not be recorded in the new one.
9 — Which fallback rung is wrong for a payment authorisation and why? Must-know
Answer
Answer: A cached or static answer: inventing "approved" or reusing an old result is dangerous. Fail fast (or queue the work idempotently) instead.
10 — Why should a breaker ignore rejections coming from a bulkhead or a rate limiter? Important
Answer
Answer: They reflect your own limits, not the dependency's health. Counting them can open the breaker because you were busy, which failsafe-go warns against.
11 — How does NGINX approximate a breaker, and what can it not do? Good to know
Answer
Answer: max_fails failures within fail_timeout mark a server unavailable for fail_timeout. It removes servers from an upstream pool but cannot return a fallback and ignores a single-server group.
12 — State the main anti-pattern about retries and non-idempotent writes. Must-know
Answer
Answer: Retrying a timed-out write without an idempotency key can duplicate the effect (a double charge). Use idempotency keys and fail fast on writes while the breaker is open.
Glossary
| Term | Meaning |
|---|---|
| Circuit breaker | A switch that stops calls to a failing dependency and probes for recovery |
| Closed | State in which calls flow and outcomes are recorded |
| Open | State in which calls are rejected without calling the dependency |
| Half-open | State in which a limited number of probe calls are admitted |
| Failure threshold | The level at which the breaker opens (consecutive failures or a rate) |
| Failure rate | Failed calls divided by recorded calls in the window |
| Slow call rate | Share of calls slower than the slow-call duration threshold |
| Minimum number of calls | Smallest number of recorded calls for which a rate is evaluated |
| Sliding window | The bounded memory of recent outcomes |
| Count-based window | Window of the last N calls |
| Time-based window | Window of the calls of the last N seconds, kept in buckets |
| Open duration | How long the breaker rejects before probing (Resilience4j: wait duration) |
| Wait duration | Resilience4j name for the open duration |
| Probe | A real trial call made in the half-open state |
| Trial request | Another name for a probe |
| Fallback | What the caller returns when a call is rejected or fails |
| Fail fast | Return an error immediately instead of waiting |
| Degraded response | A reduced answer, such as a page without recommendations |
| Per-dependency breaker | One breaker per independently failing dependency |
| Bulkhead | A cap on concurrent calls to a dependency, isolating its failure |
| Timeout | The bound on one attempt; makes a hung call a failure |
| Retry | Re-attempting a failed call, with backoff, jitter and a budget |
| Outlier detection | Envoy's passive ejection of hosts that behave unlike the others |
| Ejection | Removing a host from the load-balancing set for a time |
| max_fails | NGINX upstream parameter: failures that mark a server unavailable (default 1) |
| fail_timeout | NGINX upstream parameter: the counting period and the unavailability period (default 10 s) |
| Resilience4j | The active JVM resilience library with sliding-window breakers |
| Hystrix | Netflix's retired (maintenance-mode) fault-tolerance library |
| Polly | The .NET resilience library with FailureRatio, SamplingDuration, MinimumThroughput |
| gobreaker | sony/gobreaker, a small Go circuit breaker library |
| failsafe-go | A Go library composing retry, breaker, timeout, bulkhead and fallback |
| Envoy | The proxy with circuit-breaking limits and outlier detection |
| Istio | The service mesh that configures Envoy through DestinationRule |
| Distributed breaker | A breaker whose state is shared across instances |
| Shared state | Breaker state kept in a common store |
| Redis counter | Atomic INCR-style counters used for shared windows |
| State change event | The notification emitted at each transition |
| Metrics | Counters and gauges for state, rejections, fallbacks and transitions |
| Fake clock | A clock tests advance by hand, so no test sleeps |
| Fault injection | Deliberately causing delays, errors or aborts to test the design |
| Generation | A counter incremented at each transition so stale results are ignored |
| Nygard | Michael Nygard, author of Release It!, who popularised the pattern |
| Fowler | Martin Fowler, author of the CircuitBreaker bliki entry |
References
- Fowler, CircuitBreaker (6 March 2014): https://martinfowler.com/bliki/CircuitBreaker.html
- Nygard, Release It! Second Edition, Pragmatic Bookshelf: https://pragprog.com/titles/mnee2/release-it-second-edition/
- Resilience4j CircuitBreaker: https://resilience4j.readme.io/docs/circuitbreaker
- Resilience4j Spring Boot guide (aspect order): https://resilience4j.readme.io/docs/getting-started-3
- Netflix Hystrix, How it Works: https://github.com/Netflix/Hystrix/wiki/How-it-Works
- Netflix Hystrix README (maintenance mode): https://github.com/Netflix/Hystrix
- Envoy outlier detection: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/outlier
- Envoy circuit breaking: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/circuit_breaking
- Istio circuit breaking: https://istio.io/latest/docs/tasks/traffic-management/circuit-breaking/
- NGINX
ngx_http_upstream_module: https://nginx.org/en/docs/http/ngx_http_upstream_module.html - HAProxy configuration manual (
observe): https://docs.haproxy.org/3.0/configuration.html - Polly circuit breaker strategy: https://www.pollydocs.org/strategies/circuit-breaker.html
- sony/gobreaker: https://github.com/sony/gobreaker
- failsafe-go circuit breaker: https://failsafe-go.dev/circuit-breaker/
- Amazon Builders' Library, Timeouts, retries and backoff with jitter: https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
- Laravel 13 HTTP client: https://laravel.com/docs/13.x/http-client
- Laravel 13 Cache (atomic locks, increment): https://laravel.com/docs/13.x/cache
- Laravel 13 Pulse (custom cards): https://laravel.com/docs/13.x/pulse