# Idempotency (/idempotency)

Networks fail. When a `POST` times out you cannot tell whether CallMitra received it, and retrying blindly could create a second campaign or place a second call. Send an `Idempotency-Key` header and the retry returns the first result instead of doing the work twice.

```bash
curl -X POST https://api.callmitra.ai/api/v1/campaigns/create-with-leads \
  -H "X-API-Key: $CALLMITRA_API_KEY" \
  -H "Idempotency-Key: 6f1d2c4e-campaign-2026-11-15" \
  -H "Content-Type: application/json" \
  -d @campaign.json
```

## Which endpoints support it [#which-endpoints-support-it]

These `POST` endpoints accept `Idempotency-Key`. Their pages in the [API reference](/api-reference) list the header and the `Idempotent-Replayed` response header. On other endpoints the header is ignored.

| Resource | Endpoints |
| --- | --- |
| Agents | [Create an agent](/api-reference/agents/createAgent), [import an agent](/api-reference/agents/importAgent) |
| Calls | [Place a call](/api-reference/calls/createCall) |
| Campaigns | [Create a campaign](/api-reference/campaigns/createCampaign), [create with leads](/api-reference/campaigns/createCampaignWithLeads) |
| Leads | [Create a lead](/api-reference/leads/createLead), [bulk action](/api-reference/leads/bulkLeadAction), [add to do-not-call](/api-reference/do-not-call/addDoNotCall), [add a note](/api-reference/lead-notes/createLeadNote) |
| Tickets | [Create a ticket](/api-reference/tickets/createTicket), [add a note](/api-reference/tickets/addTicketNote) |
| WhatsApp | [Send a message](/api-reference/whatsapp/sendWhatsAppMessage) |
| Webhooks | [Create an endpoint](/api-reference/webhooks/createWebhookEndpoint) |

## Rules [#rules]

- **Key format:** any string of 1–255 characters. A UUID v4 per logical operation is a good choice. A longer or empty key is rejected with `400` [`bad_request`](/errors/bad_request) and `param: "Idempotency-Key"`.
- **Scope:** a key is scoped to the credential that sent it, plus the HTTP method and the exact path. Two different API keys can use the same key value without colliding. Send the credential the same way on every retry: the same API key sent once as `X-API-Key` and once as `Authorization: Bearer` counts as two credentials.
- **Agency keys:** the workspace in `X-Workspace-Id` is not part of the scope. When one agency key works in several client workspaces, include the client in the key (for example `client-42:campaign-2026-11-15`) so two clients never share a key ([Agencies](/guides/agencies)).
- **Lifetime:** the result is kept for **24 hours**. After that the same key starts a new request.
- **Same request, same key:** you get the stored status code and body again, with the header `Idempotent-Replayed: true`. Successes (`2xx`) and client errors (`4xx`) are stored, except `401`, `403`, `404` and `429`. "Same request" means the same method, path and byte-for-byte body; a replay returns the stored body and content type, not the other headers of the first response.
- **Different body, same key:** `409` [`idempotency_key_reused`](/errors/idempotency_key_reused). Use a new key for a new operation.
- **First request still running:** `409` [`idempotency_request_in_progress`](/errors/idempotency_request_in_progress) with `Retry-After: 1`. Wait and retry with the same key. The claim is held for as long as the first request runs; if it never finishes (for example the server restarted), the claim is released after 2 minutes.
- **Server errors, rate limits and auth errors are not stored.** If the first attempt failed with a `5xx`, a `429`, a `401`, a `403` or a `404` (or the response was larger than 1 MB), the key is released and a retry runs the request again.
- **Large request bodies:** a request body over 1 MB is processed without idempotency (the key is ignored).
- **Responses that contain a secret are never stored.** [Create a webhook endpoint](/api-reference/webhooks/createWebhookEndpoint) returns its signing `secret` once. A concurrent duplicate still gets `409` [`idempotency_request_in_progress`](/errors/idempotency_request_in_progress), but once the first request has succeeded, a retry with the same key gets `409` [`idempotency_key_reused`](/errors/idempotency_key_reused) instead of the secret. Nothing is created twice: list your endpoints and [rotate the secret](/api-reference/webhooks/rotateWebhookEndpointSecret) if you lost it.
- **Best effort.** If CallMitra's idempotency store is briefly unavailable, the request runs normally without replay protection. [WhatsApp sends](/guides/whatsapp) also keep the `Idempotency-Key` on the message permanently, so a repeated key returns the message already sent, even after 24 hours.

## Retry pattern [#retry-pattern]

Create the key once per operation, before the first attempt, and reuse it on every retry of that operation.

<Tabs groupId="language" persist items={["Node.js","Python"]}>
<Tab value="Node.js">
```js
import { randomUUID } from 'node:crypto';

async function createCampaign(payload) {
  const idempotencyKey = randomUUID();
  for (let attempt = 0; attempt < 5; attempt++) {
    try {
      const res = await fetch('https://api.callmitra.ai/api/v1/campaigns/create-with-leads', {
        method: 'POST',
        headers: {
          'X-API-Key': process.env.CALLMITRA_API_KEY,
          'Idempotency-Key': idempotencyKey,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });
      const body = await res.json();
      const inProgress = body.error?.code === 'idempotency_request_in_progress';
      if (!inProgress && res.status !== 429 && res.status < 500) return body;
    } catch {
      // Network error or non-JSON reply: safe to retry with the same key.
    }
    await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
  }
  throw new Error('Could not create the campaign');
}
```
</Tab>

<Tab value="Python">
```python
import os
import time
import uuid

import requests

def create_campaign(payload):
    idempotency_key = str(uuid.uuid4())
    for attempt in range(5):
        try:
            res = requests.post(
                "https://api.callmitra.ai/api/v1/campaigns/create-with-leads",
                headers={
                    "X-API-Key": os.environ["CALLMITRA_API_KEY"],
                    "Idempotency-Key": idempotency_key,
                },
                json=payload,
                timeout=30,
            )
            body = res.json()
            code = (body.get("error") or {}).get("code")
            if code != "idempotency_request_in_progress" and res.status_code != 429 and res.status_code < 500:
                return body
        except (requests.ConnectionError, requests.Timeout, ValueError):
            pass  # Network error or non-JSON reply: safe to retry with the same key.
        time.sleep(2**attempt)
    raise RuntimeError("Could not create the campaign")
```
</Tab>
</Tabs>

<Callout type="warn">
Only retry a `409` with the same key when its code is `idempotency_request_in_progress`. A `409 idempotency_key_reused` means your code sent a different body under an old key; fix the bug instead of retrying.
</Callout>

## If idempotency is unavailable [#if-idempotency-is-unavailable]

If CallMitra's idempotency store is briefly unavailable, the request still runs normally, without replay protection. Design receivers of [webhooks](/webhooks) to tolerate duplicates as well.

WhatsApp message sends (`POST /whatsapp/messages`) follow the same rules, and a key that already sent a message never sends a second one, even after 24 hours: the original message is returned instead. When WhatsApp is throttling or briefly unavailable the send answers `429` or `503` with `Retry-After` and nothing is delivered, so retrying with the same key sends the message.