Idempotency
Networks drop connections. An idempotency key lets you retry a request without sending the message, or charging for it, a second time.
How it works
Send an Idempotency-Key header with a unique string you choose, up to 255 characters. A UUID is ideal.
- The first request with a key runs normally. Its response is stored for 24 hours if its status is below 500.
- A retry with the same key and the same body gets the stored status and body back, with the header
Idempotent-Replayed: true. Nothing is sent or charged again. - 5xx responses are not stored, so retrying a 5xx with the same key runs the request again. That is what you want: the first attempt did not complete.
Where it applies
| Endpoint | Idempotency-Key |
|---|---|
POST /v1/sms | Required. Without it you get 400 IDEMPOTENCY_KEY_REQUIRED. |
POST /v1/verify/start | Optional, recommended. |
POST /v1/verify/check | Optional. |
POST /v1/calls | Optional, recommended. |
When a key is reused
| Situation | Response | What to do |
|---|---|---|
| Same key, same body, first request finished | The stored response, with Idempotent-Replayed: true | Treat it as the result of your send. |
| Same key, while the first request is still running | 409 IDEMPOTENCY_IN_PROGRESS | Retry shortly with the same key. |
| Same key, different body | 422 IDEMPOTENCY_KEY_REUSED | Use a new key for a new request. |
Retrying safely
Create the key once, before the first attempt, and send the identical body on every retry. Retry network errors, 5xx responses, IDEMPOTENCY_IN_PROGRESS and 429 RATE_LIMITED (after Retry-After seconds). Do not retry other 4xx errors: fix the request instead.
import { randomUUID } from "node:crypto";
// One key per logical send, created BEFORE the first attempt and reused on every retry.
async function sendSms(payload, idempotencyKey = randomUUID()) {
for (let attempt = 1; attempt <= 4; attempt++) {
let response;
try {
response = await fetch("https://api.kpododo.com/v1/sms", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.KPODODO_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify(payload), // must be identical on every retry
});
} catch (networkError) {
// No response at all: safe to retry with the same key.
await new Promise((resolve) => setTimeout(resolve, attempt * 1000));
continue;
}
const body = await response.json();
if (response.ok) {
if (response.headers.get("Idempotent-Replayed") === "true") {
console.log("Already sent earlier, this is the stored response");
}
return body;
}
const isRetryable =
response.status >= 500 ||
response.status === 429 ||
body.code === "IDEMPOTENCY_IN_PROGRESS";
if (!isRetryable) throw new Error(`${body.code}: ${body.error}`);
const waitSeconds = Number(response.headers.get("Retry-After")) || attempt;
await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1000));
}
throw new Error("Gave up after 4 attempts");
}