What Is a Webhook? How They Work and Where They Break

What is a webhook? An HTTP POST one system fires at another when an event happens. How the push model works, how signatures and retries keep it safe.

MMotherlode Lab10 min read
Magpie title card: What Is a Webhook? How They Work and Where They Break

What is a webhook? Strip the jargon and it is one system telling another, immediately, that something just happened, by sending an HTTP POST request to a URL the receiver registered in advance. A customer’s payment clears at 3 a.m. and the server knows in under a second, because the sender did the asking. The parts worth knowing are the boring ones: how a receiver verifies the payload is real, and what happens when a delivery fails.

The term, defined

A webhook is an HTTP POST request that one system sends to another as soon as a specific event happens, so the receiving system can react without asking whether anything changed. The word predates most of the tools using it: programmer Jeff Lindsay coined “webhook” in 2007, back when the alternative was screenscraping feeds on a timer.

The mechanism has three pieces:

  • The endpoint. A URL you expose, something like https://example.com/webhooks/payments. This is the webhook’s entire surface: one route that accepts POST.
  • The registration. You give that URL to the sender, usually in a dashboard (“Add endpoint” on Stripe’s Webhooks tab, “Add webhook” in a GitHub repo’s settings). The sender hands back a signing secret, which you store and never ship to a client.
  • The delivery. The event fires, the sender POSTs a JSON payload to your endpoint, and expects an HTTP 2xx response to consider it delivered.

That is the whole contract. If you can accept a POST, you can receive a webhook; no SDK is required, and no polling loop either.

How a webhook works, end to end

The lifecycle has five steps, and the failure modes live in the last two.

  1. You register your endpoint URL and subscribe to specific event types.
  2. Something happens on the sender’s side: a payment succeeds, a push lands on main, a subscription renews.
  3. The sender builds a JSON event object and POSTs it to your URL, with signature headers attached.
  4. Your handler verifies the signature, returns a 2xx quickly, and processes the event in the background.
  5. If step 4 fails (timeout, 5xx, connection refused), the sender retries on its own schedule.

You can feel the receiving side in five minutes with Python’s standard library and nothing else. Save this as hook.py:

from http.server import BaseHTTPRequestHandler, HTTPServer
import json

class Hook(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers["Content-Length"]))
        event = json.loads(body)
        print(self.headers.get("X-GitHub-Event"), event.get("ref"))
        for commit in event.get("commits", []):
            print(" ", commit["id"][:7], commit["message"])
        self.send_response(204)
        self.end_headers()

HTTPServer(("0.0.0.0", 8000), Hook).serve_forever()

Run it, then throw a webhook at it from another terminal:

$ curl -X POST http://localhost:8000/webhooks \
    -H "Content-Type: application/json" \
    -H "X-GitHub-Event: push" \
    -d '{"ref":"refs/heads/main","commits":[{"id":"c41d9ab","message":"fix: parse empty feeds"}]}'
push refs/heads/main
  c41d9ab fix: parse empty feeds

The 204 status code is what the sender checks. It means “received, safe to delete this delivery from my retry queue”. A real GitHub push payload carries the repository, pusher, and full commit list, and the same headers; the payload above is abridged to what the toy handler reads.

What is a webhook used for?

The same shape shows up everywhere one system needs to know about another system’s events without waiting for a scheduled check:

  • Payments. Stripe POSTs payment_intent.succeeded when money actually arrives, which can be minutes after checkout while a bank confirms. Fulfillment code hangs off that event.
  • CI/CD. A push to main triggers a build pipeline. The forge pushes; the build server never polls the repo.
  • Commerce. Shopify fires orders/create; invoicing and fulfillment systems subscribe.
  • Alerting and automation. Monitoring tools, form backends, and page-change watchers POST to chat channels or notification services when a threshold trips.

The pattern’s appeal is timing. The receiver learns about an event seconds after it happens, and the sender bears the transport cost.

Webhook vs API polling

