Skip to Content
Paycose Docs
Setup

Idempotency

Retry POST requests safely with the Idempotency-Key header — how keys are matched, what is replayed, and the errors you can get.

A network error or a timeout leaves you not knowing whether a request reached Paycose. Send an Idempotency-Key header with every POST, and you can retry it without paying, refunding or paying out twice: Paycose runs the request once and answers every retry with the first result.

curl "$WALLET/refunds" \
  -H "Authorization: Bearer ${SECRET_KEY}" \
  -H "X-Country: TH" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 5f0c8e2a-9d1b-4c3e-8f7a-2b6d4e1c9a03" \
  -d '{"charge": "ch_3b1f9e0a7c2d4e8f9a6b5c4d3e2f1a0b", "amount": 50000}'

A retry with the same key and the same request gets the stored response back, with the same status and body, plus this header:

Idempotent-Replayed: true

How it works

  • POST only. Keys apply to POST requests made with a secret key. PATCH and DELETE requests are not replayed.
  • The key. Any string of up to 255 characters; spaces at either end are trimmed. A longer key is refused with 400 and param: "Idempotency-Key". A UUID works well.
  • Scope. A key belongs to your secret key and the X-Country you send. The same key used with another secret key or another country is a different key.
  • 24 hours. The first result is kept for 24 hours after it completes. After that the key can be used again.
  • The same request means the same method, the same path and a byte-for-byte identical body. Serialise the body once and resend those bytes; a body re-encoded with different key order or spacing counts as a different request.

What is kept and replayed

First request ended withOn a retry with the same key
2xxThe same response, replayed.
4xx, except 409 and 429The same error, replayed. Fix the request and use a new key.
409, 429 or 5xxNot kept. The retry runs as a new request.
No response (the request failed before answering)Not kept. The retry runs as a new request.

Errors

CodeStatusWhenWhat to do
conflict.idempotency_replay (E1401)409The key was already used for a different request in the last 24 hours.Use a new key for a new request.
conflict.idempotency_in_progress (E1405)409The first request with this key is still running.Wait a moment and retry with the same key.

Both errors have type idempotency_error and param Idempotency-Key. If a first request never finishes, its key is released after two minutes and a retry runs as a new request.

Retrying well

Make one key per action

Create the key when you decide to take the action, such as "refund order 1042", and store it with your own record before you call Paycose.

Retry with the same key and body

After a network error, a timeout, a 5xx, a 429 or E1405, send the same bytes again with the same key. Wait between attempts, longer each time, and honour Retry-After when the response has one.

Stop on other errors

A 4xx other than 409 and 429 will not succeed by retrying. Fix the request and start again with a new key.

import { randomUUID } from 'node:crypto';

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function createRefund(body, idempotencyKey = randomUUID()) {
  const payload = JSON.stringify(body); // serialise once, resend the same bytes
  for (let attempt = 0; attempt < 5; attempt++) {
    let res;
    try {
      res = await fetch(`${process.env.WALLET}/refunds`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.SECRET_KEY}`,
          'X-Country': 'TH',
          'Content-Type': 'application/json',
          'Idempotency-Key': idempotencyKey,
        },
        body: payload,
      });
    } catch {
      await sleep(2 ** attempt * 500); // network error: retry with the same key
      continue;
    }
    const json = await res.json().catch(() => ({}));
    const code = json.error?.code;
    const retry =
      res.status >= 500 || res.status === 429 || code === 'conflict.idempotency_in_progress';
    if (!retry) return { status: res.status, body: json };
    const retryAfter = Number(res.headers.get('Retry-After'));
    await sleep(retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 500);
  }
  throw new Error(`refund not confirmed; retry later with key ${idempotencyKey}`);
}

Reserved keys

On POST /payouts, keys that start with auto_ or instant_ are reserved for payouts Paycose makes itself and are refused with 400 (E1101).

Without the header

A POST without Idempotency-Key runs every time you send it. Keys are also skipped, and the request runs normally, if Paycose's idempotency store cannot be reached at that moment.

What's next

On this page