Mustlist

Idempotency keys for retry-safe writes in a Next.js + Postgres app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

Clients send one Idempotency-Key per intent with each POST or Server Action. Store it in Postgres, unique per account, with a request hash and the response, in the write's transaction. Replay finished keys; return 409 while one runs and 422 for a changed body.

Forweb-appsaase-commercemarketplacepublic-apimobile-backend
Not forread-only-appsstatic-site-without-server-endpoints

Must-have checklist

11 must · 4 should

Must

01

Generate one key per user intent on the client (a v4 UUID), save it with any queued request, reuse it on every retry, and create a new one only for a new intent.

A new key on each retry turns every retry into a new order.

UX
02

Require an Idempotency-Key on POST endpoints that create orders, payments or other records that must not be duplicated, and answer a missing key with 400.

The IETF draft specifies 400 when an operation documented as needing a key gets none.

Security
03

Accept only one documented key format (for example a UUID, quoted or bare) and reject anything else with 400 before any database lookup.

The IETF draft warns that unvalidated keys invite injection and low-entropy keys let attackers guess other clients' keys.

Security
04

Make the unique key (account_id, key), or (session or cart id, key) for guests; never a key column that is unique across all users.

With a global key, anyone who learns a key can read another account's stored response.

Security
05

Store a SHA-256 hash of method, route and the validated body in canonical form; answer a known key with a different hash with 422.

The IETF draft specifies 422 for a key reused with a different payload; Stripe also rejects changed parameters.

Data
06

For Postgres-only work, insert the key row (ON CONFLICT DO NOTHING), run the business writes and save the response in one transaction.

A crash then rolls back all three, so no key stays locked and no order exists without its stored response.

Data
07

Answer a duplicate that arrives while the first request is still running with 409 and Retry-After, and set lock_timeout so it never waits indefinitely.

The IETF draft and Stripe (`idempotency_key_in_use`) use 409 here; Postgres waits forever by default.

UX
08

For a completed key, return the stored status code, body and Location header instead of running the handler again.

The retry then shows the result of the first attempt, such as the order it created.

UX
09

Store final 2xx results and deterministic business errors; store nothing for auth, validation, rate-limit or key errors, and let unexpected errors roll back.

Stripe saves no result when execution never began; a stored 500 from a rolled-back write blocks a retry that is safe.

Data
10

Never hold a transaction open across a payment or email API call: commit a started row, call the provider with a key derived from your operation id, then commit the result.

stripe-node creates a new key on every call, so a retried handler without your own key can charge twice.

Data
11

Keep keys for at least 24 hours and longer than your clients' longest retry window, delete older rows with a scheduled job, and document the window.

Stripe keeps keys for at least 24 hours; the IETF draft asks servers to publish their expiry policy.

Data

Should

12

Give started rows a locked_at lease; once it expires, let a retry take over and resume from the last committed step with the same downstream keys.

A function that times out mid-request otherwise leaves the key locked until cleanup.

Data
13

Also put a natural unique constraint on the business row, such as one order per cart or checkout id, so a retry after its key expired still cannot duplicate it.

Data
14

Disable submit buttons while a Server Action is pending, but rely on the key, not the button, to stop duplicates.

A reload, a network retry or a direct POST bypasses a disabled button.

UX
15

Store only what a replay needs; never store Set-Cookie headers, session tokens or card data, and delete stored responses together with their key.

Security

Decisions to make

Asked before building

01Which clients send the writes that must be safe to retry?

02Does the write call an external API, such as a payment provider or email service, before it returns?

03Does each operation already have a stable unique id, such as a cart, checkout or client-generated order id?

04Do you already run Redis, and is the protected work outside Postgres?

05How long after the first attempt can a client retry?

Options

3 compared
RecommendedFits your answers

Postgres idempotency-key table with a stored response

Best fit when
  • Writes create orders, payments or other records that must not be duplicated
  • Mobile apps, SDKs or API clients retry with an Idempotency-Key header
  • You want the key, the business rows and the stored response to commit together
Avoid when
  • One natural unique id already identifies a single-row write and no stored response is needed
  • Write rates are high enough that an extra row per request strains the primary database
Trade-offs
  • One extra insert and update per protected request, plus a cleanup job
  • You own lock leases, recovery steps and the retention policy

Redis key store (SET NX with an expiry)

Examples, not endorsements: Redis, Valkey, Upstash Redis

Best fit when
  • You already run Redis and the protected work is not a Postgres write
  • Very high request rates on endpoints whose work can be repeated safely after a crash
Avoid when
  • The work writes to Postgres and must commit together with the key
  • Your Redis evicts keys under memory pressure (any policy other than noeviction)
Trade-offs
  • The key and the business write cannot commit atomically, so a crash between them leaves a stuck lock or a lost response
  • Another service to pay for, secure and monitor

Natural unique constraint only (no key table)

Best fit when
  • The write creates one row with a stable id, such as one order per cart or a client-generated order id
  • Browser-only forms where a retry can simply return the existing record
