System Design Patterns: From Fundamentals to Real Systems
Vote

0% completed

​

Webhooks

What a Webhook Is

Why the Store Does Not Keep Asking

What the Provider Promises

The Receiver's Five Disciplines

  1. Verify
  1. Persist and 3. Acknowledge
  1. Deduplicate
  1. Reconcile

When the Store Sends Webhooks

When to Use Webhooks

Check Yourself

Summary

Webhooks Explained: Letting Another System Call You Back, Retries, Signatures, and Webhooks vs Polling (Video)
Webhooks
Webhooks

How does the store learn that a payment succeeded inside another company's system? The store hands each charge to a payment provider, a separate company that moves money between banks and card networks. The store cannot read the provider's database or run code on its servers. The result may also come seconds later or days later. A buyer can approve a payment in a banking app after a minute, or ask for a refund after a week.

The store could keep asking the provider whether anything has changed. Almost every answer would be "not yet." A better design reverses the direction: the provider calls the store when something changes.

That call is a webhook. This lesson explains what a webhook is, why the store does not keep asking, what the provider promises, and the five things the store must do with every webhook it receives.

What a Webhook Is

A webhook is an HTTP request that one company's system sends to another company's URL when an event happens. In programming, a hook is a place where a system runs outside code when something happens. A webhook applies that idea over the web: the outside code is behind a URL, and each event reaches that code as an HTTP request.

The setup happens once. The store gives the provider a public URL, for example https://store.example.com/webhooks/payments, and chooses which events it wants. That URL is the store's webhook endpoint, the address that receives the requests. From then on, the provider sends a POST request to the endpoint every time one of those events happens.

The body of each request describes one event:

{ "id": "evt_7Hq2", "type": "payment.succeeded", "created": 1763112135, "data": { "payment_id": "pay_8812", "order_id": "ord_5531", "amount": 4000, "currency": "usd" } }

Three fields matter most to the receiver. The id is the event's unique ID, and every repeated delivery of the same event carries the same ID. The type says what happened, and created says when the provider recorded it. The amount is in cents, so this event reports a $40 payment.

Compare this with Request-Response. The store is now the server, and another company is the caller. The provider does not wait for the store to do any work. It waits only for a short answer that means "received."

Why the Store Does Not Keep Asking

Asking again and again whether anything has changed is called polling. It is request-response repeated on a timer. The store's own numbers show why polling does not work here.

The store receives 200 orders per second on a normal day. For about one payment in ten, the charge call returns only "processing," because the buyer must approve the payment in a banking app or the money moves by bank transfer. That makes 20 new pending payments per second, and each stays pending for about 3 minutes on average. Little's law, from the Back-of-the-Envelope Math lesson, says that the number waiting equals the arrival rate times the average wait. So 20 per second × 180 seconds = 3,600 payments are pending at any moment.

Asking versus being told
Asking versus being told

The top panel shows polling. The store asks about each of the 3,600 payments every 5 seconds, which is 3,600 ÷ 5 = 720 requests per second. Only 20 of them each second find a change, so 700 out of 720, about 97 percent, are answered "no change." The provider allows each customer 100 status checks per second, separate from its limit on charges. Polling needs more than seven times that limit. A buyer also waits 2.5 seconds longer on average to see the result.

The bottom panel shows webhooks. The provider sends one request for each change, about 20 per second, and every request carries news. The store learns of each result within a second or two of the change.

Polling fails completely for events that have no deadline. A buyer can ask for a refund days later. A cardholder can dispute a charge weeks later, which means asking the bank to reverse it. The store takes 200 × 86,400 = 17,280,000 payments a day. Checking each of them once a day would add 200 more requests per second, and even then the store would learn of a refund up to a day late.

What the Provider Promises

A webhook crosses a company boundary, so the store controls only its own side. Four facts about the provider decide how the store must build its receiving side:

  • It waits only a short time. The provider waits 10 seconds for a 2xx response. If no such response arrives, it counts the delivery as failed.
  • It delivers at least once. After a failure, it sends the same event again with growing gaps: after 1 minute, 5 minutes, 30 minutes, 2 hours, and then every few hours. Sending every event one or more times is called at-least-once delivery.
  • It does not promise order. Because of retries and parallel senders, payment.refunded can arrive before payment.succeeded for the same payment.
  • It gives up. After 3 days of failures, the provider stops trying, and that event is never sent again.

A fifth fact comes from the internet itself. The endpoint is a public URL, so anyone who learns it can send a request that looks like a payment event. Together, these five facts lead to five rules for the receiving side, called the receiver's disciplines.

The Receiver's Five Disciplines

A safe receiver does five things: verify, persist, acknowledge, deduplicate, and reconcile. The first three happen inside the request, and the last two happen afterward.

The receiver's five disciplines
The receiver's five disciplines

