Track 06 · Lesson 7 of 8APIs and servers

Track 06 · APIs 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#

  1. You register an endpoint with the provider, like https://api.pizza.example/webhooks/payments, and choose which events you want.
  2. When something happens, the provider sends an HTTP POST with a JSON event to that URL.
  3. Your endpoint answers 2xx quickly 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

Your webhook handler takes 40 seconds to process each event. What goes wrong?