# Idempotency

> How to retry a POST safely, so a lost answer never makes the same reel twice.

On the web: https://www.aeyho.com/docs/api/idempotency

## Why

A network can drop an answer after the work has started. If you retry a `POST /reels` without a key, you may make two reels and use credits twice. An `Idempotency-Key` makes the retry safe.

## How it works

Send a unique value, such as a UUID, in the `Idempotency-Key` header of a `POST`:

```bash
curl -X POST https://www.aeyho.com/api/v1/reels \
  -H "Authorization: Bearer $AEYHO_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f0c8e2a-3b1d-4c5e-9a7f-2d4b6c8e0a1f" \
  -d '{"brandId": "brand_123", "title": "Why a cache stampede happens"}'
```

- The first request runs. Its answer is kept for 24 hours.
- The same key with the same request gets that first answer again, with the header `Idempotent-Replayed: true`. Nothing runs twice.
- The same key with a different request answers `409` with the code [`idempotency_mismatch`](/docs/api/errors#idempotency_mismatch).

"The same request" means the same method, the same path and the same body, byte for byte. So retry with the exact body you sent, not one built again with fields in another order.

## The details

- Keys are up to 255 characters, and they're per account: two keys of the same account share them.
- Only `POST` takes one. `PATCH` and `DELETE` are safe to repeat as they are.
- An answer of `500` or above isn't kept, so a retry after a server error runs again.
- Test keys answer with samples before this check, so nothing is kept for them.

## Try it

```bash
KEY=$(uuidgen)
for i in 1 2; do
  curl -si -X POST https://www.aeyho.com/api/v1/brands/brand_123/ideas \
    -H "Authorization: Bearer $AEYHO_KEY" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: $KEY" \
    -d '{"title": "Why a cache stampede happens"}' | grep -i idempotent
done
```
