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

# Idempotency

> Retry POST requests safely with the Idempotency-Key header

Network failures leave you in the worst spot on a write: you don't know whether the request took effect. Retrying blindly risks creating a duplicate candidate or sending an interview invite twice. The v2 API solves this with the standard `Idempotency-Key` request header: send the same key on a retry and, when the operation's successful response is JSON under 100KB, the API runs it **at most once**.

## How it works

Attach an `Idempotency-Key` header to any `POST` request:

```bash theme={null}
curl -X POST https://api.classet.ai/v2/candidates \
  -H "X-API-KEY: $CLASSET_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: create-jordan-rivera-20260707" \
  -d '{
    "first_name": "Jordan",
    "last_name": "Rivera",
    "email": "jordan.rivera@example.com",
    "job_id": "k7Hq2xVbN",
    "send_sms": true
  }'
```

The first request with a given key executes normally and, when it succeeds with a JSON body under 100KB, its response is recorded. Any later `POST` carrying the **same key** within the retention window doesn't re-execute — it gets the recorded status and JSON body back, with an extra header marking it as a replay:

```
HTTP/1.1 201 Created
Idempotency-Replayed: true
```

* **Only `POST` requests** are affected. The header is ignored on `GET`/`PATCH`/`PUT`/`DELETE`.
* **Without the header, nothing changes** — POSTs behave as before (at-least-once under retries).
* Idempotency runs **after** authentication and rate limiting: a replay never bypasses either check, and a rate-limited retry still counts against your request budget.

## Key rules

| Rule | Detail |
| - | - |
| Length | **1–255 characters.** Anything outside that range is rejected with `400 bad_request` before the handler runs |
| Scope | Keys are scoped to your **organization** and bound to the **endpoint** they were first used on — reusing a key on a *different* endpoint is rejected with `422 unprocessable` |
| Uniqueness | Use a fresh, unique key per logical operation — a UUID (`crypto.randomUUID()`) is the safe default |
| Reuse | Reuse a key **only** to retry the exact same request. Sending a *different* body with an old key replays the old response — the new body is ignored |

> [!WARNING]
>
> Keys are unique across your whole organization, so never derive them from something that can repeat across operations (like a bare candidate email). Prefix them (`send-interview-{candidateId}`) or use UUIDs. If a key is reused on a different endpoint, the API rejects it with `422 unprocessable` rather than replaying the wrong response.

## Replay semantics

| Situation | What you get |
| - | - |
| First request with a key | Executes normally; a `2xx` JSON response under 100KB is stored |
| Retry after the original returned a `2xx` that is **not JSON or over 100KB** | Re-executes. Nothing was stored, so the key gives no replay protection for that response |
| Retry after the original **completed** | The stored status + JSON body, replayed verbatim, with `Idempotency-Replayed: true` |
| Retry while the original is **still in flight** | `409` with `code: "conflict"` — wait briefly and retry with the same key |
| Retry after the original returned a **`4xx` or `5xx`** | Re-executes. Error responses are **never cached** — the stored key is discarded so a corrected or transiently blocked request gets a clean attempt |
| Same key sent to a **different endpoint** | `422` with `code: "unprocessable"` — a key is bound to the endpoint it was first used on |

The concurrent-conflict body looks like:

```json theme={null}
{
  "error": "A request with this Idempotency-Key is already in progress",
  "code": "conflict",
  "request_id": "9f6a2c1e-4b3d-4a8e-9f2a-7c1d0e5b6a3f"
}
```

Treat this `409` like a short-lived `429`: back off for a second or two, then retry with the **same** key. Once the first request finishes you'll get its replayed response.

### What's stored, and for how long

* **Retention is 24 hours.** After that a key expires and the same key would execute a fresh request. Retry loops operate on the scale of seconds to minutes, so this is ample — don't rely on keys for long-term dedupe.
* **Only JSON bodies up to 100KB are stored.** A response that is larger or isn't JSON is not stored at all: the key is released, and a retry with the same key re-executes the handler. In practice every v2 write response is JSON and well under the cap.
* Only successful `2xx` outcomes are cached. `4xx` and `5xx` outcomes discard the stored key so later attempts can be evaluated again.
* Idempotency is best-effort by design: if the idempotency store itself is briefly unavailable, your request still executes (without replay protection) rather than failing.

## Using the TypeScript SDK

Every write method on [`@classet/api-client`](/docs/guides/sdk-and-code-samples) accepts a trailing options object with `idempotencyKey`. Supplying it sends the header, and on a `POST` it also unlocks automatic retries — the SDK never retries a write it cannot prove is safe. Because server-side idempotency covers `POST` only, a key on `PATCH`/`PUT`/`DELETE` is still sent but does not enable retries:

