forestall
v0.1.3
Published
Idempotency for retried operations — same key runs the work once and replays the stored result, race-safe, storage-agnostic.
Maintainers
Readme
forestall
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 forestallUse
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 }): StoreStore 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
Storeinterface is provided. Implementclaim()atomically using RedisSET NX PX. - HTTP middleware — Wrap
forestall()in your own Express/Fastify middleware. - Request binding — Extract headers and pass them as the
keyparameter. - 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:
- @azghr/filterkit — Framework-agnostic, type-safe filtering for TypeScript
- @azghr/singlet — Deduplicate concurrent async calls
- staleness — Stale-while-revalidate caching for async functions
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
