MediumReliabilityPython 3

Circuit Breaker State

Model closed, open, and half-open breaker transitions with deterministic cooldown behavior.

35m3 sample tests6 hidden tests

Implement a small circuit breaker for protecting a dependency that's 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_threshold opens the breaker.
  • In open, requests are blocked until cooldown has elapsed.
  • The open → half_open transition happens only inside allow() when cooldown has elapsed. state() must not transition or report half_open solely because cooldown elapsed; without a successful probe allow(), state() stays "open".
  • After cooldown, exactly one trial request is allowed while half_open. Further allow() calls return False until that trial is recorded as success or failure.
  • 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.state() == "open" # cooldown alone does not half-open 9assert breaker.allow() is True 10assert breaker.state() == "half_open" 11assert breaker.allow() is False # only one half-open trial 12breaker.record_success() 13assert breaker.state() == "closed"

Constraints

  • Count consecutive failures only while closed.
  • Ignore record_success and record_failure while open because no probe was allowed. An open-state record leaves opened_at unchanged.
  • Use deterministic injected time.
  • Avoid hidden background timers.

Editor