# Idempotent requests

Which BuildBase API writes accept an Idempotency-Key, what a retry with the same key returns, and how to make sure a payment or refund never runs twice.

## In short

Networks fail. If your program asks BuildBase to refund an order and the connection drops before the answer arrives, you cannot tell whether the refund happened. An **idempotency key** fixes that: you give the request a unique name, and if you send the same request again with the same name, BuildBase does not do it twice. You get the first answer back instead.

## How to use it

Make one key per action, such as a UUID, store it with the action, and send it in the `Idempotency-Key` header on the first attempt and on every retry of that same action:

```bash
KEY=$(uuidgen)

curl -s -X POST "https://api.console.buildbase.app/api/v1/public/me/sales/$ORDER_ID/refund" \
  -H "x-session-id: $BUILDBASE_SESSION_ID" \
  -H "Idempotency-Key: $KEY" \
  -H "Content-Type: application/json" \
  -d '{}'
```

- A key is 1 to 255 printable ASCII characters. Anything else is a `400` before anything runs.
- The header is optional everywhere. Without it, each request is a new action, as it always was.
- A key is scoped to your organization (or environment), the route and the caller: two callers sending the same key never share an answer.
- A new action takes a new key. Reuse a key only to retry the same request.

## Commerce writes: replayed answers

These writes keep each key for 24 hours in your organization's own database:

| Retry with the same key when the first...  | You get                                                                         |
| ------------------------------------------ | ------------------------------------------------------------------------------- |
| Finished with a 2xx                        | Its status and body again, with `Idempotent-Replayed: true`. Nothing runs again |
| Is still running                           | `409` `IDEMPOTENCY_IN_PROGRESS`: retry shortly with the same key                |
| Sent a different method, path or body      | `422` `IDEMPOTENCY_KEY_REUSED`: use a new key for a new action                  |
| Failed or was refused (any status but 2xx) | Nothing stored: the retry is a fresh attempt                                    |

In the app API, under `/api/v1/public/workspaces/{workspaceId}` (a workspace selling) and `/api/v1/public/me` (a person selling):

| Method | Path after the prefix                        |
| ------ | -------------------------------------------- |
| `POST` | `/sales/{id}/refund`                         |
| `POST` | `/sales/{id}/parts/{index}/charge`           |
| `POST` | `/sales/{id}/shipments`                      |
| `POST` | `/sales/{id}/returns/{returnId}/approve`     |
| `POST` | `/sales/{id}/returns/{returnId}/reject`      |
| `POST` | `/sales/{id}/returns/{returnId}/refund`      |
| `POST` | `/sales/subscriptions/{id}/cancel`           |
| `POST` | `/sales/bookings/{id}/cancel`                |
| `POST` | `/affiliate-programs/payouts/{id}/mark-paid` |

And for the buyer, under `/api/v1/public/me` only: `POST /orders/{id}/parts/{index}/pay`, `POST /bookings/{id}/cancel`, and `POST /item-subscriptions/{id}/cancel`, `/resume` and `/change`.

In the server API (an API key), the commerce writes under `/api/v1/server/commerce`: refunds, part charges and stopping parts on orders, shipments and returns, subscription cancel, resume and change, booking cancels, grant revoke and deactivate, and affiliate approve, pause, resume and ban. A guest's order writes under `/api/v1/guest/{orgId}/orders/{id}` take a key too, scoped to the order token.

## Billing writes: one Stripe request per key

These writes hand the key to Stripe on every Stripe call they make, so a retry with the same key gets Stripe's first answer instead of a second checkout, plan change or purchase. They keep no copy of their own answer: a retry runs the route again, and the route reads Stripe's result.

Under `/api/v1/public/workspaces/{workspaceId}` and `/api/v1/public/me`:

| Method  | Path after the prefix                    |
| ------- | ---------------------------------------- |
| `PATCH` | `/subscription`                          |
| `POST`  | `/subscription/checkout`                 |
| `POST`  | `/subscription/cancel-at-period-end`     |
| `POST`  | `/subscription/cancel-now`               |
| `POST`  | `/subscription/resume`                   |
| `POST`  | `/subscription/pause`                    |
| `POST`  | `/subscription/convert-to-paid`          |
| `POST`  | `/subscription/billing-portal`           |
| `POST`  | `/subscription/retention-offer/accept`   |
| `POST`  | `/subscription/invoices/{invoiceId}/pay` |
| `POST`  | `/billing/checkout`                      |
| `POST`  | `/billing/payment-method/setup`          |
| `POST`  | `/billing/add-ons/{grantId}/cancel`      |
| `POST`  | `/billing/add-ons/{grantId}/decrease`    |
| `POST`  | `/credits/purchase`                      |
| `POST`  | `/credits/payment-method-setup`          |

A workspace also has `POST /subscription/move-to-user` and `POST /subscription/transfer-payer`. The SDK sends a key with each of these, one per click.

## Sending email

`POST /api/v1/server/emails/send` holds each key with a unique index, so a retried request never sends the message twice. The same key with another message is a `422`; a request with the key still being processed is a `409`.

## Retrying safely

```typescript title="refund-with-retry.ts"
import { randomUUID } from 'node:crypto';

const key = randomUUID(); // one per refund, stored with it

for (let attempt = 1; attempt <= 4; attempt++) {
  const res = await fetch(
    `${serverUrl}/api/v1/public/me/sales/${orderId}/refund`,
    {
      method: 'POST',
      headers: {
        'x-session-id': sessionId,
        'Idempotency-Key': key,
        'Content-Type': 'application/json',
      },
      body: '{}',
    }
  );
  if (
    res.ok ||
    (res.status < 500 && res.status !== 409 && res.status !== 429)
  ) {
    break;
  }
  await new Promise((r) => setTimeout(r, 1000 * 2 ** (attempt - 1)));
}
```

Examples here call the cloud, [https://api.console.buildbase.app](https://api.console.buildbase.app). A route not listed on this page ignores the header: retry it only if repeating it is harmless, or read back whether the first attempt took effect.

## Next steps

- [HTTP API errors](/http-api/errors) - which failures to retry.
- [Rate limits](/http-api/rate-limits) - waiting out a `429`.
- [The OpenAPI spec](/http-api/openapi) - each operation's source file, `x-source`.
