# Cancel safely and never double-send

The hardest failure in messaging is not a clean error. It is a timeout where the provider may have accepted the message. This guide builds a retry policy that survives it.

## 1. Always send an idempotency key

Generate one per user action and store it with the request:

```ts
const key = `order-${order.id}-welcome`;
await fetch(`${API}/api/v2/messages`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.BONGA_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": key,
  },
  body: JSON.stringify(payload),
});
```

Retrying the same key and payload returns the original result. A different payload with the same key returns `409`.

## 2. Classify the failure

| Response | Action |
| --- | --- |
| `2xx` | Store the message ID and stop |
| `429` | Wait `Retry-After`, then retry the same key |
| `5xx` before acceptance | Retry the same key with backoff |
| `409` | Do not retry; inspect the conflict |
| `4xx` validation | Fix the request |
| Timeout | Retry the same key, then check status |

A timeout is not proof of failure. The safe move is to retry with the same key; the server returns the original result if it already accepted.

## 3. Reconcile ambiguous outcomes

If the status is `submission_unknown`, do not resend. Query the message and the provider evidence:

1. `GET /api/v2/messages/{id}`.
2. Check the delivery row and provider events.
3. If unsent, create a new attempt with a new key.
4. If accepted, keep the original.

## 4. Cancel scheduled work

A scheduled managed SMS can be cancelled before dispatch. Cancellation does not refund the daily key quota, so cancel deliberately. After dispatch, use the delivery status rather than a second send.

## 5. Test the failure

- Kill the connection after the request is sent.
- Replay the same key and confirm one message.
- Replay with a changed payload and confirm `409`.
- Run two workers concurrently with the same key.
- Simulate `429` and confirm the retry window.

## 6. Operational rules

- Store the key next to your own reference ID.
- Never generate a new key on retry.
- Alert on `submission_unknown`.
- Prefer at-least-once with idempotency over exactly-once claims.
- Log the request ID on every attempt.

## Next

- [Errors and retries](/docs/errors-and-retries)
- [Messaging API v2](/docs/messaging-api-v2)
- [API reference](/docs/api-reference)