An API call is you asking. A webhook is it telling you. Most systems that send webhooks also expose the same data through a regular API, so the choice is about who initiates.

Webhook (push) API polling (pull)
Who initiates The sender, on each event You, on a schedule
Latency Seconds after the event One polling interval, average half of it
Requests when nothing happens Zero One per interval, every interval
Receiver needs a public URL Yes, reachable by the sender No, works from behind NAT
Ordering and completeness Sender-dependent, retries involved You control the pagination and order
Setup Register endpoint, store secret Cron job and an API client

The zero-requests row is where the arithmetic gets brutal for polling. A change monitor polling one URL every minute performs 1,440 requests a day. If the thing it watches changes once a day, 1,439 of those requests exist to be told nothing happened. Scale that to 50 watched URLs and you send 72,000 requests a day for one useful event each. Polling is also the pattern that bumps into rate limits first, since the polling interval is your politeness budget.

Polling still wins in one common case: your receiver has no public URL. A script on a laptop behind NAT cannot receive POSTs, so a scheduled pull of an RSS feed is the practical design there. Webhooks flip the requirement around: the sender needs to reach you, so production endpoints live on public HTTPS hosts.

Inside a webhook request

Every webhook is a plain HTTP POST. The interesting part is the headers, because that is where the sender tells you what happened and how to trust it. GitHub’s delivery headers, all documented and stable for years:

Header What it tells you
Content-Type: application/json The payload format (some senders still use form encoding)
X-GitHub-Event Which event fired: push, issues, ping
X-GitHub-Delivery A unique ID for this delivery; your dedupe key
X-Hub-Signature-256 The HMAC-SHA256 signature of the body, sha256=<hex>
User-Agent Identifies the sender: GitHub-Hookshot/<hash>

The body is the event as JSON. For a push event, the fields worth routing on are ref (the branch), pusher, and commits. Stripe’s equivalent event carries a type field like payment_intent.succeeded and nests the changed object under data.object.

GitHub sends a ping event the moment you create the webhook, a free smoke-test delivery. Stripe sends nothing until an event actually fires, which is what stripe trigger exists for.

Verify the signature before you trust the payload

Your webhook URL is public. Anyone who discovers it can POST a fake event, and a naive handler will happily “confirm” a payment that never happened. The signing secret from registration exists for exactly this: the sender computes an HMAC-SHA256 of the request and signs it, you recompute it on your side and compare.

Stripe’s scheme is worth reading once because every detail has a reason. Each delivery carries:

Stripe-Signature: t=1793577600,v1=5257a869e7e...

The t is a Unix timestamp, and the signature covers "{t}.{raw body}", so the timestamp itself is tamper-evident. Verification is four steps, in order:

  1. Reject if the timestamp is older than your tolerance. Stripe’s libraries default to 5 minutes, which bounds how long an intercepted delivery stays replayable.
  2. Compute HMAC-SHA256(secret, "{t}.{body}").
  3. Compare against v1 with a constant-time comparison, so timing leaks nothing.
  4. Reject on mismatch.

In Python, no SDK needed:

import hmac, hashlib, time

def verify(payload: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    parts = dict(p.strip().split("=", 1) for p in header.split(","))
    ts, sig = parts["t"], parts["v1"]
    if abs(time.time() - int(ts)) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{ts}.".encode() + payload,
                        hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)

GitHub uses the same primitive with a simpler header: X-Hub-Signature-256: sha256=<hex>, HMAC over the raw body only.

The trap that costs people hours sits between the framework and the crypto: verify the raw body. If your framework parses the JSON first and you re-serialize it for verification, a reordered key or reformatted float changes the bytes and the signature check fails forever. Every provider’s troubleshooting guide has this entry, because every framework makes it easy to do by accident. Read the body once as bytes, verify, then parse.

What happens when a webhook fails

