Track 06 · Lesson 7 of 8APIs and servers
Webhooks
Lesson 7 of 8· 6 min
A webhook is another service calling your API when something happens. Instead of asking a payment provider “has it gone through yet?” every few seconds, you give it a URL once, and it tells you the moment it does.
Polling or a webhook?
Change how often you poll
Polling
Webhook
Ten minutes. The black line is when the order ships.
Polling
10 requests, 9 wasted
Noticed 43s late · 1,440 requests a day per order
Webhook
1 request, 0 wasted
Noticed within a second · only when something happens
What arrives at your endpoint
POST /webhooks/shipping HTTP/1.1
Host: api.pizza.example
Content-Type: application/json
Webhook-Id: evt_1042
Webhook-Signature: t=1763200000,v1=5f2b…
{"type": "order.shipped", "orderId": 41}A webhook is the other service calling your API when something happens. You give it a URL once; it POSTs an event there every time.
How they work#
- You register an endpoint with the provider, like
https://api.pizza.example/webhooks/payments, and choose which events you want. - When something happens, the provider sends an HTTP
POSTwith a JSON event to that URL. - Your endpoint answers
2xxquickly to say “got it”. Anything else, or a timeout, and the provider retries later, often for days.
Payments, Git pushes, form submissions, deliveries, chat messages: most services that do things on your behalf can send webhooks.
Design your endpoint for the real world#
- Answer fast, work later. Save the event, put it on a queue and return
200. Slow handlers time out, and timeouts cause retries. - Expect duplicates and disorder. Retries mean the same event can arrive twice; events can arrive out of order. Process by event id, and check current state instead of assuming order.
- It’s a public URL. Anyone can POST to it. The next lesson is about proving a request really came from the provider.
Check yourself