Follow the diagram from left to right. The request enters on the left, and steps 1 to 3 finish in about 10 ms, so the 200 OK leaves long before the provider's 10-second limit. The slow work happens to the right, in a worker that reads saved events. The reconciliation job at the bottom asks the provider directly and repairs any event that never arrived.

1. Verify

The provider and the store share a secret key that nobody else knows. For each request, the provider computes a short code from the request body, a timestamp, and the secret, and puts that code in a header. The code is a signature, usually computed with HMAC-SHA256, a standard method for signing a message with a shared secret. The store computes the same code from the bytes it received and rejects the request with 401 if the two codes differ.

The timestamp blocks a second attack. Someone who copies a real signed request could send it again later, which is called a replay. The store rejects any request whose timestamp is more than 5 minutes old. When the store changes the secret, it accepts both the old and the new secret for a short time, so it can replace a leaked secret without losing events.

2. Persist and 3. Acknowledge

After verification, the store saves the raw request body to a table of received events, and only then returns 200 OK. Verifying and saving take about 10 ms together. The answer means "I have it stored safely," not "I have finished the work."

The real work happens later, in a worker that reads saved events, like the workers behind a message queue. For payment.succeeded, the worker marks the order paid, so the order can move on to shipping, and emails the buyer a payment confirmation. This email is not the receipt, which already went out when the order was placed. On a normal day this takes under half a second. Saving the raw body also helps when the worker has a bug, because the store can fix the code and then process the saved events again.

A late answer becomes a duplicate
A late answer becomes a duplicate

The timeline shows what happens when a handler does the work before it answers. On a busy afternoon, the email service slows to 12 seconds per message. The provider stops waiting at 10 seconds and counts the delivery as failed, although the store finishes the work 2 seconds later. About a minute later, the provider sends evt_7Hq2 again, and the buyer receives a second payment confirmation. The provider cannot tell whether the work happened. This is the "no answer" outcome from the request-response lesson.

4. Deduplicate

Because delivery is at least once, the same event can arrive two or more times even when the store answers quickly. The received-events table uses the event ID as its unique key. When the store tries to save the same ID a second time, the save fails, and the store returns 200 OK without a second copy. The worker also records each event ID it has finished and skips any ID it has already processed, so a restarted worker does not repeat events it has finished.

A duplicate must receive a 200, because an error makes the provider retry it for 3 days. This is the receiver's form of idempotency: processing an event twice gives the same result as processing it once.

Order is a separate problem from duplicates. An order's payment status moves in one direction only: processing, then succeeded or failed, then refunded. The worker ignores any event that would move the status backward, so a payment.succeeded that arrives after payment.refunded changes nothing. When an exact state matters, the worker treats the event as a notice and asks the provider's API for the payment's current state.

5. Reconcile

Some events never arrive. The endpoint may be down for longer than 3 days, a firewall change may block the provider, or the provider may have a bug. For a receiver, silence is a signal: a payment that stays "processing" for too long means an event was probably lost.

Reconciliation means comparing two independent records and repairing the differences. Every 15 minutes, the store's reconciliation job finds payments that have been "processing" for more than 30 minutes and asks the provider's API for each one's status. Once a day, it compares the provider's list of the previous day's events with the store's own records. A lost webhook then causes a delay of less than an hour instead of a lost order.

When the Store Sends Webhooks

The store also sends webhooks of its own. Some business customers buy in bulk through their own purchasing systems, and they want an order.shipped event instead of checking the store's website. The sender's duties match the receiver's five disciplines:

  • Sign every request, with secrets that each customer can replace.
  • Give every event a unique ID, so customers can deduplicate.
  • Keep a short timeout, like 10 seconds. Retry from a durable queue, which keeps events on disk, with one queue for each endpoint. Separate queues mean that one slow customer cannot delay deliveries to the others.
  • Publish the retry schedule, so customers know how long their endpoint can be down before they lose events.
  • Disable an endpoint that fails for days, tell the customer, and show every delivery attempt in a log with a button that sends an event again.

When to Use Webhooks

The module's question applies here too: does the caller need the answer before it can continue? For a payment result, the answer is no, because nobody can wait days for it. Inside the store, that answer leads to a queue or to publish-subscribe. Across a company boundary, the provider cannot write into the store's internal queue, so the two companies use the one thing they share, HTTP. A webhook is publish-subscribe across a company boundary: the store subscribes by registering a URL, and the provider publishes by sending a request.

SituationPattern
A payment result from the provider, seconds to days laterWebhook
A refund or a dispute, days or weeks laterWebhook, with reconciliation
Charging the card while the buyer waitsRequest-response
Telling five internal teams about order.placedPublish-subscribe
A long report that another system started202 Accepted, then a status check or a webhook
Showing order progress to a buyer in a browserNot a webhook, because a browser has no public URL

