Modules / API infrastructure

Idempotent Requests: Idempotency-Key middleware for Node.js and Postgres

Make POST endpoints safe to retry: no double charges, no duplicate orders.

TypeScriptNode.jsPostgreSQLNext.jsExpressHonoNode >= 20ESMBun / Deno / edge (Web Crypto)

Your checkout endpoint charges the card, then the connection drops before the 201 reaches the browser. The client can't tell "never arrived" from "done but unanswered", so it retries, and your customer is charged twice. Double-clicks, flaky mobile networks, load balancer retries and SDK auto-retries all end the same way. Idempotent Requests is the fix Stripe built into its own API, as a module for yours: lock the key, run once, store the answer, replay it to every retry.

The failure cases it handles

What happens What the kit does
Client retries after a timeout or dropped connection Handler is not run again; the stored response is replayed with Idempotent-Replayed: true
Double-click: two identical requests at the same instant The database picks one winner; the other gets 409 with Retry-After
Buggy client reuses a key for a different amount 422, handler not run, instead of silently returning the old payment
User B sends user A's key Keys are scoped per user or tenant: B's request is independent and never sees A's response
Handler throws or returns 503 Key is released so the retry can succeed; the error is not cached as the final answer
Process killed mid-request Retries get 409 until the lease ends, then one takes over with ctx.recovered = true
The original slow request finishes after that takeover Its ownership token is stale, so it can't overwrite the new result
Your database is down 503, fail closed: running without the lock is how double charges happen

How it looks

const idempotency = createIdempotency({ store: new PostgresStore(pool) });

// app/api/orders/route.ts
export async function POST(request: Request) {
  const user = await requireUser(request);
  return idempotency.handle(request, { scope: user.id }, async (req, { idempotencyKey }) => {
    const order = await createOrder(await req.json(), idempotencyKey); // runs once per key
    return Response.json(order, { status: 201 });
  });
}

// in the browser: one key per checkout, reused across retries
await idempotentFetch("/api/orders", { method: "POST", body }, { key });

What's in the package

src/            ~640 lines of strict TypeScript, zero runtime dependencies
migrations/     one idempotent SQL file
tests/          65 tests: middleware, client, key parsing, Node adapter, store contract (Memory + Postgres)
examples/       offline demo (npm run demo), Next.js order route + purge cron + browser checkout, node:http / Express
docs/           ARCHITECTURE.md (lifecycle and why), SECURITY.md (threat model, deployment checklist)
README.md  CHANGELOG.md  LICENSE.md

The store contract suite runs concurrent-duplicate and crash-takeover tests against a real PostgreSQL database, and you can run it against your own store implementation. npm run demo starts a real HTTP server with a "charge the card" endpoint: seven requests, including a double-click, a lost response, a reused key, a failure and a dropped connection, produce exactly three charges.

Who it is for

Teams on Node and TypeScript whose API creates things that must not be created twice: payments, orders, transfers, bookings, sent emails or messages, provisioned resources. Also teams publishing a public API who want to offer Idempotency-Key the way Stripe does.

Who it is not for

  • Receiving webhooks from Stripe or GitHub: that's Reliable Webhooks, which deduplicates by the provider's event id.
  • Streaming responses (server-sent events, large downloads): responses are buffered so they can be stored.
  • Non-JavaScript backends.
  • Exactly-once side effects: no HTTP layer can promise that. If a request crashes after its side effect and before its response is stored, the retry runs again, flagged with ctx.recovered. The kit gives you the key to pass downstream so that case is safe too, and the docs say so plainly.

New to this? Read the guide: How to implement Idempotency-Key in a Node.js API with PostgreSQL.

Read the full Idempotent Requests documentation (API, architecture, threat model) before you buy.

What you get

  • Idempotency-Key support for any Request/Response endpoint: the handler runs once per key, retries get the stored response
  • Atomic lock in the database: concurrent duplicates and double-clicks get 409 with Retry-After, never a second run
  • Request fingerprints: a key reused with a different method, path or body is rejected with 422 instead of returning the wrong response
  • Keys scoped per user or tenant, so one client can never replay another's response
  • Crash recovery with leases and ownership tokens: a dead request's key is taken over, and a stale request can't overwrite the new result
  • Sensible storage rules: 2xx–4xx are final, 5xx/408/429 and thrown errors release the key, Set-Cookie is never replayed, store outages fail closed
  • idempotentFetch client: one key across retries, exponential backoff with jitter, honours Retry-After
  • PostgreSQL store with migration, in-memory store, and a store contract test suite for other databases
  • 65 automated tests (13 run against a real PostgreSQL), runnable offline demo, architecture and security docs, changelog

