← Blog

·

WhatsApp webhook message and status order: why events arrive out of order

Updated on November 24, 2026

Meta’s documentation does not guarantee that WhatsApp webhooks arrive in the order the events happened: retries, batching and parallel deliveries shuffle inbound messages and statuses such as sent, delivered and read. To rebuild the sequence, sort by the event’s own timestamp (with an arrival number as a tiebreaker), process one contact at a time, and treat statuses as facts that accumulate, not as “the last one to arrive wins”.

This article builds on two we have already published: message status via webhook, which explains each status and how to store them without regressing, and integration architecture with queues, retries and idempotency. Here the focus is ordering: where the mess comes from, how to sort a conversation, how to collect several messages in a row before calling a bot, and how to send a sequence that must arrive in the right order.

Why events arrive out of order

Five behaviors documented by Meta explain almost every case:

BehaviorWhat the documentation saysEffect on order
RetriesIf your endpoint does not return 200, Meta retries with decreasing frequency for up to 7 days, and retries can produce duplicatesAn old event arrives after newer ones
BatchingA single POST can carry up to 1,000 updates, but batching is not guaranteedThe same kind of event sometimes comes together, sometimes in separate, simultaneous requests
Skipped statusWhen a message is delivered and read at the same time (the user has the chat open), the delivered webhook is not sentYou get read without ever getting delivered
Several statuses per messageEach sent message can produce up to three status webhooks (sent, delivered, read), plus played for voice messages and failedEach one travels independently
Sending in sequenceSeveral messages sent back to back may not be delivered in the order of your API callsThe user may see message 2 before message 1

Sources: webhooks overview, create a webhook endpoint, status webhook reference and send messages.

None of these pages promises webhook delivery order. Then add your own side: if your server runs more than one worker or replica, two POST requests arriving milliseconds apart are processed in parallel, and whichever finishes first writes first.

The field that rules: the event timestamp

Every inbound message and every status carries a timestamp in Unix seconds, as a string:

{
  "messages": [{
    "from": "5511988887777",
    "id": "wamid.HBgLNTUx...",
    "timestamp": "1764000000",
    "type": "text",
    "text": { "body": "Hi, I want to change the size" }
  }]
}

Three practical rules:

  • Sort by the event timestamp, never by the time you received it. An event retried hours later keeps its original time.
  • Expect ties. The resolution is one second. A fast typist sends two or three messages within the same second. Use an arrival number (a bigserial column) as the tiebreaker.
  • Do not sort by wamid. It is an opaque identifier: use it to deduplicate and to link statuses to messages, not to order them.

The fields for each message type are in WhatsApp webhook payload examples.

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

Store first, sort later

The most robust way to deal with ordering is not to depend on it at arrival time. The webhook only stores each message with Meta’s time and an arrival number, then returns 200. Sorting happens when you read.

CREATE TABLE inbound_messages (
  seq         bigserial PRIMARY KEY,          -- arrival order (tiebreaker)
  wamid       text UNIQUE NOT NULL,           -- deduplication
  contact_key text NOT NULL,                  -- who sent it
  meta_ts     bigint NOT NULL,                -- Meta timestamp (seconds)
  received_at timestamptz NOT NULL DEFAULT now(),
  raw         jsonb NOT NULL,
  handled_at  timestamptz
);

CREATE INDEX inbound_by_contact ON inbound_messages (contact_key, meta_ts, seq);
import pg from 'pg';

export const pool = new pg.Pool(); // reads PGHOST, PGUSER etc. from the environment

export async function saveInbound(payload) {
  const saved = new Set();
  for (const entry of payload.entry ?? []) {
    for (const change of entry.changes ?? []) {
      for (const m of change.value?.messages ?? []) {
        // Users with a username may arrive without "from"; Meta recommends
        // using from_user_id to identify the sender.
        const contactKey = m.from_user_id ?? m.from;
        await pool.query(
          `INSERT INTO inbound_messages (wamid, contact_key, meta_ts, raw)
           VALUES ($1, $2, $3, $4)
           ON CONFLICT (wamid) DO NOTHING`,
          [m.id, contactKey, Number(m.timestamp), m],
        );
        saved.add(contactKey);
      }
    }
  }
  return [...saved]; // contacts with new messages
}

