1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
Webhooks explained: how they work and how to receive them securely

Key takeaways

  • 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

  1. An event happens at the provider, such as payment.succeeded.
  2. The provider builds a JSON payload, signs it with a secret shared only with you, and POSTs it to your URL.
  3. Your endpoint verifies the signature and timestamp, records the event ID, and returns 200 quickly.
  4. 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_digest takes 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

  1. Accept HTTPS only.
  2. Verify the HMAC signature over the raw body with a constant-time comparison.
  3. Reject timestamps outside a short window.
  4. Store event IDs and ignore duplicates.
  5. Keep the secret in configuration, not code, and support rotation.
  6. Reply quickly and process in the background.
  7. 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →