# Idempotency

A network can fail after Lupeno has done what you asked but before you heard the answer. Retrying a read is harmless; retrying a create could make two orders or two discount codes. So every create — creating an order and creating a discount code — requires an **`Idempotency-Key`** header, and the same key never creates twice.

```sh
curl -X POST "https://api.lupeno.com/v1/events/$EVENT_ID/discount-codes" \
  -H "Authorization: Bearer $LUPENO_API_KEY" \
  -H "Idempotency-Key: 6f1c2b8e-5d1e-4c84-9d0e-2f6e3c1b7a90" \
  -H "Content-Type: application/json" \
  -d '{ "code": "SPRING26", "kind": "percent", "percentBp": 1500 }'
```

## The rules

- **One key per thing you mean to create.** Choose it before the first attempt and keep it for every retry of that create. A UUID is ideal; any 16–128 characters of `A–Z a–z 0–9 _ -` will do.
- **A retry gets the first answer.** Same key, same request: Lupeno answers with exactly what the first attempt returned — the same status and body — and the header `Idempotent-Replayed: true`. Nothing is created again.
- **A key is for one request.** The same key with a different body or path is refused: `422 api.idempotency_key_reused`.
- **A retry too soon waits its turn.** While the first attempt is still running, a retry answers `409 api.idempotency_in_flight` with `Retry-After`; try again a moment later.
- **A first attempt that never answered is run again.** If the server handling it went down before it could answer, the key is free again after 90 seconds: a retry with the same request runs the create once more and answers normally. Nothing is created twice — an order made by the lost attempt is the order the retry returns; a discount code it made answers `409 discount.code_taken`, and the code is in your list.
- **Keys are per API key, for 24 hours.** After that a key may be used afresh.
- **Missing or malformed key:** `400 api.idempotency_key_required`.

Other requests do not take a key: a `GET` changes nothing, and cancelling an order, revoking a code or recording an entry a second time ends in the state the first left.

## With the SDK

```ts
import { idempotencyKey, unwrap } from '@lupeno/sdk';

const key = idempotencyKey(); // keep it while you retry this one create

const code = unwrap(
  await lupeno.POST('/v1/events/{eventId}/discount-codes', {
    params: { path: { eventId }, header: { 'idempotency-key': key } },
    body: { code: 'SPRING26', kind: 'percent', percentBp: 1500 },
  }),
);
```
