WEBHOOK DELIVERY
Late, twice, out of order, and sometimes not from them
Owoleaf's receiver verifies the signature and keeps a table of event ids it has processed, skipping repeats. After the outage, the processor's retries deliver refund.succeeded for ch_1 before charge.succeeded for ch_1. Both are genuine and new. What happens?
A webhook is the provider calling you over HTTP when something changes. The network and your uptime turn that call into at-least-once delivery, with three extra problems. Retries after an outage arrive duplicated and out of order. And your endpoint is a public URL, so anyone can POST a forged event to it.
Each has its own fix. Verify the signature, so only the provider’s events count. Dedupe by event id, as in idempotency. Then stop trusting arrival order: treat the event as a hint, fetch the object from the provider’s API, and move your record forward through its states (none → succeeded → refunded, never back). A top-up is captured at once, so succeeded here is the processor’s word for captured; the full set of card states is in authorise, capture, refund. Answer 2xx fast and do the work in a queue, or your own slowness makes the provider send it again.
app.post('/webhooks/provider', async (req, res) => {
const e = req.body; // trusts whatever JSON arrives
if (e.type === 'charge.succeeded') await wallet.credit(e.charge, e.amount);
if (e.type === 'refund.succeeded') await wallet.debit(e.charge, e.amount);
await slowAccountingSync(e); // provider times out, retries
res.sendStatus(200);
});app.post('/webhooks/provider', raw(), async (req, res) => {
const e = provider.verify(req.rawBody, req.headers['signature'], { tolerance: 300 });
if (!e) return res.sendStatus(400); // forged or stale
const fresh = await db.insertIfAbsent('webhook_events', e.id);
if (fresh) await queue.push(e); // process async
res.sendStatus(200); // answer fast
});
// worker
async function process(e) {
const charge = await provider.charges.get(e.charge); // refetch: order no longer matters
await ledger.advance(charge.id, charge.status); // none → succeeded → refunded, never back
} All three receivers get the same seven deliveries. NAIVE goes red on every invariant and ends at ₦255,000. VERIFY + DEDUPE rejects the forgery and the second evt_1, but the early refund still takes the wallet to −₦45,000 and leaves ch_1 marked succeeded. The fix asks the provider for ch_1 when the refund arrives, gets “refunded”, and applies the credit and the debit in their real order; evt_1 then finds nothing to do.
This receiver verifies the signature and dedupes by event id, then applies each event as it arrives. Inject one fault that still corrupts Zainab’s wallet or the charge’s state.
GOAL: an invariant is red at the end of the run
Write the receiver. Return an HTTP status; the provider retries any genuine event that gets a non-2xx, up to 5 attempts, then puts it in its dead-letter queue. The grader sends duplicates, refunds before charges and forged events, and checks the wallet after every delivery and the charge states at the end.
Real providers document all of this. Stripe’s webhook guide says it retries for up to three days with exponential backoff in live mode, does not guarantee events arrive in the order they were generated, may deliver the same event more than once (log the event ids you have processed), and that you should return 2xx before any complex logic and process events from an asynchronous queue. Its signature header signs a timestamp with the body, its libraries default to a five-minute tolerance, and each retry is signed afresh with a new timestamp. The timestamp window and replay are covered in secrets, rotation and replay.
If you are the sender, as Ferrowave is for its payout webhooks, the other half is yours: retry with backoff and jitter while a receiver is down, move an event to a dead-letter queue and alert someone when the retries run out, and give receivers a way to refetch the object or resend the event. A refund that never arrives is as wrong as one that arrives twice.
Card and transfer processors' payment webhooks, payout status callbacks, SMS delivery reports, Git push hooks, subscription billing events. The symptoms: a refunded order still marked paid, a balance that dips below zero overnight, duplicate fulfilment after an outage, and a credit nobody can trace to a real payment.
“Design the receiver for a payment provider's webhooks.” Verify an HMAC over the raw body and a timestamp tolerance; insert the event id with a unique constraint and skip repeats; enqueue and return 2xx; in the worker, refetch the object and advance a state machine that never moves backwards. Then flip it: as the sender, sign events, retry with exponential backoff and jitter, dead-letter after the last attempt, and expose an events API for replays.
USED IN
Chapters that build on this lesson.
- Idempotency and moving money exactly oncePayments
- Integrating a payment provider: charges, verification, webhooksPayments
- Payment states, failures, reversals and refundsPayments
- Project: a wallet with funding, transfers, refunds and daily reconciliationPayments
- Authentication and authorisation for a multi-tenant SaaS and its public APISecurity
- Debugging a problem you have never seenSoftware Engineer
- Working with AI coding agentsSoftware Engineer