Circuit breakers
Stop calling what is not answering
Section titled “Stop calling what is not answering”Timeouts and retries still call the dependency. Each call to one that is down waits its timeout and fails, holding a thread, a connection and memory while it waits. The Azure Architecture Center says that these blocked requests can exhaust resources that other, unrelated parts of the system need. When a dependency is going to fail for a while, the best call is the one that is not made.
A circuit breaker is a proxy around the call that remembers how recent calls went and decides whether to let the next one through. Martin Fowler’s description is short: once the failures reach a threshold the breaker trips, and every further call returns an error without the protected call being made. He credits Michael Nygard’s Release It! with popularising the pattern. It is named after the electrical device.
Three states
Section titled “Three states”The Azure pattern describes a state machine with three states.
- Closed. Calls go through. The breaker counts recent failures. When they pass a threshold, it opens.
- Open. Calls fail at once, with an error, and the dependency is not called. A timer runs.
- Half-open. When the timer expires, a limited number of calls are let through as a test. If they succeed, the breaker closes and the count starts again. If any fails, it opens again and the timer restarts.
The half-open state is the careful part. Azure’s note says it prevents a recovering service from being flooded with requests, because a service that is just coming back may be able to take only a few before it is ready for all.
Mental model. A breaker turns a slow failure into a fast one. While it is open, a caller learns at once what it would have learned after the full timeout, and the dependency gets the quiet it needs to recover.
Try it: closed, open, half-open, open, half-open, closed
Section titled “Try it: closed, open, half-open, open, half-open, closed”The lab has one breaker in front of the dependency. The dependency is silent from 5 s to 13 s, a failure is only learned when the 1 s timeout runs out, and each request may retry three times, 0.5 s apart. Opens after is 5 failures in a row and Stays open for is 3 s.
After a few failures in a row the breaker opens and stops calling the dependency. After a pause it lets one probe through (half-open), and it closes again when the probe succeeds.
While the dependency is down, every attempt fails.
Share of attempts that fail on their own, even when the dependency is up.
Attempts the dependency can serve in any one second. It turns the rest away.
An error comes back after 0.1 s. With no answer, the caller waits the whole timeout before it can retry.
Each layer calls the next one and retries that call. The last layer calls the dependency.
How long a caller waits for an answer from the dependency.
The wait before a retry. None retries at once, fixed waits 0.5 s every time, and exponential starts at 0.5 s and doubles each time, up to 4 s.
Jitter makes each wait random. Full picks anywhere from zero to the delay, equal picks from half the delay to the delay. With no backoff there is no wait to randomise.
Each layer may retry only a share of the calls it makes, after a reserve of ten retries.
Closed, calls go through. After enough failures in a row it opens and calls fail at once. After a pause it is half-open and lets one probe through.
The lab runs in real time. Step moves on by one tenth of a second, Skip by five seconds.
What is happening
The dependency is down from 5 s to 13 s. Every attempt made now fails.
The caller makes up to 4 attempts, so one user request can become up to 4 attempts at the dependency.
In the last second, user requests: 30; attempts at the dependency: 1; served: 0. The dependency can serve 60 a second.
Without jitter, requests that fail together wait the same time and retry together, in waves. Attempts in the busiest tenth of a second of the last second: 1.
The circuit breaker is half-open: one probe call may go through. If it succeeds the breaker closes, and if it fails the breaker opens again.
- User requests
- 300150 succeeded, 104 gave up, 46 still trying
- Attempts at the dependency
- 1840.6 for each user request, the most for one: 1
- At most for one request
- 4attempts at the dependency: 4
- Attempts, last second
- 1served: 0, capacity: 60, busiest tenth of a second: 1
- Circuit breaker
- Half-opentimes opened: 1, attempts stopped: 476
- Retries refused
- 0no retry budget
- Attempts (line)
- Served (filled)
- Outage (hatched)
- ● Closed
- ✕ Open
- ◐ Half-open
| Seconds | New requests | Attempts | Served | Busiest tenth of a second | Stopped by the breaker | Circuit breaker | Dependency |
|---|---|---|---|---|---|---|---|
| 9 to 10 | 30 | 1 | 0 | 1 | 119 | Half-open | Down |
| 8 to 9 | 30 | 0 | 0 | 0 | 141 | Open | Down |
| 7 to 8 | 30 | 0 | 0 | 0 | 162 | Open | Down |
| 6 to 7 | 30 | 3 | 0 | 3 | 54 | Open | Down |
| 5 to 6 | 30 | 30 | 0 | 3 | 0 | Closed | Down |
| 4 to 5 | 30 | 30 | 30 | 3 | 0 | Closed | Up |
| 3 to 4 | 30 | 30 | 30 | 3 | 0 | Closed | Up |
| 2 to 3 | 30 | 30 | 30 | 3 | 0 | Closed | Up |
| Call | Attempts so far | For each user request | At most for one request |
|---|---|---|---|
| Layer 1 to the dependency | 660 | 2.2 | 4 |
Circuit breaker log
- At 6.2 s the breaker went from Closed to Open: 5 failures in a row.
- At 9.2 s the breaker went from Open to Half-open: the pause is over, so one probe may go through.
At 10 s, user requests so far: 300 (150 succeeded, 104 gave up, 46 still trying). Attempts at the dependency: 184, 0.6 for each request. Circuit breaker: Half-open.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- The lab advances in steps of 0.1 s. An attempt that succeeds, or that is answered with an error, takes one step, and a retry is sent on the step after the failure at the earliest, so no backoff means 0.1 s. A seeded random draw decides each failure rate and each jitter, so the same settings give the same run.
- Each layer calls the next one and retries that call. The layers above wait for the answer of the layer below, and only the attempt at the dependency has a timeout. Real services usually have a timeout at every layer, which leaves work running below after a caller has given up and can make the amplification worse than shown.
- The dependency fails in three ways: an outage window, a failure rate, and a capacity (it serves a fixed number of attempts in any one second and turns the rest away). A failure is either an error at once or silence until the timeout; real failures are a mix of both. A turned-away attempt costs the dependency nothing.
Simplifications
- A retry budget gives each layer a bucket that fills with a share of the calls it makes and loses one for each retry, starting with ten retries in reserve. One circuit breaker guards the calls to the dependency: it opens after a number of failures in a row, lets one probe through after a pause, and closes when the probe succeeds. Real libraries differ in how they count failures and how many probes they allow.
- No real client library and no connection-level effect is modelled: no connection set-up, no connection pool, no queueing in the network, no load balancer choosing another instance. The numbers illustrate the mechanism; they are not measurements of a product.
Parameter values are illustrative. They are not benchmarks of any real product.
The lab opens at 10 s. Circuit breaker says Half-open, with times opened: 1 and attempts stopped: 476. Attempts at the dependency is 184 for 300 user requests, 0.6 for each: more calls were stopped than were made. In the chart, the breaker strip shows each state with its own pattern and glyph.
Press Skip 5 s, to 15 s, and read the breaker log. It has five lines.
- At 6.2 s the breaker went from Closed to Open: 5 failures in a row.
- At 9.2 s it went from Open to Half-open: the pause is over, so one probe may go through.
- At 10.2 s it went from Half-open to Open: the probe failed.
- At 13.2 s it went from Open to Half-open: the pause is over, so one probe may go through.
- At 13.3 s it went from Half-open to Closed: the probe succeeded.
The outage began at 5 s, and the breaker opened at 6.2 s. The failures are silent, so each is learned only when its 1 s timeout runs out, and the fifth failure in a row arrives at 6.2 s. The pause is 3 s, so the first probe is at 9.2 s. The dependency is still down, and the probe, which also waits its 1 s timeout, fails at 10.2 s: back to open for another 3 s. The second probe, at 13.2 s, meets a dependency that came back at 13 s, and is answered in a tenth of a second, so the breaker is closed at 13.3 s. At 15 s, Circuit breaker says Closed, with times opened: 2 and attempts stopped: 859, and the dependency has received 284 attempts for 450 requests.
The same state machine in code
Section titled “The same state machine in code”The C# example is a small breaker: closed, open after 3 failures in a row, open for 10 s, then half-open. A fake clock stands in for time, and the dependency is down from 4 s to 22 s. One call is made every 2 s.
// A circuit breaker: closed (calls go through) -> open (calls fail at once, the dependency is left alone)// -> half-open (one probe call decides whether to close again).using ShardCraft.Playground;
var clock = new FakeClock();var service = new FlakyService(clock);service.DownBetween(TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(22)); // an outage from 4 s to 22 svar breaker = new CircuitBreaker(clock, failureThreshold: 3, openFor: TimeSpan.FromSeconds(10));var second = 0;var changes = new List<string>();breaker.StateChanged += (from, to) => changes.Add($" circuit {from} -> {to}");
// One call every 2 seconds of virtual time.for (; second <= 40; second += 2){ string result; try { result = breaker.Execute(service.Call); } catch (CircuitOpenException) { result = "rejected (circuit open, dependency not called)"; } catch (TransientFailureException e) { result = $"failed ({e.Message})"; }
Console.WriteLine($"t={second,2} s {result}"); changes.ForEach(Console.WriteLine); changes.Clear(); clock.Advance(TimeSpan.FromSeconds(2));}Console.WriteLine($"calls that reached the dependency: {service.Calls} of 21");
class CircuitOpenException() : Exception("circuit open");
enum BreakerState { Closed, Open, HalfOpen }
class CircuitBreaker(FakeClock clock, int failureThreshold, TimeSpan openFor){ private int _failures; private DateTimeOffset _openedAt;
private BreakerState _state = BreakerState.Closed;
public event Action<BreakerState, BreakerState>? StateChanged;
private BreakerState State { get => _state; set { if (value == _state) return; var from = _state; _state = value; StateChanged?.Invoke(from, value); } }
public string Execute(Func<string> call) { if (State == BreakerState.Open) { if (clock.UtcNow - _openedAt < openFor) throw new CircuitOpenException(); State = BreakerState.HalfOpen; // the wait is over: let one probe through }
try { var reply = call(); _failures = 0; State = BreakerState.Closed; // a success (or a good probe) closes the circuit return reply; } catch (TransientFailureException) { _failures++; if (State == BreakerState.HalfOpen || _failures >= failureThreshold) { State = BreakerState.Open; // a failed probe reopens it for another full wait _openedAt = clock.UtcNow; } throw; } }}
// A real breaker is shared by all callers (so it must be thread-safe), usually counts failures over a sliding// window or as a rate rather than in a row, and in half-open lets only a limited number of probes through.// Libraries such as Polly provide one: this sketch only shows the state machine.t= 0 s reply 1t= 2 s reply 2t= 4 s failed (503 service unavailable)t= 6 s failed (503 service unavailable)t= 8 s failed (503 service unavailable) circuit Closed -> Opent=10 s rejected (circuit open, dependency not called)t=12 s rejected (circuit open, dependency not called)t=14 s rejected (circuit open, dependency not called)t=16 s rejected (circuit open, dependency not called)t=18 s failed (503 service unavailable) circuit Open -> HalfOpen circuit HalfOpen -> Opent=20 s rejected (circuit open, dependency not called)t=22 s rejected (circuit open, dependency not called)t=24 s rejected (circuit open, dependency not called)t=26 s rejected (circuit open, dependency not called)t=28 s reply 7 circuit Open -> HalfOpen circuit HalfOpen -> Closedt=30 s reply 8t=32 s reply 9t=34 s reply 10t=36 s reply 11t=38 s reply 12t=40 s reply 13calls that reached the dependency: 13 of 21This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
The third failure, at 8 s, opens the breaker. The calls at 10 s to 16 s are rejected without the dependency being called. At 18 s the 10 s are over, the breaker lets a probe through, the probe fails, and the breaker opens again. At 28 s the second probe succeeds and the circuit closes. The last line says 13 of 21 calls reached the dependency: the other 8 were turned away by the breaker. The code in the page is never run in the browser: the output was produced by a CI run of the same file.
The costs and the choices
Section titled “The costs and the choices”A breaker is not free. Amazon’s article is cautious about it: it says that breakers introduce a modal behaviour that can be hard to test, and that they can lengthen the time to recover. The lab shows a small version of that second point: the dependency came back at 13 s and calls resumed at 13.3 s. A real breaker with a long break duration shuts out calls that would have worked for as long as it stays open.
A real breaker has settings the lab does not. Polly’s circuit breaker, for example, does not count failures in a row. It opens when the ratio of failures in a sampling window goes over a limit, 10% of calls within 30 s by default, and only when a minimum number of calls, 100 by default, has been made in that window. Its break duration is 5 s by default. The Azure article lists others: which exceptions count as failures, a manual override for an operator, and returning a default value from the open state instead of an error. Each of those is a decision about what the dependency’s failure should look like to the caller.
What happens if one breaker guards several shards?
Section titled “What happens if one breaker guards several shards?”Azure’s considerations include one that is easy to miss: be careful when a single breaker guards one type of resource that has several independent providers. In a data store with several shards, one shard may be fully reachable while another has a problem. If their errors are merged into one breaker, it opens, and calls to the healthy shards are blocked even though they would have worked. The breaker needs the same grain as the failure. A breaker per shard, or per instance, keeps one broken part from taking the rest with it, which is the next lesson’s idea applied to failure counting.
- A circuit breaker stops calls to a dependency that keeps failing, so that callers fail fast and the dependency is left alone.
- It has three states: closed, open after a number of failures, and half-open after a pause, to test with a probe.
- In the lab the log reads closed to open at 6.2 s, open to half-open at 9.2 s, back to open at 10.2 s when the probe fails, half-open at 13.2 s, and closed at 13.3 s when the probe succeeds.
- The C# example sends 13 of its 21 calls to the dependency and turns 8 away.
- A breaker has costs: it can shut out calls that would work, it adds behaviour that is hard to test, and one breaker for several shards blocks the healthy ones.
Next: bulkheads, which keep one dependency from using up the rest.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.