SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Long Polling
  • Server-Sent Events (SSE)
  • WebSockets
  • Webhooks
  • WebRTC
  • Short Polling
  • Push Notifications
  • MQTT
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Real-Time Communication

Webhooks

Instead of you asking again and again, the other system calls you when something happens.

⏱ 11 min readBeginnerInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A webhook is a message that one system sends to your URL when something happens. You do not keep asking. They call you.

  • It is an ordinary HTTP POST, sent from their server to yours.
  • Often called a “reverse API” or “HTTP callback”.
  • Used for payments, git pushes, shipping updates, form submissions and more.
  • You must make it secure (check the signature), fast (reply 2xx quickly) and safe to repeat (idempotent).

02Concept: What is it?

Normally you call an API. With a webhook, you give the other system a URL, and they call you when an event happens.

API call vs webhook
Polling an API
🛒Your app
↓Paid yet?
💳Payment co.No
↓Paid yet?
💳Payment co.Yes
Webhook
🛒Your appregistered a URL
↑POST: payment.succeeded
💳Payment co.calls you when paid
Asking Event pushed to you
Polling asks again and again. A webhook sends one message when it matters.

What a webhook looks like

What your server receives
POST /webhooks/payments HTTP/1.1
Content-Type: application/json
X-Signature: sha256=9f2b61c0…
X-Event-Id: evt_1042

{
  "id": "evt_1042",
  "type": "payment.succeeded",
  "data": { "order": "A-77", "amount": 49900, "currency": "INR" }
}

03Real-Life Example

🍵The courier
You order a parcel. Polling: you phone the courier every hour, “Has it arrived?”. Webhook: you give them your phone number. They call you when the parcel is at your door.
Courier
Webhook
Giving your phone number
Registering your webhook URL
Parcel delivered
An event happens (payment.succeeded)
Courier calls you
Their server POSTs to your URL
You pick up and say 'ok'
You reply 200 OK quickly
You do not pick up, they call again later
Retry with backoff
Check it is really the courier, not a stranger
Verify the signature
Payment journey with a webhook
  1. 1
    Customer pays on the payment page
  2. 2
    Bank confirms to the payment company
  3. 3
    Payment company POSTs payment.succeeded to your URL
  4. 4
    Your server checks the signature and replies 200 at once
  5. 5
    Your server marks the order paid and ships it (in the background)

04Why Do We Need It?

🗑️No wasted calls
No polling loop asking 'anything new?' thousands of times.
⚡Fast
You hear about events within seconds.
💰Cheaper
Fewer API calls, fewer rate-limit problems.
🔗Easy integration
Two systems connect with plain HTTP and JSON.
🧩Loose coupling
The sender does not need to know what you do with the event.
📉Scales well
The sender pushes only when there is news.
Webhooks turn “are we there yet?” into “I will tell you when we are there.”

05Where Do We Use It?

💳Payments
Payment succeeded, failed, refunded.
🧑‍💻Git hosting
A push or pull request triggers your build (CI).
🚚Shipping
Parcel picked up, out for delivery, delivered.
📝Forms and CRMs
A new lead or form submission.
💬Chat bots
A user sends a message to your bot.
📦E-commerce
New order, stock change, customer created.

06Types / Parts / How It Works

The parts

PartJob
EventSomething that happened, such as invoice.paid
Endpoint URLYour public HTTPS address that receives the call
PayloadThe JSON that describes the event
Signature headerProof that the sender is real and the body was not changed
Event idA unique id, used to ignore repeats
Retry policyHow the sender tries again when you do not reply with 2xx

How a delivery works

  1. 1
    You register a URL
    In the provider's dashboard or API. You also get a shared secret.
  2. 2
    An event happens at the provider
    For example, a payment completes.
  3. 3
    Provider signs and sends the POST
    It computes an HMAC of the body with the secret and adds it as a header.
  4. 4
    You verify, save, and reply 2xx fast
    Check the signature. Store the event. Reply 200 within a few seconds.
  5. 5
    You do the real work in the background
    Use a queue. Do not make the sender wait.
  6. 6
    If you fail, the provider retries
    Usually with growing waits, for hours or days (general idea).
A safe receiver
💳Provider
→↓POST + signature
🛡️1. Verify signature
→↓
💾2. Save event idskip if seen
→↓
✅3. Reply 200
→↓
📬4. Queue the work
VisualizerPolling vs webhookPress Play. A payment completes at second 20. Change the polling gap and count wasted calls.
Your shop waits for a payment to finish (it finishes at second 20). Now: 0 s
Polling: "Is it done yet?"
🛒Your shop
↔0 calls so far
💳Payment co.
Webhook: "We will call you."
🛒Your shop
←silence…
💳Payment co.
Polling calls
0
Wasted
0
answer was 'not yet'
Polling delay
–
Webhook calls
0
Webhook delay
–
Press Play. Try a smaller polling gap: more calls, faster news. Try a bigger gap: fewer calls, slower news.
VisualizerDelivery, retries and signaturesTake the receiver down, watch the backoff, then try a fake sender with and without a signature check.
Receiver
Check the signature?
Who sends it?
💳Payment co.has the secret key
→↓POST /webhooks/pay
💥Your serverdown
What the receiver gets
POST /webhooks/pay
X-Signature: sha256=9f2b…(HMAC of body + secret)
Idempotency/Event-Id: evt_1042

