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

@prash0029/circuit-breaker

v0.1.0

Published

Two-level, config-driven in-memory circuit breaker for guarding outbound server API calls (per-service + per-endpoint).

Readme

circuit-breaker

Two-level, config-driven, in-memory circuit breaker for guarding outbound server API calls. Built once at server start from a route checklist, then placed in front of every outgoing request (axios, fetch, or any promise-returning call).

Each request is matched against the rules to find its service rule and its endpoint rule. The request passes only if both matched breakers are non-open. The response status then classifies the call as success or failure on each level:

  • failure -> count + 1
  • success -> count - 1 (floored at 0; leaky bucket, not a hard reset)
  • count >= failureThreshold trips CLOSED -> OPEN

A request matching no rule passes through untouched.

States

CLOSED ──count >= failureThreshold──▶ OPEN
OPEN ──cooldownMs elapsed──▶ HALF_OPEN
HALF_OPEN ──successThreshold trial successes──▶ CLOSED
HALF_OPEN ──any trial failure──▶ OPEN

Install

npm install circuit-breaker

Configure once at startup

import { createBreaker } from "circuit-breaker";

export const breaker = createBreaker({
  // evaluated in order; first match wins per level
  rules: [
    {
      type: "service",
      match: "insurer-x.com",          // substring tested against the request path
      skipList: ["/health", "/ping"],  // endpoints NOT counted toward the service
      failureThreshold: 10,
      cooldownMs: 30_000,
    },
    {
      type: "endpoint",
      match: "/policies/create",
      failureThreshold: 5,
      cooldownMs: 30_000,
      successThreshold: 2,
      successServerStatus: [200, 201],   // optional; else default 2xx = success
      failedServerResStatus: [500, 502, 503],
      // per-rule hook: runs only for THIS endpoint's transitions
      onStateChange: (e) => {
        if (e.to === "OPEN") alertOncall(`createPolicy breaker open`);
      },
    },
  ],
  defaults: { failureThreshold: 5, cooldownMs: 30_000, successThreshold: 2 },
  matchOn: "path", // default: strips query string so tokens/PII are never matched
  onStateChange: (e) =>
    console.warn(`[breaker] ${e.level} "${e.key}" ${e.from} -> ${e.to}`),
});

Rule fields

| Field | Applies to | Meaning | | ----------------------- | ---------------- | ------------------------------------------------------------- | | type | both | "service" or "endpoint" | | match | both | substring searched in the request path; rule applies if found | | skipList | service | endpoint substrings excluded from the service's count | | successServerStatus | both (optional) | statuses counted as success | | failedServerResStatus | both (optional) | statuses counted as failure | | failureThreshold | both (optional) | count that opens the breaker | | cooldownMs | both (optional) | OPEN duration before a HALF_OPEN probe | | successThreshold | both (optional) | trial successes needed to close |

Status classification precedence: failedServerResStatus -> successServerStatus -> default (defaultIsSuccess, 2xx). A status with no response (network error) is always a failure.

Use it

axios (guards the whole instance)

import axios from "axios";
import { attachAxios } from "circuit-breaker";

const client = axios.create({ baseURL: "https://insurer-x.com" });
attachAxios(client, breaker);

await client.post("/policies/create", payload); // guarded; rejects if open

fetch

import { wrapFetch } from "circuit-breaker";

const gfetch = wrapFetch(breaker);                 // wraps global fetch (Node 18+)
const res = await gfetch("https://insurer-x.com/policies/create", { method: "POST", body });

Any promise-returning call

import { isCircuitOpenError } from "circuit-breaker";

try {
  const result = await breaker.guard(
    { url: "https://insurer-x.com/policies/create", method: "POST" },
    () => doRequest(),   // must resolve to something with a numeric `status`
  );
} catch (err) {
  if (isCircuitOpenError(err)) {
    // fail fast: queue, fall back, or return 503. err.retryAt = when to retry.
  } else {
    throw err;
  }
}

// Or wrap once:
const createPolicy = breaker.wrap(
  { url: "https://insurer-x.com/policies/create", method: "POST" },
  (body) => doRequest(body),
);
await createPolicy(body);

Inspect / operate

breaker.stateOf("service", "insurer-x.com");     // { state, count, openedAt } | null
breaker.stateOf("endpoint", "/policies/create");
breaker.reset("endpoint", "/policies/create");   // force one breaker CLOSED
breaker.resetAll();                              // force everything CLOSED

breaker.snapshots();        // { service: {key: snap}, endpoint: {key: snap} }
breaker.printStatus();      // one line per live breaker -> console.log
breaker.printStatus(log.info); // ...or to your own logger sink

State-change callbacks

Two levels, both optional, both receive { level, key, from, to, at }:

  • registry-wide onStateChange in the config — every breaker.
  • per-rule onStateChange on a rule — only that endpoint/service. Runs first, then the registry-wide one.

Email alerts (nodemailer)

emailAlerter builds an onStateChange handler that mails an alert when a breaker trips. The transporter is injected — SMTP credentials stay in your env/secrets manager, never in this package. Default trigger: OPEN only. Recipients come from each rule's alertEmails (falling back to to). Sends are non-blocking and never throw into the breaker (failures are caught + logged).

import nodemailer from "nodemailer";
import { createBreaker, emailAlerter } from "circuit-breaker";

const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: Number(process.env.SMTP_PORT),
  auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }, // from env, not code
});

const alert = emailAlerter({
  transporter,
  from: "[email protected]",
  // when: [BreakerState.OPEN]   // default
  // to: ["[email protected]"]     // fallback if a rule omits alertEmails
});

const breaker = createBreaker({
  rules: [
    { type: "endpoint", match: "/policies/create", failureThreshold: 5,
      alertEmails: ["[email protected]", "[email protected]"] },  // per-row list
    { type: "service",  match: "icicilombard.com", failureThreshold: 10,
      alertEmails: ["[email protected]"] },
  ],
  onStateChange: alert,   // attach registry-wide; fires for every rule
});

Each rule mails its own alertEmails list. Use subject/body options to customize the message.

Scope / limits

  • In-memory per process. Behind multiple replicas, each replica trips independently. No shared/distributed state.
  • HALF_OPEN admits concurrent probes (no in-flight reservation); a burst right after cooldown can all probe at once.
  • No timeout wrapping. Wrap your own request timeout inside the call.
  • Substring matching is loose. "/policy" also matches "/policy-archive". Order rules deliberately (first match wins) and prefer specific match strings.
  • A cancelled axios request that already passed the open check records no outcome.

Develop

npm install
npm test
npm run build