WhatsApp· 7 min read

A queue between WhatsApp webhooks and your workers


Answer Meta’s webhook POST as soon as the signature checks out and the event sits in durable storage. Let separate workers do the slow part. Meta asks for a median webhook latency under 250 ms, with fewer than 1% of responses above 1 second (Meta throughput page, accessed 2026-11-02). A CRM write plus an AI model call won’t fit in that budget. The HTTP handler and the business logic belong in different processes, with a queue between them.

What the receiver does before it answers 200

  1. Check X-Hub-Signature-256 against the raw body. Meta computes it as an “HMAC-SHA256 hash, calculated using the post body payload and your app secret as the secret key” (Create a webhook endpoint). The signature verification post has the code.
  2. Split the payload into one event per message or status, and insert each one into the queue with a unique key.
  3. Answer with an empty 200. Meta’s instruction is “If the request is valid, respond with HTTP status 200.”

Whenever Meta gets a status other than 200, it retries “with decreasing frequency until the request succeeds, for up to 7 days” (webhooks overview, accessed 2026-11-02). Meta adds that “These retries can result in duplicate webhook notifications.” If the handler errors or times out, Meta retries and you receive the event again. The Meta pages cited here give no timeout in seconds, so aim for the 250 ms median and never wait for a model before returning.

Size the receiver for status traffic, which can outnumber inbound messages several times over. Meta says webhook servers “should be able to withstand 3x the capacity of outgoing message traffic” plus “1x the capacity of expected incoming message traffic.” Its example is 1,000 messages per second outbound with a 30% response rate. That comes to 3,000 status webhooks plus 300 inbound messages per second. Payloads “can be up to 3 MB” (overview), so check your framework’s body size limit.

The event key and the partition key

Each queued event carries two keys. The event key makes the insert idempotent. The partition key decides which events must run one after another.

For an inbound message, the event key is the message id, the value that starts with wamid.. A status needs the message ID plus the status value, because one outbound message can produce separate sent, delivered and read events. Insert with ON CONFLICT (event_key) DO NOTHING, which PostgreSQL describes as an option that “simply avoids inserting a row as its alternative action” (PostgreSQL INSERT). A retry from Meta then inserts nothing. The n8n idempotency post applies the same rule inside a workflow.

The partition key is the WhatsApp user on one business number. The Meta webhook pages cited here state no ordering guarantee, and out-of-order webhooks need timestamps and status ranks to sort out. Serializing per user still stops two workers from answering the same person at once.

Meta’s business-scoped user IDs (BSUIDs) look like US.13491208655302741918. “BSUIDs are scoped to individual business portfolios” and are regenerated “if a user changes their phone number”. The wa_id field “will be omitted if the phone number cannot be included” (BSUID page, accessed 2026-11-02). One workable rule is the business phone number ID, a colon, then the BSUID, falling back to wa_id when there is no BSUID. A user who appears under both identifiers lands in two partitions until you map them, which the conversation schema post handles. The number prefix also keeps clients apart in a multi-tenant setup.

Choosing the queue

All three options below deliver an event more than once in some failure cases. Your workers need the event key check whichever you pick.

Queue Claim and finish Retries and dead letter Order per user
PostgreSQL table SELECT ... FOR UPDATE SKIP LOCKED, then commit an attempts column and a dead status you maintain a claim query that only takes the oldest pending event per key
Redis Streams XREADGROUP, then XACK pending list, delivery counter, XAUTOCLAIM, a second stream for dead letters not per key by default, since the group spreads messages across consumers
Amazon SQS FIFO receive, then delete before the visibility timeout ends maxReceiveCount and a dead-letter queue message group ID, one in-flight message per group

PostgreSQL with SKIP LOCKED

If you already run PostgreSQL, a table is the queue with the fewest moving parts. “With SKIP LOCKED, any selected rows that cannot be immediately locked are skipped.” The manual warns that this gives “an inconsistent view of the data”. It also says the clause “can be used to avoid lock contention with multiple consumers accessing a queue-like table” (PostgreSQL SELECT).

Redis Streams

A consumer group hands out messages, and “Each message is served to a different consumer”. Consuming one “requires an explicit acknowledgment” through XACK. The group tracks pending messages, and XAUTOCLAIM takes over those a crashed consumer held. The deliveries counter spots messages that keep failing. Redis suggests putting them “in another stream” and notifying an administrator, which it calls its dead letter concept (Redis Streams, accessed 2026-11-02). Redis 8.8 adds XNACK to release a pending message without acknowledging it. To keep per-user order, route each partition key to a fixed stream with one consumer, for example by hashing the key into a set number of streams.

Amazon SQS FIFO

A FIFO queue gives per-user order once the partition key is the message group ID. AWS describes what happens while a message from a group is in flight. “Subsequent messages in that group are not made available until the in-flight message is either deleted or the visibility timeout expires” (SQS FIFO key terms). Deduplication covers 5 minutes, while Meta retries for up to 7 days, so keep your own event key check.

