Designing Idempotent Webhook Consumers for Payment & Messaging APIs
Distributed networks operate on an at-least-once delivery guarantee, not exactly-once. Payment gateways (Razorpay, Stripe) and messaging platforms (Meta WhatsApp Cloud API, Twilio, Plivo) routinely deliver the same webhook payload twice during network retries or browser redirect races. Without idempotent webhook handlers, applications risk activating duplicate subscriptions, double-deducting wallet balances, or spawning redundant CRM leads.
1. Verify Cryptographic Signatures Before Parsing JSON
Never rely solely on IP allowlists—webhooks must verify HMAC-SHA256 headers against raw request bytes prior to modifying application state:
- Capture raw body bytes (
php://inputor raw Express buffer middleware) before framework JSON parsers re-serialize keys or alter whitespace. - Compare expected and header signatures using constant-time functions (
hash_equals()in PHP orcrypto.timingSafeEqual()in Node.js) to eliminate timing side-channel leaks.
2. Fast Acknowledgement & Queue Offloading
Most webhook providers enforce strict 3-to-5 second response timeouts before marking an endpoint degraded and retrying repeatedly. Follow the sequence outlined in the Stripe Webhook Delivery Best Practices:
- Validate the HMAC signature synchronously (~1ms).
- Persist the raw event ID + payload into an inbox table with a
UNIQUEindex on(provider, external_event_id). - If a duplicate key constraint triggers, return
HTTP 200 OKimmediately without enqueuing work again. - Dispatch a background queue job and return
HTTP 200 OKwithin milliseconds.
| Layer | Failure Mode | Idempotent Guard |
|---|---|---|
| HTTP Edge | Provider retries same event ID after timeout | Unique constraint on (provider, event_id) |
| Order Checkout | Client browser callback & server webhook run concurrently | Row lock (SELECT ... FOR UPDATE) + state guard if ($order->status === 'paid') return; |
| Downstream Sync | External CRM API fails transiently mid-job | Store granular checkpoint flags & exponential backoff retries |
3. Handling Out-of-Order Status Webhooks
Messaging webhooks frequently deliver read receipts milliseconds before delivered status events. Always model state transitions monotonically (for example, queued → sent → delivered → read) so late sent events never overwrite a newer delivered or read state in your database (see Meta WhatsApp Cloud API Webhooks Overview).
Shubham More
Lead Cloud & API Integration Engineer · WhatsApp Cloud API & Automation
Specializes in Meta WhatsApp Cloud API webhooks, clinical & healthcare workflows, automated billing ledgers, and event-driven messaging pipelines.