# Idempotency and retries

Send an Idempotency-Key so a retried call can never run or bill twice. Exactly what happens on replays, conflicts (409) and failed attempts, and which errors to retry.

A network error after you send a call leaves you unsure whether it ran. Retrying blindly could start a second paid job. An `Idempotency-Key` header makes retries safe: the same key with the same request returns the first call's outcome instead of running again.

```bash
curl -sS -X POST "https://api.primaryapi.com/v1/run/reddit.search" \
  -H "Authorization: Bearer $PRIMARYAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 5f0c2b7e-9a41-4c1e-b7a3-2d8e61f0c9aa" \
  -d '{"query":"best mechanical keyboard","limit":25}'
```

## The key

- Any string of 1 to 255 visible ASCII characters. A random UUID per logical call is the simplest choice.
- Send exactly one `Idempotency-Key` header. A malformed key answers `400 invalid_input`.
- Keys are scoped to your **account**: every key and session of the account shares the same key space.
- A key stays bound to its request for 24 hours after the request finished, on every plan. A plan that keeps results longer doesn't lengthen it.

Generate the key **once per logical operation** and reuse it for every retry of that operation. A new key per attempt defeats the purpose.

## What counts as the same request

The fingerprint of a request is its SKU, its validated input (with schema defaults applied) and its routing controls. Leaving out a field that has a default and sending the default explicitly are the same request. The `fields`, `max_items` and `summary` query parameters and the `Prefer` header are **not** part of it, so a retry may ask for a different slice or wait time.

## What happens on a repeat

| The first request with this key… | A repeat with the same request gets | Charged again |
|---|---|---|
| Succeeded, result still stored | `200` with the stored envelope, `replayed: true`, header `Idempotency-Replayed: true`, and the original `X-Request-Id` | No |
| Is still running | `202` with the running request's snapshot. No second job starts. | No |
| Failed for a temporary reason¹ | The call runs again as a new request; the key moves to it. | Only if this run succeeds |
| Failed because of the input (for example the upstream rejected it as invalid) | The same error again, with `details.replayed: true`. Nothing runs. | No |
| Finished more than 24 hours ago, or its result was deleted | The call runs again as a new request. | Only if it succeeds |

¹ Temporary reasons: `all_sources_failed`, `timeout`, `service_unavailable`, `internal_error`, `rate_limited`, and refusals that clear once something changes on your side: `insufficient_balance`, `key_limit_reached`, `trial_cap_reached`, `key_disabled`, `key_expired`. An agent that hit `402`, waited for a top-up and retried with the same key is not stuck on the old error.

A call that carries an `Idempotency-Key` and actually runs answers with `Idempotency-Replayed: false`, so you can always tell a fresh run from a replay.

Requests rejected **before** they start (invalid input, authentication, access, restricted API) never bind the key. Fix the request and retry with the same key.

## Conflicts

The same key with a **different** request (another SKU, input or routing controls) answers `409 idempotency_conflict`, and `details.requestId` names the request the key belongs to:

```json title="409 Conflict"
{
  "code": "idempotency_conflict",
  "error": "This Idempotency-Key was already used for a different request (req_01JBXT0D2F4H6K8M0P2R4T6V8X). Use a new key for a new request.",
  "requestId": "req_01JBXT4H6K8M0P2R4T6V8X0Z2B",
  "details": { "requestId": "req_01JBXT0D2F4H6K8M0P2R4T6V8X" }
}
```

A conflict is a bug in the caller: a key was reused for new work. Do not retry it; use a fresh key. In the rare case where two requests with the same new key start at the same instant, one runs and the other gets the running request's `202`, or a `409` with `retryAfterSeconds: 1`; retrying after that second returns the outcome.

## Which errors to retry

| Retry | Codes | How |
|---|---|---|
| Yes, with backoff | `rate_limited` (429), `internal_error` (500), `all_sources_failed` (502), `service_unavailable` (503), `timeout` (504), and network errors | Same `Idempotency-Key`. Honour `Retry-After` when present; otherwise exponential backoff with jitter. |
| After you act | `insufficient_balance`, `key_limit_reached`, `trial_cap_reached` (402), `key_disabled`, `key_expired` (401), `restricted_api` (403) | Fix the cause (buy credits, raise the limit, approve), then retry. |
| No | `invalid_input` (400), `unauthorized` (401), `forbidden` (403), `not_found` (404), `idempotency_conflict` (409), `unprocessable` (422) | The same request gets the same answer. Change it. |

And never retry an `output.found: false` answer: it is a successful result.

```ts tab="TypeScript"
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export async function runWithRetries(sku: string, input: object, attempts = 5) {
  const idempotencyKey = crypto.randomUUID(); // one key for every attempt of this call
  for (let i = 0; ; i++) {
    let res: Response | undefined;
    try {
      res = await fetch(`https://api.primaryapi.com/v1/run/${sku}`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.PRIMARYAPI_API_KEY}`,
          'Content-Type': 'application/json',
          'Idempotency-Key': idempotencyKey,
        },
        body: JSON.stringify(input),
        signal: AbortSignal.timeout(20_000),
      });
    } catch (err) {
      if (i + 1 >= attempts) throw err; // network error or client timeout: safe to retry with the same key
    }
    if (res) {
      const body = await res.json();
      if (res.ok) return body; // 200 (finished) or 202 (running: poll body.requestId)
      if (!RETRYABLE.has(res.status) || i + 1 >= attempts) {
        throw new Error(`${body.code}: ${body.error} (${body.requestId})`);
      }
      const retryAfter = Number(res.headers.get('retry-after'));
      if (retryAfter > 0) {
        await sleep(retryAfter * 1000);
        continue;
      }
    }
    await sleep(Math.min(2 ** i * 500, 8_000) * (0.5 + Math.random() / 2)); // exponential backoff with jitter
  }
}
```

```python tab="Python"
import os
import random
import time
import uuid
import requests

RETRYABLE = {429, 500, 502, 503, 504}

def run_with_retries(sku: str, payload: dict, attempts: int = 5) -> dict:
    idempotency_key = str(uuid.uuid4())  # one key for every attempt of this call
    for i in range(attempts):
        last = i + 1 >= attempts
        try:
            res = requests.post(
                f"https://api.primaryapi.com/v1/run/{sku}",
                headers={
                    "Authorization": f"Bearer {os.environ['PRIMARYAPI_API_KEY']}",
                    "Idempotency-Key": idempotency_key,
                },
                json=payload,
                timeout=20,
            )
        except requests.RequestException:
            if last:
                raise
            time.sleep(min(2**i * 0.5, 8) * random.uniform(0.5, 1))
            continue
        body = res.json()
        if res.ok:
            return body  # 200 (finished) or 202 (running: poll body["requestId"])
        if res.status_code not in RETRYABLE or last:
            raise RuntimeError(f"{body['code']}: {body['error']} ({body.get('requestId')})")
        retry_after = float(res.headers.get("Retry-After", 0) or 0)
        time.sleep(retry_after or min(2**i * 0.5, 8) * random.uniform(0.5, 1))
    raise RuntimeError("unreachable")
```

## In the MCP server

`run_api` takes an `idempotencyKey` argument with the same semantics (printable ASCII without spaces). Agents should pass one whenever they might repeat a call, for example after a client timeout.