```ts theme={null}
import { ClassetClient } from '@classet/api-client';
import { randomUUID } from 'node:crypto';

const classet = new ClassetClient({ apiKey: process.env.CLASSET_API_KEY! });

// Create + send — retried automatically on 429/503/5xx, never double-sent
const { data: candidate } = await classet.candidates.create(
  {
    first_name: 'Jordan',
    last_name: 'Rivera',
    email: 'jordan.rivera@example.com',
    phone: '+15125550199',
    job_id: 'k7Hq2xVbN',
    send_sms: true,
  },
  { idempotencyKey: randomUUID() },
);

// Works on every write method the same way
await classet.candidates.sendInterview(
  candidate.candidate_id,
  { send_sms: true },
  { idempotencyKey: `send-interview-${candidate.candidate_id}` },
);
```

If you manage retries yourself, generate the key **once per logical operation** — outside the retry loop — so every attempt carries the same key:

```ts theme={null}
const key = randomUUID(); // once, before retrying starts

let atsRetried = false;
for (let attempt = 0; attempt < 3; attempt++) {
  const res = await fetch('https://api.classet.ai/v2/candidates', {
    method: 'POST',
    headers: {
      'X-API-KEY': process.env.CLASSET_API_KEY!,
      'Content-Type': 'application/json',
      'Idempotency-Key': key,
    },
    body: JSON.stringify(payload),
  });

  if (res.ok) {
    if (res.headers.get('Idempotency-Replayed') === 'true') {
      console.log('replayed — the first attempt had already succeeded');
    }
    break;
  }
  if (res.status === 409) {
    // 409 is also a duplicate candidate, which never clears. Retry only the
    // in-flight-key case (a text match until it gets its own code).
    const body = await res.json();
    if (!String(body.error).includes('already in progress')) break;
  } else if (res.status === 503 || res.status === 502) {
    const body = await res.clone().json().catch(() => null);
    if (body?.code === 'service_unavailable') {
      if (res.status === 503 || atsRetried) break; // 503: permanent; 502: one retry only
      atsRetried = true;
    }
  } else if (![429, 500, 504].includes(res.status)) {
    break; // client error — don't retry
  }
  await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
}
```

## Repeats without a key

`force_create` skips the duplicate check, so a client that sets it on every create and re-posts after an error would make a new candidate, and start a new interview, on every retry. Two rules stop that whether or not you send an `Idempotency-Key`. Both look back 12 hours on the same job.

* **A repeated create returns the existing candidate.** If the API created a candidate for the same person in the last 12 hours, `POST /v2/candidates` with `force_create: true` returns that candidate with `200` and `data.replayed: true`, in place of `201`. No candidate is created.
  * "The same person" means the same phone, email and name. Two people who share a phone are two candidates.
  * `data.interview_status` is the candidate's interview status: `not_sent`, `in_progress` or `completed`. `data.call_id` is the call the candidate already has.
  * If your request asks for outreach and that candidate was never contacted (the first create had no send flags, or its send failed), the outreach is started on the existing candidate and `interview_status` is `in_progress`. You are never told "replayed" for a send that did not happen.
  * `POST /v2/calls` works the same way for a phone number and name, with or without `force_create`.
* **One outreach per destination per job.** A request that would text or call a phone number, or email an address, that was contacted in the last 12 hours through another candidate record returns `409` with `code: "recently_contacted"`. Nothing is created or sent. `Retry-After` and `data.retry_at` say when a send is accepted again. To add the record without contacting them, create it without send flags.

After 12 hours `force_create` creates a new candidate again, as documented. A candidate created by an ATS sync or a careers-page application is never returned as a replay: `force_create` on top of one still creates.

Two requests for the same person on the same job sent at the same moment are handled one at a time: the second gets `409` with `code: "request_in_progress"` and `Retry-After: 2`, and on retry it sees what the first one did. This is best-effort (if the lock store is unreachable the requests run unprotected), so an `Idempotency-Key` is still the guarantee. The `Idempotency-Replayed` header is set only for a key-based replay, not by these rules.

## When to use it

* **Always** on interview-sending POSTs (`POST /v2/candidates` with send flags, `POST /v2/candidates/:id/interview`) — a double-send reaches a real person and burns an invite slot.
* On any POST issued from a job queue, webhook handler, or cron that might redeliver.
* Whenever you retry a `5xx` on a write — see [Error handling](/docs/guides/error-handling.md#retrying-transient-failures).

## Quick rules

* One fresh key (UUID) per logical operation; same key on every retry of it.
* Keys are org-unique and endpoint-bound — reuse on a different endpoint gets a `422`.
* `409 conflict` whose `error` says `already in progress` = original still running; wait and resend the same key. Any other `409` is not a key conflict. Matching the text is a stopgap until the in-flight case gets its own `code`.
* Replays carry `Idempotency-Replayed: true`; `5xx` outcomes never replay.
* Keys expire after 24 hours — they're for retry windows, not permanent dedupe.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.