Explorer
Node.js

Implement a circuit breaker that opens after `threshold` failures. When open, it immediately fails without calling the function. Resets after `resetTimeout` ms.

Problem Statement

Implement a circuit breaker that opens after `threshold` failures. When open, it immediately fails without calling the function. Resets after `resetTimeout` ms.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: States: CLOSED (normal), OPEN (failing fast), HALF_OPEN (testing). šŸ’” Hint 2: Track failure count. When it reaches threshold, switch to OPEN. šŸ’” Hint 3: In OPEN state, check if resetTimeout has elapsed to move to HALF_OPEN and try again. āœ… Solution: ```javascript function createCircuitBreaker(fn, threshold, resetTimeout) { let failures = 0; let state = "CLOSED"; let lastFailTime = 0; return { call(...args) { if (state === "OPEN") { if (Date.now() - lastFailTime >= resetTimeout) { state = "HALF_OPEN"; } else { throw new Error("Circuit is OPEN"); } } try { const result = fn(...args); failures = 0; state = "CLOSED"; return result; } catch (e) { failures++; lastFailTime = Date.now(); if (failures >= threshold) state = "OPEN"; throw e; } }, getState() { return state; } }; } ```

Circuit Breaker Pattern

Hard
Implement a circuit breaker that opens after `threshold` failures. When open, it immediately fails without calling the function. Resets after `resetTimeout` ms.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"results":["fail","fail","fail","Circuit is OPEN"],"state":"OPEN"}