Retries and Idempotency When You Buy Numbers Through an API
A timeout is the most dangerous response an API can give. The request may have failed, or it may have succeeded and the answer got lost. If your code simply retries, it may buy a second number and charge you twice.
The problem
A buy call times out after twenty seconds. You do not know if an order exists. Retrying blindly can create a duplicate. Giving up can leave a paid order that you never read.
Safe rules
- Treat a buy timeout as unknown, not as failed.
- Before you buy again, check your own record and the provider's order list for an order made in the last few minutes.
- Keep a local order row with a unique reference before you call the API.
- Mark the row as confirmed only after the provider answers with an order ID.
- Run a small reconciliation job that finds rows stuck in the unknown state.
Which calls are safe to retry
| Call | Safe to retry? | Why |
|---|---|---|
| Read an order | Yes | It changes nothing |
| Buy a number | Only after checking | A retry may create a second order |
| Cancel an order | Yes, if you handle already cancelled | A repeat cancel should not fail your job |
| Reorder | Only after checking | It may create a new paid order |
Backoff
- Wait longer after each failure, for example one, two, four seconds.
- Add a small random delay so many workers do not retry together.
- Stop after a small number of attempts and alert a person.
Money checks
Compare your wallet balance before and after a batch. A difference you cannot explain is a bug in your retry logic and should raise an alert.
A simple reconciliation job
- Every few minutes, find local orders in the unknown state.
- Ask the provider for orders in the last hour.
- Match them by number or reference.
- Mark matches as confirmed and cancel orders you do not need.
- Alert a person for anything that does not match.
Test it before you need it
Simulate a timeout in a test and check that exactly one order exists afterward. Repeat with the provider returning an error. This is the test that saves real money.
Questions people ask
Does the API support idempotency keys?
Check the API documentation. If it does not, your local reference and reconciliation job do the same work.
How many retries are reasonable?
Two or three for reads, and none for buys until you have checked for an existing order.
Related guides and pages
Create a free OtpGet account and try it with a small balance.