Cookies, your call.

A few keep Rey running. The rest show us how the site is used, and stay off until you say yes. Cookie policy

Skip to content
All articlesengineering

Retry a payment, never pay twice.

A timeout leaves you not knowing whether the money moved. Idempotency keys remove that doubt. Here is how they work, and how Rey enforces them when requests race.

By Rey team3 min read

A row of translucent glass discs fades from faint echoes into one solid, glowing disc.

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
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_currency or destination_country differ, Rey answers 409 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 /payments honours 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

  1. 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.
  2. 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.
  3. Retry on timeouts, network errors and `5xx` with the same key and some backoff. A 500 internal_error from Rey is safe to retry with the same key.
  4. Do not retry `4xx` blindly. A 422 or 402 means the request itself needs to change. A changed request deserves a new key.
  5. Reconcile, do not guess. If you are unsure of an outcome, GET /payments/:id or the payment.* webhooks tell you the truth.
typescript
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.

Keep reading

  • private beta, onboarding partners
  • one API across web2 and web3 rails
  • on-chain travel rule, planned

Rey

Enabling builders to move money at the speed of light.

KYC / KYB, EDD, travel rule: planned

2026 Rey, all rights reserved

built for every corridor