AlgoViz

Webhooks

easy 24 min

A webhook is an HTTP request that another system sends to your URL when something happens, so you do not have to keep asking.

Video lesson · Chapter 1 of 6

Wait for changes or receive them

0:00 / 5:34

Webhooks

1:17Reel

Theory

Read or listen first. About 2 min.

What it is

Normally your program calls another company's API. A webhook turns that around: you give the other company a URL, and their system sends an HTTP POST to it each time something you care about happens. It is sometimes called an HTTP callback or a reverse API.

The sender is a client and your server is the one being called. That small change brings three new duties: prove that the call is genuine, accept it quickly, and cope when the same call arrives twice, late or in the wrong order.

Why it exists

A shop needs to know when a payment succeeded. Asking every few seconds wastes calls on both sides and still hears the news late. Being told costs one call per event and takes about one network trip.

It also joins companies that share nothing else. No common database, no common queue, no library: only HTTPS, which every system already speaks.

A short history

  1. 1997

    RFC 2104 describes HMAC, a way to sign a message with a shared secret. Most webhook signatures today use it.

  2. 2007

    Jeff Lindsay coins the term webhook, from the programming word hook: a place where you can attach your own code.

  3. 2024

    RFC 9421 standardises signatures for HTTP messages in general. Many webhook senders still use their own header.

Words to know

Event
A record that something happened, with an id, a type, a time and some data.
Endpoint
The public HTTPS URL that receives the events.
Subscription
The saved wish: this URL, these event types, this secret.
HMAC
A signature made from a message and a shared secret. Without the secret it cannot be made.
At least once
Every event arrives one or more times. Removing the extra ones is the receiver's job.
Replay
Sending an old event again: on purpose by a person, or by an attacker who copied it.

How it works

Step through the idea, or press Play.

Step 1 of 3

Register. Tell the sender your URL, the event types and keep the secret

Understand it

Start here

Are we there yet?

On a long drive a child can ask the same question every few minutes, or make a deal: tell me when we arrive. The second way is quieter, and the news comes at exactly the right moment. But now the child must know that the voice is really the driver's.

The car trip
Are we there yet?NoAsked once

One difference: a real signature never sends the secret itself. It sends a proof that only someone with the secret can make.

The idea

Asking or being told

Your shop needs to know when a payment is successful. With polling you send GET /payment/status?id=123 every 5 seconds and read pending a hundred times. With a webhook you do nothing until one POST arrives.

Webhook (push)

  • The news arrives at once
  • No wasted requests: one per event
  • Lower cost for both sides
  • You need a public, secured endpoint

Polling (pull)

  • Most calls say nothing new
  • Late by up to one interval
  • Load grows with how often you ask
  • Simple: no public endpoint, nothing to verify

What polling costs

100,000×60 s5 s=1,200,000 calls a day≈14/s, peak 42/swebhooks: 100,000≈1.2/s, peak 3.5/s\begin{gathered} 100{,}000 \times \frac{60\,\text{s}}{5\,\text{s}} = 1{,}200{,}000\ \text{calls a day} \\ \approx 14/\text{s},\ \text{peak } 42/\text{s} \\ \text{webhooks: } 100{,}000 \approx 1.2/\text{s},\ \text{peak } 3.5/\text{s} \end{gathered}
Assumption: 100,000 payments a day, each polled every 5 seconds for a minute. A day is 86,400 s and peak is 3x average. Webhooks need 12 times fewer calls.

The general choice between asking and telling, including feeds and notifications, has its own page: push vs pull. For telling a browser or a phone, see real-time APIs.

Set up

Registering a webhook

  1. 1

    You register

    Call me at this URL when X happens. In a dashboard: settings, webhooks, add endpoint, enter the URL, select events, copy the signing secret.

  2. 2

    An event occurs

    A payment succeeds, an order ships, code is pushed.

  3. 3

    You are notified

    A POST with the event data reaches your URL.

HTTP
POST /api/webhooks HTTP/1.1Content-Type: application/json{  "url": "https://shop.example/webhooks/payments",  "events": ["payment.succeeded", "payment.failed", "refund.created"]}HTTP/1.1 201 Created{ "id": "we_demo_1", "secret": "whsec_FAKE_shown_only_once" }
Registering through an API. Here the sender makes the secret and shows it once. Never put it in code or logs.

