Card 04/ 09

ConceptDifficulty: Intermediate1 min

Webhooks as a Contract

Instead of the client asking, the server calls the client's URL when something happens.

A webhook is an HTTP request the API sends to a URL the client registered, announcing that something happened, such as a job finishing or an order being paid. The receiver acknowledges it with any 2xx response, and if it does not, the sender retries. A webhook turns the usual roles around: the receiver is now running an API, and the sender is its client.

An event, a delivery that fails, a retry, and the receiver's acknowledgement

Registration. The client gives the API a URL and the event types it wants, through a dashboard or an endpoint such as POST /webhook-subscriptions. The API gives back a signing secret, covered on its own card.

The payload. Each delivery carries an event id, an event type such as order.paid, the time it happened, and either the changed resource or a link to it. Sending only the id and type, and letting the receiver fetch the current state, avoids stale copies at the cost of a request.

Acknowledgement. Any 2xx means received. The receiver should store the event and answer quickly, doing the real work afterwards, because the sender times out slow receivers and retries them.

Retries. On a non-2xx or a timeout the sender tries again with growing delays, for hours or days, and then gives up or disables the subscription. A retry may follow a delivery that in fact arrived, so the receiver must expect repeats.

Reachability. The receiver needs a public HTTPS URL the sender can call. A mobile app or a script behind a firewall has none, which is why polling stays available.

So document a webhook like any endpoint: its payload, its headers, its signature, and what the sender does on failure.