Will it work in my project?

  • Node.js 20 or newer (tested on 20, 22, 24 and 26)
  • PostgreSQL 12+ for the included store (any database via the IdempotencyStore interface)
  • A framework that gives you a Web Request (Next.js, Hono, Remix, Bun, Deno, Workers), or node:http / Express via the included adapter
  • TypeScript 5+ recommended; zero runtime dependencies

What happens after you buy

  1. Pay on Stripe. You need a Softreuse account (free, email confirmation). Card details go to Stripe, never to us.
  2. Access is granted automatically as soon as Stripe confirms the payment, usually within seconds. Stripe emails the receipt.
  3. Download from your account at any time: the .zip, its SHA-256 checksum, and the full documentation. Links are generated on demand, so you can come back in a year.
  4. Unzip, npm install, npm test, npm run demo to see it work before you touch your own code.
  5. Updates: every v1.x release appears in the same place, free.

Not working as documented? Full refund within 14 days. Questions before buying: support@softreuse.com.

Security

The security design is documented in the package (docs/SECURITY.md) with a threat model. In short:

  • Isolation: keys are namespaced by a scope you derive from authentication, so a guessed or leaked key can't replay another user's response. An empty scope is a programming error and throws.
  • Integrity: a SHA-256 fingerprint of method, path and body detects keys reused for a different request (422), and per-attempt ownership tokens stop a stale request from overwriting a newer result.
  • Fail closed: if the store is unreachable the endpoint answers 503 and your handler does not run.
  • Replay hygiene: Set-Cookie is never stored or replayed; 5xx, 408 and 429 are never cached as final answers.
  • Abuse: request bodies are capped (default 1 MiB) by Content-Length and while streaming; keys must be 16–255 visible ASCII characters.
  • Injection: all SQL values are bound parameters; the one interpolated identifier (table name) is validated; a test stores hostile scope, key and header text.
  • Privacy: logs contain event names, method, path, status and an 8-character key prefix. Never bodies, headers, scopes or full keys. This is tested.
  • Supply chain: zero runtime dependencies; npm audit --omit=dev is clean.
  • Honest limits: no authentication (you supply the scope), no encryption at rest (your database's job), no rate limiting, not exactly-once for side effects that crash mid-way. These are documented along with a deployment checklist.

Versions & changelog

v1.0.0 · Oct 27, 2026

Initial release.

  • createIdempotency().handle(request, { scope }, handler): runs a handler at most once per (scope, Idempotency-Key) and replays its response, marked Idempotent-Replayed: true.
  • Concurrent duplicates get 409 with Retry-After; a key reused for a different method, path or body gets 422; missing or malformed keys get 400. Errors are RFC 9457 problem details.
  • Request fingerprints (SHA-256 of method, path + query, body), overridable.
  • Lease-based crash recovery with ctx.recovered, and per-attempt ownership tokens so a stale request cannot overwrite a newer result.
  • Thrown errors, 5xx, 408 and 429 release the key; Set-Cookie is never stored or replayed; fails closed (503) when the store is unavailable.
  • Stores: PostgresStore (primary-key lock, ON CONFLICT … WHERE takeover) and MemoryStore, plus a public IdempotencyStore interface and contract test suite. purgeExpired() for cleanup.
  • Client: idempotentFetch reuses one key across retries, with exponential backoff, full jitter and Retry-After.
  • toNodeHandler adapter for node:http / Express; Web-standard API for Next.js, Hono, Bun, Deno, Workers.
  • 65 automated tests including a store contract suite run against a real PostgreSQL.

License

Softreuse Commercial License — Idempotent Requests

Version 1.0 · Copyright © Softreuse. All rights reserved.

"Softreuse" is the trading name of the seller identified in the Terms of Sale at https://softreuse.com/terms. Those Terms are the authoritative source for who the seller is and how to reach them.

This is the license that comes with your purchase of this package ("the Software"). Please read it; it is short on purpose.

1. What you may do

You (the individual or single company that purchased the Software, "Licensee") may, forever, for the versions covered by Section 4:

  • use, copy and modify the source code in any number of projects that you or your company own or build for your own use, commercial or not;
  • let your employees and contractors work with the source for those projects;
  • ship products that contain or are built from the Software (including compiled or bundled) to your own users and customers;
  • keep your modifications private.

2. What you may not do

  • Redistribute, resell, sublicense, publish or share the Software's source code, in original or modified form, as a standalone product, template, boilerplate, starter kit, library, SaaS feature-for-feature clone, course material or marketplace listing.
  • Publish the Software's source in a public repository or package registry. (Private repositories of your team are fine. Publishing an application that merely uses the Software is fine.)
  • Share your download access or purchase with people outside your company.
  • Remove copyright or license notices from the files.

If you are a consultancy building a product for a client, the client needs their own license unless the client is the owner of the resulting project and you transfer the project (not the Software as a standalone asset).

3. Ownership

Softreuse keeps ownership of the Software. You own everything you build with it.

4. Updates

Your purchase includes all releases of this product within the major version you bought (for example every 1.x release if you bought 1.0.0), delivered through your Softreuse account. A new major version (2.0.0) is a new paid release; versions you already have keep working under this license forever.

5. Warranty and liability

The Software is provided "as is", without warranty of any kind. Softreuse tests the Software and publishes known limitations, but you are responsible for evaluating it for your use, including security review of your own deployment. To the maximum extent permitted by law, Softreuse's total liability for any claim is limited to the amount you paid for the Software, and Softreuse is not liable for indirect or consequential damages (lost profits, lost data, business interruption).

6. Refunds

If the Software does not work as documented, tell us within 14 days of purchase and we will refund you in full. Refunded licenses end at the moment of refund.

7. Termination

This license ends automatically if you breach Section 2. Sections 3, 5 and 7 survive termination.

8. Contact

support@softreuse.com

Questions

Why not just ask an AI to write this?

You can, and for many things you should. A model will write "look up the key, run, save the response" in seconds. The hard part is what it leaves out: two requests passing the lookup at the same instant, a key reused with a different body, a crashed request holding the key forever, a slow request overwriting its own retry's result, one user's key replaying another user's response. This package comes with tests for each of those, run against a real PostgreSQL database, plus a written threat model. You still review the code. You just start from something that has already been tested against the failure modes.

What exactly do I get after paying?

A .zip with the full TypeScript source, tests, runnable examples, SQL migration, architecture and security docs, a changelog and the licence. It's available in your Softreuse account the moment Stripe confirms payment, and you can download it again any time.

What does the licence allow?

Use it in unlimited projects you or your company own, commercial or not, and modify it freely. You can't resell or redistribute it as a standalone product or library. The full text is on the product page and inside the package.

Which versions does my purchase cover?

Every release of the major version you bought. Buy v1 and you get all v1.x updates (fixes and backwards-compatible features) for free. A future v2 with breaking changes would be a separate paid release; v1 stays yours either way.

Will it work with my stack?

It targets Node.js 20 or newer, TypeScript, and PostgreSQL for the included store. It has zero runtime dependencies and wraps any Web-standard Request/Response handler, so it works in Next.js route handlers, Hono, Remix, Bun and Deno, and in node:http or Express through the included adapter. The idempotentFetch client runs in browsers and Node. Any other database works by implementing a small store interface that ships with a contract test suite. It is not for streaming responses, and not for non-JavaScript backends.

What if it doesn't work for me?

Email support@softreuse.com. If it doesn't work as documented and we can't fix it, you get a full refund within 14 days of purchase. No forms, no hoops.

Is checkout secure? Do you see my card?

Payment happens on Stripe's hosted checkout page. Your card details never touch Softreuse servers. Access is granted only after Stripe confirms the payment to us by a signed server-to-server message.

Do you charge VAT or sales tax?

Listed prices exclude VAT and sales tax. Where it applies, tax is calculated at checkout from your billing address and added to the price before you pay. If you buy as a business, you can enter your company name and VAT number at checkout. Stripe sends a receipt and an invoice for every purchase.

  • Agent Payments: Charge AI agents per request over HTTP 402: MPP (Stripe) and x402 on one route, charged exactly once, refunded when your handler fails.
  • Reliable Webhooks: Receive webhooks without losing, duplicating or double-processing them.
  • Outbound Webhooks: Send webhooks to your customers like Stripe does: signed, retried, logged and safe to point anywhere.