> Source: https://developers.terrawallet.us/docs/idempotency . Terra Wallet developer docs (early access).

# Idempotency

Networks fail. A request can time out after Terra created the payment but before you saw the response. An
`Idempotency-Key` makes the retry safe: Terra returns the original result instead of creating a second object.

> **Preview.** The API is in early access and may change before launch.

## The rules

- Every `POST` that creates something **requires** an `Idempotency-Key` header.
- The key is 8 to 128 characters. Use something unique per operation, for example `order-1042-checkout` or a
  UUID you store with the order.
- Terra stores the response for **24 hours**, keyed by the key, your organization, the route and a hash of the
  request body.
- Sending the same key with the same body within 24 hours returns the stored response. Nothing new is created.
- Sending the same key with a **different body** returns `409 IDEMPOTENCY_KEY_REUSED`.
- Sending the same key while the first request is **still running** returns `409 IDEMPOTENCY_IN_PROGRESS`.
  Wait a moment and retry with the same key.
- A create without the header returns `400 IDEMPOTENCY_KEY_REQUIRED`, and a key outside 8 to 128 printable
  characters returns `400 IDEMPOTENCY_KEY_INVALID`.

## Example

```bash
curl https://terrawallet.us/api/v1/payment_intents \
  -H "Authorization: Bearer $TERRA_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1042-checkout" \
  -d '{ "amount": "120.00", "currency": "USD", "accepted_assets": [ ... ] }'
```

Run it twice: both calls return the same `pi_...` id.

## Choosing keys

- **Derive the key from your own record**, such as the order id plus the action. A retry after a crash then
  reuses it automatically.
- **Use a new key for a new intent.** If the customer changes their cart, the body changes, so create a new key
  (for example `order-1042-checkout-2`).
- **Never reuse a key across environments or products** to mean different things.
- Keys are not secrets, but they may appear in your logs, so do not put personal data in them.

## Retrying

Retry on network errors, timeouts, `429` and `503`, with exponential backoff, and always with the **same** key.
Do not retry `409 IDEMPOTENCY_KEY_REUSED` with the same key: it means your code sent a different request under
an old key.
