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

tenant-idempotency

v0.1.0

Published

Tenant-scoped idempotency keys for Node.js — exactly-once request processing with pluggable storage (in-memory, Redis, Postgres) and zero runtime dependencies.

Downloads

160

Readme

tenant-idempotency

Stop double-charging your users. Tenant-scoped idempotency keys for Node.js — retried or duplicated requests (payments, invoices, webhooks) execute exactly once, and duplicates get the original response back. Zero runtime dependencies.

npm install tenant-idempotency

Quickstart

import { createIdempotencyStore } from 'tenant-idempotency';

const store = createIdempotencyStore(); // in-memory by default

// The handler runs exactly once per (scope, key) — duplicates get the cached value.
const { value, cached } = await store.execute(
  { key: request.headers['idempotency-key'], scope: tenantId },
  async () => chargeCustomer({ amount: 4200 }),
);

Or drop it in front of your Express mutation routes:

import express from 'express';
import { createIdempotencyStore, httpIdempotency } from 'tenant-idempotency';

const app = express();
const store = createIdempotencyStore();

app.post(
  '/payments',
  httpIdempotency(store, { scope: (req) => req.auth.tenantId }),
  async (req, res) => {
    const payment = await processPayment(req.body); // runs once per key
    res.status(201).json(payment);
  },
);

Clients send a UUID in the Idempotency-Key header. Retrying the same request replays the original 201 + body (with an Idempotency-Replayed: true header); firing it twice concurrently gets a 409 on the duplicate.

How it works

Every operation is identified by a client-generated key, isolated per scope (your tenant ID — the same key in two tenants is two independent operations). Processing walks a tiny state machine:

        reserve (atomic)
   ┌────────────┼─────────────────┐
   free      in-flight        completed
   │            │                 │
   run       reject 409      replay cached
 handler    (client retries)   response
   │
   ├─ success → complete: cache result for ttlMs
   └─ failure → release: key is retryable again

Three details make this safe in production:

  • Atomic reservation. When N requests race on the same key, the storage adapter guarantees exactly one wins (SET NX in Redis, INSERT ... ON CONFLICT in Postgres, synchronous check-and-set in memory).
  • Crash recovery. A reservation only blocks duplicates for inFlightTtlMs. If the process dies mid-request, the key unlocks automatically and a retry takes over.
  • Token fencing. reserve issues an ownership token; complete/release are no-ops without it. A slow, presumed-dead request that wakes up after its key was taken over can't clobber the new owner's result.

Failed handlers are not cached — only successful results are, so clients can safely retry errors.

Storage adapters

| Adapter | Use when | Setup | |---|---|---| | MemoryAdapter (default) | Tests, dev, single process | none | | RedisAdapter | Multi-process, you have Redis | pass an ioredis-compatible client | | PostgresAdapter | Multi-process, you have Postgres | run PostgresAdapter.schemaSql(), pass a pg Pool |

// Redis (ioredis)
import Redis from 'ioredis';
import { createIdempotencyStore, RedisAdapter } from 'tenant-idempotency';

const store = createIdempotencyStore({ adapter: new RedisAdapter(new Redis(url)) });
// Postgres (pg)
import { Pool } from 'pg';
import { createIdempotencyStore, PostgresAdapter } from 'tenant-idempotency';

const pool = new Pool({ connectionString });
await pool.query(PostgresAdapter.schemaSql()); // or ship it as a migration
const store = createIdempotencyStore({ adapter: new PostgresAdapter(pool) });

// Postgres has no native TTL — purge expired rows periodically:
setInterval(() => store.cleanup(), 60 * 60 * 1000);

Neither adapter imports its driver — you pass any client matching a minimal structural interface (RedisLikeClient / PostgresLikeClient), so the library has zero runtime dependencies. Custom backend? Implement the four-method StorageAdapter interface.

API reference

createIdempotencyStore(options?) → IdempotencyStore

| Option | Type | Default | | |---|---|---|---| | adapter | StorageAdapter | new MemoryAdapter() | storage backend | | ttlMs | number | 24 h | how long completed results are replayed | | inFlightTtlMs | number | 60 s | how long an unfinished reservation blocks duplicates; set above your slowest handler |

store.execute(ref, handler, metadata?) → Promise<{ value, cached, metadata? }>

Runs handler exactly once per ref ({ key, scope? }).

  • First call → runs the handler, caches the resolved value, returns { value, cached: false }.
  • Duplicate after completion → { value, cached: true, metadata } without running the handler.
  • Duplicate while in flight → throws IdempotencyInFlightError (code: 'IDEMPOTENCY_IN_FLIGHT') — map it to HTTP 409.
  • Handler throws → key is released (retryable) and the error propagates.

Values must be JSON-serializable; cached values come back as plain JSON. Optional metadata (e.g. { statusCode: 201 }) is stored and returned on replays.

store.reserve(ref) / store.complete(ref, token, value, metadata?) / store.release(ref, token)

Low-level primitives for when the result isn't known inside a callback (the HTTP middleware uses these). reserve returns { outcome: 'reserved', token } | { outcome: 'in_flight' } | { outcome: 'completed', value, metadata }. After reserving you must complete or release with the token.

store.cleanup() → Promise<number>

Deletes expired records (needed for Postgres/memory; Redis expires natively).

httpIdempotency(store, options?)

Express-style middleware. Options: header (default 'idempotency-key'), scope: (req) => string (derive the tenant), required (default true; false lets keyless requests pass through un-deduplicated). Behavior: missing header → 400 · replay → original status + body + Idempotency-Replayed: true · concurrent duplicate → 409 · non-2xx responses are not cached.

StorageAdapter

interface StorageAdapter {
  reserve(storageKey: string, inFlightExpiresAt: Date): Promise<ReserveResult>; // must be atomic
  complete(storageKey: string, token: string, value: unknown,
           metadata: ResultMetadata | undefined, expiresAt: Date): Promise<boolean>;
  release(storageKey: string, token: string): Promise<boolean>;
  cleanup?(): Promise<number>;
}

complete/release must be no-ops (returning false) when token no longer owns the key.

License

MIT