# Idempotency & retries

Path: `/guide/idempotency`
Summary: Safe retries, bulk partial success, and 429 backoff

Networks fail mid-request. The question is never *if* you retry, but *whether a retry is
safe*. PULPO gives you the tools to make retries safe — this page shows how to use them.

## Idempotency through natural keys

PULPO does not use a separate idempotency-key header. Instead it enforces **uniqueness on
business keys** — most importantly `order_num`. That turns a retry into a safe no-op:

- If the first request succeeded and you retry with the **same `order_num`**, the duplicate
  is rejected instead of creating a second order.
- If the first request never landed, the retry creates the order exactly once.

> **SUCCESS: The rule**
>
> Derive `order_num` deterministically from your source system's order id. Never
> generate it randomly per attempt. Same input → same `order_num` → at-most-once
> creation, no matter how many times you retry.

> **WARNING: Reused order_num is an error, not a duplicate**
>
> A repeat `order_num` returns a validation error (`has already been taken`). Treat "already
> taken" on a retry as **success** (the order exists), not as a failure to surface to a user.

## Retrying on 429

Rate limits are tenant-based (60–300 calls/min). A `429` response tells you exactly how long
to wait:

**Endpoint: Rate limit response** — `HTTP/1.1 429 Too Many Requests`

```json
{
"message": "rate_limit_reached",
"retry_after_seconds": 1.0
}
```

Honor `retry_after_seconds` (also sent as the `Retry-After` header), then back off
exponentially for anything that still fails. Parallelism does **not** help — it just burns
your budget faster.

**Example (Node.js):**

```js
async function requestWithRetry(url, init, attempt = 0) {
const res = await fetch(url, init);

if (res.status === 429) {
  const body = await res.json().catch(() => ({}));
  const headerWait = Number(res.headers.get("retry-after"));
  const wait = body.retry_after_seconds ?? (Number.isFinite(headerWait) ? headerWait : 2 ** attempt);
  await new Promise((r) => setTimeout(r, wait * 1000));
  return requestWithRetry(url, init, attempt + 1);
}

// Retry transient server errors with plain exponential backoff (cap the attempts).
if (res.status >= 500 && attempt < 5) {
  await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
  return requestWithRetry(url, init, attempt + 1);
}

return res;
}
```

**Example (Python):**

```python
import time, requests

def request_with_retry(method, url, attempt=0, **kwargs):
  res = requests.request(method, url, **kwargs)

  if res.status_code == 429:
      body = res.json() if res.headers.get("content-type", "").startswith("application/json") else {}
      wait = body.get("retry_after_seconds") or float(res.headers.get("Retry-After", 2 ** attempt))
      time.sleep(wait)
      return request_with_retry(method, url, attempt + 1, **kwargs)

  if res.status_code >= 500 and attempt < 5:
      time.sleep(2 ** attempt)
      return request_with_retry(method, url, attempt + 1, **kwargs)

  return res
```

> **TIP: Don't retry 4xx (except 429)**
>
> A `400`, `401`, `404` or `422` won't change on retry — the request itself is wrong. Fix it.
> Only `429` and `5xx` are worth retrying. See [errors & troubleshooting](/guide/errors) for
> what each one means.

## Bulk endpoints: partial success

Bulk endpoints can **partially** succeed — some records land, others fail. You must inspect
the response and retry only the failures, or you'll either drop good records or re-send ones
that already succeeded.

`POST /picking/bulk/orders` is the clearest example: it returns a `created[]` list of
the picklists that were created alongside an `errors[]` list of the fulfillment orders
that failed (see the `PickingCreateError` schema).

**Example (Node.js):**

```js
const res = await fetch(BASE + "/picking/bulk/orders", { method: "POST", headers, body });
const result = await res.json();

// Succeeded — do not resend these orders.
const done = new Set((result.created ?? []).map((c) => c.order_num));

// Failed — inspect why, fix, and retry ONLY these.
for (const err of result.errors ?? []) {
for (const item of err.items ?? []) {
  if (item.insufficient_stock) {
    console.warn("Short on stock:", err.order_num, item.insufficient_stock);
  }
}
}
```

> **WARNING: Not all 2xx means fully applied**
>
> A `2xx` on a bulk call does not guarantee every record was accepted. Always reconcile
> `created[]` against what you sent before treating the batch as complete.

## Webhook retries

Delivery is retried too. That's why your receiver must be idempotent — the same event can
arrive more than once. The receiver side is covered in
[receiving webhooks](/guide/receiving-webhooks).

---

Website version: https://connect.pulpo.co/guide/idempotency
Whole guide in one file: https://connect.pulpo.co/llms-full.txt
Index of all pages: https://connect.pulpo.co/llms.txt
