Idempotency
Guides

WhatsApp API idempotency

Send an Idempotency-Key header with a WhatsApp API write, and a retry of the same call gets the first answer back instead of running twice.

How it works#

Add an Idempotency-Key header to any POST, PATCH or DELETE call. When SheetWA sees the same key again for the same request, it answers with the first result and does not do the work twice.

bashA send with a key
curl -X POST "https://backend.sheetwa.com/v1/messages" \
  -H "Authorization: Bearer $SHEETWA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1042-shipped" \
  -d '{"contact_id": "CONTACT_ID", "template_name": "order_update", "language_code": "en", "variables": ["Asha", "#1042"]}'

What each case answers#

  • Same key, same request

    What happens: You get the first answer again, with the header Idempotent-Replayed: true. Nothing runs twice.

  • Same key, different request

    What happens: 422 IDEMPOTENCY_KEY_REUSED. Use a new key for a new request.

  • First call still running

    What happens: 409 IDEMPOTENCY_IN_PROGRESS. Wait a moment and retry with the same key.

  • No key

    What happens: The request runs every time it is sent.

Choosing a key#

  • A key is 1 to 255 visible characters.
  • Use something tied to the action, like order-1042-shipped, or a UUID you save before the first try.
  • Send the same key on every retry of that action, and a new key for each new action.
  • Keys are kept for 24 hours, so retry within that time.

Use it on every send#

Sends reach real phones and are billed. If a send times out you cannot tell whether it went, and a retry without a key could message the customer twice. With a key, the retry is safe.

jsRetry a send safely (Node.js)
import { randomUUID } from "node:crypto";

// One key for this message, reused on every retry of it.
const key = randomUUID();

for (let attempt = 1; attempt <= 4; attempt++) {
  try {
    const res = await fetch("https://backend.sheetwa.com/v1/messages", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.SHEETWA_API_KEY}`,
        "Content-Type": "application/json",
        "Idempotency-Key": key,
      },
      body: JSON.stringify({
        "country_code": "91",
        "phone": "9876543210",
        "template_name": "order_update",
        "language_code": "en",
        "variables": [
          "Asha",
          "#1042"
        ]
      }),
    });
    const body = await res.json();
    const tryAgain = res.status === 429 || res.status >= 500 || body.error?.code === "IDEMPOTENCY_IN_PROGRESS";
    if (!tryAgain) {
      console.log(res.status, res.headers.get("Idempotent-Replayed"), body);
      break;
    }
  } catch {
    // A network error: the send may or may not have happened, so retry with the same key.
  }
  await new Promise((resolve) => setTimeout(resolve, attempt * 2000));
}