Video in progress
A payment provider sends the result through a webhook. How do you build the receiving side reliably?
Accept the webhook quickly (verify the signature, store it, return 200) and do the processing asynchronously. The provider can resend and reorder events, so you also need dedup by event ID, a state machine, and a periodic check by asking the provider for the status (polling).
📖 Answer
Look from the provider's side: it sends you a POST and expects a 2xx. If there's no answer in 10 seconds, it sends again. Sometimes the same event twice, sometimes CAPTURED before AUTHORIZED. And sometimes it doesn't send at all.
The receiving part:
@PostMapping("/webhooks/payprov")
public ResponseEntity<Void> receive(@RequestBody String raw,
@RequestHeader("X-Signature") String sig) {
if (!signer.verify(raw, sig)) return ResponseEntity.status(401).build();
WebhookEvent e = parse(raw);
inboxRepo.insertIfAbsent(e.id(), raw); // unique(event_id) — a duplicate passes silently
return ResponseEntity.ok().build(); // no heavy work
}
Then a separate worker reads from the inbox and updates the payment status.
The rules:
- The signature is verified over the raw body (if you parse the JSON and serialize it again, the signature won't match). The timestamp is checked too — protection against replaying an old request.
- A state machine:
UPDATE payments SET status = 'CAPTURED' WHERE id = ? AND status IN ('PENDING','AUTHORIZED'). A lateAUTHORIZEDcan't rollCAPTUREDback. - Keep the endpoint fast — one insert into the DB. If you call other services here, timeouts and a wave of resends begin.
- Polling as a backstop: for payments "PENDING for 15 minutes", a job asks the provider's API for the status. Losing a webhook is rare, but where money is involved, rare isn't rare enough.
And a daily reconciliation — comparing the provider's report with your own records — is the last line of defense.
Sign up to mark studied questions and save your progress.