ON CONFLICT (wamid) DO NOTHING drops the retry without an error. Full deduplication, including statuses and side effects, is covered in duplicate webhooks and idempotency.

To display the conversation, the query is always the same:

SELECT wamid, meta_ts, raw
FROM inbound_messages
WHERE contact_key = $1
ORDER BY meta_ts, seq;

One note on the key: if your account sometimes receives from and sometimes only from_user_id for the same customer, keep a mapping table between the two so the conversation does not split in two.

Late events after an outage

If your endpoint was down for two hours, Meta retries what was pending once it comes back. Those events land “in the past”: their meta_ts is earlier than messages you have already processed.

With sorting at read time, the conversation view fixes itself. The care goes into automations:

  • Do not answer old messages as if they were new. Before sending an automatic reply, compare meta_ts with the current time. A question from two hours ago that an agent has already answered should not trigger the bot.
  • Recompute anything that depends on the customer’s last message. The 24-hour customer service window counts from the customer’s last message; use the highest meta_ts, not the last inserted row.
  • Button replies carry a reference. When the user taps a quick-reply button in a template, the webhook includes context.id, the wamid of the message that held the button. Use it to tie the reply to the right question even if it arrives out of order. To reply quoting a specific message, see how to reply to a specific message.

One contact at a time: serialize processing

Sorting at read time fixes the display. For processing (bot, CRM, business rules) the problem is different: two workers handling messages from the same customer at the same time can reply out of order or twice.

The fix is to serialize per contact and parallelize across contacts. In PostgreSQL, a transaction-level advisory lock does this with no extra infrastructure: only one transaction at a time holds the lock for a contact_key, and it is released on COMMIT or ROLLBACK.

export async function processContact(contactKey, handler) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    // Waits if another worker is processing this contact.
    await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [contactKey]);

    const { rows } = await client.query(
      `SELECT seq, wamid, meta_ts, raw
       FROM inbound_messages
       WHERE contact_key = $1 AND handled_at IS NULL
       ORDER BY meta_ts, seq`,
      [contactKey],
    );

    if (rows.length > 0) {
      await handler(contactKey, rows);
      await client.query(
        'UPDATE inbound_messages SET handled_at = now() WHERE seq = ANY($1::bigint[])',
        [rows.map((r) => r.seq)],
      );
    }
    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

If you use a queue, the principle is the same: the partition key is the contact. In queues with groups or partitions, use contact_key as the key; in simple queues, keep the lock in the database. The article on a WhatsApp API queue with Redis and BullMQ covers the sending side.

A warning: handler runs inside the transaction, so slow calls (AI, CRM) hold the connection. At high volume, switch to an “in progress” flag with a deadline and release the transaction before the external call.

Several messages in a row: buffer before calling the bot

WhatsApp users write in bursts: “hi”, “how are you?”, “I wanted to ask about my order”, “it’s 4821”. If the bot answers each one, the user gets four disjointed replies, and their order depends on which AI call finished first.

The pattern is a short per-contact buffer (debounce): each new message pushes the reply back a few seconds, with a ceiling for people who keep typing. When the deadline passes, the bot receives all pending messages at once, already sorted.

CREATE TABLE pending_turns (
  contact_key text PRIMARY KEY,
  first_at    timestamptz NOT NULL DEFAULT now(),
  due_at      timestamptz NOT NULL
);
const QUIET_SECONDS = 4;  // wait after the last message
const MAX_SECONDS = 15;   // ceiling counted from the first one

export async function scheduleTurn(contactKey) {
  await pool.query(
    `INSERT INTO pending_turns (contact_key, due_at)
     VALUES ($1, now() + make_interval(secs => $2))
     ON CONFLICT (contact_key) DO UPDATE SET
       due_at = LEAST(
         pending_turns.first_at + make_interval(secs => $3),
         now() + make_interval(secs => $2)
       )`,
    [contactKey, QUIET_SECONDS, MAX_SECONDS],
  );
}

