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

# Idempotency

> Send an Idempotency-Key on every call that spends credits, so a retry after a timeout never charges twice.

Networks fail. If a request times out you do not know whether it ran. An `Idempotency-Key` lets you send it again safely: PostChamp runs the work once and answers the retry with the first answer.

## Where it is required

Send the header on every call that spends credits. Without it the call answers `400 idempotency_key_required` and nothing runs.

| Endpoint | Credits |
| - | - |
| `POST /workspaces/{workspaceId}/posts/generate` | Post generation |
| `POST /workspaces/{workspaceId}/posts/generate-batch` | Five variations |
| `POST /workspaces/{workspaceId}/carousels` | Carousel creation |
| `POST /workspaces/{workspaceId}/carousels/{id}/changes` | Per slide added or redrawn |
| `POST /workspaces/{workspaceId}/infographics` | Infographic creation |
| `POST /workspaces/{workspaceId}/infographics/{id}/edit` | Infographic edit |

Other calls (saving, editing, scheduling, content styles) are free and ignore the header.

## The key

* 1 to 100 printable characters, no spaces. A UUID or an id from your own system works well, such as `order-8812-post-1`.
* It is scoped to your API key. Two different keys can use the same value.
* Use a **new value for each new request**, and the **same value only when retrying the same request**.

## How it behaves

| You send | You get |
| - | - |
| A new key | The call runs. The answer is stored for 86400 seconds (24 hours). |
| The same key and the same request again | The stored answer, with the status you first got and the header `Idempotent-Replayed: true`. No second run, no second charge. |
| The same key with a different request | `409 idempotency_conflict`, with `details.reason: "idempotency_key_reused"`. |
| The same key while the first call still runs | `409 conflict` with `details.reason: "request_in_progress"`. Wait and retry with the same key. |

"Same request" means the same method, path and body (after defaults are applied). Changing the prompt changes the request.

```bash
# First call: runs and charges
curl -i -X POST "https://api.postchampai.com/api/v1/workspaces/$WS/posts/generate" \
  -H "x-api-key: $POSTCHAMP_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-gen-001" \
  -d '{"prompt": "Why founders should write down their weekly wins", "versions": 1}'

# Same call again: HTTP 200, header "Idempotent-Replayed: true", "creditsLeft" unchanged

# Same key, other prompt:
#   409 {"error":{"code":"idempotency_conflict","message":"This Idempotency-Key was already used with a different request.","details":{"reason":"idempotency_key_reused"}}}
```

## When the key is freed

You can reuse the same key (and retry the same request) when nothing was charged:

* **The call failed.** Any error answer frees the key, so retry with the same key after fixing the cause.
* **The model asked a question.** A generation that answers `"status": "needs_input"` is free and is not stored. Send the same request plus an `answers` array with the same key. See the [recipe](/api/recipes/generate-and-schedule.md).

An unfinished call frees its key after 900 seconds (15 minutes).

## Jobs and replays

Carousel and infographic creation start a job and answer `202`. A retry with the same key returns the same carousel or infographic id (and `Idempotent-Replayed: true`) instead of starting a second one.

For a carousel change, a retry of a change that was already charged answers `409 conflict` with `details.reason: "already_done"`. Read the carousel to see the result.

## Streaming

A post generation sent with `Accept: text/event-stream` uses the same key. The request is checked before anything streams. A replay arrives as a single `result` event. See [Jobs and streaming](/api/jobs-and-streaming.md).

## If the store is down

When PostChamp cannot check the key, it answers `503 service_unavailable` and starts nothing (it fails closed). Retry with the same key.

## Retry pattern

```javascript JavaScript
import { randomUUID } from "node:crypto";

async function postWithRetry(url, body, { tries = 4 } = {}) {
  const idempotencyKey = randomUUID(); // one key for all attempts of this request
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(url, {
        method: "POST",
        headers: {
          "x-api-key": process.env.POSTCHAMP_API_KEY,
          "Content-Type": "application/json",
          "Idempotency-Key": idempotencyKey,
        },
        body: JSON.stringify(body),
      });
    } catch (err) {
      if (attempt >= tries) throw err; // network error or timeout: safe to retry
      await new Promise((r) => setTimeout(r, 1000 * attempt));
      continue;
    }
    const retryable = res.status === 429 || res.status === 503 || res.status >= 500;
    if (res.ok || !retryable || attempt >= tries) return res;
    const wait = Number(res.headers.get("Retry-After")) || attempt;
    await new Promise((r) => setTimeout(r, wait * 1000));
  }
}
```

```python Python
import os, time, uuid, requests

def post_with_retry(url, body, tries=4):
    idempotency_key = str(uuid.uuid4())  # one key for all attempts of this request
    for attempt in range(1, tries + 1):
        try:
            res = requests.post(
                url,
                json=body,
                headers={
                    "x-api-key": os.environ["POSTCHAMP_API_KEY"],
                    "Idempotency-Key": idempotency_key,
                },
                timeout=330,
            )
        except requests.RequestException:
            if attempt == tries:
                raise
            time.sleep(attempt)
            continue
        retryable = res.status_code in (429, 503) or res.status_code >= 500
        if res.ok or not retryable or attempt == tries:
            return res
        time.sleep(int(res.headers.get("Retry-After", attempt)))
```

> [!NOTE]
>
> Post generation can run for minutes as one JSON request. Set a client timeout of at least 5 minutes, or use the [streaming form](/api/jobs-and-streaming.md#stream-a-post-generation).

> [card] [Errors](/api/errors.md)
>
> The 409 and 503 codes in detail.

> [card] [Rate limits](/api/rate-limits.md)
>
> What a 429 looks like.
