Protect your service from a misbehaving downstream by failing fast.
[ Closed ] --(N consecutive failures)--> [ Open ]
^ |
| (after T seconds)
| v
+------(probe success)---- [ Half-Open ]
(probe failure)
back to Open
class Breaker:
def __init__(self, fail_threshold=5, reset_seconds=30):
self.fail = 0
self.threshold = fail_threshold
self.reset = reset_seconds
self.open_until = 0
def call(self, fn, *a, **kw):
if time.monotonic() < self.open_until:
raise CircuitOpen()
try:
r = fn(*a, **kw); self.fail = 0; return r
except Exception:
self.fail += 1
if self.fail >= self.threshold:
self.open_until = time.monotonic() + self.reset
raise
An electrical breaker in your house: too many appliances trip it, halting the kitchen to protect the rest.
Interview tip: Quote the closed/open/half-open transition explicitly — candidates forget half-open often.