Backend and APIs · Question 20 of 50
How do you make webhooks reliable?
Delivery guarantees, security and idempotency together.
The answer
A webhook is the provider calling your URL when something happens, such as a payment succeeding. Plan for three things. It can fail because your server was down, so providers retry with backoff. It can arrive more than once, so the handler must be idempotent: store the event id and skip repeats. It can be forged, so verify the signature (an HMAC of the raw body with your shared secret) and reject old timestamps.
Answer 2xx quickly and do the slow work from a queue. And do not rely on webhooks alone: reconcile by asking the provider's API about anything stuck.
const expected = crypto.createHmac('sha256', SECRET).update(rawBody).digest('hex')
const ok = signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
if (!ok) return res.sendStatus(401)
if (await seen(event.id)) return res.sendStatus(200) // a repeat
await queue.add(event)
res.sendStatus(200)The picture
provider ── POST event ──▶ /webhook: signature ok? → seen id? → queue → 200
│ no 2xx? │
└── retries with backoff: 1 min, 5 min, 30 min... ▼ a worker does the work
every night: reconcile with the provider's API (anything missed)Why use the raw body for the signature?
Show the answer
The signature covers the exact bytes that were sent; parsing and re-serialising the JSON can change them.