# ETag and optimistic concurrency

Every `/api/v1/*` GET on a single resource emits an `ETag`. Send it back in the **`x-rr-if-match`** request header on your next mutation and the server rejects the request with 412 if someone else updated the record in the meantime. Opt-in: omit it and the route falls back to last-writer-wins.

> **Send `x-rr-if-match`, not the standard `If-Match`.** This API is served behind an edge that enforces HTTP `If-Match` preconditions itself: on a *successful* write it can rewrite the 2xx into a spurious 412 (the post-write entity tag never equals the token you sent), so a standard `If-Match` is unreliable on the public surface. The server reads the token from `x-rr-if-match` first and tolerates a standard `If-Match` only as a fallback, so always send `x-rr-if-match`.

## ETag format

A weak validator: 16 hexadecimal digits, the record's last-updated time in milliseconds. Treat it as opaque and send back exactly what you were given.

```
ETag: W/"0000019018a5e3c2"
```

The strong form (`"<hex>"` without the `W/` prefix) is accepted on input and compared as if it were weak. The server always sends the weak form; you may send either.

## Endpoints

The server sends an `ETag` on:
- Every single-resource GET (`/api/v1/registers/{id}`, `/api/v1/risks/{id}`, etc.).
- Every successful mutation response (POST creates, PATCH updates, plus verb endpoints like `/risks/{id}/assess`).

These accept the `x-rr-if-match` token:
- Every PATCH and DELETE.
- Every verb endpoint that changes a record (`/assess`, `/treat`, `/request-review`, `/complete-review`, `/cancel-review`).

POST creates don't accept the token: there's nothing to compare against. Use `Idempotency-Key` for safe POST retries.

## Sending the token

```
x-rr-if-match: W/"0000019018a5e3c2"
```

Or:

```
x-rr-if-match: "0000019018a5e3c2"
```

(Strong form, normalised to weak on the server.)

**`x-rr-if-match: *` is not supported.** It returns `412 PRECONDITION_FAILED` with `details.subcode = 'IF_MATCH_WILDCARD_UNSUPPORTED'`. The wildcard semantic is "any current version" and we'd rather force the client to use an explicit ETag so a deliberate retry against a known version stays auditable.

## Failure modes

All 412s carry a stable subcode in `details.subcode`:

| Subcode | Meaning | Recovery |
| --- | --- | --- |
| `ETAG_MISMATCH` | The record changed since you read it. `details.currentETag` and `details.suppliedETag` are populated. | Re-GET the resource, show your user the latest version, and let them re-apply their change on top of it. |
| `IF_MATCH_MALFORMED` | The header value doesn't match the expected `W/"<16-hex>"` or `"<16-hex>"` shape. | Fix the header. |
| `IF_MATCH_WILDCARD_UNSUPPORTED` | You sent `x-rr-if-match: *`. | Use an explicit ETag. |

A 412 with `ETAG_MISMATCH` is the "someone else got there first" condition. Tell your user that someone else updated the record, and offer to reload it. The 412 body carries the current ETag but not the current data. To merge, re-GET the resource; to overwrite deliberately, resend the change with `details.currentETag` in `x-rr-if-match`.

## Worked example

```bash
# Read the risk
RESP=$(curl -i https://riskregister.com/api/v1/risks/RISK-0042 \
  -H "Authorization: Bearer rr_pat_live_...")
ETAG=$(echo "$RESP" | grep -i '^etag:' | sed 's/[Ee][Tt][Aa][Gg]: //' | tr -d '\r\n')

# Update with concurrency safety
curl -X PATCH https://riskregister.com/api/v1/risks/RISK-0042 \
  -H "Authorization: Bearer rr_pat_live_..." \
  -H "Content-Type: application/json" \
  -H "x-rr-if-match: $ETAG" \
  -d '{"status":"under_review"}'
# → 200 if nobody else touched the risk
# → 412 PRECONDITION_FAILED + details.subcode=ETAG_MISMATCH if they did
```

## Why opt-in?

Last-writer-wins is fine for most workflows (one user at a time editing a risk, or two users editing different fields). Forcing every client to manage ETags would be friction. Send the token only when you actually need the safety:

- Multiple admins editing the same register concurrently.
- A long-running form where the user might leave the tab open for hours.
- Verb endpoints where you're encoding a meaningful state transition (`/assess`, `/treat`, `/complete-review`) and want to be sure the row hasn't changed under you.

## Pairing with Idempotency-Key

ETag and idempotency solve different problems:

- **ETag** stops you from overwriting changes you didn't see.
- **Idempotency-Key** stops a retry from creating a duplicate when the original request succeeded but you never saw the response.

On the same call, both are useful: ETag protects against concurrent edits; the idempotency key protects against network retries. The canonical race-safe order on every mutation is:

```
entity edit lock → idempotency replay → ETag check → write
```

Idempotency replay fires first because a network-dropped retry with the same key but the original (now stale) `x-rr-if-match` should replay the original result, not answer 412 because the first (successful) write, which the client never saw, moved the record's ETag on.

See [Idempotency](https://riskregister.com/docs/idempotency.md) for the full retry contract.

## A verb call always changes the ETag

Every successful call to a verb endpoint (`/assess`, `/treat`, `/request-review`, `/complete-review`, `/cancel-review`) gives the risk a new ETag, even when the payload changes nothing. A call that changes nothing still writes an audit entry and sends a webhook event, so an ETag read before it must not pass afterwards: the risk has forensically relevant activity the reader has not seen.

## See also

- [Errors](https://riskregister.com/docs/errors.md) - the 412 surface and shared error envelope.
- [Idempotency](https://riskregister.com/docs/idempotency.md) - the safe-retry primitive.