Avoid when
  • The handler has several side effects or calls external APIs
  • You must detect a key reused with a different body (422)
Trade-offs
  • No stored response; a retry sees the record's current state, not the original response
  • Nothing expires, so the protection never lapses

Why this approach

Networks drop responses, users double-click, and mobile apps and job queues retry, so any POST that creates an order or payment can run twice. With an idempotency key, a retry becomes a lookup: the client sends one key per intent, and the server stores the key, a request hash and the final response, unique per account. In the same Postgres database, the key, the business rows and the stored response commit in one transaction, so a crash never leaves half a result. Use a natural unique constraint alone when one stable id identifies a single-row write, and Redis only when the work is not in Postgres.

Lenses

Treat the key as untrusted input and check it against one documented format before any query: the IETF draft warns that unvalidated keys invite injection and low-entropy keys let attackers guess other clients' keys. The draft's value is a Structured Field String, quoted on the wire, while Stripe-style clients send it bare, so strip the quotes and accept both. Authenticate and authorize before claiming a key, and scope every lookup by account (or session or cart id for guests), so no key alone selects someone else's stored response. Never build keys from email addresses or other personal data, as Stripe also advises. Keep only what a replay needs in stored responses. When calling Stripe or another provider, send a stable key derived from the operation, never a fresh UUID per attempt.

Version notes

next>=16.0.0 <17.0.0
  • Server Actions are public POST endpoints. The client sends them one at a time, but the server neither queues nor deduplicates them: check the key inside each action.
  • experimental.useOffline (16.3+) re-sends a Server Action whose request failed, including one already in flight; if the first attempt reached the server, it runs twice.
  • In 'use cache' scopes (Cache Components), crypto.randomUUID() is captured once for every visitor: generate keys in the browser.
stripe>=23.0.0 <24.0.0
  • Pass your own key per call, stripe.paymentIntents.create(params, { idempotencyKey }), derived from your operation; the SDK's automatic key covers only its own retries.
  • v1 keeps keys at least 24 hours and replays the first result, including 500s; changed parameters give idempotency_error, and a running request gives 409 idempotency_key_in_use.
  • After a 500 or a timeout, retry with the same key or reconcile through webhooks; never retry with a new key while the outcome is unknown.
Official docsContext7docs.stripe.com
postgresql>=14.0.0
  • An INSERT that conflicts with an uncommitted row waits for that transaction, and ON CONFLICT DO NOTHING ... RETURNING returns no row for an existing key.
  • That wait is a lock on the first transaction's id, which lock_timeout (default 0) covers: SET LOCAL lock_timeout makes a duplicate fail fast with 55P03, for a 409.
  • idle_in_transaction_session_timeout also defaults to 0, so a transaction left open across an API call keeps its locks.
Official docswww.postgresql.org

Verify checks

12 checks
01

Sending the same POST twice with one key creates one order, and the second response has the same status code and body as the first.

integrationData
02

Ten concurrent requests with one key create exactly one order; every other request gets the replayed response or 409 with Retry-After, never a 5xx.

integrationData
03

Reusing a key with a different body, or on a different route, returns 422 and writes nothing.

integrationSecurity
04

When account B sends a key that account A already used, B's request runs as its own and never receives A's stored response.

integrationSecurity
05

An endpoint that requires a key returns 400 for a missing key or one outside the documented format, and creates no key row.

integrationSecurity
06

A request that fails validation leaves no key row, so a corrected request with the same key succeeds.

integrationData
07

An error thrown after the business insert but before commit leaves neither an order nor a key row, and a retry with the same key creates exactly one order.

integrationData
08

If the process dies right after the payment provider call, a retry after the lease expires reuses the same provider key and ends with one provider payment.

integrationData
09

Double-clicking submit on a Server Action form, and resubmitting after a simulated network failure, each create only one record.

e2eUX
10

Two visitors who load the same form page get different keys, showing that no key is captured in a prerendered or cached shell.

e2eSecurity
11

The cleanup job deletes keys older than the retention window and keeps newer ones; after a key is deleted, the natural unique constraint still blocks a duplicate order.

integrationData
12

Stored responses contain no Set-Cookie header, session token or payment card data.

unitSecurity

Common mistakes

  • Generating a new key on every retry, or on the server per request, so retries never match.
  • A unique index on key alone, which lets one account replay another account's response.
  • Checking for the key with a SELECT and then inserting, so two concurrent requests both run.
  • Saving the response in a later transaction, so a crash leaves an order without a stored response and the retry creates another.
  • Storing a 500 from a rolled-back transaction, which blocks a retry that would have been safe.
  • Holding a transaction open across a Stripe call, or calling Stripe without your own key.
  • Running the handler again for a duplicate that arrives mid-flight instead of returning 409.
  • Deleting keys after a few minutes, shorter than mobile and queue retry windows.
  • Turning on experimental.useOffline before Server Actions are idempotent.

Sources

23 sources