{ "type": "payment.succeeded", "id": "evt_1042" }
Delivery attempts (waits double: 1s, 2s, 4s, 8s)
No attempts yet.
    Attempts
    0
    Delivered
    No
    Duplicates ignored
    0
    Start with the receiver down: retries wait longer each time. Bring it up and watch the next retry succeed.

    07How to Use It / Steps / Implementation

    Receiving webhooks well

    1. Use HTTPS only so no one can read or change the message on the way.
    2. Verify the signature (HMAC). Compute HMAC-SHA256 of the raw body with your secret. Compare it with the header using a constant-time compare. Reject if it differs.
    3. Check the timestamp (if given) and reject old messages. This blocks replay attacks.
    4. Reply 2xx quickly, in a second or two. Put the real work in a queue.
    5. Be idempotent. The same event can arrive twice. Store the event id and skip repeats.
    6. Do not rely on order. Events may arrive out of order. Use timestamps or fetch the latest state from the API.
    7. Log everything and allow replay of failed events.
    Verify a signature (Node.js, general idea)
    import crypto from "node:crypto";
    
    function isValid(rawBody, headerSig, secret) {
      const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
      const a = Buffer.from(expected);
      const b = Buffer.from(headerSig);
      return a.length === b.length && crypto.timingSafeEqual(a, b);
    }

    Sending webhooks well (if you are the provider)

    • Sign every message and give each endpoint its own secret.
    • Retry with exponential backoff (and a little jitter). Stop after a limit and show failures in a dashboard.
    • Send a unique event id and a timestamp.
    • Use short timeouts. A slow customer must not block your sender.
    • Let customers replay events and see delivery logs.
    • Protect yourself (SSRF): do not let a customer point a webhook at your internal network.

    08Key Terms to Know

    TermMeaning in easy words
    WebhookAn HTTP request sent to your URL when an event happens
    Callback URL / endpointThe address you give the sender
    PayloadThe data inside the message
    HMACA secret-key checksum that proves who sent it and that it was not changed
    Shared secretA key known only to you and the sender
    IdempotentSafe to process the same event more than once
    Retry / backoffTrying again later, waiting longer each time
    Replay attackSending a copy of an old valid message again
    Dead letterA message that kept failing and is parked for a human to look at
    2xxA success status code (200, 202, 204)

    09Pros, Cons and Trade-offs

    ✅ Pros
    • Real-time feel without polling
    • Fewer API calls and lower cost
    • Simple: plain HTTP and JSON
    • Works between companies and across languages
    • The sender stays loosely coupled to you
    ⚠️ Cons
    • You need a public HTTPS endpoint (hard on localhost)
    • Delivery is 'at least once', so duplicates happen
    • Order is not guaranteed
    • If you are down, you depend on the sender's retries
    • You must secure and monitor an open door to your system

    Polling vs webhooks vs streaming

    PollingWebhookSSE / WebSocket
    Who starts it?YouThe other serverServer pushes over your open connection
    Talks toServerServer (your backend)Browser or app
    DelayUp to polling gapSecondsInstant
    ConnectionNew each timeNew for each eventStays open
    Good forSimple checksServer-to-server eventsLive UI updates

    10Common Problems and Mistakes

    Common mistakes

    1. No signature check. Anyone who knows your URL can send a fake “payment.succeeded”.
    2. Doing slow work before replying. The sender times out and retries, and you process it twice.
    3. Not handling duplicates. The customer gets two emails or two refunds.
    4. Assuming order. “updated” may arrive before “created”.
    5. Parsing the body before verifying. The signature is over the raw bytes. Re-encoded JSON will not match.
    6. Returning 500 on bad input forever. The sender retries without end. Return a clear 4xx for permanent errors.
    7. Using the payload as the truth. For important data, fetch the latest state from the provider's API.
    🔁Retry storm
    You were down for an hour. Thousands of retries arrive when you return. Use a queue and rate-limit workers.
    🕳️Lost events
    You were down for longer than the retry window. Keep a reconcile job that lists recent events from the API.

    11Real-World Examples

    💳Payment gateways
    Payment companies send events such as payment succeeded, failed or refunded, signed with a secret.
    🧑‍💻Git hosting and CI
    A push or pull request calls a webhook, which starts a build.
    💬Team chat tools
    Incoming webhooks post a message into a channel. Outgoing ones send channel events to your bot.
    🚚Shipping and logistics
    Status updates for parcels are pushed to shops.
    Webhook is a good fit
    • Server-to-server events
    • Events are rare or bursty
    • You can expose an HTTPS endpoint
    • Seconds of delay is fine
    Choose something else
    • Updating a browser live: SSE or WebSockets
    • Huge event volume: a message broker or stream
    • You cannot expose a public URL: poll, or use a relay

    12Related Topics to Read Next

    What is an API?→

    A webhook is an API in reverse: they call you.

    Idempotency→

    Duplicates are normal, so handlers must be safe to repeat.

    Message Queues→

    Queue the work after replying 200.

    Dead Letter Queues→

    Where events go when they keep failing.

    Delivery Semantics→

    Webhooks are 'at least once'.

    Long Polling→

    The alternative when you cannot expose a URL.

    13Interview Questions with Short Answers

    14Quick Revision Cheat-Sheet

    • ✔What: the other system POSTs to your URL when an event happens.
    • ✔Why: no polling, fewer calls, faster news.
    • ✔Receiver rules: HTTPS, verify the HMAC signature, reply 2xx fast, queue the work.
    • ✔Be idempotent: store event ids. Duplicates and odd order are normal.
    • ✔Sender rules: sign, retry with backoff, give logs and replay.
    • ✔Guarantee: at least once, not exactly once.
    • ✔One line: “Do not call us, we will call you.”
    ← Previous
    WebSockets
    Next →
    WebRTC