Meta APIs
Handling Meta Webhooks in Production: Verification, Signatures, and Idempotency
Messenger, Instagram, and WhatsApp all deliver events through webhooks. The patterns I use to receive them reliably without losing or duplicating messages.
Why Meta webhooks need careful design
In messaging products, the webhook endpoint is the front door for every customer message. If it is slow, Meta retries. If it fails silently, messages are lost. If it processes retries twice, customers receive duplicate replies. I design the webhook layer as a small, reliable ingestion service, separate from the business logic.
The same design works for Messenger, Instagram, and the WhatsApp Cloud API, with small differences in payload shape.
Webhook endpoint verification
When a webhook is configured, Meta sends a GET request with hub.mode, hub.verify_token, and hub.challenge. The endpoint checks that the mode is subscribe and the token matches the value in configuration, then returns the challenge as plain text. Anything else returns 403.
@app.get("/meta/webhook")
def verify(request: Request):
params = request.query_params
if (params.get("hub.mode") == "subscribe"
and params.get("hub.verify_token") == settings.META_VERIFY_TOKEN):
return PlainTextResponse(params.get("hub.challenge", ""))
return PlainTextResponse("forbidden", status_code=403)Validating X-Hub-Signature-256 on every payload
Each POST request includes an X-Hub-Signature-256 header in the form sha256=<hex digest>. Compute an HMAC-SHA256 of the raw request body using the app secret and compare with a constant-time comparison. This must happen on the raw bytes, before any JSON parsing changes the body.
@app.post("/meta/webhook")
async def receive(request: Request):
body = await request.body()
expected = "sha256=" + hmac.new(settings.META_APP_SECRET.encode(),
body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(request.headers.get("x-hub-signature-256", ""), expected):
return Response(status_code=401)
await events.store_raw(body) # durable copy first
await queue.enqueue("process_meta_event", body)
return Response(status_code=200)Acknowledge fast, process later
- Validate the signature and store the raw event durably.
- Push the event to a queue and return 200 immediately.
- Let background workers handle parsing, AI processing, database updates, and replies.
- Keep the request path free of external API calls and slow database queries.
- If the queue is unavailable, fail with a 5xx so Meta retries, instead of returning 200 and losing the event.
Idempotency and message ordering
Meta can deliver the same event more than once. I use a unique key per event, such as the message ID, and skip events that were already processed. A unique database constraint is the simplest reliable guard.
For conversations where order matters, workers process events per conversation in sequence, while different conversations run in parallel. A per-conversation lock or a queue partitioned by conversation ID both work. Without this, a fast second message can be answered before the first.
Normalizing Messenger, Instagram, and WhatsApp events
Payloads differ by product. Messenger and Instagram events arrive under entry and messaging, while WhatsApp events arrive under entry, changes, and value, including message status updates. I convert all of them into one internal event: channel, account, conversation, sender, type, content, and timestamp. The rest of the system, including the AI reply agent, only sees the normalized format.
Inbound timestamps also drive messaging window logic, such as the WhatsApp customer service window and the Human Agent window, so store them accurately.
Observability for webhook pipelines
- Count events by type and channel, and alert on sudden drops to zero.
- Track time from webhook receipt to processing completion.
- Alert on signature failures, which can mean a misconfigured secret.
- Track queue depth and worker retries.
- Keep a dead-letter queue for events that repeatedly fail, with a way to replay them.
Most messaging incidents I have seen were visible in webhook metrics before customers noticed.
Scaling webhook processing
Webhook traffic is bursty. A marketing campaign, a viral post, or a busy evening can multiply message volume in minutes. Because the endpoint only validates and enqueues, it scales easily behind a load balancer. The workers are where capacity matters, and they should scale on queue depth rather than CPU.
I separate queues by work type: fast operations such as storing messages and updating statuses, and slow operations such as AI replies or calls to external systems. A slow AI provider then cannot delay status updates or block simple replies. Each queue has its own retry policy and dead-letter queue, so one failing dependency does not affect the rest of the pipeline.
Local development and testing
Use a tunnel to expose a local endpoint during development, but keep a separate verify token and app for development. Save real payloads, with personal data removed, as test fixtures. Then test signature validation, duplicate delivery, out-of-order delivery, and unknown event types in automated tests.
Frequently asked questions
What happens if my webhook returns an error?
Meta retries delivery for a period of time. Return a 5xx only when you could not store the event, and make processing idempotent so retries are safe.
Should I parse JSON before checking the signature?
No. Compute the signature on the raw request body. Parsing and re-serializing can change bytes and break the comparison.
Can one endpoint handle Messenger, Instagram, and WhatsApp?
Yes. Use the object field in the payload to route events, then normalize them into one internal format.
Where do I find the app secret?
In the Meta App Dashboard under the app's basic settings. Store it as a secret, never in client code.