async function tick(answerWithBot) {
  const { rows } = await pool.query(
    `DELETE FROM pending_turns
     WHERE contact_key IN (
       SELECT contact_key FROM pending_turns
       WHERE due_at <= now()
       ORDER BY due_at
       LIMIT 20
       FOR UPDATE SKIP LOCKED
     )
     RETURNING contact_key`,
  );
  for (const r of rows) {
    await processContact(r.contact_key, answerWithBot);
  }
}

export function startTurnWorker(answerWithBot) {
  setInterval(() => {
    tick(answerWithBot).catch((err) => console.error('turn worker', err));
  }, 1000);
}

In the webhook, after saveInbound, call scheduleTurn for each returned contact. FOR UPDATE SKIP LOCKED lets you run several workers without two of them grabbing the same contact, and processContact keeps the order inside it. The 4 and 15 second values are a starting point; tune them to your audience. To build the bot itself, see the guide to an AI chatbot on the WhatsApp API.

Statuses: derive state from history, not from the last event

For messages you send, ordering problems show up in statuses. The message status article shows how to update a row without regressing. An alternative that solves ordering, duplicates and the race with sending all at once is to keep every status you receive in a log and compute the state from it.

The race goes like this: you call the API, Meta answers with the wamid, but the sent webhook can arrive before you store that wamid in your database. If the webhook code runs UPDATE ... WHERE wamid = $1, nothing is updated and the status is lost. With a log, the status is kept even without a matching message.

CREATE TABLE status_events (
  wamid      text NOT NULL,
  status     text NOT NULL,
  meta_ts    bigint NOT NULL,
  raw        jsonb NOT NULL,
  PRIMARY KEY (wamid, status, meta_ts)
);
const RANK = { sent: 1, delivered: 2, read: 3, played: 4 };

// Same result in any arrival order (commutative) and with duplicates.
export function deriveState(events) {
  const s = { status: null, rank: 0, sentAt: null, deliveredAt: null,
              readAt: null, playedAt: null, failed: null, pricing: null };

  for (const e of events) {
    const ts = Number(e.timestamp);
    if (e.pricing) s.pricing = e.pricing; // only present in one of the statuses

    if (e.status === 'failed') {
      s.failed = { ts, code: e.errors?.[0]?.code ?? null };
      continue;
    }
    const rank = RANK[e.status];
    if (!rank) continue; // unknown status: skip here, log it

    const key = `${e.status}At`;
    s[key] = s[key] === null ? ts : Math.min(s[key], ts);
    // read without delivered: Meta does not send delivered when delivery and
    // read happen together, so a read implies delivery.
    if (rank >= 3) s.deliveredAt = s.deliveredAt === null ? ts : Math.min(s.deliveredAt, ts);
    if (rank > s.rank) { s.rank = rank; s.status = e.status; }
  }
  if (s.rank === 0 && s.failed) s.status = 'failed';
  return s;
}

In the webhook, run INSERT ... ON CONFLICT DO NOTHING into status_events and recompute the message state from all rows for that wamid. After sending, when you store the wamid in your outbound messages table, recompute as well: any statuses that arrived earlier are already in the log. The pricing object appears in only one of the statuses, so keeping it when it shows up (as in the code) avoids losing billing information.

Sending in sequence: wait for delivered

Meta’s sending page is direct: if you send several messages, they may not be delivered in the order of your API calls; if order matters, confirm each one was delivered through the delivered status before sending the next. That applies to step-by-step instructions, a boleto (a Brazilian bank payment slip) followed by how to pay it, or a photo followed by the price.

Since delivered can be skipped when the message has already been read, accept either delivered or read as the release signal. And because both can arrive (and arrive twice), advancing must be idempotent:

