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

async-guard-js

v1.9.6

Published

AsyncGuardJS | Safely run async tasks with retries, timeouts, backoff & circuit breaker + fallback support ;)

Readme

async-guard-js

NPM

A dependency-free utility to run async functions with retries, timeouts, cancellation, rate limiting, circuit breakers, fallbacks & lightweight metrics.


Installation

npm install async-guard-js@latest

Basic Usage

import AsyncGuardJS from "async-guard-js";

const result = await AsyncGuardJS.run(
    async ({ attempt, signal, timeout }) => {
        return fetch("api-url", { signal });
    },

    {
        retries: 3,
        timeout: 2000
    }
);

Retry & Timeout

AsyncGuardJS.run(task, {
    retries: 5,
    timeout: 3000,
    retry_if_timeout: 5000,

    retry_if: (error, context) => {
        return error instanceof NetworkError && context.attempt < 3;
    },

    backoff: (attempt) => attempt * 200,
    max_backoff: 2000
});
  • Retries are bounded.
  • Timeouts are enforced per attempt.
  • Backoff supports jitter and hard caps.
  • retry_if may be async and is itself time-bounded.
  • retry_if_timeout (default: 5000) - Maximum time for the retry_if function to execute.

AbortSignal Support

const controller = new AbortController();

AsyncGuardJS.run(task,  {
    signal: controller.signal
});

Abort signals are respected across retries & timeouts.


Circuit Breaker

AsyncGuardJS.run(task, {
    circuit_breaker: {
        name: "external-api",
        threshold: 5,
        window: 10000,
        recovery: 5000
    }
});

Circuit states:

  • CLOSED ~ Normal operation.
  • OPEN ~ Requests fail immediatly.
  • HALF_OPEN ~ Limited test execution after recovery.

Circuit Status

const status = AsyncGuardJS.get_circuit_status("external-api");

Returns:

{
    state: "CLOSED" | "OPEN" | "HALF_OPEN",
    failures: number,
    opened_at: number | null
}

Reset manually if needed

AsyncGuardJS.reset_circuit("external-api");

Rate Limiting

AsyncGuardJS provides an in-memory sliding-window rate limiter.

AsyncGuardJS.run(task, {
    rate_limit: {
        name: "api",
        max_requests: 10,
        window_ms: 1000,
        queue: true,
        queue_max_wait_ms: 30000
    }
});

Behavior:

  • Requests are tracked in a sliding time window.
  • If queue is false (default), execution fails immediatly when the limit is reached.
  • If queue is true, execution waits until a slot becomes available.
  • NOTE: queue_max_wait_ms (default 30000) - Maximum time to wait in queue before throwing an error.

NOTE: Queueing is time-based, not FIFO.

Rate Limit Status

const status = AsyncGuardJS.get_rate_limit_status("api");

Returns:

{
    current_requests: number,
    capacity_remaining: number,
    oldest_request_timestamp: number | null,
    ms_until_next_slot: number,
    window_ms: number,
    is_at_limit: boolean
}

Reset manually:

AsyncGuardJS.reset_rate_limit("api");

Fallbacks

AsyncGuardJS.run(task, {
    fallback: () => "default value"
});

Behavior:

  • If all attempts fail, the fallback is executed.
  • If the fallback succeeds, it's value is returned.
  • If the fallback fails, AsyncGuardJS throws an error containing:

    The original error$ The fallback error Execution context metadata


Metrics (EXPERIMENTAL)

AsyncGuardJS collects lightweight, in-memory metrics (counters & timers) during execution.

  • Metrics are process-local.
  • Nothing is exported or persisted automatically.
  • Metrics are only exposed when requested.
  • Timers automatically compute useful stats (min, max, mean, p50/p90/p95/p99).
  • Opt custom exporter hook for external systems (logs, Prometheus, StatsD, ect.).
  • Exposed on-demand via get_metrics()
const raw_metrics = AsyncGuardJS.get_metrics(); // -> { counters: {...}, timers: {... raw arrays} }
const json_metrics = AsyncGuardJS.get_metrics("json");

console.log(raw_metrics);
console.log(json_metrics)

// Json output example
{
    counters: {
        "asyncguardjs.attempt": [
            { labels: { attempt: "1" }, value: 42 },
            { labels: {}, value: 100 }
        ],
    },

    timers: {
        "asyncguardjs.task.duration_ms": [
            {
                labels: { attempt: "1" },

                stats: {
                    count: 42,
                    sum: 8400,
                    min: 50,
                    max: 800,
                    mean: 200,
                    percentiles: { p50: 180, ... }
                }
            }

            // ...
        ]
    }
}

Reset metrics:

AsyncGuardJS.reset_metrics();

TypeScript Support

AsyncGuardJS ships with first-class TypeScript definitions (.d.ts) included in the package. Public types includes:

  • AttemptContext
  • AsyncGuardOptions<T>
  • CircuitBreakerConfig
  • CircuitStatus
  • CircuitState
  • RateLimitConfig
  • RateLimitStatus
  • MetricsSnapshot

No additional configurations is required.

Example Usage

import AsyncGuardJS, { AttemptContext, AsyncGuardOptions } from "async-guard-js";

type User = { id: number; name: string };

const fetch_user = async ({ attempt, signal }: AttemptContext): Promise<User> => {
    console.log(`Attempt: #${attempt}`);

    const response = await fetch("api-url", { signal });

    if (!response.ok) {
        throw new Error("Failed To Fetch.");
    }

    return response.json();
};

const options: AsyncGuardOptions<User> = {
    retries: 3,
    timeout: 5000,
    backoff: attempt => 200 * attempt,
    fallback: { id: 0, name: "Fallback" }
};

console.log(await AsyncGuardJS.run(fetch_user, options));

Notes & Limitations

  • Metrics keys use Prom-like syntax internally (name{label1:val1,...}).
  • Circuit breakers, rate limiters, and metrics are in-memory & process-local.
  • This library does not coordinate state across multiple processes or servers.
  • No dependencies.