Circuit Breakers
Stop calling a broken service.
If the payment service is completely down, retrying every call just wastes time and adds load. A circuit breaker notices repeated failures, and stops calling for a while, like a fuse in your house.

- Payment is down
- Retries just add load
- Trip the breaker
A tiny circuit breaker
The breaker has three states. Closed means calls go through normally. After three failures in a row, it opens, and calls fail instantly without trying. After a cool down, it goes half open, and lets one test call through. If that succeeds, it closes again. Run it. You can see it open, block calls, and then recover.
class Breaker:
def __init__(self, limit=3, cooldown=3):
self.fails, self.limit, self.cooldown, self.opened_at = 0, limit, cooldown, None
def call(self, ok, now):
if self.opened_at is not None:
if now - self.opened_at < self.cooldown:
return "blocked (open)"
self.opened_at = None # half-open: try once
if ok:
self.fails = 0
return "ok"
self.fails += 1
if self.fails >= self.limit:
self.opened_at = now
return "failed"
b = Breaker()
for t, ok in enumerate([False, False, False, False, False, True, True, True]):
print(f"t={t} -> {b.call(ok, t)}")t=0 -> failed t=1 -> failed t=2 -> failed t=3 -> blocked (open) t=4 -> blocked (open) t=5 -> ok t=6 -> ok t=7 -> ok
Why it helps
A circuit breaker helps both sides. The caller fails fast, and can show a fallback, like, payment is busy, try again in a minute. And the broken service gets breathing room to recover, instead of being hammered. Combine breakers with timeouts and retries, and failures stay contained.
| key | value |
|---|---|
| Caller | fails fast |
| Fallback | a friendly message |
| Broken service | time to recover |
| Together | timeouts + retries + breaker |
Summary
A circuit breaker stops calls to a failing service, then tests it before closing again. It protects both caller and callee. Next, keeping one problem from sinking the whole ship.
Key takeaways- Closed: normal
- Open: fail fast
- Half-open: test