TExcelTAD

Circuit Breakers

When a dependency is down, calling it anyway costs the caller a timeout per request, ties up threads and connections, and adds load to a service that is trying to recover. A circuit breaker wraps calls to a dependency, watches their outcomes, and after too many failures stops calling it for a while: requests fail immediately (or use a fallback) instead of waiting for a timeout. The name comes from the electrical breaker that cuts the circuit before the wiring catches fire.

Three states

            failure rate over threshold
  CLOSED  ────────────────────────────────▶  OPEN
 (calls go       ▲                          (calls fail fast,
  through)       │ probe calls succeed       no load on the dependency)
                 │                               │ wait time elapsed
                 └────────  HALF-OPEN  ◀─────────┘
                          (a few probe calls;
                           any failure → OPEN again)
State Behaviour Leaves when
closed every call goes through; outcomes are recorded in a sliding window the failure rate in the window passes the threshold (after a minimum number of calls)
open calls fail immediately with a "circuit open" error, or go to a fallback the open wait time has passed
half-open a limited number of probe calls go through probes succeed → closed; a probe fails → open again

A breaker in a simulation

The client calls a payment dependency once per tick. The dependency fails every call from tick 20 to tick 59 and then recovers. A failed call costs the full 1-second timeout; a call rejected by an open breaker costs nothing. The breaker opens when at least half of the last 10 calls failed (with at least 5 calls recorded), stays open 10 ticks, then lets one probe through:

python · try it yourself
class CircuitBreaker:
    def __init__(self, window=10, min_calls=5, threshold=0.5, open_ticks=10):
        self.window, self.min_calls, self.threshold, self.open_ticks = window, min_calls, threshold, open_ticks
        self.state, self.outcomes, self.opened_at = "closed", [], None

    def move(self, new, now):
        print(f"  t={now:>3}: {self.state} -> {new}")
        self.state = new
        if new == "open":
            self.opened_at = now
        if new == "closed":
            self.outcomes = []

    def allow(self, now):
        if self.state == "open" and now - self.opened_at >= self.open_ticks:
            self.move("half-open", now)
        return self.state != "open"

    def record(self, ok, now):
        if self.state == "half-open":
            self.move("closed" if ok else "open", now)
            return
        self.outcomes = (self.outcomes + [ok])[-self.window:]
        failures = self.outcomes.count(False)
        if len(self.outcomes) >= self.min_calls and failures / len(self.outcomes) >= self.threshold:
            self.move("open", now)

def dependency_ok(t):
    return not 20 <= t < 60

def run(use_breaker):
    cb = CircuitBreaker()
    waited = calls = fast_fail = 0
    for t in range(100):
        if use_breaker and not cb.allow(t):
            fast_fail += 1
        else:
            calls += 1
            ok = dependency_ok(t)
            waited += 0.05 if ok else 1.0           # success in 50 ms, failure = 1 s timeout
            if use_breaker:
                cb.record(ok, t)
    print(f"  calls to the dependency {calls}, rejected fast {fast_fail}, time spent waiting {waited:.1f} s")

print("without breaker:")
run(False)
print("with breaker:")
run(True)
without breaker:
  calls to the dependency 100, rejected fast 0, time spent waiting 43.0 s
with breaker:
  t= 24: closed -> open
  t= 34: open -> half-open
  t= 34: half-open -> open
  t= 44: open -> half-open
  t= 44: half-open -> open
  t= 54: open -> half-open
  t= 54: half-open -> open
  t= 64: open -> half-open
  t= 64: half-open -> closed
  calls to the dependency 64, rejected fast 36, time spent waiting 10.8 s

Without a breaker the client sends all 40 calls during the outage and waits a full timeout for each. With the breaker it learns after a handful of failures, rejects most calls instantly, probes every 10 ticks, and closes again shortly after the dependency recovers. The dependency, meanwhile, receives only the probes while it recovers.

What to do when the circuit is open

An open breaker is only useful if the caller has something better to do than show an error:

Fallback Example
a cached or stale value product prices from a cache that is 5 minutes old
a default "recommendations unavailable": show bestsellers
a degraded mode accept the order and charge the card later ("pending payment")
fail fast with a clear error at least the user doesn't wait 30 seconds for the same error

Configuration examples

Libraries such as Resilience4j (Java), Polly (.NET) and gobreaker (Go) implement breakers in code. A Resilience4j configuration in Spring Boot application.yml (sample):

yaml
resilience4j:
  circuitbreaker:
    instances:
      payments:
        slidingWindowType: COUNT_BASED
        slidingWindowSize: 20
        minimumNumberOfCalls: 10
        failureRateThreshold: 50            # percent
        slowCallDurationThreshold: 2s       # slow calls can count as failures too
        slowCallRateThreshold: 80
        waitDurationInOpenState: 10s
        permittedNumberOfCallsInHalfOpenState: 3

In a service mesh, the closest equivalent is outlier detection, which ejects individual failing hosts from the load-balancing pool rather than the whole dependency. An Istio DestinationRule (sample):

yaml
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
  name: payments
spec:
  host: payments.prod.svc.cluster.local
  trafficPolicy:
    connectionPool:
      http:
        http2MaxRequests: 200          # cap concurrent requests to the service
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 10s
      baseEjectionTime: 30s
      maxEjectionPercent: 50

Pitfalls

  • Breakers per dependency, not per process: one breaker for "all HTTP calls" opens for everything when one dependency fails.
  • Tune on real traffic: a minimum number of calls avoids opening on the first two failures of a quiet service.
  • Alert on breaker state changes as a signal, and show them on dashboards: an open breaker is an incident in progress somewhere.
  • Don't count client errors (400s) as failures; they say nothing about the dependency's health.

Test yourself

What happens to calls while the breaker is open?

  1. They are queued until it closes
  2. They fail immediately or go to a fallback, without calling the dependency
  3. They are retried three times
  4. They go to a random host

What is the half-open state for?

  1. Sending half the traffic
  2. Letting a few probe calls test whether the dependency has recovered
  3. Logging errors
  4. Rate limiting

Why should 400 Bad Request responses not count as breaker failures?

  1. They are rare
  2. They are caused by the caller's input and say nothing about the dependency's health
  3. They are slow
  4. Breakers can't see status codes