Implement a circuit breaker
Implement a circuit breaker in JavaScript: after repeated failures stop calling a service and fail fast until a pause passes. Node.js 24.
A service that keeps failing gets slower and drags callers down with it. A circuit breaker counts failures and then rejects calls immediately for a while.
function circuitBreaker(fn, { threshold = 3, resetMs = 1000, now = Date.now } = {}) {
let failures = 0;
let openedAt = 0;
return async (...args) => {
if (failures >= threshold && now() - openedAt < resetMs) {
throw new Error('circuit open');
}
try {
const result = await fn(...args);
failures = 0;
return result;
} catch (error) {
failures += 1;
if (failures >= threshold) openedAt = now();
throw error;
}
};
}
let time = 0;
const flaky = circuitBreaker(async () => { throw new Error('down'); }, { now: () => time });
for (let i = 0; i < 4; i++) {
await flaky().catch((error) => console.log(error.message));
}
time = 1500;
await flaky().catch((error) => console.log(error.message));down
down
down
circuit open
downThree failures open the circuit, so the fourth call fails at once without touching the service. After resetMs one call is let through; it fails again here, which reopens the circuit.
This version has no half-open limit, so every call after the pause goes through until one fails. Libraries such as opossum add that, plus timeouts and fallbacks. The code uses top-level await, so it runs as an ES module.