Every integration eventually sends a request and gets no answer. The connection drops, a load balancer times out, or the process is restarted mid-call. The hard part is that no answer is not the same as failure: the request may have reached 402pay, created a payment, and lost only the response on the way back.
Retrying blindly risks a second payment or a second checkout for the same order. Not retrying risks an order that never gets a payment at all. Idempotency is how an API lets a client retry without having to know which of those happened. This post covers how 402pay implements it, where it applies, and how to build a client that retries safely.
Why POST needs help
HTTP already defines some methods as idempotent: sending the same PUT or DELETE twice has the same effect as sending it once[1]. POST makes no such promise, and in a payments API POST is the method that creates things: payments, checkouts, remainder requests, and wallet sends.
An idempotency key closes that gap. The client attaches a unique value to an operation, and the server remembers what it answered for that value. A retry with the same key gets the same answer rather than a second execution. The convention is being standardized as the Idempotency-Key header[2], which is the name 402pay uses.
How 402pay handles a key
Any POST to the API accepts an Idempotency-Key header. When one is present:
- A successful response, any 2xx, is stored for 24 hours. A retry with the same key, method, path, and body gets that response again, marked with
Idempotent-Replayed: true. - An error isn't stored. It frees the key, so you can fix the request and send it again with the same key.
- With a secret key, the same key with a different method, path, or body answers 409
idempotency_key_reused. That is a bug in the client, not a condition to retry. - A retry that arrives while the first request is still running answers 409
idempotency_key_in_use. Wait a moment and try again. - A key is 1 to 255 characters, and keys are kept per business, so they never collide with another business's.
Three requests require a key and refuse to run without one: creating a checkout, requesting the rest of an underpaid payment, and sending from the wallet. Those are the calls where a duplicate does the most damage, a second quote and address for one customer, or a second request for the same shortfall.
Where the header is ignored
PATCH and DELETE don't use it, since repeating them is already safe. Creating a webhook endpoint and rotating its secret ignore it too, so a replay never hands out a signing secret twice. A retried endpoint creation adds a second endpoint, so list your endpoints before you try again.
References: idempotency that outlives the key
Payments have a second line of defense. A payment can carry a reference, your own identifier for what's being paid, up to 64 characters, such as an order number. Creating a payment with a reference that already names a live payment of the same amount and currency returns that payment instead of making a new one.
curl -X POST "https://dash.402pay.co/api/v1/payments" \ -H "Authorization: Bearer $PAY402_SECRET_KEY" \ -H "Idempotency-Key: 6f0c1b8e-5d0a-4a43-9a51-3f1e2d7c9b10" \ -H "Content-Type: application/json" \ -d '{ "amount": "49.00", "currency": "USD", "reference": "order_1042" }'The reference has rules of its own, and they are deliberately strict. If the live payment it names is for a different amount or currency, or has already received funds, the request answers 409 reference_in_use rather than guessing which one you meant. Once a payment is canceled or expired, its reference is free for a new attempt at the same order.
Use both. The idempotency key protects the exact request for 24 hours. The reference protects the business fact, one live payment per order, for as long as the payment is live, including when a retry comes from a different process that never saw the first key.


The key deduplicates requests. The reference deduplicates orders.
Making keys that actually work
Most idempotency bugs come from how the key is made, not how it is sent. A key has to identify one operation and survive every retry of it:
| One key per operation | Generate it when you decide to create the payment, not inside the function that sends the request, or every attempt gets a fresh key and protects nothing. |
|---|---|
| Store it first | Save the key with the order before the first attempt. A worker that crashes and restarts then retries with the same key instead of a new one. |
| Random, not clever | A random UUID is the safe default. A key built from a timestamp or a counter can collide or change between attempts. |
| Same body on retry | Rebuild the body from stored data, not from the current time or a fresh price, or the retry answers idempotency_key_reused. |
Deciding what to retry
A safe retry still has to be a sensible one. Retrying a request that can never succeed wastes time and hides bugs. The API's answers fall into three groups:
| Retry with the same key | No response at all, 500 internal_error, and 503 upstream_unavailable. Back off between attempts. |
|---|---|
| Retry after waiting | 429 rate_limited, after the seconds in its Retry-After header; 409 idempotency_key_in_use, after a short pause; and 503 temporarily_unavailable, which means something is paused and is worth trying later rather than in a tight loop. |
| Don't retry | Other 4xx answers, such as invalid_request, permission_denied, or reference_in_use. Fix the request or handle the conflict. |
const RETRYABLE = new Set([429, 500, 503]); // key is made once per operation and stored with it, so a restart reuses it.export async function post(path, body, key, attempts = 5) { for (let attempt = 1; ; attempt++) { let response; try { response = await fetch(`https://dash.402pay.co/api/v1${path}`, { method: "POST", headers: { Authorization: `Bearer ${process.env.PAY402_SECRET_KEY}`, "Content-Type": "application/json", "Idempotency-Key": key, }, body: JSON.stringify(body), }); } catch (error) { // No answer at all: the request may or may not have run. Same key, try again. if (attempt === attempts) throw error; await sleep(backoff(attempt)); continue; } const payload = await response.json(); if (response.ok) return payload.data; const code = payload.error?.code; const retryable = RETRYABLE.has(response.status) || code === "idempotency_key_in_use"; if (!retryable || attempt === attempts) { throw new Error(`${code}: ${payload.error?.message} (${payload.error?.request_id})`); } const retryAfter = Number(response.headers.get("Retry-After")); await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff(attempt)); }} // Exponential, capped, with jitter so many clients don't retry in step.const backoff = (attempt) => Math.min(30_000, 500 * 2 ** attempt) * (0.5 + Math.random() / 2);const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));Every response also carries a 402pay-Request-Id header, and every error body a request_id. Log it with the error. It is the fastest way for our support team to find the exact request you are asking about.
The other direction
Idempotency runs both ways. Your client retries requests to 402pay, and 402pay retries webhook deliveries to your server until it answers. The same discipline applies on your side: each event carries an ID that stays the same across retries, and your handler should process each one once. Our post on webhook signatures and retries covers that half. The full rules are in the idempotency reference and the error codes.
Common questions
- 24 hours. A successful response is stored for that long and replayed, with Idempotent-Replayed: true, to a retry with the same key, method, path, and body.
- Creating a checkout, requesting the rest of an underpaid payment, and sending from the wallet. Every other POST accepts one, and you should send it.
- With a secret key, the request answers 409 idempotency_key_reused and nothing runs. Use a new key for each operation.
- Only if you send a reference. A retry with the same reference, amount, and currency returns the payment the first request made. Without either, a retry can create a second payment.
- No. Errors aren't stored, so the key is freed and you can fix the request and send it again with the same key.
References
- [1]RFC 9110: HTTP Semantics, section 9.2.2, Idempotent Methods. IETF.
- [2]The Idempotency-Key HTTP Header Field. IETF HTTPAPI Working Group, Internet-Draft.
See what 402pay can do for you.
Discover how 402pay helps your business accept any card and get paid in crypto, straight to a wallet you control.







