# WhatsApp webhooks arrive out of order: how to sequence them

> Why WhatsApp webhooks reach you out of order, how to sort them by timestamp and status rank, and a tested debounce for users who send bursts.

Published 2026-11-02. Z-API Omni team.

Don't process WhatsApp webhooks in the order they reach your server. Sort inbound messages by the `timestamp` inside each message and rank status updates so they only move forward. Then hold a user's messages for a few seconds of silence before your agent answers. Meta's webhook documentation promises delivery with retries and nothing about order, so build every handler to accept events late, twice or in a batch.

## Why arrival order is not event order

Three documented behaviours break ordering. The first is retries. When your endpoint does not return 200, Meta "retries delivery with decreasing frequency until the request succeeds, for up to 7 days" ([webhooks overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)). A message that failed at 14:02:10 can be redelivered after the one the user sent at 14:02:12.

The second is batching. Webhook POSTs "are aggregated and sent in a batch with a maximum of 1000 updates. However, batching cannot be guaranteed" ([Create a webhook endpoint](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). Two messages can share one request or travel in two, and you cannot tell in advance which.

The third is outbound order. "When sending a series of messages, the order in which messages are delivered is not guaranteed to match the order of your API requests" ([send messages](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages)). Meta's fix for your own sends is to wait for a `delivered` status before you send the next message.

Your stack adds a fourth. Queue-mode n8n, serverless functions and worker pools run requests in parallel, so a short message can finish before a long one with media.

## Order inbound messages by their timestamp

Every object in the `messages` array has a `timestamp`, a string of Unix seconds ([messages webhook reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages)). Save it on every inbound row and sort by it, never by your insert time.

Two limits apply. The resolution is one second, and a user who types fast sends two messages inside the same second. Break ties with your own arrival sequence. And Meta's text message reference describes the field as "Unix timestamp indicating when the webhook was triggered" ([text messages reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text)). Use it to order messages, and don't read it as the moment the user pressed send.

```sql
CREATE TABLE inbound_messages (
  wamid       text PRIMARY KEY,
  wa_id       text    NOT NULL,
  msg_ts      bigint  NOT NULL,          -- messages[].timestamp
  arrival_seq bigserial,                 -- tie-breaker within the same second
  body        jsonb   NOT NULL,
  answered    boolean NOT NULL DEFAULT false
);

SELECT wamid, body
FROM inbound_messages
WHERE wa_id = $1 AND NOT answered
ORDER BY msg_ts, arrival_seq;
```

The primary key on `wamid` turns Meta's retried duplicates into conflicts. Ignore them with `ON CONFLICT DO NOTHING`. [Duplicate webhooks in n8n](/academy/articles/n8n-duplicate-webhooks-idempotency/) has that pattern in full. On coexistence numbers, an `unsupported` 131060 placeholder can share its `wamid` with the real message that follows. Update a placeholder row instead of ignoring the conflict; see [the 131060 article](/academy/articles/whatsapp-coexistence-131060-unsupported-message-same-wamid/).

## Rank status updates so they only move forward

Status webhooks for your outbound messages have the same problem with a different fix. A `read` can reach you before the `sent` it follows, and Meta skips `delivered` entirely when a message is delivered and read at once ([status webhook reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/status)). Give `sent`, `failed`, `delivered`, `read` and `played` increasing ranks. Update a row only when the incoming rank is higher. [WhatsApp message statuses](/academy/articles/whatsapp-message-status-webhooks-sent-delivered-read-failed/) has the table and the guarded `UPDATE`.

## Wait for the user to stop typing

Ordering fixes the data. Conversation needs one more step. People write "hi", then "I ordered last week", then "the box arrived broken" as three messages over ten seconds. An agent that answers each webhook as it lands sends three replies to half a question. If the second message's webhook is retried, the agent also answers out of order.

Debounce per sender. Buffer each user's messages, restart a short timer on every new one, and when the timer runs out pass the whole batch, sorted, to the agent. Cap the total wait so a user who keeps typing still gets an answer.

### A small worker in Python

This class runs inside any asyncio web server, such as aiohttp or FastAPI. It drops duplicate message ids, sorts by Meta's timestamp with arrival order as the tie-breaker, and calls your handler once per burst.

```python
import asyncio
import time

QUIET_SECONDS = 8    # answer after this much silence from the user
MAX_WAIT_SECONDS = 30  # but never hold a user longer than this

class Debouncer:
    def __init__(self, handler, quiet=QUIET_SECONDS, max_wait=MAX_WAIT_SECONDS):
        self.handler = handler
        self.quiet = quiet
        self.max_wait = max_wait
        self.buffers = {}   # wa_id -> {message id: (arrival, message)}
        self.first_at = {}  # wa_id -> monotonic time of the first buffered message
        self.timers = {}    # wa_id -> asyncio.TimerHandle
        self.arrivals = 0

    def add(self, wa_id, message):
        self.arrivals += 1
        buf = self.buffers.setdefault(wa_id, {})
        prev = buf.get(message["id"])  # drops retried duplicates
        if prev is None or (prev[1].get("type") == "unsupported" and message.get("type") != "unsupported"):
            buf[message["id"]] = (self.arrivals, message)  # real content replaces a placeholder
        now = time.monotonic()
        first = self.first_at.setdefault(wa_id, now)
        delay = min(self.quiet, max(0.0, first + self.max_wait - now))
        old = self.timers.pop(wa_id, None)
        if old:
            old.cancel()
        self.timers[wa_id] = asyncio.get_running_loop().call_later(delay, self._flush, wa_id)

    def _flush(self, wa_id):
        self.timers.pop(wa_id, None)
        self.first_at.pop(wa_id, None)
        entries = self.buffers.pop(wa_id, {}).values()
        ordered = sorted(entries, key=lambda e: (int(e[1]["timestamp"]), e[0]))
        asyncio.get_running_loop().create_task(self.handler(wa_id, [m for _, m in ordered]))
```

Create one instance with `Debouncer(handler)`, where `handler` is an `async def handler(wa_id, messages)`. In the webhook route, verify the signature, return 200, then call `add(msg["from"], msg)` for every entry in every `messages` array of the payload. The state lives in one process's memory. A restart loses the buffer, and two replicas behind a load balancer each hold half of a burst. Store the messages in `inbound_messages` before you call `add`. Past one process, move the timer to Redis or to the n8n pattern below.

### The same debounce in n8n

The Redis node's Increment operation "atomically increments a key by 1" and creates the key if missing ([Redis node](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.redis/)). The Wait node pauses one execution. Each webhook execution bumps a per-user counter, waits, and continues only if no newer message bumped it meanwhile.

1. Webhook node with Respond set to Immediately. Then a Split Out node with Field to Split Out set to `body.entry[0].changes[0].value.messages`, one item per message ([Split Out](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.splitout/)). Then a Postgres node that inserts each message into `inbound_messages`.
2. Redis node, operation Increment, key `debounce:{{ $('Split Out').item.json.from }}`. Turn on Expire and set TTL to 120. Rename the node `Increment`. Its output is one field named after the key, holding the new count.
3. Wait node, Resume After Time Interval, Wait Amount 8, Wait Unit Seconds. Waits under 65 seconds keep the execution in memory instead of offloading it to the database ([Wait node](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.wait/)).
4. Redis node, operation Get, same key, Name `latest`. Then an If node with a String condition: `{{ String($json.latest) }}` is equal to `{{ String(Object.values($('Increment').item.json)[0]) }}`.
5. On the true output, run the `SELECT` above, pass the rows to your agent and set `answered = true`. The false output ends; a later execution owns the reply.

Status webhooks carry a `statuses` array and no `messages`, so filter them out before the Split Out node or give them their own workflow.

Keep Respond on Immediately. A Webhook node that waits for the last node holds Meta's request open through the Wait node. On n8n Cloud, a webhook that takes more than 100 seconds to respond fails ([common issues](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook/common-issues/)). The [WhatsApp AI agent in n8n](/academy/articles/whatsapp-ai-agent-n8n-step-by-step/) post builds the agent that sits on the true output.

## Choosing the quiet period

Treat eight seconds as a starting value. Shorter windows split slow typists into two answers. Longer windows make every reply feel late. Log the gap between consecutive messages from the same user for a week. Then set the quiet period just above the gap most bursts fall under.

*Z-API Omni team*
