# Idempotency: retry a write safely

> Send an Idempotency-Key header on a write so a retry after a timeout cannot do the work twice.

A network error can leave you unsure whether a write happened. Send an `Idempotency-Key` header and you can retry without creating a second record.

## How to use it

Add the header to any `POST` or `PATCH`. Use a new random value for each new request, such as a UUID. The key is 8 to 128 printable characters with no spaces.

```bash
curl -X POST "https://app.staffedly.com/api/v1/leave" \
  -H "Authorization: Bearer $STAFFEDLY_API_KEY" \
  -H "Idempotency-Key: 6f1c2a9e-7b1d-4a53-9d55-2f6f3a1c0b77" \
  -H "Content-Type: application/json" \
  -d '{"providerId":"<providerId>","start":"2027-01-12","end":"2027-01-14","type":"vacation"}'
```

If the call times out, send exactly the same request again with the same key.

## What happens on a retry

| Situation | Answer |
| --- | --- |
| Same key, same method, path and body, first request finished | The first answer again, with the header `Idempotent-Replayed: true`. Nothing is done twice |
| Same key, different request | `422 idempotency_key_reused` |
| Same key while the first request is still running | `409 request_in_progress`. Try again in a moment |

## The details

- The header is optional. Without it, every request is carried out.
- Answers are remembered for 24 hours, separately for each API key.
- A refusal (a 4xx answer such as a validation error) is remembered and replayed. A failure on Staffedly's side (5xx) and a rate-limit answer (429) are not, so the retry runs.
- A first request that never finished stops blocking retries after one minute.
