Skip to content

Idempotency and safe retries

How to retry any request, including one that changes your balance, without ever paying twice.

Sandbox: test money only. No request moves real money.

Networks fail after the server has acted. A timeout does not tell you whether the order was created, so the API lets you ask the same question again: send the same request with the same Idempotency-Key, and you get the operation it created, never a duplicate.

The header

Idempotency-Key is a string of 16 to 64 characters from A-Z, a-z, 0-9, _ and -. A UUID is the easy choice. Generate it once, before the first attempt, and store it with the thing you are creating (the invoice, the cart line), so a retry from anywhere, including after a restart, sends the same key.

OperationThe keyBehaviour
Create an orderPOST /ordersRequiredBound permanently to the order it created.
Simulate a GRAM depositPOST /sandbox/funding/depositsRequiredBound permanently to the simulated deposit; a retry credits nothing.
Simulate a deposit that names its assetPOST /sandbox/depositsRequiredBound permanently to the simulated deposit; a retry credits nothing.
Request a statementPOST /statementsRequiredBound permanently to the statement it requested. It moves no money, but a retry must never prepare a second one: it answers 200 with Idempotent-Replayed: true and the same statement.
Create a quotePOST /quotesOptionalBound permanently to what the first request made. A retry answers 200 with Idempotent-Replayed: true and repeats nothing.
Create a webhook endpointPOST /webhook-endpointsOptionalBound permanently to what the first request made. A retry answers 200 with Idempotent-Replayed: true and repeats nothing.
Rotate a webhook secretPOST /webhook-endpoints/{id}/rotate-secretOptionalBound permanently to what the first request made. A retry answers 200 with Idempotent-Replayed: true and repeats nothing.
Replay a deliveryPOST /webhook-deliveries/{id}/replayOptionalBound permanently to what the first request made. A retry answers 200 with Idempotent-Replayed: true and repeats nothing.
Run a safe testPOST /sandbox/test-runsOptionalBound permanently to the run it made. A retry answers 200 with Idempotent-Replayed: true and runs nothing again.

No other operation takes the header. POST /webhook-endpoints/{id}/test takes none: each request sends one test event.

Requests that change your balance

POST /orders, POST /sandbox/funding/deposits and POST /sandbox/deposits change your balance: the contract marks them as moving money, and the key is required. The first accepted request binds the key to the operation it created, permanently. A later request with that key answers 200 with the header Idempotent-Replayed: true and the operation as it is now, so a replay of an order that has since succeeded shows succeeded.

Your serverNasfam APIPOST /ordersIdempotency-Key: K1202 · ord_1the connection drops; the order exists, heldPOST /ordersthe same request, the same key K1200 · ord_1Idempotent-Replayed: trueOne key, one order. A new key would be a new order.
A lost response, the same request again with the same key, and one order.

The same key with a different request body is refused with idempotency_key_reused. For the minimal order the key is bound to the order the body asks for, after the server normalises it: stars and telegram_stars, or @name and name, are the same order and answer as a replay. A retry that arrives while the first attempt is still running waits for it and gets the same answer; one that cannot wait long enough is refused with idempotency_in_progress: send the same request again with the same key.

The example makes the key once and keeps it in a variable, which is the whole technique. Its Replay tab is the answer a retry gets.

Code for Requests that change your balance
POST /v1/ordersSandbox, test key
// npm install axiosimport axios from 'axios';// One key per purchase: make it once, keep it with the purchase, and send the same key on every retry.const idempotencyKey = process.env.IDEMPOTENCY_KEY;if (!idempotencyKey) throw new Error('Set IDEMPOTENCY_KEY once for this purchase (a new UUID) and keep it for every retry');try {  const { status, data: order } = await axios.post(    'https://sandbox-api.nasfampay.com/v1/orders',    {      quote_id: 'quo_01K7SAMP000000000000000090',      reference: 'TEST-0001',    },    {      headers: {        Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,        'Idempotency-Key': idempotencyKey,      },    },  );  console.log(status, order);} catch (error) {  if (!axios.isAxiosError(error) || !error.response) throw error;  const problem = error.response.data;  throw new Error(`${problem.status} ${problem.code}: ${problem.title} (request ${problem.request_id})`);}

Duplicate protection

  • The Idempotency-Key makes one request one operation, however many times it is sent.
  • Your reference makes one invoice or cart line one order: a second order with it is refused with duplicate_reference, whatever its key.
  • The event id makes one event one action in your receiver: record it, and ignore an id you have seen.

Use all three. The key covers a retry of the same request, the reference covers the same purchase sent as a new request, and the event id covers a delivery that arrives twice.

Requests that move no money

Creating a quote or a webhook endpoint, rotating a secret and replaying a delivery move no money, so the key is optional. Send one and it is bound permanently to what the first request made, as an order's key is: a retry with the same key and the same request answers 200 with Idempotent-Replayed: true and the quote, endpoint or delivery as it is now, and nothing is priced, created, rotated or re-armed again. A retried endpoint creation is one endpoint, and a retried rotation rotates once.

A replay never returns a secret: the secret is in the first answer only, so store it from there. The same key with another request, or on another operation, is refused with idempotency_key_reused. Without a key, every request is performed.

Retries

  • A timeout or a dropped connection: send the same request with the same key. The outcome is unknown, not failed.
  • idempotency_in_progress: the first attempt is still running and this one could not wait for it. Send the same request again with the same key after a short wait.
  • rate_limited, or a 503 with Retry-After: wait at least the seconds in Retry-After, then send the same request with the same key.
  • Any other problem: read its code. Errors says for each one whether the same request can be sent again.
  • GET requests: safe to retry freely; they change nothing.

Duplicate events

A failed attempt is retried and any delivery can be replayed, so your endpoint can receive one event more than once. Record the event id and ignore an id you have seen; a replay carries the same event and the same webhook id. Replaying a delivery never creates a financial event.

Common mistakes

  • Making a new key to retry. A new key is a new order. Reuse the key you stored before the first attempt.
  • Changing the body between retries. The same key with a different body is refused. Send the request exactly as it was.
  • Treating a timeout as a failure. The order may exist. Retry with the same key, or look it up by your reference, before you tell anyone it failed.
  • Relying on the key alone for one invoice. Put your own reference on the order as well: a second order with the same reference is refused with duplicate_reference.