# Idempotency keys

> Retry any write or model call safely; Nexus applies it once.

Every write (`POST`, `PUT`, `PATCH`, `DELETE`) and every model call accepts an `Idempotency-Key` header. Send the same
key again and Nexus answers with the first result instead of running the request twice.

```sh
curl -X POST "$NEXUS_URL/v1/teams" \
  -H "Authorization: Bearer $NEXUS_API_KEY" \
  -H "Idempotency-Key: 6f1c2a9e-1d4b-4e0a-9f53-0c8b7d2e4a11" \
  -H "Content-Type: application/json" \
  -d '{"slug": "platform"}'
```

A key is 1 to 255 printable ASCII characters, typically a UUID. It belongs to your organization and the credential
that sent it, and is kept for **24 hours**.

| Case | Answer |
| --- | --- |
| First request | Runs; its answer is kept |
| Same key and same request, within 24 hours | The kept answer, with `Idempotent-Replayed: true`; nothing runs |
| Same key, different method, path or body | `422` `idempotency_key_reused` |
| Same key while the first request is still running | `409` `idempotency_in_progress`: retry in a moment |
| Same key for a streamed model call that has finished | `409` `idempotency_stream_replay`: a stream is neither replayed nor run again. A stream whose call failed (cut, provider error) gives its key back, so the retry runs |
| The first answer was a `5xx` or `429` | Not kept: a retry with the key runs again |
| The first answer was too large to keep (over 2 MB) | `409` `idempotency_response_not_stored`: it never runs again |
| The first request was cut off before it answered (Gateway's `504` `timeout` or `module_timeout`, or the connection closed) | `409` `idempotency_interrupted` for 24 hours: it may have run in part, so it never runs again. Check the state it changes, then use a new key. A retry in the first moments may still get `409` `idempotency_in_progress` |

## A settled call is never charged twice

A model call with a key that succeeds runs once, and its success is charged once. The [ledger](/docs/concepts/ledger)
checks this on its own as well: it refuses a second reservation under a key that has one open (`409`
`idempotency_in_progress`) or a settled charge in the last 24 hours (`409` `idempotency_already_charged`). A retry after
a `5xx` or `429` answer runs again: the key is released, and the failed attempt is not a settled charge. Each attempt is
charged for the tokens it used, and a failure that used none charges nothing. A finished stream is never run again.

## The CLI does it for you

The `nexus` CLI sends a fresh key with every command that changes something, and retries with the same key when the
connection drops after sending or Gateway answers `502`, `503`, `504` or `409` `idempotency_in_progress`. Your own code
can do the same with `createCoreClient({ idempotency: true })` from `@nexus/kit`.
