# Idempotency

Every `/api/v1/*` mutation accepts an optional `Idempotency-Key` header. Supply one to make retries safe: the second call with the same key returns what the first call made instead of creating a second resource. The contract is modelled on Stripe's, with the differences noted under [Scope](#scope) and [Retention](#retention).

## When to use it

Network failures are common. Without idempotency, a timeout on `POST /api/v1/registers/{id}/risks` leaves you guessing whether the risk was created. Retry blindly and you may create duplicates.

Supply `Idempotency-Key: <your-uuid>` on the first call, then retry with the **same key** on failure. If the original succeeded, the retry returns `200` with the record the original made or changed, as it stands now. That holds for a create too: the first call answers `201 Created`, a replay of it answers `200`, so accept both. If the original failed before anything was saved, the retry does the work.

## Header format

```
Idempotency-Key: <1-200 chars, [A-Za-z0-9_-]>
```

- Charset: `A-Z`, `a-z`, `0-9`, `_`, `-`. No other characters.
- Length: 1 to 200 characters.
- Case-sensitive at the comparison layer (matched byte-for-byte).
- UUID v4 is the safe default: generate a new one per operation, and reuse it only to retry that operation.

Malformed keys return `400 VALIDATION_ERROR`.

## Replay semantics

The server stores a body hash alongside every idempotency-keyed audit entry. On retry:

| Retry's key | Retry's body | Behaviour |
| --- | --- | --- |
| Same | Same canonical JSON (see below) | Replay: `200` with the record the original call made or changed. Nothing new is created, and no further audit entry is written. |
| Same | Different | `409 CONFLICT` with `details.subcode = 'API_V1_IDEMPOTENCY_BODY_MISMATCH'`. Fix your request body or use a fresh key. |

A `DELETE` is the exception: it accepts the header and checks its format, but doesn't replay. Deleting twice is harmless anyway: the retry of a delete that succeeded answers `404`, which you can treat as proof the first one worked.

"Same body" means the same canonical JSON. The server canonicalises by sorting object keys recursively; array order is preserved (order is semantically meaningful in JSON arrays). Whitespace and key order in your raw request don't matter.

## Scope

A key is scoped to the organisation, the person the token acts as, and the action. Two people who happen to choose the same key never see each other's results, and the same key used against `/risks/{id}/assess` and `/risks/{id}/treat` gives two independent results, because they are different actions.

The record in the path counts as well, so a key never replays one record's result onto another. Reusing a key and body against a different record is either refused with `409` (`API_V1_IDEMPOTENCY_BODY_MISMATCH`) or treated as a new request, depending on the route. Don't rely on either: use a key for one operation on one record.

This differs from Stripe, where a key is unique across the whole account and cannot be reused on a different endpoint. Most clients generate a fresh key per call and never notice.

## Concurrent same-key calls

If two requests with the same key arrive at the same moment, the server handles them one at a time. One makes the change; the other replays the result. No duplicates.

The verb endpoints (`/assess`, `/treat`, `/request-review`, `/complete-review`, `/cancel-review`) take a per-risk lock first, so concurrent verb calls on the same risk run one at a time. The canonical race-safe order on every mutation is `entity edit lock → idempotency replay → ETag check → write`. See [ETag and optimistic concurrency](https://riskregister.com/docs/etag-concurrency.md) for why the idempotency check fires before the ETag check.

### `AI_GENERATION_IN_FLIGHT` (special case)

`POST /api/v1/registers/from-context` is the one endpoint that cannot hold the idempotency lock for its whole duration: it waits several seconds for an AI model, far longer than a lock should be held.

Instead, the first call reserves the key while it runs. Concurrent same-key calls receive `409 CONFLICT` with `details.subcode = 'AI_GENERATION_IN_FLIGHT'` and `Retry-After: 60`. Retry after the original completes; the same key returns the original generation.

The losing request stops before it uses any of your AI allowance, so a concurrent retry costs no extra AI calls. A reservation left behind by a call that never finished lapses after 5 minutes.

## Retention

A replay reads the audit log entry the original call wrote, so a key can be replayed for as long as that entry is kept. By default audit entries are never deleted. An Enterprise organisation that sets an audit-log retention period (365 days at least) loses the replay when the entry is removed, and the key is then treated as new. This also differs from Stripe, which keeps a key for 24 hours. In practice, retry within a few hours of the original.

## Worked example

```bash
KEY=$(uuidgen)

# First attempt
curl -X POST https://riskregister.com/api/v1/registers/REG-0001/risks \
  -H "Authorization: Bearer rr_pat_live_..." \
  -H "Idempotency-Key: $KEY" \
  -H "Content-Type: application/json" \
  -d '{"title":"Phishing","categoryId":"<category-uuid>","inherentLikelihood":4,"inherentImpact":5,"residualLikelihood":2,"residualImpact":3,"treatment":"mitigate","status":"open"}'
# → 201 Created with the new risk

# Network hiccup; retry with the same key + same body
curl -X POST https://riskregister.com/api/v1/registers/REG-0001/risks \
  -H "Authorization: Bearer rr_pat_live_..." \
  -H "Idempotency-Key: $KEY" \
  -H "Content-Type: application/json" \
  -d '{"title":"Phishing","categoryId":"<category-uuid>","inherentLikelihood":4,"inherentImpact":5,"residualLikelihood":2,"residualImpact":3,"treatment":"mitigate","status":"open"}'
# → 200 with the same risk id. No duplicate created.

# Different body, same key
curl -X POST https://riskregister.com/api/v1/registers/REG-0001/risks \
  -H "Authorization: Bearer rr_pat_live_..." \
  -H "Idempotency-Key: $KEY" \
  -H "Content-Type: application/json" \
  -d '{"title":"Different risk","categoryId":"<category-uuid>","inherentLikelihood":1,"inherentImpact":1,"residualLikelihood":1,"residualImpact":1,"treatment":"accept","status":"open"}'
# → 409 with details.subcode = "API_V1_IDEMPOTENCY_BODY_MISMATCH"
```

`<category-uuid>` is a category's `id` from `GET /api/v1/risk-categories`; a name is refused with `400`.

## See also

- [Errors](https://riskregister.com/docs/errors.md) - the 409 / `Retry-After` surface.
- [ETag and optimistic concurrency](https://riskregister.com/docs/etag-concurrency.md) - pairs with idempotency for safe retries.
