> ## Documentation Index
> Fetch the complete documentation index at: /llms.txt
> Use this file to discover all available pages before exploring further.

# Idempotency

> Retry a request without sending a message twice.

Networks fail. If a request times out you cannot tell whether Cerium received it. Retrying a plain request could create a **second conversation** or send the **same message twice**.

An `idempotencyKey` solves this. Send a unique key with a request; if Cerium has already seen the key it returns the original result instead of repeating the work.

## How it works

```mermaid
sequenceDiagram
  participant You
  participant Cerium
  You->>Cerium: POST /messages (key: order-1042-msg-2)
  Cerium-->>You: 201 Created
  Note over You,Cerium: The response is lost
  You->>Cerium: POST /messages (key: order-1042-msg-2)
  Cerium-->>You: 200 OK (the first message)
```

| Result | Status |
| - | - |
| First time the key is seen | `201` |
| The key was already used | `200`, with the **first** message and `"message": "Message already received."` |

## Where to use it

* [`POST /conversations`](/api-reference/conversations/start-a-conversation)
* [`POST /conversations/{conversationId}/messages`](/api-reference/messages/send-a-message)

`POST /customers` does not need one: it is already create-or-get.

## Choosing a key

* Up to **64 characters**.
* **Unique per message**, and **stable across retries** of that message.
* Derive it from something you already have, such as `order-1042-msg-2`, a message row id, or a UUID you store with the message before sending.

> [!WARNING]
>
> Do not generate a new key on each retry: that defeats the point. Create it once, store it, and reuse it for every attempt at the same message.

## A retry pattern

```javascript
async function sendWithRetry(url, body, attempts = 4) {
  for (let i = 0; i < attempts; i++) {
    try {
      const res = await fetch(url, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.CERIUM_API_KEY}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(body), // includes the same idempotencyKey every time
      });

      if (res.status < 500 && res.status !== 429) return res.json();

      const wait = Number(res.headers.get("retry-after")) * 1000;
      await new Promise((r) => setTimeout(r, wait || 2 ** i * 500));
    } catch {
      await new Promise((r) => setTimeout(r, 2 ** i * 500));
    }
  }
  throw new Error("Cerium request failed after retries");
}
```

Only retry on network errors, `429` and `5xx`. A `4xx` means the request itself is wrong and will fail again.
