HardPro challengePython

Circuit Breaker

PythonDesignResilience

The circuit breaker pattern prevents cascading failures by "tripping" after
consecutive errors and blocking calls while the downstream service recovers.

Implement create_circuit_breaker(threshold, cooldown):

  • threshold — consecutive failures needed to open the circuit.
  • cooldown — number of blocked calls before a test call is allowed.

States:

  • CLOSED — pass calls through; count consecutive failures.
  • OPEN — block calls; count blocked calls. After cooldown blocked calls → HALF_OPEN.
  • HALF_OPEN — let one test call through:

- Success → CLOSED (reset failure counter).
- Failure → OPEN (reset cooldown counter).

cb['call'](fn)fn is () -> result (raises on failure).
Returns the fn result, or raises a CircuitOpenError when blocked.

Sample tests

Test #1Opens after 2 failures; a half-open test failure re-opens the circuit
Input: [2,2,[false,false,true,true,true,true,true,false]]
Output: ["ok","ok","error","error","blocked","error","blocked","ok"]
Test #2threshold=1 opens immediately; half-open test also fails, then recovers on retry
Input: [1,1,[false,true,true,false]]
Output: ["ok","error","error","ok"]
Test #3Stays CLOSED when there are no failures
Input: [3,2,[false,false,false]]
Output: ["ok","ok","ok"]
Test #4cooldown=3 blocks two calls before the half-open test; the test also fails
Input: [2,3,[true,true,true,true,true,false]]
Output: ["error","error","blocked","blocked","error","blocked"]