CREATE TABLE sequence_steps (
  id        bigserial PRIMARY KEY,
  seq_id    text NOT NULL,
  position  int  NOT NULL,
  to_wa_id  text NOT NULL,
  payload   jsonb NOT NULL,
  wamid     text,
  sent_at   timestamptz,
  UNIQUE (seq_id, position)
);
export async function onStatusForSequence(st, sendMessage) {
  if (st.status !== 'delivered' && st.status !== 'read') return;

  // Claims the next step only once, even with delivered + read + retries.
  const { rows } = await pool.query(
    `UPDATE sequence_steps nxt SET sent_at = now()
     FROM sequence_steps cur
     WHERE cur.wamid = $1
       AND nxt.seq_id = cur.seq_id
       AND nxt.position = cur.position + 1
       AND nxt.sent_at IS NULL
     RETURNING nxt.id, nxt.to_wa_id, nxt.payload`,
    [st.id],
  );

  for (const step of rows) {
    const wamid = await sendMessage(step.to_wa_id, step.payload);
    await pool.query('UPDATE sequence_steps SET wamid = $2 WHERE id = $1', [step.id, wamid]);
  }
}

Two caveats. First, your code sends step one when it creates the sequence; the webhook only handles the following steps. Second, delivered can take a while if the customer’s phone is off, and the sequence waits until then. For content that does not need strict order, put everything in a single message (for example, an image with a caption) and skip the wait.

Showing the conversation on screen

If you run your own agent inbox, three decisions prevent confusion:

  • Sort by meta_ts and break ties by arrival. For sent messages, use the timestamp of the sent status as the message time.
  • Show the most advanced status seen so far. If read arrived, show it as read, even without delivered.
  • Reposition late events. A message that arrives with an old time belongs in the right place in the conversation, not at the end. If the UI updates in real time, push the event with its meta_ts and let the client re-sort.

How to do this with Vectalk

Vectalk is a proxy for Meta’s official Cloud API: the Hub receives events from Meta and forwards them to the URLs you registered with the same payload, according to the Vectalk webhooks documentation. Everything in this article applies unchanged: timestamp, wamid, context and statuses are the same fields.

Two specific points:

  • The Hub expects 200 in under 20 seconds and retries if it does not get it. As with Meta, retries are a source of late and duplicate events, and the “store, respond, sort later” pattern handles both.
  • You can register several URLs per instance with POST https://apis.vectalk.com.br/api/webhooks, and all of them receive the same event. If two of your services consume the same number, decide which one replies to the customer so replies are not duplicated.

Sending uses POST https://apis.vectalk.com.br/api/messages with the same JSON as the Cloud API, as in the quickstart. For the big picture, see the official WhatsApp API guide. To get started, create your account.

Frequently asked questions

Does Meta guarantee webhook order?

No. The webhook pages do not promise delivery order, and retries for up to 7 days make old events arrive after new ones. Sort by the event timestamp.

Why did I get read without delivered?

Because when a message is delivered and read at the same time (the user has the chat open), Meta does not send the delivered webhook. Treat read as proof of delivery.

Two messages with the same timestamp: which came first?

The timestamp has one-second resolution, so ties are common. Use an arrival number in your database as the tiebreaker. Do not sort by wamid: it is an identifier, not a sequence.

How do I make sure the user receives my messages in the order I sent them?

Send the next one only after you receive delivered (or read) for the previous one, as Meta’s sending documentation recommends. If order is not critical, put the content in a single message.

I use a queue: do I need to worry about order?

Yes. Several consumers processing the same contact in parallel will shuffle the order. Partition by contact or use a per-contact lock, like the advisory lock in the example.


Official sources checked on November 24, 2026: Meta: webhooks overview, Meta: create a webhook endpoint, Meta: status webhook, Meta: messages webhook, Meta: button webhook, Meta: send messages, PostgreSQL: advisory locks, PostgreSQL: SELECT … SKIP LOCKED, Vectalk: webhooks, Vectalk: quickstart.

Try the official WhatsApp API today

Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.