Skip to Content
Apex Settlement

Idempotency

Retry payout and End Customer creation safely with the Idempotency-Key header.

Why it matters

A request can time out after we acted on it. Without protection, sending it again could create a second Payout. With an Idempotency-Key, the retry gets the first answer back and nothing runs twice.

Which requests take a key

RequestIdempotency-Key
POST /v1/payoutsRequired
POST /v1/end-customersRequired

Without the header these requests are refused with idempotency_key_required (400). Other requests ignore it.

Choose a key

  • Any string of 1 to 128 characters. A UUID v4 is a good choice. A longer key is refused with idempotency_key_invalid (400).
  • One key per operation: generate it when you decide to make the payout, store it with your own payment record, and reuse it for every retry of that payout.
  • Never reuse a key for a different operation.
curl
curl -X POST "$APEX_BASE_URL/v1/payouts" \
  -H "Authorization: Bearer $APEX_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 3f6c1d2e-8a4b-4c9d-b1e7-5a2f9c8d0e13" \
  -d '{"quote_id":"qt1.eyJkIjoiNmUyYTljNGYtOGIxZC00ZjM3..."}'

What happens on a retry

A key is held per API key, per End Customer you act for (when you send Apex-End-Customer), per method and path. Within that scope:

SituationAnswer
First requestRuns normally. A successful answer is stored for 24 hours.
Same key, same body, after a successThe stored answer, with the same status and body, and the header Idempotency-Replayed: true. Nothing runs again.
Same key, different bodyidempotency_key_reused (422).
Same key while the first request is still runningidempotency_in_progress (409). Retry in a moment; a request that never finishes frees the key within a minute.
Same key after the first request ended in an errorRuns again. Errors are not stored, so a request refused for a reason you have since fixed can go through under the same key.
More than 24 hours laterRuns as a new request.

Send the same bytes

"Same body" means byte for byte. Keep the serialised body you sent the first time and send it again; re-encoding an object can reorder keys or change spacing and is then refused as idempotency_key_reused.

Because the scope includes the API key, a retry sent with a different key is a new request. For payouts a second guard still holds: a Quote becomes one Payout only, and accepting it again answers quote_already_used (409). If you meet that code, read your recent Payouts with GET /v1/payouts to find the one that was created.

A retry helper

The helpers below retry on network errors, 429 and 5xx with the same key and the same body bytes.

import { randomUUID } from "node:crypto";

export async function createPayout(quoteId, idempotencyKey = randomUUID()) {
  const body = JSON.stringify({ quote_id: quoteId }); // serialise once
  for (let attempt = 0; attempt < 5; attempt++) {
    let res;
    try {
      res = await fetch(`${process.env.APEX_BASE_URL}/v1/payouts`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.APEX_API_KEY}`,
          "Content-Type": "application/json",
          "Idempotency-Key": idempotencyKey,
        },
        body,
      });
    } catch {
      await sleep(backoff(attempt));
      continue; // network error: the payout may exist, so retry with the same key
    }
    if (res.ok) return res.json();
    const err = await res.json().catch(() => ({}));
    if (res.status === 429) {
      await sleep(Number(res.headers.get("Retry-After") ?? "1") * 1000);
    } else if (res.status >= 500 || err.code === "idempotency_in_progress") {
      await sleep(backoff(attempt));
    } else {
      throw Object.assign(new Error(err.message), err);
    }
  }
  throw new Error(`payout not confirmed; retry later with key ${idempotencyKey}`);
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const backoff = (n) => Math.min(1000 * 2 ** n, 16000) + Math.random() * 250;

When the helper gives up, the payout may or may not exist. Keep the key: a later retry with the same key and body within 24 hours returns the Payout if it was created, or creates it if it was not and the Quote is still valid.

On this page