Webhooks Explained: How They Work and How to Receive Them Securely
Webhooks let one system tell another the moment something happens, by sending an HTTP request to a URL you choose. Learn how they differ from polling, how to verify signatures, and how to survive retries and replays, with a receiver we ran.
- Webhooks are HTTP POST requests a provider sends to your URL when an event happens, so you do not have to keep asking.
- Anyone can call a public URL, so verify an HMAC signature over the raw body with a constant-time comparison.
- Reject old timestamps to stop replays, and store event IDs so retried deliveries are processed only once.
- In our run, the receiver accepted a valid event, ignored its retry, and rejected a tampered body, a wrong secret and a 10-minute-old replay.
Your app needs to know when a payment succeeds, a build finishes or a form is submitted on another service. You could ask that service every minute, “anything new?”, but most answers would be “no”. Webhooks flip the direction: you give the service a URL, and it calls you the moment the event happens.
To test the ideas rather than just describe them, we wrote a small webhook receiver and sender with Python 3.13’s standard library, ran both on one machine, and fired valid, tampered, replayed and retried requests at it. The results below are copied from that run. If APIs in general are new to you, read what is an API first.
What is a webhook?
A webhook is an HTTP callback. You register an endpoint, such as https://example.com/hooks/payments, with a provider and choose which events you care about. When one happens, the provider sends a POST request to that URL with a JSON body describing the event. Your server reads it, checks it is genuine, does its work and replies with a 2xx status code.
People sometimes call webhooks “reverse APIs”. With a normal API call, your code asks and the provider answers. With a webhook, the provider starts the conversation.
Webhooks vs polling
| Aspect | Polling an API | Webhooks |
|---|---|---|
| Who starts | Your app, on a timer | The provider, on each event |
| Delay | Up to one polling interval | Usually seconds |
| Wasted calls | Many empty responses | Almost none |
| Your server needs | Outbound access only | A public HTTPS endpoint |
| Missed events | Rare; you ask again | Possible if retries run out |
Polling also burns through rate limits, as our API rate limiting guide explains. Many teams use both: webhooks for speed, plus a periodic check that catches anything a failed delivery missed.
How a webhook delivery works
- An event happens at the provider, such as
payment.succeeded. - The provider builds a JSON payload, signs it with a secret shared only with you, and POSTs it to your URL.
- Your endpoint verifies the signature and timestamp, records the event ID, and returns 200 quickly.
- If your endpoint fails or times out, the provider retries later, usually with growing gaps.
What a payload looks like
POST /hook HTTP/1.1
Content-Type: application/json
X-Timestamp: 1794500000
X-Signature: b82128c3c09fb40a...
{"id": "evt_1", "type": "payment.succeeded", "amount": 500}
The timestamp and signature values above are shortened illustrations. Header names differ by provider, but most send an event ID, an event type, a timestamp and a signature. Our Python JSON guide covers parsing the body safely.
Signing and verifying requests
Your webhook URL is public, so anyone who learns it could send fake events, such as a fake “payment succeeded”. The standard defence is an HMAC signature. The provider computes a SHA-256 HMAC of the timestamp and raw body using a shared secret, and you recompute it on your side:
import hmac, hashlib, time
SECRET = b"whsec_demo_only" # load from an environment variable in real code
def sign(body: bytes, ts: str) -> str:
return hmac.new(SECRET, f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
def verify(body: bytes, ts: str, sig: str) -> bool:
if not ts.isdigit() or abs(time.time() - int(ts)) > 300:
return False # stale or missing timestamp
return hmac.compare_digest(sign(body, ts), sig)
Three details matter:
- Use the raw body bytes. If a framework parses and re-serialises the JSON first, spacing or key order can change and the signature will not match.
- Compare in constant time.
hmac.compare_digesttakes the same time whether the first or last character differs, which defeats timing attacks. A plain==can stop at the first mismatch. - Keep the secret out of code. Store it in environment variables or a secrets manager, and rotate it if it leaks.
Our test results
We started the receiver on a local port and sent six kinds of request:
1 valid: (200, 'ok')
2 same event again (retry): (200, 'duplicate ignored')
3 tampered body: (401, 'bad signature')
4 wrong secret: (401, 'bad signature')
5 replay 10 min old: (400, 'stale timestamp')
processed events: ['payment.succeeded', 'order.created']
For the tampered case, we signed a body with "amount": 500 and then changed it to 5000 in transit. The signature no longer matched, so the request was rejected. A signature made with a guessed secret failed the same way. Only two events were processed in total, even though more requests arrived. The status codes follow normal HTTP meaning, as listed in our HTTP status codes cheat sheet.
Replay protection
A valid signature proves the provider created the request, but not that it is fresh. An attacker who captures one genuine request could resend it later. Including the timestamp inside the signed data, and rejecting anything older than a few minutes, closes that gap. Our 10-minute-old request was rejected before its signature was even checked. Keep server clocks synced, or genuine events can be rejected too.
Tip: log the reason for every rejected webhook, but never log the secret or full signature. Rejection logs are how you notice a misconfigured secret after a rotation.
Retries with backoff
Providers retry when your endpoint fails, times out or returns a non-2xx status. We simulated an endpoint that failed twice before recovering, with a sender that waited longer between each try:
attempt 1: 500 temporarily down
attempt 2: 500 temporarily down
attempt 3: 200 ok
delivered: True
Our sender doubled the wait each time (50, 100, then 200 milliseconds). Real providers use the same idea over minutes and hours, often for a day or more, then give up and may disable the endpoint. Return 4xx only for requests you will never accept, such as bad signatures, because some providers stop retrying on client errors.
Idempotency: processing each event once
Retries mean you will receive some events more than once, for example when your server processed an event but the response was lost. Your handler must be idempotent: handling the same event twice must have the same effect as handling it once. We stored each event ID and answered repeats with “duplicate ignored”. In production, store the IDs in a database table with a unique constraint, so two parallel deliveries cannot both slip through.
Respond fast, work later
Providers wait only a few seconds for your reply. If your handler sends emails, calls other APIs or runs reports, do that work after replying: verify, save the event to a queue or table, return 200, then process it in a background job. This keeps deliveries from timing out and avoids a storm of retries during a slow period. Events can also arrive out of order, so check the current state of the object rather than assuming each event is the latest.
How to test webhooks
- Unit-test the verifier with a known body, timestamp and expected signature, plus tampered and expired cases.
- Run the receiver locally and send signed requests, as we did, or use the provider’s CLI or dashboard to send test events.
- Use a tunnelling tool to expose a local port when the provider must reach your laptop; close it afterwards.
- Test duplicates, out-of-order events and slow downstream services, not just the happy path.
Tools like Postman can send hand-built webhook requests too; see our API testing with Postman guide.
Webhook security checklist
- Accept HTTPS only.
- Verify the HMAC signature over the raw body with a constant-time comparison.
- Reject timestamps outside a short window.
- Store event IDs and ignore duplicates.
- Keep the secret in configuration, not code, and support rotation.
- Reply quickly and process in the background.
- Treat the payload as untrusted input; fetch critical details from the provider’s API if in doubt.
Final thoughts
Webhooks are simple on the surface, just an HTTP POST, but a reliable receiver needs a few deliberate habits. Our tests showed each one working: signatures stopped tampering and fake senders, timestamps stopped replays, event IDs stopped double processing, and backoff carried a delivery through a short outage. Build those in from the first version, and webhooks become one of the most dependable integrations you run.
Frequently asked questions
What is a webhook in simple terms?
A webhook is an automatic HTTP request one system sends to a URL you choose when an event happens, such as a payment succeeding. It saves you from repeatedly polling for changes.
What is the difference between a webhook and an API?
With an API, your code asks the provider for data. With a webhook, the provider sends data to your endpoint when something happens. Many services offer both.
How do I verify a webhook signature?
Recompute an HMAC, usually SHA-256, over the raw request body and timestamp with your shared secret, then compare it to the header using a constant-time function such as hmac.compare_digest.
Why do I receive the same webhook twice?
Providers retry when they do not get a 2xx response in time, even if you already processed the event. Store event IDs and skip duplicates so handling stays idempotent.
What status code should a webhook endpoint return?
Return a 2xx code quickly once the event is verified and stored. Return 4xx for requests you will never accept, such as bad signatures, and 5xx when you want the provider to retry.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.