npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

breaker-box

v10.1.0

Published

A zero-dependency circuit breaker implementation for Node.js

Readme

Breaker Box

A zero-dependency circuit breaker implementation for Node.js.

Installation

npm install breaker-box

Basic 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 protect
  • options: 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 below errorThreshold, otherwise it reopens. Transient errors (see errorIsTransient) don't count and free their trial slot (default: minimumCandidates)
    • minimumCandidates: Minimum settled calls while closed before calculating error rate; also the default for halfOpenProbes (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) => boolean to 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's errorWindow. Returns NaN if 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. Supports using syntax.

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 error
  • isTransient: true if the error was classified as transient via errorIsTransient

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 milliseconds
  • signal: 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.