# How Do Webhooks Work? A Hands-On Explanation

> How webhooks work, step by step: the HTTP request, payload and headers, retries, timeouts and signature checks, plus a live URL to watch one arrive.

- Published: 2026-11-16
- Page: https://www.otterkit.com/blog/how-do-webhooks-work

When something happens in one app, a webhook sends an HTTP request (usually a POST with a JSON body) to a URL you gave that app. Your server reads the request, replies quickly with a 2xx status, and does whatever the event calls for.

That's the whole idea. The rest of this post covers what the request looks like, why a fast reply matters, how to tell a real delivery from a forged one, and how to watch a live webhook arrive in your browser.

## Webhooks vs polling

You can learn that something changed in another system in two ways.

**Polling:** your code asks the other service's API over and over: "Any new orders? Any new orders?" Most of those calls come back empty. If you poll less often to save calls, you find out about changes later.

**Webhooks:** you give the service a URL once. When an event happens, the service sends a request to that URL. Nothing is sent while nothing is happening.

```
Polling:   your app ──GET /orders?──▶ provider   (every N seconds, mostly empty)
Webhook:   provider ──POST /webhook──▶ your app  (only when an event happens)
```

That's why webhooks are sometimes called a "reverse API" or a "push API". The usual roles are swapped: the provider calls your endpoint. The name combines "web" (the request travels over HTTP) and "hook" (your code hooks into an event).

Typical uses:

- a payment succeeds or a subscription is cancelled
- a new order is placed in a shop
- someone pushes code or opens a pull request, which starts a CI build or a deploy
- a form is submitted or a user signs up
- a CRM record changes and starts an email sequence

## What happens when an event fires

A delivery has four steps.

1. **You register a URL.** In the provider's webhook settings you enter an HTTPS endpoint (sometimes called a callback URL) and choose which events you want. This isn't an OAuth "redirect URI". It's just the address the provider will POST to.
2. **An event happens.** A customer pays, or a pull request opens.
3. **The provider sends an HTTP request.** It's almost always a POST, with headers that describe the event and a body that holds the data.
4. **Your server replies.** A 2xx status means "received". Anything else, including a timeout, counts as a failed delivery.

A redirect doesn't count as success. If your endpoint answers with a 302, most senders treat that as a failure. Answer the request directly with a 2xx.

## Anatomy of a webhook request

Here's roughly what a GitHub delivery for a newly opened issue looks like on the wire, shortened:

```
POST /webhook HTTP/1.1
Host: example.com
Content-Type: application/json
X-GitHub-Event: issues
X-GitHub-Delivery: 72d3162e-cc78-11e3-81ab-4c9367dc0958
X-Hub-Signature-256: sha256=7d38cdd689735b008b3c702edd92eea23791c5f6...

{
  "action": "opened",
  "issue": { "number": 42, "title": "Login button does nothing" },
  "repository": { "full_name": "acme/web" },
  "sender": { "login": "ada" }
}
```

Each part has a job:

- **Method and path.** Usually `POST` to the path you registered.
- **Content-Type.** Most providers send `application/json`, but some can send form-encoded bodies. If your handler expects JSON and gets `payload=%7B%22action...`, check this setting first.
- **Event type header.** GitHub puts the event type in `X-GitHub-Event` and the specific action in a top-level `action` field in the body, as its [webhook best practices](https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks) explain. Check both before you act on anything.
- **Delivery ID.** A unique ID for this delivery. You'll use it to spot duplicates.
- **Signature.** A hash of the body, computed with a secret that only you and the provider know. More on this below.
- **Body.** The event data.

Providers send one of two kinds of payload. A **full payload** includes the whole object, such as the order or the invoice. A **thin payload** includes only an event type and an ID, and you call the provider's API to get the current object. Thin payloads mean an extra API call, but you always work with fresh data. Full payloads save that call, but the data may already be out of date by the time you process it.

## A minimal receiver you can run

This standard-library Python server accepts GitHub-style deliveries on port 3000. It checks the signature against the raw body before parsing anything, and replies straight away:

```python
import hashlib, hmac, json, os
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ["WEBHOOK_SECRET"].encode()

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        raw = self.rfile.read(length)  # raw bytes: verify these, not parsed JSON

        expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
        received = self.headers.get("X-Hub-Signature-256", "")
        if not hmac.compare_digest(expected, received):
            self.send_response(401)
            self.end_headers()
            return

        event = json.loads(raw)
        print(self.headers.get("X-GitHub-Event"), event.get("action"))
        # In a real app: store the event, enqueue the work, then reply.
        self.send_response(200)
        self.end_headers()

HTTPServer(("", 3000), Handler).serve_forever()
```

Two details matter here, and they come up again in the next sections. The signature is computed over the **raw bytes**, and the comparison uses **`hmac.compare_digest`**, which runs in constant time, so an attacker can't learn the signature from how long the comparison takes.

## Retries, timeouts and why a fast 200 matters

Senders don't wait long. GitHub expects a 2xx reply [within 10 seconds](https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks). If none comes, it drops the connection and marks the delivery as failed. Slack expects a reply to an event within 3 seconds.

