How to Implement a Circuit Breaker for Async Calls
Implement a circuit breaker for async calls in JavaScript with closed, open and half-open states, a failure threshold, a reset timer and fast failure.

When a dependency is down, calling it harder does not help. Each call waits for a timeout, ties up a connection and a bit of memory, and adds to the load on a service that is already struggling. A page that calls three services, one of them dead, becomes as slow as the dead one's timeout. A circuit breaker stops the damage: after enough failures, it opens and rejects calls immediately without touching the dependency, then after a pause lets a trial call through to see whether things have recovered. This post implements a circuit breaker for async calls in plain JavaScript for Node.js 24, with the three states, thresholds, a reset timer and printed output from a simulated outage. It complements retrying with backoff, which handles brief failures, while the breaker handles sustained ones.
The three states
A breaker is a small state machine. In the closed state, calls pass through and failures are counted. When failures reach a threshold, the breaker moves to open: calls fail at once with a specific error, and no request is made. After a cool-down period, the breaker moves to half-open and allows a limited number of trial calls. If a trial succeeds, the breaker closes and normal service resumes. If it fails, the breaker opens again for another cool-down.
The name comes from electrical wiring, where a breaker trips to protect a circuit from overload. The software version protects both sides: your caller from slow failures, and the dependency from a flood of requests while it recovers.
A minimal implementation
The class wraps an async function. It tracks consecutive failures, the time the breaker opened and the current state.
export class CircuitOpenError extends Error {
constructor() {
super("circuit is open");
this.name = "CircuitOpenError";
}
}
export class CircuitBreaker {
#state = "closed";
#failures = 0;
#openedAt = 0;
#trialInFlight = false;
constructor(fn, { failureThreshold = 3, resetMs = 1000, now = () => Date.now() } = {}) {
this.fn = fn;
this.failureThreshold = failureThreshold;
this.resetMs = resetMs;
this.now = now;
}
get state() {
return this.#state;
}
async call(...args) {
if (this.#state === "open") {
if (this.now() - this.#openedAt < this.resetMs) throw new CircuitOpenError();
this.#state = "half-open";
}
if (this.#state === "half-open") {
if (this.#trialInFlight) throw new CircuitOpenError();
this.#trialInFlight = true;
}
try {
const result = await this.fn(...args);
this.#onSuccess();
return result;
} catch (error) {
this.#onFailure();
throw error;
} finally {
this.#trialInFlight = false;
}
}
#onSuccess() {
this.#failures = 0;
this.#state = "closed";
}
#onFailure() {
this.#failures += 1;
if (this.#state === "half-open" || this.#failures >= this.failureThreshold) {
this.#state = "open";
this.#openedAt = this.now();
}
}
}The now function is injected so tests can control the clock without real waiting. In half-open state only one trial call is allowed at a time, and other callers are rejected immediately, which stops a recovering service from being hit by a crowd the moment the cool-down ends.
Watching an outage and a recovery
Simulate a dependency that fails four times and then recovers, with a controllable clock.
import { CircuitBreaker, CircuitOpenError } from "./breaker.js";
let clock = 0;
let healthy = false;
const breaker = new CircuitBreaker(
async () => {
if (!healthy) throw new Error("service down");
return "ok";
},
{ failureThreshold: 3, resetMs: 1000, now: () => clock }
);
async function attempt(label) {
try {
const result = await breaker.call();
console.log(`${label}: ${result} [${breaker.state}]`);
} catch (error) {
const kind = error instanceof CircuitOpenError ? "rejected fast" : error.message;
console.log(`${label}: ${kind} [${breaker.state}]`);
}
}
await attempt("call 1");
await attempt("call 2");
await attempt("call 3");
await attempt("call 4");
clock = 1200;
healthy = true;
await attempt("call 5");
await attempt("call 6");call 1: service down [closed]
call 2: service down [closed]
call 3: service down [open]
call 4: rejected fast [open]
call 5: ok [closed]
call 6: ok [closed]The third consecutive failure opens the circuit. Call 4 never reaches the service and fails at once, which is the point. After the clock passes the reset time, call 5 goes through as a trial in the half-open state, succeeds and closes the circuit. The output shows the state after each call.
Choosing what counts as a failure
Not every error is the dependency's fault. A 404 or a validation error means the service is healthy and your request was wrong, and counting those toward the threshold would open the circuit on a perfectly working service. Pass a predicate that decides which errors count, such as network errors, timeouts and 5xx statuses, in the spirit of retrying only on specific errors. Time matters too: a breaker that counts consecutive failures forever is fooled by one failure a day for three days. Count failures in a rolling window, for example the last ten seconds, or reset the counter on each success, as the simple version above does.
Add a timeout, or the breaker never trips
A call that hangs does not fail, so a breaker that waits for errors never opens while the dependency hangs. Put a timeout on every call inside the breaker, using AbortSignal.timeout, and treat the timeout as a failure.
import { CircuitBreaker } from "./breaker.js";
const callWithTimeout = (fn, ms) => (...args) =>
Promise.race([
fn(...args),
new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), ms)),
]);
const slow = () => new Promise((resolve) => setTimeout(resolve, 500));
const breaker = new CircuitBreaker(callWithTimeout(slow, 20), { failureThreshold: 2 });
for (let i = 1; i <= 3; i++) {
try {
await breaker.call();
} catch (error) {
console.log(`call ${i}: ${error.message} [${breaker.state}]`);
}
}call 1: timeout [closed]
call 2: timeout [open]
call 3: circuit is open [open]After two timeouts the circuit opened and the third call failed instantly. Without the timeout, each call would have waited half a second, and the breaker would have counted nothing. Prefer passing an abort signal to the real call so the slow request is canceled, not merely abandoned, as in implementing a cancelable promise.
Fallbacks make the failure useful
An open circuit tells you the dependency is unavailable, and the caller still has to do something. Good options include returning cached data with a staleness flag, returning a default such as an empty recommendations list, queueing the work for later, or showing the user a clear message. Decide the fallback per call site, since a missing recommendation widget is harmless, while a missing payment service is not. Catch CircuitOpenError specifically, so the fallback runs only for the open circuit and not for every error.
Where the state lives
An in-process breaker sees only the calls made by that process. With ten instances, each learns about the outage separately, after its own three failures. That is usually acceptable, since the cost is a few failed calls per instance. Sharing state between instances needs a store such as Redis, and adds a dependency to the path that exists to handle dependency failures, which is rarely worth it. Libraries such as opossum provide a tested breaker with rolling windows, events and metrics, and are the better choice for production services.
Monitoring the breaker
A breaker that trips silently hides an outage from the people who could fix it. Emit an event or a log line on every state change, with the name of the dependency, the old and new states and the error that caused the trip. Export the current state as a metric, with a value for each state, so a dashboard can show which dependencies are open right now. An alert on "open for more than five minutes" is more useful than one on each trip, since short trips are the breaker doing its job.
Also record how many calls were rejected while open. That count is a direct measure of the load the breaker kept off the dependency and of the number of user requests that got a fallback instead of a result. When the outage ends, the numbers give you the impact of the incident without anyone reconstructing it from logs.
Common mistakes
One breaker for everything. A single breaker shared by unrelated endpoints trips on the worst one and blocks the healthy ones. Make one breaker per dependency, and sometimes one per operation when their failure modes differ, such as a read endpoint that is up while the write endpoint is down.
Counting client errors. A burst of invalid requests from one user should not open the circuit for everybody. Count only failures that reflect the dependency's health.
No half-open limit. Letting every waiting caller through when the cool-down ends sends a thundering herd at a service that has just come back. Allow one trial, or a small number, and keep the rest failing fast until a trial succeeds.
Opening forever. A breaker with no path back to closed turns a short outage into a permanent one until a restart. The half-open trial is that path, so test it, including the case where the trial itself fails.
Testing with an injected clock
The injected now function makes the full cycle testable in a few lines. Create a breaker with a threshold of two and a reset time of one second, fail twice and assert the state is open. Advance the fake clock by 999 milliseconds and assert that a call is still rejected, then advance by one more and assert that the next call reaches the function. Make that trial fail, and assert the breaker is open again with a fresh cool-down. Finally make a trial succeed and assert the state is closed and the failure count is zero. Those four steps cover every transition, and none of them needs a real timer.


