# Idempotency and safe retries

> Send an Idempotency-Key header on any POST and you can retry it without doing the work twice. The first response is kept for 24 hours and replayed, marked Idempotent-Replayed true. PUT and DELETE are idempotent by design and don't need the header.

Networks fail. If a request times out you can't tell whether it reached us, and retrying a "create user" or "enrol" blindly could do it twice. Idempotency keys make retries safe.

## Using an Idempotency-Key

Add a unique `Idempotency-Key` header to a POST request. Use a new value for each new operation (a UUID is ideal), and the **same** value when you retry that operation.

```bash
curl https://your-team.continuumlearn.com/api/v2/users \
  -H "Authorization: Bearer $CONTINUUM_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f1c2d1e-8a4b-4c7e-9d2f-1b3a5c7e9f01" \
  -d '{"email": "ali@example.org", "name": "Ali Khan", "external_id": "M-1042"}'
```

```php
<?php
$key = bin2hex(random_bytes(16)); // keep it with the job, so a retry reuses it

$response = $client->post('users', [
    'headers' => ['Idempotency-Key' => $key],
    'json' => ['email' => 'ali@example.org', 'name' => 'Ali Khan', 'external_id' => 'M-1042'],
]);
```

```js
import { randomUUID } from 'node:crypto';

const key = randomUUID(); // keep it with the job, so a retry reuses it
const res = await fetch('https://your-team.continuumlearn.com/api/v2/users', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CONTINUUM_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': key,
  },
  body: JSON.stringify({ email: 'ali@example.org', name: 'Ali Khan', external_id: 'M-1042' }),
});
```

## What happens

| Situation | Result |
|---|---|
| First request with a key | Processed normally. The response is stored for **24 hours**. |
| Same key, same method, path and body, within 24 hours | The stored response is returned with the original status code and the header `Idempotent-Replayed: true`. Nothing is done again. |
| Same key, different path or body | `422` with `error.code` `idempotency_key_reused`. Nothing is done. |
| Same key while the first request is still running | The second request waits up to 5 seconds for the first to finish, then gets the stored response. If the first is still running, it gets `409` `idempotency_in_progress` with `Retry-After: 1`. |
| A key that isn't 1 to 255 characters of `A-Z a-z 0-9 _ - : .` | `422` `invalid_idempotency_key`. |
| No `Idempotency-Key` header | Processed normally, with no protection against duplicates. |

Details worth knowing:

- **Keys are per API key.** Two different API keys can use the same idempotency key without clashing.
- **Successes and client errors are stored; server errors are not.** A `2xx` or a `4xx` response (except `429`) is kept and replayed. A `5xx` or a `429` is not stored, so retrying with the same key really tries again.
- **The body is compared byte for byte**, so send exactly the same JSON when you retry. Re-serialising an object with keys in a different order counts as a different body.
- **Replays count against your rate limit**, like any other request.

## PUT and DELETE

`PUT` and `DELETE` endpoints are idempotent by design, so they ignore the header and never need it. For example, `PUT /users/{user}/enrolments/{course}` returns `201` the first time and `200` after that, with one enrolment either way, and `DELETE /users/{user}/enrolments/{course}` returns `200` whether or not there was an enrolment to remove.

The same goes for some POST endpoints that describe a state rather than an action, such as `POST /users/{id}/deactivate`. They are safe to repeat, but sending a key does no harm.

## Frequently asked questions

### Should every POST have an Idempotency-Key?

Yes, for anything you might retry automatically. It costs nothing and turns a timeout into a safe retry.

### Can I reuse a key after 24 hours?

The stored response expires after 24 hours, after which the key is treated as new. Don't rely on this: generate a new key for each new operation.
