# Designing webhooks: retries, signatures and idempotency

> How would you design a webhook system for a payment platform, covering delivery guarantees, security and consumer behaviour?

Canonical: https://www.internhack.in/learn/interview/api-design-interview/api-webhooks-design
Last updated: 2026-11-28

Difficulty: Advanced

## Question

How would you design a webhook system for a payment platform, covering delivery guarantees, security and consumer behaviour?

## Answer

Webhooks are the API in reverse. Instead of clients polling 'is my payment done yet?', the server calls the client's URL when something happens. It is like asking a courier to ring your bell rather than checking the tracking page every five minutes. They matter for asynchronous events such as payment.captured, refund.processed or order.delivered, and are how Razorpay, Stripe and GitHub notify integrators.

Delivery semantics: assume at-least-once. You cannot guarantee exactly-once over a network, since a timeout after the consumer processed the event looks the same as a failure. So the sender retries until it gets a 2xx, and the receiver must handle duplicates. Also, ordering is not guaranteed: retries and parallel delivery mean payment.captured might arrive before payment.authorized. Design events to carry timestamps or sequence numbers, and encourage consumers to fetch the current resource state via the API when order matters.

Sender design. Persist an event record first, then enqueue delivery jobs; never send inline within the business transaction, or a slow consumer will block your request path (use a transactional outbox for reliability). Each delivery is an HTTP POST with a JSON body containing a unique event id, type, created timestamp and the data object. Use a short timeout, say 5 to 10 seconds, and treat non-2xx or timeouts as failure. Retry with exponential backoff and jitter over a bounded window, for example over 24 to 72 hours (Stripe retries for up to three days), then mark the delivery failed and alert the merchant. Provide a dashboard to see attempts and response codes, and a manual resend button. Disable or pause endpoints that keep failing to protect your workers, and isolate per-customer queues so one slow endpoint doesn't cause head-of-line blocking for others.

Security. The receiver must know the call really came from you. Sign each payload with HMAC-SHA256 using a per-endpoint secret and send the signature in a header, e.g. X-Signature: t=timestamp,v1=hexdigest, where the signed content is timestamp + '.' + raw body. The consumer recomputes the HMAC over the raw body (not re-serialised JSON) and compares using a constant-time comparison. Including the timestamp and rejecting events older than five minutes defends against replay attacks. Also require HTTPS, support secret rotation with an overlap period, and optionally publish IP ranges. Never put secrets in the URL.

Consumer best practices: verify the signature first; respond 2xx quickly and process asynchronously via a queue, because long processing causes timeouts and needless retries; deduplicate by event id, storing processed ids with a unique constraint; make handlers idempotent; and treat webhook payloads as a hint, re-fetching the resource from the API if authoritative state is needed. Return 4xx only for genuinely unprocessable payloads, since a permanent 4xx may stop retries or trigger endpoint disablement.

Event design: versioned event schemas, thin or fat payloads (fat payloads reduce round trips; thin ones avoid stale data and sensitive leakage), and let subscribers choose event types. Keep names as resource.action, e.g. payment.captured.

Testing and observability: offer a test-mode trigger or CLI forwarding, log every attempt with latency and status, and provide replay of events from a time window so consumers recover from their own outages.

## Code examples

### Webhook request with signature

```
POST /hooks/payments HTTP/1.1
Content-Type: application/json
X-Signature: t=1790000000,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd

{
  "id": "evt_01HZX",
  "type": "payment.captured",
  "created": 1790000000,
  "data": { "id": "pay_abc", "amount": 49900, "currency": "INR" }
}
```

The event id enables dedup; the signature and timestamp enable authenticity and replay protection.

### Verifying and deduplicating in Express

```
import crypto from 'crypto';
app.post('/hooks/payments', express.raw({ type: 'application/json' }), async (req, res) => {
  const [t, v1] = req.header('X-Signature').split(',').map((p) => p.split('=')[1]);
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return res.status(400).end();
  const expected = crypto.createHmac('sha256', SECRET).update(t + '.' + req.body).digest('hex');
  if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1))) return res.status(401).end();
  const event = JSON.parse(req.body);
  const fresh = await db.query('INSERT INTO processed_events(id) VALUES($1) ON CONFLICT DO NOTHING RETURNING id', [event.id]);
  if (fresh.rowCount) await queue.add('handle-event', event); // process async
  res.status(200).end();
});
```

Raw body HMAC check with timestamp tolerance, constant-time compare, unique-id dedup, then fast 200 and async processing.

## Key points

- Assume at-least-once delivery and possible reordering.
- Sign the raw body with HMAC and a timestamp to stop forgery and replay.
- Retry with exponential backoff and jitter; alert and disable persistently failing endpoints.
- Consumers should ack fast, process async, and dedupe by event id.
- Use an outbox so events are not lost when the business transaction commits.

## Common follow-up questions

- How do you handle a customer endpoint that is down for two days?
- Thin versus fat payloads: which and why?
- How do you rotate webhook secrets without downtime?
- How would you guarantee ordering?

## Interview tips

- Cover both the sender and the receiver side; most candidates do only one.
- Mention constant-time comparison and raw body verification.

## Concepts covered

webhooks, HMAC signatures, retries, idempotency

Previous: [GraphQL N+1 problem and DataLoader batching](https://www.internhack.in/learn/interview/api-design-interview/api-graphql-n-plus-one-dataloader) · Next: [Long-running operations: 202 Accepted and polling](https://www.internhack.in/learn/interview/api-design-interview/api-long-running-operations) · [All of API Design](https://www.internhack.in/learn/interview/api-design-interview)

## More API Design questions

- [Bulk and batch endpoints: partial failure handling](https://www.internhack.in/learn/interview/api-design-interview/api-bulk-batch-endpoints)
- [API documentation with OpenAPI and contract-first design](https://www.internhack.in/learn/interview/api-design-interview/api-openapi-documentation)
- [Backward compatibility and deprecating an API safely](https://www.internhack.in/learn/interview/api-design-interview/api-backward-compat-deprecation)
- [API gateway: responsibilities and trade-offs](https://www.internhack.in/learn/interview/api-design-interview/api-gateway)
- [Design the API for a URL shortener](https://www.internhack.in/learn/interview/api-design-interview/api-design-url-shortener)
- [Design the order API for a food delivery app](https://www.internhack.in/learn/interview/api-design-interview/api-design-food-delivery-order)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [API Design](https://www.internhack.in/learn/interview/api-design-interview)
