Queues and idempotency in WhatsApp agents

How to avoid duplicate, out-of-order or lost replies in a WhatsApp agent: id deduplication, queue, per-conversation order and idempotency keys.

WhatsApp event delivery is built not to lose messages, and that has a price: the same message can arrive more than once. An AI agent that replies to every delivery replies twice, and the customer notices. Queues and idempotency are the two techniques that turn a system that sometimes answers twice into one that answers exactly once.

Why does the agent answer the same message twice?

Because delivery is at least once, not exactly once. CRPRO Hub resends an event when your endpoint does not answer 2xx within 10 seconds, when it answers with an error or when it crashes after processing but before replying. Each of these is normal, not a defect.

The Hub guide on receiving messages distinguishes two cases. On a retry, the same delivery comes back with the same X-Hub-Delivery-Id. On a manual replay, the same event is delivered again as a new delivery, with a different delivery id. What repeats in both cases is the event id, in the body; that is what you deduplicate by. The webhooks reference has the headers and the redelivery policy.

The cost of ignoring this is higher in an agent than in an ordinary system: each repeated processing calls the model again, spends tokens, and the generated text may differ from the first.

How do you deduplicate reliably?

With a uniqueness constraint in the database, not a check in code. Checking whether the id was seen and then writing it leaves a gap between the two operations, where two simultaneous deliveries pass together. An insert with conflict handling solves it atomically.

-- Atomic deduplication: the unique constraint decides, not an "if" in code CREATE TABLE eventos_processados ( evento_id text PRIMARY KEY, -- the "id" of the event envelope recebido_em timestamptz NOT NULL DEFAULT now() ); CREATE TABLE respostas_geradas ( message_id text PRIMARY KEY, -- data.message_id (the received wamid) texto text NOT NULL, enviado boolean NOT NULL DEFAULT false ); -- In the webhook: if it inserted, it is new; if not, it was already seen INSERT INTO eventos_processados (evento_id) VALUES ($1) ON CONFLICT (evento_id) DO NOTHING RETURNING evento_id;

If the insert returns a row, the event is new and goes to the queue; if it returns nothing, it was already seen and the handler answers 2xx without doing anything else. Answering 2xx for a duplicate matters: an error would make Hub resend again.

There is a subtlety. Marking the event as processed before the work finishes means a failure midway loses the event. That is why webhook deduplication records that the event was accepted and queued, and the queue is what guarantees processing finishes, with retries. Each stage has its own guarantee.

What exactly does the queue solve?

Three problems: the webhook deadline, retries and order. The handler only enqueues and answers 2xx, the worker does the slow work without deadline pressure, and a failing job goes back to try again with growing delay, instead of depending on Hub to resend.

  • Deadline: the model call leaves the webhook path, which has 10 seconds.
  • Retries: a model or send failure becomes a new attempt with backoff, not a lost event.
  • Dead letters: after a retry limit, the job goes to a separate queue and the conversation is handed to a person.
  • Throughput: the queue absorbs spikes and keeps the send rate under your control. Through Hub, the limit is 60 sends per minute per channel.

How do you keep a conversation’s messages in order?

By processing one job at a time within each conversation, and different conversations in parallel. Without that, two consecutive messages from the same customer are handled by two workers at once, and replies come out of order or each unaware of the other.

// One job at a time PER CONVERSATION; different conversations run in parallel async function processarJob(job) { const chave = job.canal + ':' + job.contato await travas.comExclusao(chave, async () => { // 1. Reuse the reply already generated for this message (retry or replay) let r = await respostas.buscar(job.messageId) if (!r) { const texto = await agente.gerar(job) // model call r = await respostas.guardar(job.messageId, texto) } if (r.enviado) return // already handed to the API // 2. Send with a key derived from the incoming message const envio = await enviar(job.canal, job.contato, r.texto, 'ia-' + job.messageId) if (envio.ok) await respostas.marcarEnviado(job.messageId) else throw new Error('envio ' + envio.status) // the queue retries with backoff }) }

The per-conversation lock can be a database lock, a key in a fast store or a queue partitioned by the channel and contact key. What matters is the property: two jobs of the same conversation never run together. That also prevents one job from reading the history while another is still writing it.

Bursts, when the customer sends three messages in ten seconds, call for a separate technique, merging messages before replying, covered in the latency article in this series.

How does the idempotency key prevent duplicate sends?

By making the same send request produce the same result no matter how many times it is repeated. Through Hub’s API, the Idempotency-Key header identifies the send: derived from the incoming message id, the key is the same on any reprocessing, and the API returns the original send instead of dispatching another reply.

The condition is that the body is also the same. If the same key comes back with a different text, the result is 409 IDEMPOTENCY_KEY_REUSED. That is why the code above stores the generated text before sending and reuses it on repeats: calling the model again would produce another text and break idempotency. The 202 response means accepted and queued, not delivered.

SituationWhat happens unprotectedProtection
Redelivery of the same eventTwo repliesInsert with conflict on the event id
Job repeated by the queueModel called again, different textGenerated text stored by message_id
Repeated sendTwo WhatsApp messagesIdempotency-Key derived from message_id
Two consecutive customer messagesOut-of-order repliesOne job at a time per conversation

What do you do when the send fails?

Tell recoverable errors from final ones. A network failure or a rate limit is retried with backoff; a closed window or an invalid number is not worth repeating. The send returns codes that say which case it is, and they are listed in Meta’s error reference.

  • Per-contact limit (131056): growing backoff. Two automated systems talking to each other run into it.
  • Outside the window (131047): do not retry. The way out is an approved template.
  • Model failure: retry with backoff and, once exhausted, tell the customer and call a person.
  • Failure after the text was generated: reuse the stored text, without calling the model.

With atomic deduplication, a queue, per-conversation order and an idempotency key derived from the message, the result is an agent where repeating any step is safe. To send the replies, see the quickstart.

Frequently asked questions

Which id should I use to deduplicate?

The event id, in the envelope body, because it repeats on both retry and manual replay. X-Hub-Delivery-Id changes on replay and is not enough alone.

Can I generate the idempotency key randomly?

For sending a reply, no. A random key changes on every attempt and does not protect against duplicates. Derive it from the incoming message id.

What does a 409 response on send mean?

IDEMPOTENCY_KEY_REUSED: the same key was used with a different body. In an agent, it usually means the model was called again and produced another text.

Do I need a dedicated queue service?

Not at first. A jobs table with attempts and a per-conversation lock handle low volume. Move to a dedicated queue when there are several workers.

Fontes

Documentação oficial da Meta, conferida em 31 de outubro de 2026.