Modules / Idempotent Requests / Documentation

Idempotent Requests documentation

The README, architecture and security documents shipped in v1.0.0 of the package, published so you can judge the API before you buy. Markdown version.

Get Idempotent Requests · $39Source, tests and examples · v1.0.0 · one-time

Idempotent Requests (@softreuse/idempotency-kit) v1.0.0

Make POST endpoints safe to retry. A client that times out, double-clicks or loses its connection sends the same request again with the same Idempotency-Key; your handler runs once and every retry gets the original response. About 640 lines of TypeScript with zero runtime dependencies.

  • Node >= 20 (also runs on Bun, Deno and edge runtimes: Web Crypto + Request/Response only)
  • TypeScript strict · ESM · PostgreSQL store included (any DB via the IdempotencyStore interface)
  • Server side (createIdempotency) and client side (idempotentFetch) in one package
  • Follows the IETF Idempotency-Key header draft and the conventions Stripe popularised

Contents of this package

src/                     the library (read it: it is short)
  idempotency.ts         lock → run once → store → replay; key release on failure
  client.ts              idempotentFetch: retries with the same key, backoff, Retry-After
  key.ts                 header parsing and request fingerprints
  stores/                postgres.ts, memory.ts
  logger.ts, types.ts, adapters/node.ts
migrations/001_idempotency_keys.sql
tests/                   65 tests: middleware, client, keys, Node adapter, store contract (Memory + Postgres)
examples/
  payments-demo/         runnable offline demo (`npm run demo`)
  next-app-router/       order route, purge cron, browser checkout, Postgres wiring
  node-http/             node:http / Express
docs/ARCHITECTURE.md     how it works and why
docs/SECURITY.md         threat model and deployment checklist
CHANGELOG.md · LICENSE.md

1. See it work (30 seconds)

npm install
npm run demo

The demo starts a real HTTP server with a "charge the card" endpoint and walks through: a double-click (charged once, second click gets 409), a lost response (retry gets the stored answer), a key reused for a different amount (422), a failure mid-request (key released, retry succeeds once) and the client helper recovering from a dropped connection. Seven requests, three charges.

Run the tests: npm test. To also run the Postgres store tests against a real database: DATABASE_URL=postgres://... npm test (it creates and drops its own temporary table).

2. Install into your project

Option A — copy the source (recommended). Copy src/ to e.g. src/lib/idempotency-kit/ and migrations/001_idempotency_keys.sql into your migrations. You own the code; adjust freely.

Option B — local package. npm run build, then npm install ../path/to/this/folder. Import from @softreuse/idempotency-kit.

The examples import from ../../src/index.js; in your app import from wherever you placed it.

3. Quick start (Next.js App Router + Postgres)

  1. Run migrations/001_idempotency_keys.sql on your database.
  2. Create one instance (examples/next-app-router/idempotency.ts):
import { Pool } from "pg";
import { createIdempotency, PostgresStore } from "@softreuse/idempotency-kit";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

export const idempotency = createIdempotency({
  store: new PostgresStore(pool),
  leaseMs: 30_000, // longer than your slowest request
});
  1. Wrap the endpoint (app/api/orders/route.ts):
export async function POST(request: Request) {
  const userId = await currentUserId(request);
  if (!userId) return Response.json({ error: "unauthorized" }, { status: 401 });

  return idempotency.handle(request, { scope: userId }, async (req, { idempotencyKey }) => {
    const order = await createOrder(await req.json(), idempotencyKey);
    return Response.json(order, { status: 201 });
  });
}
  1. Send a key from the client, the same one on every retry (examples/next-app-router/checkout-button.ts):
const key = crypto.randomUUID(); // once per operation, not per click
await idempotentFetch("/api/orders", { method: "POST", body: JSON.stringify(order) }, { key });
  1. Delete expired keys once a day (examples/next-app-router/cron-route.ts): await idempotency.purgeExpired().

That is the whole integration. Everything below is reference.

4. How a request is handled

