Imagine a checkout page. The user clicks "Pay," the button spins for thirty seconds, and the request times out. They don't know whether they were charged, so they click again. This time it works. A few minutes later they get two confirmation emails and two charges.
The first request didn't fail. It succeeded on the server, but the response never made it back. Stripe's error handling documentation describes this exactly: "Restoring connectivity doesn't tell you whether the original request succeeded." The client can't tell the difference between "the server never got it" and "the server did it, and the answer was lost."
The fix is to make the second attempt recognizable as the same request:
- Give each logical submission an idempotency key, generated once in the browser and sent with every retry.
- Claim the key atomically in PostgreSQL, in the same transaction that creates the order.
- Return the stored result for repeats instead of doing the work again.
- Back it with a business unique constraint, so a lost key still can't create a second order.
- Design the UI for "we're not sure yet", instead of re-enabling a bare Pay button.
Timeouts also raise the question of cancelling work the user has abandoned, which is a separate topic. This article is about making the retry safe. Library behavior below reflects documentation as of November 2026.
Why disabling the button isn't enough
Disabling the submit button while a request is pending is still worth doing. React's useFormStatus hook exposes a pending flag for exactly this, and the Next.js forms guide suggests using it to "disable the submit button while the action is being executed." But it only stops one kind of duplicate: a fast second click on the same page.
It doesn't help with:
- A refresh or back button after a timeout, which loads a fresh page with an enabled button.
- A second tab with the same form open.
- Queued actions. React's useActionState documentation says "React queues and executes multiple calls to dispatchAction sequentially," so repeated dispatches become repeated requests, one after another. The same docs warn that "aborting the network request doesn't undo the server-side change."
- Retries nobody chose explicitly. Several layers can repeat a request on their own.
Those automatic retries are easy to miss:
- HTTP client libraries. In axios-retry 4.5.0, the default retry condition retries network errors without checking the HTTP method, so a POST can be retried by default. The README's description focuses on idempotent methods for 5xx errors, so read the source or set an explicit
retryCondition. The GitHub repository also shows as archived, so check the status of anything you depend on. - Framework features. Next.js has an experimental useOffline option that automatically retries "failed navigation, prefetch, and Server Action requests," including ones "already in flight when the connection dropped." The docs don't discuss idempotency, but a Server Action that reached the server before the connection dropped could run again, so the action itself needs to be safe to repeat.
- Proxies and service meshes. RFC 9110 says "A proxy MUST NOT automatically retry non-idempotent requests," and nginx follows that by default: since version 1.9.13, a POST that has already been sent upstream isn't passed to the next server unless you enable
non_idempotent. Envoy doesn't retry unless you configure a retry policy, but once you do, check how it applies to POST.
What an idempotency key is, and the standard that isn't one yet
RFC 9110 defines GET, PUT, DELETE, and other safe methods as idempotent, which means repeating them has the same effect as sending them once. POST isn't. The RFC says a client "SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent."
An idempotency key is that "means to know." The client sends a unique value with the request, usually in an Idempotency-Key header. The server records the key with the result. If the same key arrives again, the server returns the recorded result instead of creating another order.
The IETF is standardizing the header, but as of November 2026 it's still a working draft, draft-ietf-httpapi-idempotency-key-header-08, published October 22, 2026, not an RFC. Payment and cloud APIs already implement the idea, with different details:
- Stripe stores the first result for at least 24 hours in its v1 API, and treats requests with the same key within 30 days as replays in its v2 API (idempotent requests).
- Adyen keeps keys valid for 7 to 14 days and limits them to 64 characters (API idempotency).
- PayPal uses a
PayPal-Request-Idheader, with retention that varies by API. - AWS uses a
ClientTokenon many operations. The AWS Builders' Library describes the goal as a "semantically equivalent response" for the same request identifier. - Microsoft's Azure API guidelines use
Repeatability-Request-IDandRepeatability-First-Sentheaders, from the OASIS Repeatable Requests specification.
The shared idea is simple. The details you need to decide are when the key is created, how the server claims it, what repeats return, and how long keys live.
The key's life in the browser
The key identifies one logical attempt: "this user is placing this order." It has to stay the same across every retry of that attempt, and change when the attempt changes.
- Generate it once, when the form is shown or on the first submit, with
crypto.randomUUID(). MDN notes it generates a v4 UUID with a cryptographically secure random generator and is "available only in secure contexts (HTTPS)." The IETF draft recommends "a UUID or a similar random identifier." - Reuse it on every retry, whether the retry comes from the user, your code, or a library.
- Keep it across a refresh. Storing the pending key in
sessionStorage, tied to the form or cart, means a reload after a timeout sends the same key instead of a new one. - Rotate it only after a definitive outcome, such as a confirmed success or a validation error the user fixes, or when the user changes what they're submitting.
- Or derive it from a business object. Stripe suggests deriving the key "from a user-attached object, like the ID of a shopping cart," which gives you protection against double submissions without storing anything extra in the browser.
Keep personal data out of keys. Stripe's docs say to avoid "sensitive data (for example, email addresses or personal identifiers)" as idempotency keys.
Claiming the key in PostgreSQL without a race
The most common bug in idempotency code is checking for the key and then inserting it as two separate steps. Two requests with the same key arrive together, both check, both find nothing, and both create an order.
Let a unique index make the decision instead. A table such as idempotency_keys with a unique index on (user_id, key), plus columns for status, a request fingerprint, the stored response status and body, and timestamps, gives PostgreSQL the job of deciding who wins. Scoping keys to the user or tenant stops one customer's key from colliding with another's.
There are two reasonable ways to use it:
- Claim and create in one transaction. Insert the key row and the order in the same transaction, and store the response before committing. The PostgreSQL documentation explains what a concurrent duplicate sees: if the conflicting row is from an uncommitted transaction, "the would-be inserter must wait." If the first transaction commits, the second gets a unique violation and can read the stored result. If it rolls back, there's no conflict and the second request proceeds. This is simple, but the duplicate holds a connection while it waits.
- Commit a "processing" claim first. Insert the key with a
processingstatus and commit, do the work, then update the row with the result. A duplicate that arrives in between finds theprocessingrow and gets a 409 right away, which is what the IETF draft and Stripe do. This is better for slow work or work that calls other services, but you need to handle rows left inprocessingby a crash.
PostgreSQL gives you a few tools for the claim itself. Its INSERT documentation says INSERT ... ON CONFLICT DO NOTHING "simply avoids inserting a row," and because RETURNING only returns rows that were actually inserted or updated, an empty result tells you the key already existed. In PostgreSQL 18, RETURNING can also return OLD and NEW values, which helps distinguish a new row from an existing one in one statement. Transaction-level advisory locks such as pg_advisory_xact_lock are another option when you need to serialize work on a key that isn't a row yet.
What to return on a repeat
Once you can detect a repeat, decide what it gets back. The IETF draft and Stripe give a useful contract:
- Same key, same request, finished: return the stored status and body. Stripe adds an
Idempotent-Replayed: trueheader so clients can tell it was a replay. The draft says the response should be "consistent with the request being completed according to the user's intent." - Same key, still in progress: return 409. Stripe's guidance to clients is to "wait and retry with that key and the same parameters," because "A new key can start a second operation."
- Same key, different request: reject it. The draft says a key "MUST NOT be reused with another request with a different request payload" and suggests 422. Stripe compares parameters and returns an error when they differ.
- Missing key on an endpoint that requires one: the draft suggests 400.
Two design choices need a deliberate answer:
- Do you replay errors? Stripe's v1 API saves the first response after execution begins, "including 500 errors," and replays it. Its v2 API instead "re-executes the failed requests and returns the new response." Either can be right. Don't store validation failures as the final answer for a key; Stripe doesn't save the result when parameters fail validation.
- What counts as "the same request"? A fingerprint, such as a hash of the request body, lets you detect a reused key with a different payload. Decide whether to hash the raw body or the validated DTO, and normalize field order so harmless differences don't count as changes. The draft treats the fingerprint as optional.
Building it in NestJS
NestJS's request lifecycle runs middleware, then guards, then interceptors, then pipes, then the controller. That order shapes the design:
- Use an interceptor after authentication. Guards have already identified the user, so the interceptor can scope the key to them. An interceptor can also short-circuit: returning a stored response with
of()means "the route handler won't be called at all." - Remember pipes run later. The interceptor sees the raw body before validation. If you fingerprint the validated DTO instead, do it in the service.
- Don't reuse the cache interceptor. NestJS's built-in caching only caches GET endpoints by default, and a cache isn't a claim.
- Let the service own the transaction, so the key claim and the order are written together.
- Turn unique violations into replays, not 500s. PostgreSQL reports a unique violation as error code
23505. Prisma surfaces it asP2002, "Unique constraint failed on the {constraint}," in its v7 error reference. When you catch it on the key or the order, look up the stored result and return it.
There's no official NestJS idempotency module. Several third-party packages exist; evaluate how they handle concurrent duplicates and storage before adopting one.
A business unique constraint as the backstop
Idempotency keys depend on the client doing the right thing. A key can be lost when a user opens a new tab, or a bug can generate a new key per click. A unique constraint on the business data catches what keys miss.
For an order, that might be a unique checkout_id or cart_id on the orders table, or a rule that a cart can have only one active payment. A second order for the same checkout fails with a unique violation, which you can map to the existing order. The key gives you a clean replay; the constraint guarantees the invariant.
Calling a payment provider: pass the key on
If your order flow charges a card through a provider, the external call needs its own protection. Derive the provider's idempotency key from yours, for example by combining your key with the operation name, so a retry of your endpoint sends the same key to the provider and can't create a second charge.
Stripe's guidance on uncertain results applies here too. It says to "Treat the outcome of a request that returns 500 as indeterminate" and "Don't retry with a new idempotency key until you've resolved the original outcome." Reconcile through the provider's API or webhooks before trying again with anything new.
Side effects such as confirmation emails are best sent after the order commits, from a record written in the same transaction. That's the transactional outbox pattern, and it keeps a replay from sending a second email.
The "we're not sure yet" screen
After a timeout, the worst thing the UI can do is show the same Pay button as if nothing happened. The user will press it, and you've relied entirely on the backend to save you.
A better flow:
- Show a checking state, such as "We're confirming your order," instead of an error.
- Retry with the same key, automatically or behind a "Check again" button, so a repeat returns the stored result.
- Offer a status lookup, for example the order list or a status endpoint keyed by checkout ID.
- Only offer "Try again" with a new attempt after you know the first one failed.
After a successful submission, redirect to a confirmation page with a GET, the Post/Redirect/Get pattern, so a refresh reloads the confirmation instead of resubmitting the form. MDN notes that a 303 redirect is "often sent back as a result of PUT or POST methods so the client may retrieve a confirmation."
Expiry, stuck requests, and cleanup
Keys can't live forever, but they must outlive retries.
- Keep keys longer than your longest retry window. If clients can retry for an hour, or a user might come back the next day to check, a 15-minute key window lets a late retry create a new order. Stripe keeps v1 keys for at least 24 hours, Adyen for 7 to 14 days, and Brandur Leach's widely cited Postgres design suggests a reaper threshold of about 72 hours. Publish your window, as the IETF draft recommends.
- Recover rows stuck in "processing." A crash after the claim commits can leave a key stuck. Store when the claim was taken, and treat it as abandoned after a timeout that's longer than the work can take, either by letting a retry take it over or by finishing it with a background job.
- Clean up expired keys with a scheduled job, so the table doesn't grow forever.
Test it with real concurrency
Idempotency bugs only show up when requests overlap, so test with overlap:
- Two parallel POSTs with the same key. Exactly one order should exist, and both responses should describe it.
- The same key with a different body. Expect a 422 or your chosen error, and no second order.
- A crash after commit but before the response. Retry with the same key and confirm you get the stored result.
- A retry after the key expires, to confirm your business constraint still prevents a duplicate.
- A retry through your real proxy, with its retry settings, to confirm nothing upstream repeats the request unexpectedly.
A duplicate submission checklist
- The submit button is disabled while pending, and the whole form is handled in one submit handler.
- Each logical attempt has one idempotency key, generated with
crypto.randomUUID()or derived from a cart or checkout ID. - The key is reused on every retry and survives a refresh.
- HTTP clients, framework retries, and proxies are audited, so nothing retries POST without the key.
- The server claims keys with a unique index, never with check-then-insert.
- The claim and the order are written in one transaction, or a committed "processing" claim returns 409 to duplicates.
- Repeats replay the stored result, mismatched payloads are rejected, and missing keys are rejected where required.
- Unique violations map to a replay, not a 500.
- A business unique constraint prevents a second order even without a key.
- Payment provider calls carry a derived idempotency key.
- The UI handles unknown outcomes with a checking state and a status lookup.
- Keys outlive the longest retry window, stuck claims are recovered, and old keys are cleaned up.
- Concurrency tests cover parallel duplicates, mismatches, crashes, and expiry.
A timeout tells you nothing about whether the order exists. An idempotency key turns "click again and hope" into "ask again and get the same answer."



