HardPro challengeJavaScriptTypeScript

Circuit Breaker

Node.jsDesign

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

Implement createCircuitBreaker(threshold, cooldown):

  • threshold — consecutive failures 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 (throws on failure).
Returns the fn result, or throws 'CIRCUIT_OPEN' when blocked.

Sample tests

Test #1Opens after 2 failures, recovers after 2 blocked calls
Input: [2,2,[false,false,true,true,true,true,true,false]]
Output: ["ok","ok","error","error","blocked","blocked","ok","ok"]
Test #2threshold=1 opens immediately, cooldown=1 recovers fast
Input: [1,1,[false,true,true,false]]
Output: ["ok","error","ok","ok"]
Test #3Stays CLOSED with non-consecutive successes (no failures)
Input: [3,2,[false,false,false]]
Output: ["ok","ok","ok"]
Test #4cooldown=3 blocks 3 calls before half-open test
Input: [2,3,[true,true,true,true,true,false]]
Output: ["error","error","blocked","blocked","blocked","ok"]