
# Idempotency

Networks fail halfway. A request that timed out may or may not have happened, and sending it again could create a second site build, contact or entry. An `Idempotency-Key` makes a POST safe to repeat.

```sh
curl https://api.unvop.com/v1/sites/site_…/contacts \
  -H "Authorization: Bearer $UNVOP_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: signup-8f14e45f" \
  -d '{ "email": "sam@example.com", "name": "Sam Rivera" }'
```

## How it works

- The key is any string up to 200 characters. Make one per operation you intend to do once, such as a UUID, or an id from your own system.
- The first answer is stored for 24 hours, per key and path. The same request again gets that answer replayed, with `Idempotent-Replayed: true`.
- While the first is still running, a repeat gets `409 conflict`. Wait and try again.
- The same key with a different body gets `422 idempotency_mismatch`. A key names one request, not a slot to reuse.
- Answers with a 5xx status aren't stored, so retrying those runs the request again.

The reference marks every operation that takes the header. Builds are protected twice: the same build request sent within two minutes returns the build already running, key or not.

## Retry safely

```js
async function post(url, body, key) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(url, {
      method: 'POST',
      headers: { ...headers, 'Content-Type': 'application/json', 'Idempotency-Key': key },
      body: JSON.stringify(body),
    });
    if (res.status < 500 && res.status !== 409 && res.status !== 429) return res;
    if (attempt === 4) return res;
    await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
  }
}
```
