# Safe retries

Source: https://developers.weerom.com/docs/idempotency

> Send an Idempotency-Key with a POST or a PATCH, and a retry after a timeout changes nothing twice.

A request to make a booking times out. Did WeerOm make it? Your code cannot tell. Send it again without protection and the customer may have two bookings.

`Idempotency-Key` solves this. Send any unique text in that header with a `POST` or a `PATCH`. WeerOm runs the first request and keeps its answer for 24 hours. A retry with the same key and the same request gets that answer back, and nothing runs a second time.

```bash
curl https://api.weerom.com/v1/bookings \
  -H "Authorization: Bearer $WEEROM_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f1c2b8e-9d4a-4f3e-8b7c-2a1d0e9f8c7b" \
  -d '{
    "service_id": "c2a41f6e-8d3b-4e97-b5a0-1f7c9e2d4a68",
    "staff_id": "8e1d5b7c-3a9f-4d20-b6c4-7a2e0f9d1c53",
    "starts_at": "2026-11-30T09:00:00.000Z",
    "customer": { "name": "Lotte Peeters", "phone": "+32470123456", "email": "lotte@example.com" }
  }'
```

## The rules

| You send | WeerOm answers |
| --- | --- |
| A new key | Runs the request and keeps the answer. |
| The same key and the same request, after the first one finished | The first answer, with its status, and the header `Idempotent-Replayed: true`. Nothing runs. |
| The same key while the first request still runs | 409 `request_in_progress`. Wait a second and send it again. |
| The same key with another method, path or body | 409 `idempotency_mismatch`. Use a new key for a new request. |
| The same key after the first request failed | Runs the request. A request that answered an error keeps nothing, so you may fix it and send it again under the same key. |

- The key is any text up to 255 characters. A UUID from `crypto.randomUUID()` is a good choice.
- Keys belong to one API key. Two tools with their own API keys cannot collide.
- WeerOm keeps a key for 24 hours. After that the same key runs the request again.
- `GET` ignores the header. Reading twice changes nothing.
- If the first request died on WeerOm's side without an answer, a retry a minute later runs it again.

The endpoints that take it: `POST /bookings`, `POST /bookings/{id}/cancel`, `POST /bookings/{id}/reschedule` and `PATCH /customers/{id}`.

## One key for each thing you mean to do

Make the key when you decide to do something, store it with that intent, and reuse it for every retry of it. A booking form makes one when the customer presses Book. A sync job can build it from its own data, such as `cancel-0b6f2a4e-...` for the cancellation of one booking, so a job that restarts sends the same key again.

Make a new key when the request changes: another time, another customer, another body.

## Retry with the same key

```js
const BASE = "https://api.weerom.com/v1";

async function post(path, body, idempotencyKey) {
  for (let attempt = 1; ; attempt++) {
    let response;
    try {
      response = await fetch(`${BASE}${path}`, {
        body: JSON.stringify(body),
        headers: {
          Authorization: `Bearer ${process.env.WEEROM_KEY}`,
          "Content-Type": "application/json",
          "Idempotency-Key": idempotencyKey,
        },
        method: "POST",
      });
    } catch (networkError) {
      if (attempt === 4) throw networkError;
      await wait(attempt);
      continue;
    }

    const json = await response.json();
    if (response.ok) return json;

    const { code } = json.error;
    const again = code === "request_in_progress" || response.status >= 500;
    if (!again || attempt === 4) {
      throw new Error(`${response.status} ${code}: ${json.error.message}`);
    }
    await wait(attempt);
  }
}

const wait = (attempt) => new Promise((done) => setTimeout(done, 2 ** attempt * 1000));

const booking = await post("/bookings", bookingBody, crypto.randomUUID());
```

The waits grow: 2, 4, then 8 seconds. The sketch retries a lost connection, a 500 and `request_in_progress`. Other 4xx answers are about the request itself, such as `slot_taken` or `invalid_request`, so it stops and reports them. A 429 waits the seconds in `Retry-After` first: see [Rate limits](https://developers.weerom.com/docs/rate-limits).