Event names that explain themselves

AreaEvents
Ordersorder.created, order.paid, order.fulfilled, order.cancelled, refund.created, inventory.low
Paymentspayment.pending, payment.succeeded, payment.failed, subscription.created, subscription.cancelled, dispute.opened
Thing, dot, what happened to it, in the past tense. Subscribe only to what you use.

Receive

Accept fast, work later

The receiver

A payment company outside our system sends a signed POST to our webhook endpoint. The endpoint saves the event in an event store with a unique event id and puts the event id on a queue. A worker takes it from the queue, runs the business logic and marks the event done in the store.
The endpoint does three quick things. Everything slow is behind the queue.
  • Endpoint

    Public HTTPS URL. Checks the signature, saves, answers 200 within milliseconds.

  • Queue

    Redis, RabbitMQ or SQS. Separates receiving from processing, absorbs spikes, allows retries.

  • Worker

    Runs the business logic at its own speed. Can retry, and scales on its own.

  • Event store

    Every event with its status. Removes duplicates, allows replay and debugging, and is the audit trail.

The handler, message by message

Receive, verify, remove duplicates, store, queue, answer. The answer comes before the work and after the save.

Trust

Check the signature

Your URL is public. Anyone who learns it can post "order 88 is paid" and receive free goods. So every event carries a proof.

  1. 1

    The sender signs

    signature = HMAC-SHA256(secret, time + "." + body)

  2. 2

    It sends the proof in a header

    For Stripe: Stripe-Signature: t=1700000000,v1=9c1d... (values shortened).

  3. 3

    You compute the same

    With your copy of the secret, over the raw request bytes.

  4. 4

    Compare in constant time

    Equal means trusted. A constant-time comparison does not leak how many characters were right.

Why guessing does not work

2256≈1.2×1077 possible signatures2^{256} \approx 1.2 \times 10^{77}\ \text{possible signatures}
HMAC with SHA-256 gives 256 bits. The weak points are elsewhere: a leaked secret, a skipped check or a replayed message.

Accept or refuse

Order matters: an unverified request never reaches the database.

Signatures of well-known senders

SenderHeaderMethod
StripeStripe-SignatureHMAC-SHA256 of time and body
GitHubX-Hub-Signature-256HMAC-SHA256
ShopifyX-Shopify-Hmac-SHA256HMAC-SHA256, base64
TwilioX-Twilio-SignatureHMAC-SHA1 of URL and parameters by default; SHA-256 with a shared key
PayPalPAYPAL-TRANSMISSION-SIGSHA-256 with a certificate (public key)
Use the sender's official library when there is one.

More layers

  • Time check

    Refuse events older than 5 minutes, so a copied message cannot be replayed later. The sender signs each retry with a new time.

  • Event ids

    Keep the ids you handled. The same event is never processed twice.

  • HTTPS only

    The body may hold personal data. Plain HTTP shows it to anyone on the path.

  • Known addresses

    If the sender publishes its IP ranges, allow only those at the network edge. An extra layer, never the only one.

Reliability

Retries with growing waits

A typical schedule

AttemptWait before itTime since the first
1none0
21 minute1 min
35 minutes6 min
430 minutes36 min
52 hours2 h 36 min
61 day26 h 36 min
An example, not a standard. Real ones differ: Stripe tries for up to three days, PayPal up to 25 times in 3 days, Shopify up to 8 times in four hours, Slack three more times. GitHub does not retry by itself.

What counts as a failure

AnswerMeaning for most senders
2xxDelivered. Stop.
No answer in time, connection refused, DNS failureFailed. Retry.
5xxFailed. Retry.
4xxFailed. Most senders retry this too, because your bad deployment may be fixed soon. The Standard Webhooks specification suggests that a sender stops after 410 Gone.
3xxUsually a failure. Redirects are not followed.
So answer 2xx for anything you understood, also for a duplicate or an event type you ignore.

The life of one delivery

Waits that double or grow, with a random part, are explained under retries.

Choosing waits and jitter in general: retries. How long to wait for an answer: timeouts.

Correctness

Twice, late and out of order

