# Retries and idempotency

> Retry changes safely with an Idempotency-Key.

Networks fail. If a request that changes something times out, you can't tell whether it went through, and retrying might do it twice. Send an `Idempotency-Key` header with every change, and retry with the same key:

```bash
curl -X POST https://developers.playbookops.ai/v1/projects/PROJECT_ID/items \
  -H "Authorization: Bearer $PLAYBOOKOPS_API_KEY" \
  -H "Idempotency-Key: 6f1d2c1e-8a3b-4b8e-9d55-2c0f9e7a1b42" \
  -H "Content-Type: application/json" \
  -d '{"title": "Call the venue"}'
```

## How it works

- The first request makes the change. Retries with the same key and the same body return the first answer and change nothing.
- Using the key again with a different body or endpoint returns `409` with the code `idempotency_key_reused`.
- Keys are remembered per API key. Use a new UUID for each change.
- Only changes that succeed are remembered, so a request that failed with an error can be retried with the same key.

## Retrying in code

Make the key once per change, outside the retry loop:

**Python**

```python
import time
import uuid

import httpx

def create_item(api, project_id, body, attempts=4):
    key = str(uuid.uuid4())
    for attempt in range(attempts):
        try:
            res = api.post(f"/projects/{project_id}/items", json=body, headers={"Idempotency-Key": key})
        except httpx.TransportError:
            time.sleep(2**attempt)
            continue
        if res.status_code == 429 or res.status_code >= 500:
            time.sleep(int(res.headers.get("Retry-After", 2**attempt)))
            continue
        res.raise_for_status()
        return res.json()
    raise RuntimeError("Gave up after retries")
```

**JavaScript**

```javascript
async function createItem(projectId, body, attempts = 4) {
  const key = crypto.randomUUID();
  for (let attempt = 0; attempt < attempts; attempt++) {
    try {
      const res = await fetch(`${base}/projects/${projectId}/items`, {
        method: "POST",
        headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": key },
        body: JSON.stringify(body),
      });
      if (res.status !== 429 && res.status < 500) {
        if (!res.ok) throw new Error((await res.json()).error.message);
        return await res.json();
      }
    } catch (e) {
      if (!(e instanceof TypeError)) throw e;
    }
    await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
  }
  throw new Error("Gave up after retries");
}
```

> **MCP calls aren't deduplicated**
> There's no header over MCP, so a retried tool call runs again. Agents should look before retrying a change, for example by listing items before creating one again.
