breaker-box
v10.1.0
Published
A zero-dependency circuit breaker implementation for Node.js
Maintainers
Readme

Breaker Box
A zero-dependency circuit breaker implementation for Node.js.
Installation
npm install breaker-boxBasic Usage
import { createCircuitBreaker } from "breaker-box"
// Wrap an unreliable async function
async function unreliableApiCall(data: string) {
const response = await fetch(`https://api.example.com/data/${data}`)
if (!response.ok) throw new Error("API call failed")
return response.json()
}
const protectedApiCall = createCircuitBreaker(unreliableApiCall, {
errorThreshold: 0.5, // Open circuit when more than 50% of calls fail
errorWindow: 10_000, // Track errors over 10 second window
// Fallback receives the same parameters as the original function
fallback: (data) => ({ data: "fallback data", error: "API call failed" }),
minimumCandidates: 1, // Need at least 1 call before calculating error rate
resetAfter: 30_000, // Try again after 30 seconds
})
try {
const result = await protectedApiCall("user-123")
console.log("Success:", result)
} catch (error) {
console.error("Circuit breaker error:", error.message)
}The above example creates a function named protectedApiCall which, when called will execute the unreliableApiCall function with circuit breaker protection. If the underlying function fails, then fallback is called instead. If more than 50% of the calls fail within a 10-second sliding window, then the circuit breaker will open and subsequent calls to protectedApiCall will always use the fallback for the next 30 seconds.
Timeout & Retry
createCircuitBreaker supports built-in timeout and retry via options:
Timeouts
If the call doesn't complete within timeout milliseconds, it rejects and counts as a failure.
const protectedApiCall = createCircuitBreaker(unreliableApiCall, {
timeout: 5000,
})Retries
Failed calls can be retried automatically. Use retryLimit to set the maximum
number of attempts, retryTest to filter which errors are retryable, and
retryDelay to control the delay between attempts.
const protectedApiCall = createCircuitBreaker(unreliableApiCall, {
retryLimit: 3,
retryTest: (error) => error.statusCode !== 404,
retryDelay: useExponentialBackoff(60),
})Cooldowns
When using retry logic, you can introduce a delay between retries to avoid
overwhelming the remote system. The retryDelay option accepts either a number
(fixed delay in milliseconds) or a function returning a promise.
breaker-box offers helper functions to generate retry delays:
delayMs(ms: number): Returns a promise that resolves after the specified number of milliseconds.useExponentialBackoff(maxSeconds: number): Returns a function that calculates the delay using exponential backoff.useFibonacciBackoff(maxSeconds: number): Returns a function that calculates the delay using Fibonacci sequence.
import {
createCircuitBreaker,
delayMs,
useExponentialBackoff,
useFibonacciBackoff,
} from "breaker-box"
const protectedApiCall1 = createCircuitBreaker(unreliableApiCall, {
retryLimit: 3,
retryDelay: 1_000, // Fixed 1-second delay
})
const protectedApiCall2 = createCircuitBreaker(unreliableApiCall, {
retryLimit: 3,
retryDelay: useExponentialBackoff(60),
})
const protectedApiCall3 = createCircuitBreaker(unreliableApiCall, {
retryLimit: 3,
retryDelay: useFibonacciBackoff(60),
})Complete Example
import { createCircuitBreaker, useExponentialBackoff } from "breaker-box"
const protectedApiCall = createCircuitBreaker(unreliableApiCall, {
errorThreshold: 0.5,
errorWindow: 10_000,
minimumCandidates: 1,
resetAfter: 30_000,
timeout: 4_000,
retryLimit: 3,
retryDelay: useExponentialBackoff(60),
fallback: (data) => ({ data: "fallback data" }),
})Observability
The following callbacks are available:
const protectedFunction = createCircuitBreaker(unreliableApiCall, {
onClose: () => {
console.log("🟢 Circuit closed - normal operation resumed")
},
onHalfOpen: () => {
console.log("🟡 Circuit half-opened - waiting for success")
},
onOpen: (cause) => {
console.log("🔴 Circuit opened due to:", cause.message)
},
})The following methods can retrieve information about the circuit breaker:
// Check current state: "closed", "open", "halfOpen", "disposed"
console.log("Current state:", protectedFunction.getState())
// Check failure rate: Number between 0 and 1, or NaN if there is not enough data
console.log("Failure rate:", protectedFunction.getFailureRate())
// Get the last error that caused the circuit to open: undefined or Error object
console.log("Last error:", protectedFunction.getLatestError())Cleanup
// Preferred: use explicit resource management
{
using protectedFunction = createCircuitBreaker(unreliableApiCall)
// automatically disposed at end of block
}
// Or dispose manually
const protectedFunction = createCircuitBreaker(unreliableApiCall)
protectedFunction[Symbol.dispose]()API Reference
createCircuitBreaker(fn, options?)
Creates a circuit breaker around the provided async function.
Parameters
fn: The async function to protectoptions: Configuration object (optional)errorIsTransient: Function to determine if an error is transient; when true, the error is thrown to the caller but does NOT count toward the circuit breaker's failure rate (default:() => false)errorThreshold: Failure rate (0-1) that must be exceeded to open the circuit (default:0)errorWindow: Time window in ms for tracking errors (default:10_000)fallback: Function to call when an error occurs or circuit is open (default: undefined)halfOpenProbes: Number of trial calls allowed while half-open; once they have all settled, the circuit closes if their failure rate is at or belowerrorThreshold, otherwise it reopens. Transient errors (seeerrorIsTransient) don't count and free their trial slot (default:minimumCandidates)minimumCandidates: Minimum settled calls while closed before calculating error rate; also the default forhalfOpenProbes(default:1)onClose: Function called when circuit closes (default: undefined)onHalfOpen: Function called when circuit enters half-open state (default: undefined)onOpen: Function called when circuit opens (default: undefined)resetAfter: Milliseconds to wait before trying half-open (default:30_000)retryDelay: Delay between retries; a number (ms) for fixed delay or a function(attempt, signal) => Promise<void>(default:0)retryLimit: Maximum number of attempts per call (default:Infinity)retryTest: Function(error) => booleanto decide if an error is retryable (default:() => true)timeout: Per-call timeout in milliseconds; 0 disables (default:0)
Returns
A function with the same signature as fn and additional methods:
.getFailureRate(): Calculates the failure rate (0-1) of calls settled within the current state'serrorWindow. ReturnsNaNif not enough settled calls, or if circuit is open..getLatestError(): Returns the error which triggered the circuit breaker..getState(): Returns current circuit state ('closed','open','halfOpen','disposed').[Symbol.dispose](): Clean up resources and reject future calls. Supportsusingsyntax.
Helper Functions
CircuitError
Error class thrown by the circuit breaker, with a prefixed message: ERR_CIRCUIT_BREAKER_CALL_FAILURE, ERR_CIRCUIT_BREAKER_MAX_RETRIES, ERR_CIRCUIT_BREAKER_NON_RETRYABLE, or ERR_CIRCUIT_BREAKER_HALF_OPEN. Not every rejection is a CircuitError: transient errors are re-thrown as-is, calls made while the circuit is open (without a fallback) reject with the error that opened it, and calls after disposal reject with a ReferenceError.
Properties:
message: Prefixed error code (e.g.,"ERR_CIRCUIT_BREAKER_MAX_RETRIES")cause: The underlying error that triggered the circuit breaker errorisTransient:trueif the error was classified as transient viaerrorIsTransient
useExponentialBackoff(maxSeconds)
Returns a retry delay function that implements exponential backoff (2^n seconds, capped at maxSeconds).
Parameters:
maxSeconds: Maximum delay in seconds before capping
Returns: Function (attempt: number, signal: AbortSignal) => Promise<void>
useFibonacciBackoff(maxSeconds)
Returns a retry delay function that implements Fibonacci backoff (Fibonacci sequence in seconds, capped at maxSeconds).
Parameters:
maxSeconds: Maximum delay in seconds before capping
Returns: Function (attempt: number, signal: AbortSignal) => Promise<void>
delayMs(ms, signal?)
Returns a promise that resolves after the specified number of milliseconds. Supports optional abort signal for cancellation.
Parameters:
ms: Delay in millisecondssignal: Optional AbortSignal for cancellation
Returns: Promise<void>
Development Commands
| Command | Purpose |
| --------------------------- | -------------------------------------- |
| npm run build | Build with pkgroll (CJS + ESM + types) |
| npm run dev | Run tests in watch mode (vitest) |
| npm run format | Format with Prettier |
| npm run lint | Lint with ESLint (auto-fix) |
| npm run test:coverage | Run tests with coverage |
| npm test | Run tests once (includes typecheck) |
| npx tsc --noEmit | Type-check without emit |
| npx vitest <file>.test.ts | Run single test file |
| npx vitest -t "test name" | Run specific test by name |
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
