Writing
Fullstack English

Webhooks That Don't Lose Money: Signatures, Retries, and Dedupe

Receiving webhooks looks trivial and fails expensively. Verify signatures, ack fast, process async, and dedupe by event id.

  • Published
  • 1 min read

A payment provider’s webhook is production code you did not write, calling production code you did. When it goes wrong, the failure is silent and the symptom is an angry customer whose paid order says “pending”.

The four rules

  1. Verify the signature, on the raw body. Parse-then-verify fails because JSON re-serialization changes bytes:
typescript
const sig = createHmac('sha256', WEBHOOK_SECRET).update(rawBody).digest()
const given = Buffer.from(c.req.header('X-Signature') ?? '', 'hex')
if (given.length !== sig.length || !timingSafeEqual(sig, given)) return c.text('no', 401)
  1. Ack in milliseconds, process async. Insert the event into a queue/table and return 200. Providers time out at 5-10 s and mark you as failing - which pauses your deliveries. Your inventory logic has no business inside the request handler.

  2. Dedupe by event id. Every provider redelivers - that is a feature. INSERT ... ON CONFLICT (event_id) DO NOTHING; if no row was inserted, you have processed it before, stop.

  3. Treat order as unknown. payment.settled can arrive before payment.created. Process events as state assertions (“this payment is now settled”), not as a story told in sequence.

And a reconciliation job

Webhooks are best-effort even from the best providers. A nightly job that pulls the provider’s API and diffs against your database is the safety net that turns “we lost 14 orders” into a log line nobody had to escalate.