# Retrying an SMS send without sending it twice

> How idempotency keys make a send safe to retry, what a retry returns, how the cost hold works, and which send errors to retry and which never to.

Source: https://sms.bweze.com/guides/retry-sms-safely/ · Updated 2026-11-19

Some failures leave you unsure whether a message went out. Your request times out, or the connection drops before the response arrives, and you cannot tell whether BWEZE took the message. Send it again without a key and the user may get two codes, and you pay for both. An idempotency key makes the retry safe.

## Idempotency keys

`POST /v1/messages` takes a key in an `Idempotency-Key` header, or as `idempotencyKey` in the body:

```bash
curl -X POST https://api.bweze.com/v1/messages \
  -H "authorization: Bearer bw_sk_..." \
  -H "content-type: application/json" \
  -H "Idempotency-Key: signup-4821" \
  -d '{ "to": "+250788123456", "template": "Your code is {{code}}", "data": { "code": 4821 } }'
```

What BWEZE does with the key:

| You send                            | BWEZE answers                                                                   |
| ----------------------------------- | ------------------------------------------------------------------------------- |
| A key it has not seen               | The send, as usual                                                              |
| The same key with the same content  | The first result, with `replayed: true`. Nothing is sent again or charged again |
| The same key with different content | `409 idempotency_key_reuse_mismatch`                                            |

The docs ask for a key on every call that changes something, and a send is one.

## Choosing a key

A key belongs to one message. Every attempt to send that message carries it.

- **Make it once,** when you decide to send, before the first attempt. Keep it with the message until the message goes out.
- **Reuse it unchanged** on every retry, with the same content. A retry that renders the template again with a new code is different content, and gets `409 idempotency_key_reuse_mismatch`.
- **Make a new one for a new message.** A user who asks for a second code gets a second key. With the old key, the send returns the first result and sends nothing.

The [quickstart](https://docs.bweze.com/docs/quickstart) keys each sign-in code by the phone number and the moment the code was issued, `otp-${phone}-${issued.sentAt}`. That moment does not change between attempts, so every retry of the code carries the same key. A key made from the time of the attempt, or a random value made on each attempt, would send the code again.

## Timeouts

Set a timeout on your own HTTP client, so a stuck request does not hold up the person waiting for the code. When it fires, you do not know whether the message went out. Retry with the same key. If BWEZE already sent the message, you get the first result back with `replayed: true` and nothing is sent again. Either way the message goes out once.

The same applies when the connection drops, or when your process restarts in the middle of a send. This is why the key has to be stored with the message and not made inside the function that sends it.

## The cost hold

What a send can spend is your available balance: the wallet, plus this month's plan credit left, minus what is already committed. Each SMS send holds its cost for a moment, so two sends at once can never spend the same money.

- A send the available balance cannot cover is refused with `402 insufficient_balance`. Nothing is charged, and an SMS send never takes the wallet below zero.
- A retry with a key BWEZE has seen returns the first result and charges nothing.

So a keyed retry never adds a charge. You pay 15 RWF per segment for the message that went out, once.

## Failures to retry

The [error codes](https://docs.bweze.com/docs/errors) page says for every code whether a retry can help. _Later_ means wait and back off.

| Failure                                        | Retry                                                                                                   |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| No response: a timeout or a dropped connection | Yes, with the same key                                                                                  |
| `503 messaging_unavailable`                    | Later, with the same key, so the message goes out once                                                  |
| `500 internal_error`                           | Later, with the same key. If it keeps happening, write to hello@bweze.com with the time and the request |
| `401 rate_limited`                             | After the minute. A token can make 300 requests a minute                                                |
| `402 insufficient_balance`                     | After a top-up, not on a timer                                                                          |

Back off between attempts, waiting longer each time, and give up after a few. A sketch in Node:

```js
const RETRY_LATER = new Set(['messaging_unavailable', 'internal_error']);

// key: made once for this message, before the first attempt
async function sendSms(message, key, attempts = 4) {
  let last;
  for (let i = 0; i < attempts; i++) {
    if (i > 0) await new Promise((r) => setTimeout(r, 1000 * 2 ** i));
    let res;
    try {
      res = await fetch('https://api.bweze.com/v1/messages', {
        method: 'POST',
        headers: {
          authorization: `Bearer ${process.env.BWEZE_API_KEY}`,
          'content-type': 'application/json',
          'Idempotency-Key': key,
        },
        body: JSON.stringify(message),
        signal: AbortSignal.timeout(10_000), // your own limit
      });
    } catch (err) {
      last = err; // no answer: it may or may not have gone out, so retry
      continue;
    }
    const json = await res.json();
    if (res.ok) return json; // 200 sent or 202 queued
    if (!RETRY_LATER.has(json.error.code)) throw json.error;
    last = json.error;
  }
  throw last;
}
```

You do not retry around a carrier outage yourself. Carrier failover is automatic: if a carrier bind is down, sends route through the surviving carrier.

## Failures never to retry

These fail again however long you wait. Change the request, the token or the account first.

| Failure                                                           | What has to change first                                                |
| ----------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `409 recipient_opted_out`                                         | The recipient texted STOP. They have to opt back in, with TUMA or START |
| `400 invalid_recipient`, `empty_body`, `message_too_long`         | The number or the text                                                  |
| `messaging_rejected` (4xx)                                        | The message: the SMS gateway refused it, and `message` says why         |
| `409 idempotency_key_reuse_mismatch`                              | Your keys: a new message needs a new key                                |
| Token errors such as `token_expired` or `token_permission_denied` | The token                                                               |

A loop that retries these spends requests against the rate limit and sends nothing. [SMS API errors](/guides/sms-errors/) explains each code and what your code should do about it.

## The full reference

The [messaging docs](https://docs.bweze.com/docs/messaging#idempotency) cover idempotency and failure modes, and [billing](https://docs.bweze.com/docs/billing#your-available-balance) covers the available balance and holds. The [API reference](https://docs.bweze.com/docs/api#conventions) has the rate limit and the `replayed` field.

## Sources

- [BWEZE docs: Messaging (idempotency, failure modes)](https://docs.bweze.com/docs/messaging)
- [BWEZE docs: API reference (conventions)](https://docs.bweze.com/docs/api)
- [BWEZE docs: Error codes](https://docs.bweze.com/docs/errors)
- [BWEZE docs: Billing (available balance)](https://docs.bweze.com/docs/billing)
- [BWEZE docs: Quickstart](https://docs.bweze.com/docs/quickstart)