What happens after a failure depends on the provider. Many retry with growing gaps between attempts. GitHub's best practices ask you to redeliver missed events yourself. Check your provider's docs for its exact rules.

These rules lead to a few habits:

- **Acknowledge first, work later.** Check the signature, store the event, return 200 or 202, then do the slow work (database writes, emails, model calls) from a queue. GitHub recommends this pattern too.
- **Make handlers idempotent.** Retries mean the same event can arrive twice. Record each delivery or event ID, and when an ID you've already handled shows up again, return 200 and do nothing. Don't answer duplicates with an error, because the sender will just try again.
- **Don't assume order.** Retries and parallel deliveries mean that "subscription updated" can arrive before "subscription created". Check the object's current state, or its timestamps, before acting.
- **Pick status codes on purpose.** A 5xx tells the sender that your side failed and it should retry. A 4xx says the request itself was rejected. OtterKit's guide to [4xx codes for webhook endpoints](https://www.otterkit.com/http-status-codes) explains how senders react to each one.

## Security: signatures and authentication

A webhook URL is a public address. Anyone who finds it can POST to it, so a hard-to-guess URL on its own isn't enough protection.

Most providers sign each delivery. They compute an HMAC of the body with a secret you share with them and send the result in a header. GitHub, for example, sends an HMAC-SHA256 hex digest in `X-Hub-Signature-256`, prefixed with `sha256=`. Checking it confirms that the delivery came from GitHub and wasn't changed on the way ([GitHub's validation guide](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries)).

The checklist:

- **Use HTTPS** so the payload and headers can't be read on the way.
- **Verify the raw body before parsing.** Many frameworks parse JSON before your code runs. If you serialise it again and hash that, the bytes are different and a genuine request fails the check. This is the most common reason a check fails even when the secret is right.
- **Compare in constant time**, as in the example above.
- **Reject stale requests.** Some providers put a timestamp in the signed data. Refuse requests whose timestamp is too old, so a captured request can't be replayed later.
- **Keep secrets per environment.** A test-mode secret won't verify live-mode events.
- **Subscribe to as few events as you need.** Fewer event types means less to handle and less to secure.

## Troubleshooting when nothing arrives

When a delivery never reaches your code, the problem is usually one of these:

- **The URL points at localhost.** The provider can't reach `http://localhost:3000`. It needs a public HTTPS address.
- **DNS or TLS problems.** The domain doesn't resolve, or the certificate is expired or self-signed.
- **Firewalls or IP allowlists** block the sender's IP addresses.
- **Timeouts.** The handler does slow work before replying.
- **A proxy in front of your app** rewrites the body, drops the signature header, or rejects large bodies with a 413.

Most providers show a delivery log with the status and response for each attempt. Check that first. If the provider shows a failure but your app log is empty, the request never reached your code.

## Watch a real webhook arrive in your browser

The quickest way to understand all of this is to watch a request arrive. The [OtterKit webhook tester](https://www.otterkit.com/try) gives you a live URL like `https://try-….otterkit.app` with no account or install. The demo URL:

- lasts 30 minutes and captures up to 50 requests
- accepts any method on any path
- answers every request with `200` and `{"received":true}`

Send it something with curl:

```
curl -X POST https://try-….otterkit.app/orders \
  -H "content-type: application/json" \
  -d '{"order_id":"ord_42","total":128}'
```

Or click the sample buttons on the page: a JSON order, a Stripe-style `checkout.session.completed` event, a GitHub-style push to `main`, and a form submit to `/signup`. Each request appears in the feed with its method, path, headers and body, so you can find the content type, event type, delivery ID and signature header described above. You can also paste the URL into a provider's webhook settings in test mode. GitHub sends a `ping` event when you save the webhook. The URL is public, so use only test data.

To run deliveries through your own code, log in and claim the URL with `npx otterkit login`, then `npx otterkit webhook --claim <code>`. A claimed endpoint can send a copy of each request to your local port with `--deliver 3000`. It can also check signatures for providers such as Stripe, GitHub and Shopify, and answer with whatever status or delay you choose, so you can see how a sender retries. The full loop is in [how to test webhooks locally](https://www.otterkit.com/blog/test-webhooks-locally).

## FAQ

**Is a webhook the same as an API?**
No. A webhook is an HTTP request the provider sends to you when an event happens. An API is something you call when you want data. Many integrations use both: the webhook says something changed, and an API call gets the details.

**Are webhooks always POST requests?**
Almost always, with a JSON or form-encoded body. Make sure your route accepts POST, or it will answer 405.

**What status code should my webhook endpoint return?**
A 2xx, as soon as the event is safely stored. Return a 4xx only when you mean to reject the request, such as a bad signature, and don't use redirects.

**Can a webhook be delivered more than once?**
Yes. Retries after timeouts or errors mean the same event can arrive several times, so store delivery or event IDs and skip ones you've already handled.

**When should I use WebSockets or polling instead?**
Webhooks suit server-to-server event notifications. If a browser needs a continuous live stream, WebSockets or server-sent events fit better. If the provider doesn't offer webhooks, polling is the fallback.
