Python › Exception Handling
How would you implement a circuit breaker pattern using exception handling, to stop repeatedly calling a service that's consistently failing?
AdvancedAnswer
Track consecutive failure counts; once a threshold is exceeded, the circuit 'opens' and immediately raises a CircuitOpenError WITHOUT even attempting the real call for a cooldown period, protecting the failing service from being hammered with more requests — after the cooldown, allow a single 'trial' call through to test if the service has recovered.
class CircuitBreaker:
def __init__(self, threshold=3, cooldown=30):
self.failures = 0
self.threshold = threshold
self.cooldown = cooldown
self.opened_at = None
def call(self, func, *args):
if self.opened_at and time.time() - self.opened_at < self.cooldown:
raise RuntimeError("Circuit is open")
try:
result = func(*args)
self.failures = 0
self.opened_at = None
return result
except Exception:
self.failures += 1
if self.failures >= self.threshold:
self.opened_at = time.time()
raiseReal-world example Preventing a struggling downstream service (like a flaky third-party API) from being overwhelmed with continued retry attempts during an outage.