# Idempotency

Networks fail. When a `POST` times out you cannot know whether it reached the API. With an `Idempotency-Key` you can send it again without verifying, creating or charging twice.

## How it works

Add the header to any `POST`: `/verify`, `/batches` and `/batches/{batch_id}/cancel`.

```bash
curl https://api.salchimail.com/v1/verify \
  -H "Authorization: Bearer $SALCHIMAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f1c1c0e-6d1f-4f0e-9f58-0d6b0a1c2e3f" \
  -d '{"email": "ana@example.com", "mode": "mailbox"}'
```

- The key is any unique string of up to 255 characters. A UUID is a good choice.
- Keys are kept **24 hours**, per account.
- A retry with the same key and the same body returns the stored response, with the header `Idempotent-Replayed: true`, and **charges nothing**.

## Conflicts

| HTTP | `code` | Meaning | What to do |
| --- | --- | --- | --- |
| 409 | `idempotency_key_reused` | The key was already used with a different body | Use a new key for a new request |
| 409 | `idempotency_in_progress` | The first request with that key is still running | Wait and retry with the same key |

```json
{
  "error": {
    "type": "conflict",
    "code": "idempotency_key_reused",
    "message": "This Idempotency-Key was already used with a different request.",
    "request_id": "req_4b5c6d7e8f9a0b22"
  }
}
```

## Use it well

- Generate **one key per operation**, not per attempt: create it before the first try and reuse it on every retry.
- Store the key next to the job it belongs to (the sign-up, the import) so that a restarted process retries with the same key.
- Retry on network errors, `429`, `500` and `503`, with the same key and an increasing wait. See [Limits and errors](https://docs.salchimail.com/limits-and-errors.md).
- Do not retry `400`, `401`, `402`, `403` or `404` without changing something: the answer will be the same.

Idempotency matters most when you [create a batch](https://docs.salchimail.com/batches.md): without a key, a retry after a timeout can create a second batch and reserve its credits too.

`GET` requests are safe to repeat and need no key.
