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

forestall

v0.1.3

Published

Idempotency for retried operations — same key runs the work once and replays the stored result, race-safe, storage-agnostic.

Readme

forestall

npm version MIT License

Idempotency for retried operations — same key runs the work once and replays the stored result, race-safe, storage-agnostic.

The problem

Clients retry POST requests due to flaky networks, impatient users, or proxy retries. Without idempotency, retried "create payment" or "send email" operations run multiple times, causing duplicate charges or spam. Common solutions using flags or database locks have race conditions when two retries arrive simultaneously.

Install

npm install forestall
# or
pnpm add forestall
# or
yarn add forestall

Use

import { forestall, createMemoryStore } from "forestall";

const store = createMemoryStore();
const idempotent = forestall({ store, ttlMs: 60000 });

// 3 concurrent calls → 1 execution
const [r1, r2, r3] = await Promise.all([
  idempotent("order-123", () => chargeCard("order-123")),
  idempotent("order-123", () => chargeCard("order-123")),
  idempotent("order-123", () => chargeCard("order-123"))
]);

HTTP example:

import { forestall, InFlightTimeout } from "forestall";

const execute = forestall({ store: createMemoryStore(), ttlMs: 3600000 });

app.post("/charge", async (req, res) => {
  const key = req.headers["idempotency-key"];
  try {
    const result = await execute(key, () => stripe.charges.create(req.body));
    res.status(200).json(result);
  } catch (error) {
    if (error instanceof InFlightTimeout) return res.status(425).send("Too Early");
    throw error;
  }
});

API

forestall(options)

Creates an idempotency function preventing duplicate executions.

function forestall(options: ForestallOptions): <T>(key: string, fn: () => Promise<T>) => Promise<T>

Parameters: store (Store interface), ttlMs (default: 86400000), waitMs (default: 5000), pollMs (default: 50), replayErrors (default: false), clock, sleep

Returns: Function (key, fn) => Promise<T>

Behavior: First caller claims key and executes; concurrent callers wait and replay result. Sequential calls within TTL replay stored result. After TTL expiry, function runs again. Throws InFlightTimeout if peer doesn't complete within waitMs.

createMemoryStore(options?)

Creates an in-memory Store with automatic cleanup.

function createMemoryStore(options?: { cleanupIntervalMs?: number }): Store

Store interface

Storage abstraction for idempotency entries.

interface Store {
  get(key: string): Promise<StoredEntry | undefined>;
  set(key: string, entry: StoredEntry, ttlMs: number): Promise<void>;
  claim(key: string, ttlMs: number): Promise<boolean>;
  release(key: string): Promise<void>;
}

InFlightTimeout error

Thrown when in-flight peer doesn't complete within waitMs.

StoredEntry type

type StoredEntry = { status: "done"; value: unknown } | { status: "failed"; error: string };

Non-goals

This package provides only the core idempotency mechanism. It does NOT include:

  • Redis/SQL stores — Only the Store interface is provided. Implement claim() atomically using Redis SET NX PX.
  • HTTP middleware — Wrap forestall() in your own Express/Fastify middleware.
  • Request binding — Extract headers and pass them as the key parameter.
  • Framework integration — Core is runtime-agnostic; works with Node, browsers, edge.

Redis example (conceptual):

class RedisStore implements Store {
  async claim(key: string, ttlMs: number): Promise<boolean> {
    const result = await redis.set(key, "in-flight", "NX", "PX", ttlMs);
    return result === "OK";
  }
}

TypeScript

Fully typed with strict TypeScript. The Store interface is designed for easy implementation in your preferred storage backend.

Related Packages

Caching & Concurrency:

Text Processing:

  • @azghr/shorn — Truncate strings by byte budget without breaking graphemes
  • seriatim — Sequential processing utilities

HTTP & Network:

  • forbear — Read server rate-limit instructions from HTTP responses
  • obviate — Render operations unnecessary through caching

System & Process:

  • quiesce — Ordered, timeboxed graceful shutdown for Node
  • sortition — Deterministic percentage rollouts and A/B bucketing
  • stanch — Stop flows or operations based on conditions

Utilities:

  • expunge — Remove or exclude items from collections
  • occlude — Hide or mask data and functionality
  • placemark — Geographic location and mapping utilities
  • specie — Currency and financial calculations

License

MIT