A delivery “fails” when the sender gets anything other than a clean 2xx: connection refused, timeout, 4xx, 5xx. Note that a redirect counts as a failure on Stripe, which surprises anyone whose endpoint 302s to a canonical URL. The retry policies differ by sender:

Sender Retry behavior on failure
Stripe, live mode Re-attempts for up to 3 days with exponential backoff; manual resend via dashboard (15 days) or CLI (30 days)
Stripe, sandbox 3 retries over a few hours
GitHub No automatic retry. 10-second response window, then the connection is terminated and the delivery marked failed; redelivery is manual

GitHub’s 10-second rule is the one that bites hardest. Your handler has ten seconds to return a 2xx before the delivery is dead, so the handler’s job is to acknowledge, not to process: enqueue the event, return, work through the queue at your own pace.

Two properties of the transport follow from all this, and handlers should assume both:

  • At-least-once delivery. Retries mean duplicates. Stripe’s own guidance is to log processed event IDs and skip repeats; GitHub’s X-GitHub-Delivery header gives you the equivalent dedupe key. Write handlers that survive seeing the same event twice.
  • No ordering guarantee. Stripe documents that events can arrive out of order, so invoice.paid can precede invoice.created. Don’t build state machines on arrival order; fetch current state from the API when an event arrives.

Test one without deploying anything

The fastest loop needs no account: open webhook.site, copy the URL it generates, and curl -X POST something at it. The page shows you the exact headers and body, which is the view your handler will get. For sender-side testing, Stripe’s CLI replays real event shapes at localhost without a public URL:

$ stripe listen --forward-to localhost:8000/webhooks
Ready! Your webhook signing secret is 'whsec_...' (^C to quit)

Then stripe trigger payment_intent.succeeded in a second terminal and watch the delivery land. ngrok fills the same gap when you need a temporary public HTTPS URL for a sender that can’t run locally, and the Stripe docs recommend it for exactly that.

The same plumbing carries page-change alerts. A release-watching guide on this site shows the full chain: a monitor posts a JSON body to a local receiver when a tracked page changes, with a delivery ID header to dedupe against. I ran that exact chain end to end, monitor to an ntfy receiver on 127.0.0.1, and the POST arrived with a webhook-id header like msg_9f3ac2..., the same header pattern these platform deliveries use. A cron-plus-webhook recipe for SEC filing alerts covers the variant where the site itself offers no endpoint and you generate the event yourself.

FAQ

What is a webhook in simple terms? An automated HTTP POST. When an event happens on system A, it sends the event’s data to a URL system B registered earlier. B reacts immediately instead of asking A “anything new?” on a timer.

What’s the difference between a webhook and an API? An API is pull: your code calls it whenever it wants data. A webhook is push: the provider calls your URL when an event happens. Most providers offer both, and webhooks usually carry a reference you resolve with the API.

Are webhooks secure? The transport is, when both sides use HTTPS. The payload isn’t automatically trustworthy: verify the HMAC signature with your signing secret, check the timestamp window, and process events idempotently. An unverified webhook endpoint is a public API for forging events.

What happens if a webhook fails? The sender retries, usually with exponential backoff, then gives up. Stripe retries live-mode deliveries for up to 3 days; GitHub marks the delivery failed and waits for you to redeliver manually. Check the sender’s delivery log before assuming silence means success.

Do webhooks require a public URL? For production, yes: the sender’s servers must reach your endpoint over HTTPS. During development, tunnel localhost with ngrok or use the provider’s CLI forwarder (stripe listen) so nothing public is exposed.

Where to take this next

Register an endpoint on a platform you already use, point it at webhook.site first, and read the ping delivery’s headers before writing any handler code. The signature section above is the part to get right before going live; everything else is a retry log waiting to happen. The glossary hub holds the surrounding vocabulary, and the web crawler entry covers the fetch-and-extract side of watching the web for a living.

Stop renting credits.

One flat price, your machine, your keys.

Download free for Windows, macOS and Linux

Windows · macOS · Linux $49/mo flat, cancel anytime