Situation Response Handler runs?
Method not in methods (default POST, PATCH) your handler's yes, unprotected
No key, required: true (default) 400 no
Key malformed or outside 16–255 chars 400 no
Body larger than maxBodyBytes 413 no
First request with this key your handler's, stored yes
Same key, same request, finished stored response + Idempotent-Replayed: true no
Same key, same request, still running 409 + Retry-After: 1 no
Same key, different method, path or body 422 no
Same key from a different scope independent key yes
Handler throws error propagates; key released retry runs it
Handler returns 5xx, 408 or 429 returned, not stored; key released retry runs it
Store unreachable 503 + Retry-After: 1 (fail closed) no
Previous request crashed (lease expired) retry takes over, ctx.recovered = true yes
Key older than ttlMs (default 24 h) treated as new yes

Errors produced by the kit are application/problem+json (RFC 9457), as the IETF draft recommends. Details and reasoning: docs/ARCHITECTURE.md.

5. The handler

idempotency.handle(request, { scope: user.id }, async (req, ctx) => {
  await req.json();       // a fresh Request: the body is still readable
  ctx.idempotencyKey;     // the client's key (null only when keys are optional and none was sent)
  ctx.scope;              // what you passed
  ctx.recovered;          // true when taking over from a request that crashed mid-way
  return Response.json(result, { status: 201 });
});
  • Return the response you want every retry to see. 2xx–4xx (except 408 and 429) become the final answer for the key.
  • Throw, or return 5xx, when the client should retry: the key is released.
  • Pass ctx.idempotencyKey downstream (e.g. as Stripe's Idempotency-Key, or a unique column on your insert). That is what protects you when a request crashes after its side effect and is then retried.
  • ctx.recovered === true means a previous run may have done part of the work. Check before redoing it.
  • Not for streaming responses: the whole body is buffered so it can be stored.

6. The client

const res = await idempotentFetch(url, init, {
  key: "…",          // default: crypto.randomUUID(); pass your own to resume an operation later
  maxAttempts: 5,
  baseDelayMs: 250,  // exponential backoff with full jitter
  maxDelayMs: 8000,  // also caps Retry-After
  retryOn: (res) => [409, 425, 429, 502, 503, 504].includes(res.status), // the default
});

Network errors are retried; aborts (init.signal) are not. The body must be re-sendable (string, bytes, Blob, FormData, URLSearchParams); streams are refused. Works in browsers, Node, Bun and Deno (anything with fetch and crypto.randomUUID).

7. Configuration

Option Default Meaning
store required PostgresStore, MemoryStore or your own IdempotencyStore
methods ["POST", "PATCH"] Methods that use keys; others pass straight through
headerName "Idempotency-Key" Header carrying the key (plain or quoted form)
required true false lets keyless requests through unprotected
minKeyLength / maxKeyLength 16 / 255 Rejects counters and short keys that collide
ttlMs 24 h How long a key is remembered
leaseMs 60 000 How long a request may hold a key before a retry may take over. Must exceed your slowest handler
maxBodyBytes 1 MiB Larger bodies get 413
shouldStore < 500, not 408/429 Which statuses become the final answer
excludeHeaders ["set-cookie"] Response headers never stored or replayed
fingerprint SHA-256(method, path + query, body) What counts as "the same request"
logger JSON lines to console silentLogger or your own { info, warn, error }
now () => new Date() Clock, for tests

PostgresStore(pool, { table }) accepts anything with query(text, values) (node-postgres Pool/Client, most wrappers).

8. Express / node:http

app.post("/v1/transfers", toNodeHandler((request) =>
  idempotency.handle(request, { scope: accountIdFrom(request) }, handler)));

Mount it without express.json() on that route: the body is fingerprinted from the raw bytes. Your handler is written against Request/Response. See examples/node-http/server.ts.

9. Other databases

Implement IdempotencyStore (begin, complete, release, get, purgeExpired). begin must be atomic: twelve concurrent calls for one key must produce exactly one started. Run tests/store.contract.test.ts against your implementation by adding it to the impls list.

10. Troubleshooting

Symptom Cause / fix
Every request gets 400 The client is not sending the header, or keys are shorter than 16 characters. Use crypto.randomUUID().
422 on a genuine retry The retry is not byte-identical: a timestamp or nonce in the body, or a different query string. Generate the body once, or pass a fingerprint that ignores the volatile field.
409 for a long time after a crash The key waits for its lease to end (leaseMs). Lower it, but keep it above your slowest handler.
Handler runs twice after a crash Expected when a request dies after its side effect but before storing the response. Use ctx.idempotencyKey downstream and check ctx.recovered.
Replay lacks a cookie By design: set-cookie is never replayed. Issue sessions outside idempotent endpoints.
MemoryStore lets duplicates through in production It is per process. Use PostgresStore with more than one instance or serverless.

Requirements and dependencies

Node 20+ (tested on 20, 22, 24 and 26). PostgreSQL 12+ for PostgresStore. Zero runtime dependencies. Development only: typescript, vitest, tsx, and pg for the Postgres tests and examples.

Licence

Commercial, see LICENSE.md. Use it in unlimited projects you or your company own; don't redistribute it as a standalone product.


Architecture

The problem

A client sends POST /payments. The server charges the card, then the connection drops before the 201 arrives. The client cannot tell "never arrived" from "done but unanswered", so it retries, and the customer is charged twice. Double-clicks, mobile networks, load balancer retries and SDK auto-retries all produce the same shape.

The fix is old and well understood: the client names the operation with a unique key, and the server remembers what it answered for that key. The details are where implementations go wrong.

Lifecycle of a keyed request

parse key ─▶ read body ─▶ fingerprint ─▶ begin (atomic) ─┬─ started ──▶ handler ─┬─ stored status ─▶ complete ─▶ response
                                                         │                       └─ 5xx / throw ──▶ release ──▶ response / error
                                                         ├─ completed ─▶ replay stored response
                                                         ├─ in_progress ─▶ 409 Retry-After
                                                         └─ mismatch ─▶ 422

1. begin is the lock, and the database decides it

if (!(await exists(key))) { run(); save(); } has a race: two requests both see "no key" and both run. The kit instead makes one atomic statement claim the key. In Postgres it is an INSERT … ON CONFLICT DO UPDATE … WHERE on the primary key (scope, idem_key): concurrent requests serialise on the row and exactly one gets a row back. The losers read the row and learn why they lost (finished, running, or a different request). The contract test runs twelve concurrent begin calls and requires exactly one winner.

2. Fingerprints catch key reuse

A client that reuses a key for a different operation (a bug, or a key generated per page instead of per checkout) would silently receive the previous operation's response. The kit stores a SHA-256 of method, path + query and the exact body bytes, and answers 422 when a key comes back with a different request. Method and path are JSON-encoded before hashing so no byte arrangement can make two different requests collide.

3. Leases, not locks, survive crashes

A process killed mid-request cannot release anything. The record therefore carries locked_until; while it is in the future, retries get 409. After it passes, the next retry of the same request takes over and runs with ctx.recovered = true. The lease must be longer than the slowest handler, or a slow request would be taken over while still running.

4. Ownership tokens stop stale writers

After a takeover, the original slow request may still finish. Each begin writes a random token; complete and release only apply while that token still owns the in-progress row. The stale request's result is discarded, and the stored answer is the one the retry produced. Tested in the store contract.

5. What gets stored, and what gets released

The stored response is the final answer for the key, so it must be one the client should accept forever:

  • 2xx, 3xx and 4xx are stored. A declined card (402) or a validation error (400) will not change on retry.
  • 5xx, 408 and 429 release the key. They mean "try again"; storing them would turn a transient failure into a permanent one.
  • A thrown error releases the key and propagates, so your framework's error handling still works.
  • Set-Cookie is never stored or replayed. A replay must not hand out a session minted for another moment.

6. Scopes

Keys are client-generated, so they are not secrets. Without a namespace, user B sending user A's key would receive user A's response. Every call passes scope (the user or tenant id), and the primary key is (scope, idem_key). An empty scope throws.

7. Fail closed

If the store is unreachable, the kit answers 503 Retry-After: 1 and does not run the handler. Running without the lock is exactly the double-execution the kit exists to prevent.

What it cannot do

A request that crashes after its side effect and before complete will run again on retry, because nothing recorded that it finished. No HTTP-level library can close that gap alone. Two things do: pass ctx.idempotencyKey to downstream systems that support idempotency (payment providers, your own unique constraints), and check ctx.recovered. If the database write is your side effect, you can also put it in the same transaction as the record (implement a store method that takes your client), which some teams prefer for money movement.

Choices and alternatives

  • Buffered bodies. Request and response bodies are held in memory so they can be hashed and stored. Both are limited (maxBodyBytes for requests). Streaming endpoints are out of scope.
  • Postgres over Redis. A row with a primary key gives atomicity, durability and TTL cleanup with no extra infrastructure for teams already on Postgres. A Redis store is a short implementation of the same interface.
  • 24 h TTL. Long enough for client retry windows and next-morning reconciliation scripts; the same default Stripe uses. Raise it if clients retry over days.
  • Required keys by default. You wrapped the endpoint because it must not run twice; a client that forgets the header should fail loudly in development, not silently lose protection.

Security notes

Reviewed against the Softreuse Product Standard. This documents what the module defends against, what it does not, and what you must do in your deployment.

Threat model

Threat Mitigation in the kit
Duplicate execution (retries, double-clicks, concurrent duplicates) One atomic begin per (scope, key), enforced by the database primary key; concurrent duplicates tested against real Postgres.
Cross-user response disclosure via a guessed or leaked key Keys are namespaced by scope, which you set from your authentication. An empty scope throws. Tested.
Key reused with a different request (bug or tampering) SHA-256 fingerprint of method, path + query and body; mismatch → 422, handler not run.
Session fixation / stale session via replay Set-Cookie is never stored or replayed (configurable excludeHeaders). Tested.
Running unprotected when the store is down Fails closed with 503; the handler is not run. Tested.
Stale request overwriting a newer result after a takeover Per-attempt ownership token; complete/release from a non-owner are ignored. Tested.
Oversized body (memory DoS) maxBodyBytes (default 1 MiB) checked against Content-Length and again while streaming.
Malformed or hostile keys Only 16–255 visible ASCII characters without quotes or backslashes are accepted; everything else is 400 before any storage.
SQL injection Every value is a bound parameter. The only interpolated identifier (table name) is validated at construction. Hostile scope, key and header text round-trip in a test.
Leaking request data via logs The kit logs event names, method, path, status and the first 8 characters of the key. Never bodies, headers, scopes or full keys. Tested.

What it does NOT do

  • No authentication. scope is only as trustworthy as the user id you pass. Authenticate first, then call handle.
  • No encryption at rest. Stored responses may contain personal data (order details, names). Restrict the table to your application's role, use your database's encryption, and keep ttlMs no longer than you need.
  • No exactly-once side effects. A request that crashes after its side effect but before its response is stored will run again on retry (with ctx.recovered = true). See ARCHITECTURE.md, "What it cannot do".
  • No rate limiting. Keys do not limit how many different operations a client can start.
  • No protection for unwrapped endpoints or other methods. Only requests passed through handle with a method in methods are protected.

Your deployment checklist

  1. Derive scope from your authenticated session or API key, never from a header or body field the client controls.
  2. For public, unauthenticated endpoints (e.g. sign-up), use a fixed scope only if a replayed response to a stranger who sends the same key is harmless; otherwise, don't key that endpoint.
  3. Use PostgresStore (or another shared store) whenever more than one process serves the route. MemoryStore is per process.
  4. Set leaseMs above your slowest handler, including upstream timeouts.
  5. Pass ctx.idempotencyKey downstream to payment providers and use it in a unique constraint for your own writes.
  6. Schedule purgeExpired() daily and restrict the table to your application's database role.
  7. Alert on the idempotency.complete_failed and idempotency.store_unavailable log events.
  8. On Express, mount the route without a body parser so the fingerprint is computed from the raw bytes.

Dependencies

Zero runtime dependencies. Development dependencies (typescript, vitest, pg, tsx) are not shipped. npm audit --omit=dev reports nothing for this package.

Reporting a vulnerability

Email support@softreuse.com with details. We acknowledge within 3 business days and ship fixes as patch releases to all customers.

Get Idempotent Requests · $39Source, tests and examples · v1.0.0 · one-time