Catalog My learning Blog
API Design Course: REST and GraphQL Best Practices · Phase 4 · Lesson 25 · 4 min read

Webhooks Explained: Event-Driven APIs

On this page
  1. What are webhooks? Push instead of polling
  2. Designing a webhook event payload
  3. Webhook delivery: retries and at-least-once
  4. Signing and verifying webhooks with HMAC
  5. More webhook provider responsibilities
  6. Check yourself

What are webhooks? Push instead of polling

A store integrates with a payment provider. Without webhooks, it polls "is payment 91 done yet?" every few seconds for every pending payment: wasteful for both sides and still slow. With webhooks, the provider sends an HTTP POST to the store's URL the moment the payment succeeds.

Designing a webhook event payload

JSON
{
  "id": "evt_301",
  "type": "payment.succeeded",
  "createdAt": "2026-10-11T14:30:00Z",
  "data": { "paymentId": "pay_1", "amount": 4200, "currency": "USD" }
}
  • A unique event ID for deduplication.
  • A type in resource.action form, so consumers subscribe to the events they care about.
  • Thin or fat payloads: include enough data to act on, or just IDs and let consumers fetch the current state from the API. Thin events avoid acting on stale data when events arrive out of order.

Webhook delivery: retries and at-least-once

Networks fail and consumers have outages, so providers retry: typically with exponential backoff over hours or days, until the consumer returns a 2xx. That means:

  • Consumers will receive duplicates, and events may arrive out of order.
  • Consumers should respond quickly (within seconds) and do the real work asynchronously from a queue; slow responses look like failures and cause more retries.
  • Providers should show delivery history and let customers replay events, and disable endpoints that fail for days.
The provider signs each event with a shared secret and retries until acknowledged; the consumer verifies the signature and timestamp, ignores duplicate IDs, and queues the work.
The provider signs each event with a shared secret and retries until acknowledged; the consumer verifies the signature and timestamp, ignores duplicate IDs, and queues the work.

Signing and verifying webhooks with HMAC

Anyone who discovers the webhook URL can POST to it. The provider signs each delivery with a shared secret, over a timestamp plus the raw body; the consumer recomputes and compares.

HMAC is the tool for this. Think of a wax seal that only two people can make: both know the secret, the sender stamps the message with it, and the receiver stamps the same message itself and checks the two seals match. Change one byte of the message, and the seals no longer match. Unlike encryption, the message itself stays readable; HMAC only proves who sent it and that it wasn't changed.

The provider side is short. Sign the exact bytes you're about to send:

JavaScript
function signedDelivery(event, secret) {
  const body = JSON.stringify(event);                  // these exact bytes go on the wire
  const t = Math.floor(Date.now() / 1000);
  const v1 = crypto.createHmac('sha256', secret).update(`${t}.${body}`).digest('hex');
  return { headers: { 'Content-Type': 'application/json', 'Webhook-Signature': `t=${t},v1=${v1}` }, body };
}

It produces a header like Webhook-Signature: t=1793392918,v1=2e80b70df3f5..., which the consumer below verifies. A tested Express consumer:

JavaScript
app.post('/webhooks/payments', express.raw({ type: 'application/json' }), (req, res) => {
  const parts = Object.fromEntries((req.get('Webhook-Signature') ?? '').split(',').map(p => p.split('=')));
  const timestamp = Number(parts.t);
  if (!timestamp || Math.abs(Date.now() / 1000 - timestamp) > 300)
    return res.status(400).send('stale or missing timestamp');            // blocks replays

  const expected = crypto.createHmac('sha256', SECRET).update(`${timestamp}.${req.body}`).digest();
  const given = Buffer.from(parts.v1 ?? '', 'hex');
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected))
    return res.status(401).send('bad signature');

  const event = JSON.parse(req.body);
  if (seen.has(event.id)) return res.status(200).send('duplicate, ignored');
  seen.add(event.id);
  res.status(200).send(`accepted ${event.type}`);   // then process from a queue
});

Five deliveries against it:

Code
valid:           200 accepted payment.succeeded
redelivered:     200 duplicate, ignored
tampered body:   401 bad signature
replayed (1 h):  400 stale or missing timestamp
re-serialized:   401 bad signature

What each line teaches:

  • Redelivery is acknowledged with 200 so the provider stops retrying, but not processed twice. In production, store event IDs in a database table with a unique constraint.
  • Tampering with the amount breaks the signature.
  • Replay of a captured request an hour later fails the timestamp check, which is why the timestamp is inside the signed string.
  • Re-serialized JSON with the same data but different whitespace fails too. Verify the raw bytes as received (express.raw), never JSON.stringify(req.body) after parsing.
  • timingSafeEqual compares in constant time, so the comparison doesn't leak how many bytes matched.

Stripe uses this timestamp-plus-HMAC scheme, and the Standard Webhooks specification describes a common format other providers have adopted.

More webhook provider responsibilities

  • SSRF protection on customer-supplied URLs (Day 24).
  • Secret rotation: allow two active secrets during a changeover.
  • HTTPS only, and a test-event button for customers.

Check yourself

Providers retry until they get a 2xx, so the same event can arrive more than once, for example after a timeout.

So a captured request can't be replayed later. The consumer checks that the signed timestamp is recent, within five minutes for example, and rejects older ones, and an attacker can't change the timestamp without breaking the signature.

Parsing and re-serializing JSON can change bytes such as whitespace or key order, which makes a valid signature fail to match.

Providers time out after a few seconds and retry. Acknowledge with 2xx after storing the event, then process it from a queue.

A delivery log, a way to replay events, the ability to rotate signing secrets, and an API to fetch the current state, since events can arrive out of order.