← Blog

·

WhatsApp API integration architecture: queues, retries and idempotency

Updated on November 4, 2026

A reliable WhatsApp API integration separates two things: receiving the webhook and processing the event. The webhook endpoint only validates, stores the raw payload, enqueues it and returns 200 in milliseconds; a worker processes it later, deduplicating by message ID (wamid), because Meta retries for up to 7 days when it doesn’t get a 200 and those retries produce duplicates. Sending follows the same pattern in reverse: an outbound queue, controlled pacing and retries with backoff only for temporary errors such as 130429, 131056, 131000 and network failures.

This article is for developers who can already send a message. If you’re not there yet, start with the official WhatsApp API guide and the WhatsApp API webhooks guide.

What Meta guarantees (and what it doesn’t)

Before the design, here are the documented facts that drive each decision:

FactSourceWhat it means for your code
If the webhook doesn’t get HTTP 200, Meta retries with decreasing frequency for up to 7 daysWebhooks overviewYour endpoint must respond fast, and only once it has stored the event
Retries can produce duplicate notificationsWebhooks overviewDeduplication is mandatory
Webhook payloads can be up to 3 MBWebhooks overviewServer body limit above 3 MB
Meta changes its source IPs periodically and recommends mTLSWebhooks overviewDon’t rely on an IP allowlist alone
A message can go straight to read without deliveredStatus webhookTreat status as a state machine, not a sequence
The pricing object appears in only one of the related status webhooksStatus webhookDon’t expect billing data on every status
Message delivery order is not guaranteed to match request orderSend messagesFor strict sequences, wait for delivered before the next one
Errors should be handled by code and details, not HTTP statusError codesRetry decisions are based on the error code

The documentation does not promise webhook delivery order or a maximum response time. In practice, treat both as uncertain: respond within a few seconds and never depend on arrival order.

The overall design

# Inbound (Meta -> you)
Meta --POST--> [Webhook endpoint] --stores--> [webhook_raw]
                      |                          |
                      +--returns 200             +--enqueues id--> [Inbound queue]
                                                                          |
                                                                  [Inbound worker]
                                                                    - dedupes (wamid)
                                                                    - updates status
                                                                    - runs business rules

# Outbound (you -> Meta)
[Your system] --creates--> [outbox] --> [Outbound queue] --> [Send worker] --POST--> Graph API
                                                                |
                                                                +-- 2xx: store wamid
                                                                +-- temporary error: retry with backoff
                                                                +-- permanent error: mark failed

The components can be simple. A Postgres table with SELECT ... FOR UPDATE SKIP LOCKED already works as a queue for moderate volumes; Redis with BullMQ, RabbitMQ, SQS or Pub/Sub handle larger ones. What matters is the separation: the process that answers Meta never calls the send API, never queries the CRM and never runs AI inside the request.

Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →

Receiving the webhook: a fast 200

The endpoint does three things, in this order:

  1. Validates the signature X-Hub-Signature-256 with the App Secret, over the raw body. Step by step in WhatsApp webhook signature validation.
  2. Stores the raw payload in a table, with a received timestamp.
  3. Enqueues the record ID and returns 200.

Example in Node.js with Express and Postgres:

import express from "express";
import crypto from "node:crypto";
import pg from "pg";

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const app = express();

// raw body for the signature; limit above Meta's 3 MB
app.use("/webhook", express.raw({ type: "application/json", limit: "5mb" }));

app.get("/webhook", (req, res) => {
  const ok = req.query["hub.mode"] === "subscribe" &&
             req.query["hub.verify_token"] === process.env.VERIFY_TOKEN;
  return ok ? res.send(req.query["hub.challenge"]) : res.sendStatus(403);
});

app.post("/webhook", async (req, res) => {
  const sig = req.get("x-hub-signature-256") || "";
  const expected = "sha256=" + crypto
    .createHmac("sha256", process.env.APP_SECRET)
    .update(req.body)
    .digest("hex");
  const valid = sig.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
  if (!valid) return res.sendStatus(401);

  try {
    await db.query(
      "INSERT INTO webhook_raw (body, received_at) VALUES ($1, now())",
      [req.body.toString("utf8")]
    );
    // the worker reads webhook_raw WHERE processed_at IS NULL
    return res.sendStatus(200);
  } catch (err) {
    console.error("failed to store webhook", err);
    return res.sendStatus(500); // Meta will retry
  }
});