The sender cannot tell a lost event from a lost answer, so it sends again. That makes delivery at least once. Two rules make it harmless.

  1. 1

    Let a unique key decide

    Insert the event id into a table with a unique constraint. If the insert is refused, answer 200 and stop. A read followed by a write has a gap in which two copies can pass.

  2. 2

    Compare versions, not arrival times

    Apply an event only if it is newer than what you have. If it has no version, use it as a hint and fetch the current object from the sender's API.

  3. 3

    Retry your own failures

    A failed event must be taken again from the queue. If you only look whether the id exists, a failed event is skipped for ever.

A lost answer makes a duplicate

The general theory, and the same idea for your own API, is on the idempotency page.

More about keys, races and crashes: idempotency.

Send

When you are the sender

The sender

Inside our system, an order service writes the order and the event to one database. The event goes to a delivery queue, where retries wait. A dispatcher signs it and posts it to the endpoints of customer A and customer B, which are outside our system.
Order and event are written in one transaction, so there is never an order without its event.
  • Outbox

    Write the event in the same transaction as the change. A relay then moves it to the queue.

  • One lane per customer

    A customer who answers slowly must not delay the others. Limit concurrent calls per endpoint.

  • Safe URLs

    A customer's URL could point at your internal network. Resolve it, refuse private addresses, do not follow redirects.

  • A delivery log

    Show attempts, answers and a replay button. Customers can then help themselves.

Operate

Watch, log and test

Alert onMeasureLog
A jump in signature failuresEvents received a minutePayload, without secrets and personal data
More processing errorsShare processed successfullyProcessing time
Queue getting longerAverage and p99 processing timeErrors with stack traces
Slower answersShare of duplicatesEvent id as correlation id

Testing

  1. 1

    On your machine

    A tunnel such as ngrok http 3000 gives your local server a public HTTPS address.

  2. 2

    From the command line

    Many senders have a tool, for example stripe listen --forward-to localhost:3000/webhooks.

  3. 3

    Replay

    Most dashboards can send an old event again.

  4. 4

    Reconcile

    Once a day list the objects changed at the sender and compare with yours. This finds events that were missed for good.

Do

  • Use a queue for the work
  • Verify every signature
  • Store the event id and remove duplicates
  • Keep the raw payload, protected, for debugging
  • Monitor and alert
  • Use HTTPS only
  • Answer 200 as soon as it is saved

Do not

  • Process before you answer
  • Trust a request because it found the URL
  • Assume events come in order
  • Ignore duplicates
  • Put secrets in code or logs
  • Use plain HTTP
  • Answer an error for an event you already handled

Numbers

Size the receiver

After an outage of one hour

3.5/s×3600 s=12,600 events waiting12,60020−3.5≈764 s≈13 min3.5/\text{s} \times 3600\,\text{s} = 12{,}600\ \text{events waiting} \qquad \frac{12{,}600}{20 - 3.5} \approx 764\,\text{s} \approx 13\,\text{min}
Assumption: the outage falls in the peak and workers handle 20 events a second. Capacity above the arrival rate is what clears a backlog.

Who uses it

Common senders

SenderTypical events
Stripe, PayPalPayments, refunds, subscriptions, disputes
GitHubPushes, pull requests, issues, releases
ShopifyOrders, customers, inventory
TwilioMessages received, calls, delivery status
SlackMessages, reactions, channels
SendGridEmail delivered, opened, bounced
ZoomMeeting started, ended, joined

Summary

The whole topic in one minute.

A webhook replaces asking with being told. The sender posts a signed event to a URL you registered. Your endpoint checks the signature over the raw bytes, inserts the event under its unique id, puts it on a queue and answers 200. A worker does the rest.

Delivery is at least once and not in order. So duplicates must be harmless, old news must be ignored, and a regular comparison with the sender's API must find whatever was missed for good.

  • A webhook is a POST to your URL when something happens: being told instead of asking.
  • Check the HMAC signature over the raw bytes, and the time, before anything else.
  • Save the event once under a unique id, queue it, answer 200, and work later.
  • Delivery is at least once and unordered, so duplicates and old news must be harmless.
  • Senders use an outbox, growing waits, one lane per customer and a replay button.

Sources