MediumReliabilityPython 3
Circuit Breaker State
Model closed, open, and half-open breaker transitions with deterministic cooldown behavior.
35m1 sample tests1 hidden tests
Implement a small circuit breaker for protecting a dependency that is failing.
Requirements
- Define
CircuitBreaker(failure_threshold, cooldown_seconds, now). allow()returns whether a request may be attempted.record_success()records a successful attempt.record_failure()records a failed attempt.state()returns"closed","open", or"half_open".- In
closed, requests are allowed and consecutive failures are counted. - Reaching
failure_thresholdopens the breaker. - In
open, requests are blocked until cooldown has elapsed. - After cooldown, one trial request is allowed in
half_open. - A half-open success closes the breaker; a half-open failure opens it again.
Example
python
1clock = {"t": 0}
2breaker = CircuitBreaker(2, 10, now=lambda: clock["t"])
3breaker.record_failure()
4breaker.record_failure()
5assert breaker.state() == "open"
6assert not breaker.allow()
7clock["t"] = 10
8assert breaker.allow()Constraints
- Count consecutive failures only while closed.
- Use deterministic injected time.
- Avoid hidden background timers.
Editor
Results
Run sample tests or submit all tests.