A webhook receiver is awkward to test. The sender is a remote service that decides when to call you, from addresses you do not control, with payloads you have seen only in documentation, and with retry behaviour that is hard to trigger on demand. Developers often test with one happy-path example and discover the problems in production: a signature check that fails on proxied requests, a handler that times out under a burst, a duplicate that is processed twice, or a field that is sometimes missing. A disciplined approach makes webhook handling dependable. It starts with local development through a tunnel, adds recorded events that you can replay, covers signature verification and failure cases with automated tests, runs a small set in continuous integration and ends with safeguards in production. This guide walks through each stage. It extends signature verification, handler reliability and webhooks vs polling.
Stage 1: Understand the payload
Read the provider's documentation for each event type: delivered, deferred, bounced (hard and soft), complained, unsubscribed, opened, clicked. Note the identifier fields (event ID, message ID, your metadata), timestamps, the signature header and the algorithm, and how batches are formed (one event per request or an array). Capture real examples from your sandbox or a test account, not from memory. Remember that fields can be added over time, so a robust parser ignores unknown fields instead of rejecting them. See message tags and metadata for how your own IDs return.
Stage 2: Local development with a tunnel
Your laptop has no public address, so the provider cannot call it directly. A tunnel service or reverse proxy gives your local port a temporary public HTTPS URL. Register that URL as the webhook endpoint in a test environment, trigger events by sending to sandbox addresses and watch requests arrive.
- Use a throwaway endpoint and a test account, not your production webhook configuration.
- Check that the tunnel passes the raw body. Signature checks need the exact bytes the sender signed; a proxy that re-encodes JSON will break them.
- Use the tunnel's request inspector to view headers and bodies, and to replay a request to your local server after you fix a bug.
- Do not leave tunnels open. Anyone with the URL can post to your machine. Always verify signatures, even in development.
- Protect secrets. Keep signing secrets in environment variables, never in source control. See API key security.
- Alternative: run a mock sender script that posts signed fixtures to localhost, which needs no tunnel at all.
Stage 3: Build fixtures and a replay tool
Record real payloads for every event type you handle, with secrets and personal data removed. Store them as files in your repository. A small script can post any fixture to your endpoint with a valid signature computed from a test secret:
# replay.py: post a fixture with a valid signature
import hmac, hashlib, json, time, sys, requests
secret = b"test-secret"
body = open(sys.argv[1], "rb").read()
ts = str(int(time.time()))
sig = hmac.new(secret, ts.encode() + b"." + body, hashlib.sha256).hexdigest()
r = requests.post("http://localhost:8000/hooks/email", data=body,
headers={"X-Timestamp": ts, "X-Signature": sig, "Content-Type": "application/json"})
print(r.status_code, r.text)The header names and signing scheme above are illustrative; follow your provider's specification. With such a tool you can reproduce any scenario in seconds, including batches and unusual events.
Stage 4: Automated tests
| Test | What it proves | How |
|---|---|---|
| Valid signature accepted | Your verification matches the provider's scheme | Sign a fixture with the test secret; expect 2xx |
| Invalid signature rejected | Forged requests do nothing | Alter one byte; expect 401 or 403 and no side effects |
| Old timestamp rejected | Replay protection works | Use a timestamp beyond the tolerance |
| Malformed JSON | No crash, no partial processing | Send truncated JSON; expect 400 |
| Unknown event type or extra fields | Forward compatibility | Add fields; handler ignores them and returns 2xx |
| Duplicate delivery | Idempotency | Send the same event ID twice; side effects occur once |
| Out-of-order events | State logic is sound | Send delivered before processed, or a bounce before a click; final state is correct |
| Hard bounce triggers suppression | Business rule | Send a bounce fixture; address is suppressed |
| Complaint triggers suppression and alert | Business rule | Send a complaint fixture; check list and counters. See suppression lists |
| Large batch | Throughput and memory | Send a batch of thousands of events; response stays fast because work is queued |
| Slow dependency | Timeout behaviour | Make the database slow; handler still acknowledges quickly or fails predictably |
Stage 5: Simulate the sender's behaviour
Providers retry when your endpoint fails or is slow, and the exact policy matters. Check how many attempts, over how long, and what status codes count as success. Then test your side of it: return a 500 once and confirm that a replay is processed exactly once; take the endpoint offline for a period and confirm that reconciliation recovers the gap; return success after processing starts but before it finishes and verify nothing is lost when a worker crashes. A queue between receipt and processing makes these cases manageable. See API error handling for the sending side of the same ideas.
Stage 6: Continuous integration
- Run the unit and integration tests above on every change, with fixtures committed to the repository.
- Spin up the receiver and a test database in the pipeline, replay a representative set and assert the resulting state.
- Include a contract test that validates fixtures against the provider's published schema, if available, and refresh fixtures when the provider changes the format.
- Keep tests fast by mocking external dependencies, with a small number of end-to-end tests against a sandbox.
- Fail the build if the handler logs secrets or personal data. A simple check on log output catches accidents.
Stage 7: Staging and production safeguards
- Staging with the provider's sandbox: send real test messages to addresses that simulate bounce and complaint outcomes. See staging and sandbox testing.
- Respond within a second or two and process asynchronously.
- Log the event ID, type and result, not the full payload with recipient addresses.
- Monitor the rate of events received, failures, queue depth and processing delay. Alert on silence too: if events stop arriving, the integration may be broken.
- Add reconciliation by polling or export to find gaps. See webhooks vs polling.
- Roll out changes carefully: deploy a new handler version before changing the data model it relies on, and keep the old one working until the queue drains.
- Rotate signing secrets with an overlap period in which both old and new are accepted.
Common pitfalls
- Verifying the signature against parsed and re-serialised JSON instead of the raw body.
- Using a framework body parser that consumes the stream before you can read the raw bytes.
- Comparing signatures with ordinary string equality instead of a constant-time comparison.
- Treating each webhook request as one event when it contains a batch.
- Assuming order, assuming uniqueness, assuming that fields are present.
- Testing only with the provider's dashboard "send test event" button, which sends an idealised example.
- Leaving test endpoints registered with the provider after the work is done.
Webhook handling is an integration between two systems that fail independently, so treat it as a contract. Capture real fixtures, test every rule you rely on and rehearse failure. After that, an event arriving in production is just another replay.
Develop against a documented events API Sandbox testing, signed webhooks and event logs.
References and further reading
Frequently asked questions
How can I receive webhooks on my laptop?
Use a secure tunnel to expose a local port, or avoid the network by posting signed fixtures to localhost with a replay script.
Why does my signature check fail behind a proxy?
The proxy or framework changed the body bytes. Verify against the raw request body exactly as received.
How do I test retries?
Return an error once from a test endpoint and verify that the replayed event is processed exactly once.
Should I test with real customer data?
No. Use sandbox events or fixtures with personal data removed.
What should I monitor in production?
Event rate, failures, queue depth, processing delay and unexpected silence.