> ## Documentation Index
> Fetch the complete documentation index at: /llms.txt
> Use this file to discover all available pages before exploring further.

# Idempotency

> Send an Idempotency-Key so that a retried request never moves money twice.

An idempotency key lets you send the same request again without doing the work again. If your first attempt timed out, you cannot know whether Payve received it. Retry with the same key and Payve returns the first result instead of creating a second payout.

```bash
curl -X POST "$PAYVE_API_URL/v1/payouts" \
  -H "x-api-key: $PAYVE_API_KEY" \
  -H "Idempotency-Key: 7f3d2b1a-0c4e-4f8a-9b6d-5e2a1c3f4b70" \
  -H "Content-Type: application/json" \
  -d '{ "sourceCurrency": "NGN", "destinationCurrency": "NGN", "amount": 5000000, "...": "..." }'
```

> [!WARNING]
>
> **One key per operation. Same key on every retry. Never the same key for a different operation.**
> These three rules are what stop a double payment. A new key on a retry tells Payve it is a new
> payout.

## Where the header is required

| Endpoint | `Idempotency-Key` |
| - | - |
| `POST /v1/payouts` | Required |
| `POST /v1/payouts/bulk` | Required |
| `POST /v1/payins` | Required |
| `POST /v1/conversions` | Required |
| Any other `POST`, `PATCH`, `DELETE` | Optional, and honoured when sent |

`GET` requests ignore the header.

A required key that is missing returns `400 validation_idempotency_key_required`. A key longer than 255 characters returns `400 validation_idempotency_key_invalid`.

## How a key behaves

Keys are scoped to your account. Two businesses can use the same key value without touching each other.

**1. First request**

Payve runs the request and remembers the response for **24 hours**.

**2. Same key, same request, after it finished**

Payve returns the stored response with the original status code, and adds the header
`Idempotent-Replayed: true`. Nothing runs again.

**3. Same key, while the first is still running**

Payve returns `409 idempotency_conflict`. Wait a moment and send the same request with the same
key.

**4. Same key, different endpoint or different body**

Payve returns `422 idempotency_key_reused`. The first request stands. This one is refused.

### 409: a request with this key is in flight

```json
{
  "error": {
    "code": "idempotency_conflict",
    "message": "An in-flight request with this idempotency key already exists."
  }
}
```

Retry with the **same** key after a short wait. Do not switch to a new key: the first request may still complete.

### 422: the key was used for something else

```json
{
  "error": {
    "code": "idempotency_key_reused",
    "message": "This idempotency key was already used with a different request body. Use a new key for a new request.",
    "requestId": "req_8a1c4e2f9b7d3a60",
    "details": { "differs": "body" }
  }
}
```

`details.differs` is `body` or `route`. The body comparison ignores the order of JSON keys, so reordering fields is not a different request. Changing any value is.

> [!WARNING]
>
> A `422 idempotency_key_reused` is a bug in your code, not a transient failure. The first request
> under that key may already have moved money. Find out what it did before you send anything new.

## What is and is not remembered

* **Successful responses are remembered** for 24 hours.
* **Failed requests are not.** If a request ends in an error, the key is released and you can retry with the same key.
* **Payouts, pay-ins and conversions are also de-duplicated permanently** on your account and key. Sending a key you used for a payout last month returns that payout, not a new one.

> [!NOTE]
>
> The 24-hour window is how long a replay returns the stored response and how long a changed body is
> detected. It is not how long a key stays unique for a payout. Never recycle keys.

## Choose a good key

Use a random UUID, or derive the key from your own record, such as `payout-<your order id>`.

```javascript Node
import { randomUUID } from 'node:crypto';

// 1. Create the key and save it with the order BEFORE calling Payve.
const idempotencyKey = randomUUID();
await db.orders.update(orderId, { payveIdempotencyKey: idempotencyKey });

// 2. Send. On a timeout or a 5xx, call this again with the SAME key.
async function sendPayout(body, key) {
  return fetch(`${process.env.PAYVE_API_URL}/v1/payouts`, {
    method: 'POST',
    headers: {
      'x-api-key': process.env.PAYVE_API_KEY,
      'Idempotency-Key': key,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });
}
```

```python Python
import os, uuid, requests

# 1. Create the key and save it with the order BEFORE calling Payve.
idempotency_key = str(uuid.uuid4())
db.orders.update(order_id, payve_idempotency_key=idempotency_key)

# 2. Send. On a timeout or a 5xx, call this again with the SAME key.
def send_payout(body, key):
    return requests.post(
        f"{os.environ['PAYVE_API_URL']}/v1/payouts",
        headers={
            "x-api-key": os.environ["PAYVE_API_KEY"],
            "Idempotency-Key": key,
        },
        json=body,
        timeout=30,
    )
```

## When to retry

| You got | Do this |
| - | - |
| Timeout or dropped connection | Retry with the same key. |
| `500`, `502`, `503` | Retry with the same key, with backoff. |
| `429` | Wait for `Retry-After` seconds, then retry with the same key. |
| `409 idempotency_conflict` | Wait, then retry with the same key. |
| `422 idempotency_key_reused` | Stop. Fix your code. |
| Any other `4xx` | Do not retry unchanged. Fix the request. A corrected request is a new operation and needs a new key. |

## Cautions

> [accordion] Do not generate the key inside the retry loop
>
> A key created on each attempt is a different key each time. Create it once, outside the loop,
> and store it.

> [accordion] Do not reuse a key after changing the amount or the recipient
>
> A changed body under an old key is refused with `422`. A new payout needs a new key.

> [accordion] Do not use a timestamp as the key
>
> Two attempts made at different times produce two keys, and two payouts.

> [accordion] A bulk payout key covers the whole batch
>
> Replaying a bulk request with the same key returns the first response and creates nothing new.
> See [Bulk payouts](/guides/bulk-payouts.md).

> [accordion] Idempotency on your side matters too
>
> Payve delivers webhooks at least once. Record each event id so your own handler does its work
> once. See [Handle events safely](/webhooks/handling-events.md).
