The ambiguous timeout
Your server sends POST /payments. Thirty seconds later the connection drops. Did the payment go out?
You cannot know. The request may never have arrived. It may have arrived, created the payment, and lost the response on the way back. It may still be running. Every networked system has this failure mode, and with payments both wrong answers are expensive. Retry blindly and you might pay twice. Give up and you might not pay at all.
The fix: name the intent
An idempotency key is a unique value you generate once per intended payment and send with every attempt to create it. The server records the key alongside the payment it creates. When it sees the same key again, it does not create anything; it returns the original payment.
That turns "did it work?" into a question you can always safely ask again. Retry the same request with the same key as many times as you like, and exactly one payment exists at the end.
curl https://rey.example/api/v1/payments \
-H "Authorization: Bearer rey_sk_test_…" \
-H "Idempotency-Key: 6f1c2d8e-4b7a-4f0e-9a51-3c2b1d0e9f87" \
-H "Content-Type: application/json" \
-d '{"amount":50000,"currency":"USD","destination_currency":"USD","destination_country":"US","strategy":"fastest","beneficiary":{"name":"Ana Souza"}}'The rules Rey applies
- Same key, same request: you get the original payment back, whatever state it is in now.
- Same key, different request: if the
amount,currency,destination_currencyordestination_countrydiffer, Rey answers409 idempotency_conflict. A key names one intent, and reusing it for another is almost always a bug. - Scope: keys are per workspace, kept indefinitely, and Rey reads the first 255 characters.
- Where:
POST /paymentshonours the header. Other endpoints ignore it.
When requests race
The naive implementation, which checks whether the key exists and inserts it if not, has a gap. Two retries that arrive in the same millisecond both look, both see nothing, and both create a payment.
Rey closes the gap in the database, not in application code. The key is part of a unique constraint on the payment row, scoped to the workspace. Whichever request inserts first wins. The other one hits the constraint, re-reads, and returns the winner's payment. No lock to forget and no window to slip through.
Failover without double-paying
Idempotency matters inside Rey too. When a rail fails with a retryable error, Rey fails over to the next-ranked rail. The full amount is held once, when the payment is created. Every attempt is recorded on the payment, and the ledger posts once, against the rail that paid out, or releases the hold if every attempt failed. A failover is a new attempt at the same payment, never a second payment.
Using keys well
- Generate the key before the first attempt, and store it with your own record of the payout. A key generated inside the retry loop is a new key every time, which defeats the point.
- Derive it from your own ID when you have one, such as
payout_8812, so a crash-and-restart in your worker finds the same key again. - Retry on timeouts, network errors and `5xx` with the same key and some backoff. A
500 internal_errorfrom Rey is safe to retry with the same key. - Do not retry `4xx` blindly. A
422or402means the request itself needs to change. A changed request deserves a new key. - Reconcile, do not guess. If you are unsure of an outcome,
GET /payments/:idor thepayment.*webhooks tell you the truth.
async function payOut(payout: Payout) {
// stored with the payout the first time we try — stable across restarts
const key = payout.idempotencyKey ?? (await savePayoutKey(payout.id, crypto.randomUUID()));
for (let attempt = 1; ; attempt++) {
const res = await fetch(`${REY}/api/v1/payments`, {
method: "POST",
headers: { Authorization: `Bearer ${KEY}`, "Idempotency-Key": key, "Content-Type": "application/json" },
body: JSON.stringify(payout.request),
}).catch(() => null);
if (res && res.status < 500) return res.json(); // success, or a 4xx to handle
if (attempt === 5) throw new Error("Rey unreachable, retry later with the same key");
await new Promise((r) => setTimeout(r, 2 ** attempt * 250));
}
}The same idea, everywhere
Idempotency runs the other way too. Rey's webhooks can arrive more than once, because a delivery is retried until your endpoint answers 2xx. Handle them idempotently on the event id. We go deeper in Signed webhooks, done right.