Dead letters and order conflict here. AWS warns “Don’t use a dead-letter queue with a FIFO queue if you don’t want to break the exact order of messages or operations.” It also says to “set the maxReceiveCount high enough to allow for sufficient retries”. The dead-letter queue’s retention should be longer than the source queue’s (SQS dead-letter queues). The default visibility timeout is 30 seconds, with a 12-hour maximum (SQS visibility timeout, accessed 2026-11-02).

A PostgreSQL worker in Python

The script creates the table, queues demo events and runs one worker. It uses psycopg 3 (pip install "psycopg[binary]") and reads DATABASE_URL. Run python worker.py demo once, then start python worker.py in two or more terminals.

# worker.py: DATABASE_URL=postgresql://USER:PASSWORD@HOST/DB python worker.py [demo]
import os
import sys
import time

import psycopg
from psycopg.types.json import Jsonb

MAX_ATTEMPTS = 8

SCHEMA = """
CREATE TABLE IF NOT EXISTS webhook_events (
  id            bigserial PRIMARY KEY,
  event_key     text NOT NULL UNIQUE,
  partition_key text NOT NULL,
  payload       jsonb NOT NULL,
  status        text NOT NULL DEFAULT 'pending',
  attempts      int NOT NULL DEFAULT 0,
  available_at  timestamptz NOT NULL DEFAULT now(),
  last_error    text
);
CREATE INDEX IF NOT EXISTS webhook_events_pending
  ON webhook_events (partition_key, id) WHERE status = 'pending';
"""

# Claim the oldest due event whose partition has no older pending event.
CLAIM = """
SELECT id, attempts, payload
FROM webhook_events e
WHERE status = 'pending'
  AND available_at <= now()
  AND NOT EXISTS (
    SELECT 1 FROM webhook_events older
    WHERE older.partition_key = e.partition_key
      AND older.status = 'pending'
      AND older.id < e.id)
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED
"""


def enqueue(conn, event_key, partition_key, payload):
    """Call from the receiver after the signature check, before answering 200."""
    cur = conn.execute(
        "INSERT INTO webhook_events (event_key, partition_key, payload) "
        "VALUES (%s, %s, %s) ON CONFLICT (event_key) DO NOTHING",
        (event_key, partition_key, Jsonb(payload)),
    )
    return cur.rowcount == 1  # False means Meta sent this event before


def handle(payload):
    # Your business logic: CRM write, AI agent, reply. Raise to retry.
    print("processing", payload)


def work_one(conn):
    with conn.transaction():
        row = conn.execute(CLAIM).fetchone()
        if row is None:
            return False
        event_id, attempts, payload = row
        try:
            with conn.transaction():  # savepoint, so a failed handler keeps the claim
                handle(payload)
        except Exception as exc:
            attempts += 1
            conn.execute(
                "UPDATE webhook_events SET attempts = %s, last_error = %s, status = %s, "
                "available_at = now() + make_interval(secs => %s) WHERE id = %s",
                (attempts, repr(exc), "dead" if attempts >= MAX_ATTEMPTS else "pending",
                 2.0 ** attempts, event_id),
            )
            return True
        conn.execute("UPDATE webhook_events SET status = 'done' WHERE id = %s", (event_id,))
    return True


def main():
    with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as conn:
        conn.execute(SCHEMA)
        if sys.argv[1:] == ["demo"]:
            demo = [("wamid.A", "PHONE_ID:u1"), ("wamid.B", "PHONE_ID:u1"),
                    ("wamid.C", "PHONE_ID:u2"), ("wamid.A", "PHONE_ID:u1")]
            for key, part in demo:
                print(key, "queued" if enqueue(conn, key, part, {"id": key}) else "duplicate")
            return
        while True:
            if not work_one(conn):
                time.sleep(1)


if __name__ == "__main__":
    main()

The claim only returns an event when no older pending event exists for the same partition key. While one worker holds a user’s oldest event, SKIP LOCKED hides that row from the others. The NOT EXISTS blocks the same user’s later events, so the other workers move on to different users.

A failed event stays pending with a growing delay of 2, 4, 8 seconds and so on. That user’s later events wait behind it, which keeps their order. After 8 attempts the status becomes dead and the user’s queue moves on. SELECT * FROM webhook_events WHERE status = 'dead' is your dead-letter list.

The handler runs inside the claiming transaction, so each worker holds one connection and one row lock while it works. If a worker crashes, PostgreSQL rolls the transaction back and the event becomes claimable again. A reply the handler already sent will then go out twice. Check, before sending, whether you already answered that wamid. Rows marked done pile up, so delete them on a schedule.

An event that crashes the process never reaches dead, because the rollback also undoes the attempt count. It is claimed again at once and holds back that user’s later events. Set a timeout on handle() shorter than idle_in_transaction_session_timeout on the database role, so a slow handler fails and counts before the server ends the session. If crash loops matter, claim with a committed lease (status = 'running', attempts + 1, lease_until) and requeue expired leases.

A row with a lower id can commit after a higher one, so a worker may process the later event first. Sort by the webhook timestamp when order matters.

For an n8n stack, queue mode with webhook processors applies the same split between receiving and running.

If your numbers run on Z-API Omni, webhooks are included without limit (View documentation).

Z-API Omni team