app.listen(3000);

Why store before responding: if you return 200 and the process dies before saving, the event is lost, because Meta doesn’t resend what got a 200. If you store and die before responding, Meta resends and deduplication handles it. Always prefer the duplicate side.

Why keep the raw payload: when a parser bug, a new Meta field or a billing discrepancy shows up, you reprocess from the original. Without it, the event only exists in the shape your code understood at the time. The raw table also becomes the basis for your conversation history, since the API offers no history lookup.

Processing: deduplicating by message id

The worker opens the payload and walks entry[].changes[].value. Inside value you may find messages[] (incoming messages) and statuses[] (statuses of your messages). Treat both as lists.

The deduplication key:

EventUnique key
Incoming messagemessages[].id (the wamid)
Status of a sent messagestatuses[].id + statuses[].status
Other fields (templates, account)Hash of value content + field

Let the database enforce uniqueness instead of “check, then insert”, which breaks with two workers running at once:

CREATE TABLE inbound_messages (
  wamid        TEXT PRIMARY KEY,
  phone_number_id TEXT NOT NULL,
  wa_from      TEXT NOT NULL,
  type         TEXT NOT NULL,
  payload      JSONB NOT NULL,
  received_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE message_status_events (
  wamid      TEXT NOT NULL,
  status     TEXT NOT NULL,
  ts         BIGINT NOT NULL,
  payload    JSONB NOT NULL,
  PRIMARY KEY (wamid, status)
);

The Python worker, with ON CONFLICT DO NOTHING deciding whether the event is new:

import json
import psycopg

RANK = {"sent": 1, "delivered": 2, "read": 3}

def process_raw(conn, raw_id, body):
    data = json.loads(body)
    for entry in data.get("entry", []):
        for change in entry.get("changes", []):
            value = change.get("value", {})
            pnid = value.get("metadata", {}).get("phone_number_id")

            for msg in value.get("messages", []):
                cur = conn.execute(
                    """INSERT INTO inbound_messages (wamid, phone_number_id, wa_from, type, payload)
                       VALUES (%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING""",
                    (msg["id"], pnid, msg.get("from", ""), msg["type"], json.dumps(msg)),
                )
                if cur.rowcount == 1:      # first time we see this wamid
                    handle_new_message(pnid, msg)

            for st in value.get("statuses", []):
                cur = conn.execute(
                    """INSERT INTO message_status_events (wamid, status, ts, payload)
                       VALUES (%s, %s, %s, %s) ON CONFLICT DO NOTHING""",
                    (st["id"], st["status"], int(st["timestamp"]), json.dumps(st)),
                )
                if cur.rowcount == 1:
                    apply_status(conn, st)

    conn.execute("UPDATE webhook_raw SET processed_at = now() WHERE id = %s", (raw_id,))

handle_new_message is where business rules live: reply, call a bot, open a CRM ticket. If that step needs to send a message, it doesn’t send directly: it creates a record in the outbound queue. That way, reprocessing never sends the same reply twice.

Status ordering: a state machine

Webhooks can arrive out of order, and delivered may never arrive if the message was already read. So don’t overwrite status with “whatever arrived last”. Use a rank and only move forward:

def apply_status(conn, st):
    new = st["status"]
    if new == "failed":
        code = (st.get("errors") or [{}])[0].get("code")
        conn.execute(
            "UPDATE outbound_messages SET status='failed', status_rank=4, error_code=%s WHERE wamid=%s AND COALESCE(status_rank, 0) < 3",
            (code, st["id"]),
        )
        return
    rank = RANK.get(new, 0)
    conn.execute(
        """UPDATE outbound_messages SET status=%s, status_ts=%s, status_rank=%s
           WHERE wamid=%s AND COALESCE(status_rank, 0) < %s""",
        (new, int(st["timestamp"]), rank, st["id"], rank),
    )

Practical rules:

  • read implies delivered. If read arrives first, count the message as delivered too.
  • failed can arrive after sent. The errors[].code field tells you why; the common ones are in WhatsApp API error codes.
  • Store pricing when it arrives, but don’t expect it on every status: Meta sends it on only one of them.
  • A status can arrive before you store the wamid returned by the send call (a race between the HTTP response and the webhook). That’s why message_status_events keeps the event even without a matching message; reapply it once you store the wamid.

What each status means is covered in WhatsApp API message status webhooks.

Sending: outbound queue, pacing and retries with backoff

Sending also goes through a queue. The outbound_messages table works as an outbox: your system records the intent to send with a unique internal key, and the worker calls the API.

CREATE TABLE outbound_messages (
  id            BIGSERIAL PRIMARY KEY,
  idempotency_key TEXT UNIQUE NOT NULL,   -- e.g. "order-8812:invoice-issued"
  phone_number_id TEXT NOT NULL,
  to_wa_id      TEXT NOT NULL,
  body          JSONB NOT NULL,
  attempts      INT NOT NULL DEFAULT 0,
  next_try_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
  wamid         TEXT,
  status        TEXT NOT NULL DEFAULT 'queued',
  status_rank   INT,
  status_ts     BIGINT,
  error_code    INT
);

The idempotency_key stops one business event from producing two messages: if the ERP fires the “invoice issued” notice twice, the second INSERT fails and nothing goes out twice.

Which errors deserve a retry

From Meta’s error table:

CodeMeaningAction
130429Number’s throughput limit reachedRetry with backoff and slow down
131056Too many messages to the same recipient in a short timeWait and retry only for that number; others keep going
4, 80007App or account call rate limitRetry with backoff and reduce volume
131000, 131016, 2Unknown error, service unavailable, temporary overloadRetry with backoff; check Meta’s status page
Timeout, connection refused, HTTP 5xx with no bodyNetwork or server failureRetry with backoff (see the caveat below)
131049Not delivered to protect engagementDon’t resend before 24 hours
131047More than 24 hours since the customer’s last messageDon’t repeat: send a template
100, 132000, 132012Wrong parameter or template mismatchDon’t repeat: fix the payload
131026Recipient can’t receive the messageDon’t repeat: use another channel
190Invalid or expired tokenPause the queue and replace the token
368Account restricted for policy violationPause the queue; retrying won’t help

Pacing and error 131056 are covered in detail in WhatsApp API rate limits and throughput.

Send worker in Python

import random, time
import requests

GRAPH = "https://graph.facebook.com/v26.0"
RETRYABLE = {130429, 131056, 4, 80007, 131000, 131016, 2}
STOP_QUEUE = {190, 368}
MAX_ATTEMPTS = 8

def backoff(attempt):
    # 2s, 4s, 8s... up to 10 min, with jitter
    return min(600, 2 ** attempt) * random.uniform(0.5, 1.5)

def send_one(conn, row, token):
    try:
        r = requests.post(
            f"{GRAPH}/{row['phone_number_id']}/messages",
            headers={"Authorization": f"Bearer {token}"},
            json=row["body"], timeout=15,
        )
    except requests.RequestException:
        return schedule_retry(conn, row, None)

    if r.ok:
        wamid = r.json()["messages"][0]["id"]
        conn.execute("UPDATE outbound_messages SET wamid=%s, status='accepted' WHERE id=%s",
                     (wamid, row["id"]))
        reapply_pending_statuses(conn, wamid)  # your function: applies statuses that arrived early
        return

    try:
        code = (r.json().get("error") or {}).get("code")
    except ValueError:  # 5xx without a JSON body
        code = None
    if code in STOP_QUEUE:
        pause_queue(row["phone_number_id"], code)  # your function: stops the queue and alerts the team
        return schedule_retry(conn, row, code, delay=3600)
    if code in RETRYABLE or r.status_code >= 500:
        return schedule_retry(conn, row, code)
    conn.execute("UPDATE outbound_messages SET status='failed', error_code=%s WHERE id=%s",
                 (code, row["id"]))

def schedule_retry(conn, row, code, delay=None):
    attempts = row["attempts"] + 1
    if attempts >= MAX_ATTEMPTS:
        conn.execute("UPDATE outbound_messages SET status='failed', error_code=%s WHERE id=%s",
                     (code, row["id"]))
        return
    wait = delay or backoff(attempts)
    conn.execute(
        """UPDATE outbound_messages SET attempts=%s, error_code=%s,
           next_try_at = now() + make_interval(secs => %s) WHERE id=%s""",
        (attempts, code, wait, row["id"]),
    )

The worker picks rows with status = 'queued' AND next_try_at <= now() using FOR UPDATE SKIP LOCKED, so several workers can run in parallel without grabbing the same message.

The timeout caveat

A send timeout is ambiguous: Meta may have accepted the message and the response got lost. If you retry, the customer may receive it twice. Three ways to reduce the risk:

  • A generous timeout (10 to 15 seconds) so slow responses aren’t cut off.
  • Few attempts for sensitive messages, such as billing, and more for notices where a duplicate is tolerable.
  • Check via webhook: use the optional biz_opaque_callback_data field on the send (up to 512 characters, returned in status webhooks) to carry your idempotency_key, so you can match a status to the record even without the wamid.

Minimum observability

Four metrics catch almost every problem before the customer does:

MetricAlert when
Age of the oldest item in the inbound queueExceeds 1 minute
Rate of non-200 responses at the webhook endpointAny sustained increase
Share of failed by code over recent hoursA new code appears or spikes
accepted messages with no status after 1 hourMore than a handful

If webhooks stop arriving, follow the WhatsApp webhook not working checklist.

Multiple numbers and multiple clients

If your integration serves more than one number, route by each event’s metadata.phone_number_id and store tokens per number, not in a global variable. Pace sending per number too, because throughput is per number. In a multi-client SaaS, this isolation becomes a requirement; the full design is in multi-tenant SaaS on the WhatsApp API.

The same architecture with Vectalk

Vectalk is a proxy for the official Cloud API. For the architecture, three details change:

  • Sending: POST https://apis.vectalk.com.br/api/messages with Authorization: Bearer and Meta’s body. With an instance token, the number is resolved from the token and you don’t put phone_number_id in the URL.
  • Receiving: you register one or more URLs per instance (POST https://apis.vectalk.com.br/api/webhooks), and all of them receive the same payload Meta sends. According to the documentation, your endpoint must return HTTP 200 in under 20 seconds; otherwise the event is resent. The “store, enqueue, return 200” pattern still applies, as does wamid deduplication.
  • Billing: each delivered message is deducted from your prepaid platform balance. Monitor the balance alongside the other metrics so the queue doesn’t stall for lack of credit.

Vectalk has no send queue or inbox in its dashboard; the queue, retries and business rules live in your system, as described here. See Webhooks in the documentation and create your account.

Frequently asked questions

How fast must the webhook respond?

Meta’s documentation doesn’t set a time; it only says any response other than 200 triggers a retry. The recommendation is to respond within a few seconds, after storing the event. On Vectalk, the documentation asks for a 200 in under 20 seconds.

How long does Meta keep retrying a webhook?

Up to 7 days, with decreasing frequency, until it gets a 200. If your server is down for a few hours, the events arrive later, possibly duplicated and out of order.

Do I need Kafka or RabbitMQ?

Not necessarily. A Postgres table with SKIP LOCKED handles moderate volumes. Switch to a dedicated queue when volume or the number of consumers grows.

Does the WhatsApp API have an idempotency key for sending?

The send documentation doesn’t describe one. Create your own: a unique key per business event in the outbound table, plus biz_opaque_callback_data to carry that key to the status webhook.

How do I deduplicate message statuses?

Use the wamid + status pair as the unique key. Each combination is applied once, and the rank (sent < delivered < read) stops an older status from overwriting a newer one.


Official sources checked on November 4, 2026: Webhooks overview (Meta), Status messages webhook reference (Meta), Error codes (Meta), Send messages (Meta), Messages reference (Meta), Webhooks in the Vectalk documentation, Sending messages in the Vectalk API.

Put your business on the official WhatsApp

Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.