Webhooks fit poorly in two cases. The first is a receiver that cannot accept incoming requests, like a phone or a browser. The next lesson, Server-Sent Events, covers that case. The second is a caller that needs the answer now, which is request-response.

Check Yourself

Q1. The provider adds a new payment method. One payment in five uses it, and each one stays pending for 10 minutes on average. At 200 orders per second, how many requests per second would polling every 5 seconds need, and how many would webhooks need?

<details> <summary>Show answer</summary>

New pending payments arrive at 200 × 0.2 = 40 per second. Each stays pending for 600 seconds, so 40 × 600 = 24,000 payments are pending at any moment. Polling each one every 5 seconds needs 24,000 ÷ 5 = 4,800 requests per second, and only 40 of them find a change, so about 99 percent are answered "no change." Webhooks need about 40 requests per second, one for each change.

</details>

Q2. On a busy afternoon, some buyers receive two payment confirmation emails for one order. The webhook handler marks the order paid, moves it on to shipping, and sends the email, and then returns 200 OK. The email service is taking 12 seconds per message. What happened, and what should change?

<details> <summary>Show answer</summary>

The provider waits 10 seconds for an answer. The handler took about 12 seconds, so the provider counted the delivery as failed and sent the same event again about a minute later, and the handler sent a second email. Two changes fix it. The handler should verify, save the raw event, and answer within about 10 ms, leaving the work to a worker. The worker should skip any event ID it has already processed, because duplicates can arrive even when the answer is fast.

</details>

Q3 (incident). A firewall change blocks all requests from the payment provider for 4 days before anyone notices. The store has no reconciliation job. After the fix, which events reach the store, and what should change?

<details> <summary>Show answer</summary>

The provider retries each event for 3 days and then gives up. Events from the first day of the outage ran out of retries before the fix and are never sent again, so those buyers paid but their orders stay "processing." Events from the last 3 days arrive as their retries continue. A reconciliation job that runs every 15 minutes and checks payments pending for more than 30 minutes would have repaired each order within about 45 minutes. The growing number of stuck payments would also have shown the firewall problem on the first day instead of the fourth.

</details>

💡 In the interview: When an arrow in your diagram comes from another company, name it a webhook and list the receiver's five disciplines. A strong answer sounds like this: "The payment provider sends signed webhooks to our endpoint. We verify the signature, save the raw event, and return 200 within milliseconds. A worker processes saved events and skips any event ID it has already seen, because delivery is at least once and out of order. A job every 15 minutes asks the provider about payments stuck in processing, because a webhook can be lost." Expect a follow-up about a lost event or a duplicate confirmation email. Answer it with the provider's retry window and the event ID check.

Summary

<span style="white-space:nowrap">Problem</span>The store must learn payment results from another company, seconds to weeks later. With 3,600 payments pending, polling every 5 seconds costs 720 requests per second, and about 97 percent of the answers say no change. That is more than seven times the provider's limit of 100 status checks per second.
<span style="white-space:nowrap">Mechanism</span>The store registers a public endpoint once, and the provider sends a POST for each event, about 20 per second, with an event id, a type, and a created time. The provider waits 10 seconds for a 2xx, retries for 3 days with at-least-once delivery, and does not promise order.
<span style="white-space:nowrap">Costs</span>The receiver must verify the HMAC-SHA256 signature and timestamp, persist the raw body, acknowledge in about 10 ms, deduplicate by event ID, and reconcile every 15 minutes. Silence is a signal, because some events never arrive. Slow work before the answer causes retries, like a second payment confirmation email.
<span style="white-space:nowrap">When to skip</span>Skip it when the receiver cannot accept incoming requests, like a phone or a browser, which has no public URL (use server-sent events). Skip it when the caller needs the answer now (use request-response). Inside the store, telling five internal teams about an order uses publish-subscribe.
<span style="white-space:nowrap">30-second answer</span>The payment provider sends signed webhooks to our endpoint, and we verify the signature, save the raw event, and return 200 within milliseconds. A worker skips any event ID it has seen, because delivery is at least once and out of order. A job every 15 minutes checks payments stuck in processing, because a webhook can be lost.
Flashcards Review

What is a webhook?

1 / 22
General
Test Your Knowledge
Check your understanding and reinforce the key concepts covered in this section with a short, targeted assessment.
9 Questions
~14 mins
Your progress is saved automatically

Reading Progress

0%


Vote for new content

On This Page

What a Webhook Is

Why the Store Does Not Keep Asking

What the Provider Promises

The Receiver's Five Disciplines

  1. Verify
  1. Persist and 3. Acknowledge
  1. Deduplicate
  1. Reconcile

When the Store Sends Webhooks

When to Use Webhooks

Check Yourself

Summary