DEV Community

Ahmed Memon
Ahmed Memon

Posted on Originally published at digisysalpha.com

Webhooks that process once: signatures, locks and idempotency

To make a webhook process only once, verify its signature, take a lock on the record it changes, and check an idempotency key before changing any state. This is the pattern we recommend for payment and shipping integrations.

Providers retry webhooks. They can arrive twice, out of order, or while your server is mid-deploy. A handler that assumes one clean delivery will eventually duplicate an email, a label or a payout.

1. Verify the signature first

Compute an HMAC of the raw request body with your shared secret and compare it in constant time. Reject anything that does not match before touching the database. Some hosts strip custom headers, so we also support a secret token in the URL as a fallback.

$expected = hash_hmac('sha256', $rawBody, $secret);
if (!hash_equals($expected, $signature)) { http_response_code(401); exit; }
Enter fullscreen mode Exit fullscreen mode



  1. Take a lock on the record

Two copies of the same event can arrive at the same moment. A lock keyed to the order (for example a database lock) makes the second copy wait or exit instead of running in parallel.

3. Check an idempotency key

Store the provider's event ID when you finish handling it. If you see the same ID again, return success and do nothing. Acknowledge quickly and do slow work in a queue.

When not to rely on this alone

  • If the event can be replayed days later, also check the current state of the record before applying it.
  • If you handle money, log each event and its outcome so a mismatch can be reconciled.

Is a lock enough without an idempotency key? No. A lock stops parallel runs, but a retry that arrives later still needs the stored event ID to be ignored.

Source: Stripe documentation: webhooks


Originally published at digisysalpha.com. I'm Ahmed Memon. I fix and build payment and webhook integrations in Laravel and WooCommerce.

Top comments (0)