> For the complete documentation index, see [llms.txt](https://developer.esw.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/best-practices/idempotency-and-retries.md).

# Idempotency and Retries

Retry ESW API calls without duplicates: dedup keys, duplicate responses, recipes.

Networks fail in the middle of requests. When a call times out or returns a `5xx`, you do not know whether ESW processed it. Retrying blindly can create a second package, fulfil a second unit, or cancel more than you meant to. Never retrying loses work.

An operation is **idempotent** when sending it twice has the same effect as sending it once. This page tells you, for each ESW API, which calls are naturally idempotent, which field ESW uses to detect a duplicate, and what to do before you resend.

{% hint style="info" icon="robot" %}
**For AI coding agents:** follow this page whenever a write call fails, times out, or returns an ambiguous response. If a call is not listed here, treat it as non-idempotent and read state before resending.
{% endhint %}

## The four rules

1. **Know the call's class before you retry it.** Reads are always safe. Writes are safe to retry only when they carry a key ESW deduplicates on, or when they fully replace state.
2. **One key per logical action, reused across its retries.** When you generate an identifier for an action, such as a `transactionReference` or a `packageReference`, store it before you send. Send the same value on every retry of that action. Generate a new one only for a new action.
3. **On a timeout or `5xx` for a write, read before you resend.** Look up the resource. If the first attempt landed, stop. Resend only if it did not.
4. **Never retry a client error unchanged.** `400`, `403`, `404`, `409`, and `422` mean the request itself is the problem, or the action already happened. Fix the request or read current state.

## Backoff

| Response                          | Retry?                  | Delay                                                          | Max attempts |
| --------------------------------- | ----------------------- | -------------------------------------------------------------- | ------------ |
| `401`                             | Once, after a new token | Immediately                                                    | 1            |
| `429`                             | Yes                     | Wait `Retry-After` (default 5 s), up to 60 s, with jitter      | 5            |
| `500`, `502`, `503`               | Yes, after rule 3       | Exponential from 1 s, capped at 30 s, plus up to 1 s of jitter | 3            |
| Timeout, no response              | Yes, after rule 3       | As for `5xx`                                                   | 3            |
| `400`, `403`, `404`, `409`, `422` | No                      | —                                                              | 0            |

```js
const delay = (attempt) => Math.min(1000 * 2 ** attempt, 30_000) + Math.random() * 1000;
```

Jitter stops many clients retrying at the same moment after an outage.

## Outbound calls: what to do per API

| API and call                                      | Class              | Deduplication key                             | What a duplicate returns                                                                                            | Safe retry recipe                                                             |
| ------------------------------------------------- | ------------------ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| **Pricing Advisor**, all `GET`s                   | Read               | —                                             | Same data                                                                                                           | Retry freely                                                                  |
| **Inventory**, availability                       | Read               | —                                             | Same data                                                                                                           | Retry freely                                                                  |
| **Order**, Get Order                              | Read               | —                                             | Same data                                                                                                           | Retry freely                                                                  |
| **Checkout**, PreOrder                            | Write              | `retailerCartId`                              | `400` with code `360` `InvalidCartIdAlreadyExists`                                                                  | See [PreOrder](#preorder)                                                     |
| **Order**, create                                 | Write              | `brandOrderReference`, `transactionReference` | Not documented                                                                                                      | See [Order create](#order-create)                                             |
| **Order**, `LineItemActivity` and `OrderActivity` | Irreversible write | `transactionReference`                        | Not documented                                                                                                      | See [Order activities](#order-activities)                                     |
| **Package**, create                               | Write              | `packageReference`                            | `409`, code `333` `PackageNotCreatedAsAlreadyExists`                                                                | Resend the same body. Treat `409` as "already created" and `GET` the package  |
| **Package**, update (`PUT`)                       | Replace            | Package reference in the path                 | Same result. `409` if the package is no longer updatable                                                            | Resend the same body. On `409`, `GET` the package                             |
| **Package**, delete                               | Write              | Package reference in the path                 | `404` or code `328` `PackageNotFound`                                                                               | Treat "not found" after a timed-out delete as done, after a `GET` confirms it |
| **Customs Catalog**, update products              | Replace            | Product record                                | Same result. The full record overwrites the stored one                                                              | Resend the same full record                                                   |
| **Fulfillment**, Pick & Pack confirm              | Write              | `confirmationId`                              | Not documented                                                                                                      | See [Pick & Pack](#pick-and-pack-confirmation)                                |
| **Returns**, create or update return              | Write              | Order and articles                            | `UndeliverableReturns` codes `2` and `3` ("already exists", "already returned"); `UpdateReturn` codes `5`, `7`, `8` | Treat "already" codes as done. Read the return order before changing anything |

### PreOrder

`retailerCartId` must be unique per cart. A PreOrder does not create an order, it opens a checkout session, so a stray duplicate is low risk.

1. On a timeout, resend the same body with the same `retailerCartId`.
2. If you get code `360`, the first request was accepted, but you do not have its `redirectUrl`. Send a new PreOrder for the same cart with a new `retailerCartId`, and record that the old one was abandoned.
3. Do not construct a checkout URL yourself.

### Order create

`202 Accepted` means ESW received the request, not that it created the order.

1. Generate `transactionReference` once for this create and store it with `brandOrderReference`.
2. On a timeout or `5xx`, do not resend yet. Poll `GET /api/v2/Order/{brandOrderReference}` every 2 seconds for up to 2 minutes.
3. If the order appears, stop. The first attempt worked.
4. If it is still `404` after 2 minutes, resend with the **same** `brandOrderReference` and `transactionReference`.

### Order activities

Fulfil and cancel activities are irreversible. They are also **quantity-based**, which makes blind retries dangerous. If a line has 2 units and your first `Fulfil` for quantity 1 landed, a resent one can fulfil the second unit too.

1. Generate `transactionReference` once for the activity and store it.
2. On a timeout or `5xx`, read the order. Count the line's articles by status: `Created`, `Shipped`, `Cancelled`.
3. If the counts already reflect your activity, stop.
4. Resend only if they do not, with the **same** `transactionReference`.
5. A cancel also starts a refund of any pre-authorized payment. Never resend one without step 2.

### Pick and Pack confirmation

For a `TimeOut` or `TransientError` result, retry with the **same** `confirmationId` and `eswOrderReference`. Never generate a new `confirmationId` for a retry. Use a new one only for a separate event, such as the final result after `AcceptedForProcessing`. A confirmation that reports a cancelled item triggers a refund, so check the order's status before resending one that contains cancellations. Do not retry a `BadAddress` or `_3PLNotConfigured` failure unchanged. See [Response Status and Failure Reasons](https://developer.esw.com/fulfillment-api/fulfillment-api/concepts/response-status-and-failure-reasons).

## Inbound: webhooks ESW sends you

ESW retries deliveries it could not complete, and may deliver the same event more than once. Your handlers must be safe to run twice.

### Order Confirmation

| Mode                  | Deduplication key                                   | Retries                                                                            |
| --------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------- |
| Synchronous (default) | None supplied. Use `RetailerCartId`                 | Three times, after 1.25, 1.5, and 2 seconds                                        |
| Asynchronous          | `Idempotency-Key` header, the same on every attempt | Three times over about two minutes, then ESW cancels the order and issues a refund |

`Esw-Delivery` is unique **per attempt**. Use it for logging, never for deduplication.

A safe handler:

1. Authenticates the request.
2. Reads the key: `Idempotency-Key` if present, otherwise `RetailerCartId`.
3. If it has already processed that key, returns the **same** success response, including the same `orderNumber`, without creating anything.
4. Otherwise creates the order and records the key and response **in one atomic operation**, so two overlapping deliveries cannot both create it.
5. Returns `2xx` quickly. A `4xx` or `5xx` marks the shopper's order as canceled.

```js
app.post("/eventSink", async (req, res) => {
  if (req.get("Authorization") !== process.env.ESW_WEBHOOK_AUTH) return res.sendStatus(401);

  const key = req.get("Idempotency-Key") ?? `sync:${req.body.RetailerCartId}`;

  // insertIfAbsent must be atomic, for example a unique index on `key`.
  const record = await idempotencyStore.insertIfAbsent(key, async () => ({
    orderNumber: await createOrderInYourSystem(req.body),
  }));

  res.status(200).json({ orderNumber: record.orderNumber });
});
```

### Other events

The same pattern applies to order, cancellation, appeasement, and return events. Expect duplicates and out-of-order delivery. Key on the event's own identifiers, and make each handler compare against current state rather than assuming events arrive in sequence. See [Webhooks best practices](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/best-practices/webhooks.md).

## Checklist

* [ ] Every write stores its identifier before it is sent, and reuses it on retry
* [ ] Timeouts and `5xx` on writes trigger a read before any resend
* [ ] Order activities compare article counts before resending
* [ ] `400`, `403`, `404`, `409`, and `422` are never retried unchanged
* [ ] `429` honors `Retry-After`; all retries use capped exponential backoff with jitter
* [ ] Webhook handlers deduplicate on `Idempotency-Key` or `RetailerCartId`, atomically
* [ ] Duplicate webhook deliveries return the same response as the first


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/best-practices/idempotency-and-retries.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
