# Retry writes safely

> Use idempotency keys so a retried send or change never runs twice.

A network failure can hide whether a write ran. Without protection, retrying a
send can deliver the same WhatsApp message twice. Send an `Idempotency-Key`
with each write and reuse it when you retry: Polymorfa runs the write at most
once and tells you what happened to the first attempt.

This page shows how to use keys in your integration. For every method that
accepts a key and what each repeat returns, see
[Idempotent requests](https://docs.polymorfa.com/api/idempotent-requests).

## Choose a key for each write

Give every logical write its own key, and derive it from something your system
already knows about that write:

- An order event that triggers a message: `order-1042-shipped`.
- A queued job: the job ID.
- A one-off action with no natural ID: a UUID that you store before you send.

Store the key with the job before the first attempt. A process that restarts
and retries the job then sends the same key. Never reuse a key for a different
message or change: Polymorfa rejects it with `422 idempotency_conflict`.

Messaging writes and campaign lifecycle requests on both APIs retain a key for
one hour. Other Platform metadata receipts keep their documented windows. A key
is bound to its credential and `Polymorfa-Version`; use both again on a retry.

## Send the key

```bash cURL
curl https://api.polymorfa.com/messaging/support/messages/send \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Idempotency-Key: order-1042-shipped" \
  -H "Content-Type: application/json" \
  -d '{"conversation":{"phoneNumber":"+15550001111"},"content":{"text":"Your order shipped."}}'
```

```typescript TypeScript
await messaging.messages.send(
  "<number-id>",
  { conversation: { phoneNumber: "+15550001111" }, content: { text: "Your order shipped." } },
  { idempotencyKey: "order-1042-shipped" },
);
```

```bash Graph API
# On the Graph API, only template creation and deletion take a key.
curl -X POST "https://api.polymorfa.com/graph/whatsapp/v26.0/$WABA_ID/message_templates" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Idempotency-Key: order-update-template-1" \
  -H "Content-Type: application/json" \
  -d '{"name":"order_update","language":"en_US","category":"UTILITY","components":[{"type":"BODY","text":"Your order has shipped."}]}'
```

*TypeScript:*

The SDK retries a write only when it has a key. Message sends, reactions,
edits, deletes, channel reactions, campaign create, launch, pause, resume and
stop, webhook tests and operation cancels create a random key for each call when you pass none, so
their automatic retries are safe within that call. Pass your own key so a
restarted process also reuses it. See
[Retries in the SDK](https://docs.polymorfa.com/development/error-handling#sdk-retries).

Platform webhook, customer, event replay, delivery retry, operation cancel and
BanSafe incident writes require the header. Without it they return `400`.

**Graph API:** Meta Cloud API Numbers: Partly supported. Linked Devices Numbers: Partly supported.

Graph message sends accept an `Idempotency-Key`. A Hybrid Number requires it and
returns `400` without it. Reuse the same key after an uncertain Hybrid send and
do not switch transport to retry. Graph template creation and deletion
[accept an optional key](https://docs.polymorfa.com/api/idempotent-requests#messaging-writes) and need a
Meta Cloud API Number.

## Handle the answer to a retry

When you retry with the same key, read the result before you act on it.

| You receive | It means | Do this |
| --- | --- | --- |
| A normal success | The first attempt never reached Polymorfa, or this is a write that stores its result | Continue. |
| `503 idempotency_replay_unavailable` | The first request finished, but exact replay data is unavailable | Keep the same key and read events or the resource. The write is not executed again. |
| `409 idempotency_in_progress` | The first attempt is still running | Wait for `Retry-After`, then retry with the same key. |
| The first attempt's server error, with `Idempotent-Replayed: true` | The first attempt may have run | Check events before you decide anything. Do not change the key. |
| `409 idempotency_outcome_unknown` | Polymorfa did not record the first attempt's outcome | Check events or the resource. Use a new key only if the write did not happen. |
| `422 idempotency_conflict` | The key was used for a different request | Fix the bug that reused the key. Use a new key for the new write. |

An error alone does not prove nothing ran. Only refusals known to precede
execution allow another attempt with the same key after fixing the cause.
Never switch keys merely to bypass a recorded or unknown outcome.

Graph template writes return these outcomes in Meta's error object, with the
Polymorfa code, such as `idempotency_completed`, in the `X-Polymorfa-Error-Code`
header. After an uncertain result, list the templates before you write again.

## Recover a lost response

Opaque message and campaign response bodies are not retained by default. A
completed request with unavailable replay data returns
`503 idempotency_replay_unavailable`. To recover a lost result:

1. Keep the first response whenever you receive it, and store the message ID
   with your job.
2. If the response was lost, match the
   [`message.sent`](https://docs.polymorfa.com/api/events#message-sent) or
   [`message.failed`](https://docs.polymorfa.com/api/events#message-failed) event to
   your job.
3. If neither event arrives, the outcome stays unknown. Use the available
   delivery evidence to decide whether any next step is safe. Do not change keys
   merely to bypass the uncertainty.

Audience and campaign recipient writes are the exception: a repeat returns the
stored result. See
[Audience and recipient writes](https://docs.polymorfa.com/api/idempotent-requests#stored-result-writes).

## Deduplicate on your side too

Idempotency keys protect your requests to Polymorfa. They do not protect your
webhook handler. Webhook delivery is at least once, so store each event's `id`
and skip an event you already processed. See
[Handle retries and duplicates](https://docs.polymorfa.com/development/webhooks/quickstart#handle-retries-and-duplicates).

## See also

- [Idempotent requests](https://docs.polymorfa.com/api/idempotent-requests)
- [Handle errors](https://docs.polymorfa.com/development/error-handling)
- [Errors](https://docs.polymorfa.com/api/errors#idempotency-conflict)
