No. 36API8 min read2,185 words
Webhook best practices: receiving and sending done right
Webhook best practices for developers wiring up Stripe, GitHub or partner events: verify signatures, return fast, process async, and survive retries.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways ยท 05
The short version
- 01Treat every webhook as untrusted, at-least-once and out-of-order: verify the signature on the raw body, dedupe on the provider's event ID, and never assume an earlier event arrived first.
- 02Verify signatures against the exact raw request bytes with a constant-time compare, and reject events whose signed timestamp is too old to block replay attacks.
- 03Return a 2xx within a second or two by only verifying and persisting the event; do the real work in a background worker so slow processing never triggers provider retries.
- 04A unique constraint on the event ID plus INSERT ... ON CONFLICT DO NOTHING is the simplest reliable deduplication, because the database enforces it under concurrency.
- 05If you send webhooks, sign them with HMAC, include an event ID and timestamp, retry with exponential backoff, and block delivery to private network addresses to prevent SSRF.
On this page ยท 11
Webhook best practices fit in one sentence: verify the signature against the raw body, store the event and return a 2xx immediately, process it in a background worker, and make that worker idempotent and tolerant of events arriving out of order. Webhooks look trivial, since each one is just an HTTP POST, but the part that bites is everything around the handler: signatures, retries, ordering, and the fact that the sender does not care about your database.
Most webhook bugs do not show up in the demo. They show up three weeks later when Stripe retries a payment event you already processed and a customer gets credited twice in your ledger. Here is how to build a receiver that holds up in production, and what to do if you are the one sending webhooks.
How webhooks fail in production
Before the fixes, it helps to name the failure modes. Every one of these is documented provider behaviour, not an edge case:
| What happens | Why it happens | The defence |
|---|---|---|
| Same event arrives twice | Delivery is at least once; retries after timeouts | Dedupe on the provider's event ID |
| Events arrive out of order | Providers deliver in parallel and retry independently | Compare timestamps or versions; upsert instead of assuming a prior event ran |
| Your handler times out | Slow downstream calls inside the request | Persist and return 2xx; process in a worker |
| Forged requests | Your endpoint URL is public | Verify the HMAC signature on every request |
| Replayed old requests | An attacker captured a valid signed request | Reject signed timestamps outside a tolerance window |
| Events silently missed | Your endpoint was down beyond the retry window, or disabled | Periodic reconciliation against the provider's API |
Stripe's webhook documentation states plainly that endpoints may receive the same event more than once and that delivery order is not guaranteed. Design for that from day one.
Verify the signature first, on the raw body
The most common mistake is verifying a signature against a parsed and re-serialised body. Signatures are computed over the exact bytes that were sent. If your framework parses JSON and you re-stringify it, key order and whitespace can change, and the signature will not match. Worse, some teams "fix" the mismatch by skipping verification in production.
In a Next.js App Router route handler, read the raw text before anything touches it:
// app/api/webhooks/stripe/route.ts
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;
export async function POST(req: Request) {
const body = await req.text(); // raw bytes, do NOT call req.json()
const signature = req.headers.get("stripe-signature");
if (!signature) {
return new Response("Missing signature", { status: 400 });
}
let event: Stripe.Event;
try {
// Also checks the signed timestamp against a tolerance window
event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
} catch {
return new Response("Invalid signature", { status: 400 });
}
await enqueue(event); // persist, see below
return new Response("ok", { status: 200 });
}Rolling your own verification
Some providers do not ship an SDK helper. GitHub, for example, documents validating webhook deliveries with an HMAC-SHA256 of the payload sent in the X-Hub-Signature-256 header. Compute the HMAC yourself and compare with a constant-time function such as Node's crypto.timingSafeEqual, so the comparison does not leak timing information:
import { createHmac, timingSafeEqual } from "node:crypto";
function verifyGitHub(rawBody: string, header: string | null, secret: string): boolean {
if (!header?.startsWith("sha256=")) return false;
const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(header);
// timingSafeEqual throws on unequal lengths, so check first
return a.length === b.length && timingSafeEqual(a, b);
}Block replays with a timestamp
A valid signature proves the provider sent the request once. It does not prove they sent it just now. If the provider signs a timestamp along with the body (Stripe does, and so does the Standard Webhooks specification), reject events whose timestamp is more than a few minutes old. Stripe's helper does this for you with a default tolerance. If you roll your own, include it.
Two more habits: keep separate signing secrets per environment and per endpoint, and support two active secrets during rotation so you can roll a leaked secret without dropping events.
Return 2xx fast, do the work later
Webhook senders have short timeouts. If your handler calls three downstream APIs, sends an email and updates four tables before responding, you will eventually blow past that timeout. The sender then treats the request as failed and retries, even though your code actually ran. Now you have the same event twice, and you caused it.
The fix is to split receipt from processing:
- Verify the signature.
- Persist the raw event with its ID.
- Return 2xx.
- A worker picks up the persisted event and does the real work.
That split is exactly where background jobs and queues earn their keep. The persistence step is small:
async function enqueue(event: Stripe.Event) {
// The primary key on id makes this idempotent at the database level.
await db.query(
`INSERT INTO webhook_events (id, provider, type, payload, status, received_at)
VALUES ($1, 'stripe', $2, $3, 'pending', now())
ON CONFLICT (id) DO NOTHING`,
[event.id, event.type, event],
);
}That ON CONFLICT DO NOTHING clause is doing a lot of work. It is your first line of defence against duplicates, and it is enforced by the database rather than by application logic you hope runs correctly under concurrency. Store the whole event, not just event.data: the type, timestamps and API version are useful later.
Make every handler idempotent
Idempotent means running the handler once or five times leaves the system in the same state. The deduplication table stops the same event ID being processed twice, but you still need to protect against two workers racing, and against two different events that imply the same action.
When the worker processes a row, it claims it, does the side effect, and marks it done inside one transaction:
BEGIN;
-- Claim the event. Zero rows returned means another worker has it: stop.
UPDATE webhook_events
SET status = 'processing', claimed_at = now()
WHERE id = $1 AND status = 'pending'
RETURNING id;
-- The actual work, guarded so a repeat is a no-op
UPDATE orders SET paid_at = now() WHERE id = $2 AND paid_at IS NULL;
UPDATE webhook_events SET status = 'done', processed_at = now() WHERE id = $1;
COMMIT;The AND status = 'pending' clause plus RETURNING is a cheap optimistic lock, so two workers do not process the same event. The paid_at IS NULL guard means even if the same logical action runs twice (say, from two different event types that both mean "paid"), the second is a no-op.
Because the claim is inside the transaction, a crash mid-work rolls the claim back and the event returns to pending. If you claim in a separate transaction instead, add a sweeper that resets rows stuck in processing past a timeout.
Do not key idempotency on payload contents or timestamps. The provider's event ID is the only stable handle you get. And if the side effect is an external call, such as sending an email or creating a charge somewhere else, pass an idempotency key derived from the event ID to that API too, so a retry of your worker does not repeat it. The same idea appears in our guide to designing REST APIs that last.
Handle out-of-order events
A customer.subscription.updated can arrive before customer.subscription.created. A delete can land before the create it logically follows. Providers parallelise delivery and retry on their own schedule, so the order events reach you is not the order they happened.
Three defences:
- Do not assume a prior event ran. If an update arrives and you have no row, upsert one from the payload instead of throwing.
- Ignore stale events. When the payload carries a timestamp or version, only apply it if it is newer than what you have:
UPDATE subscriptions
SET status = $1, source_updated_at = $2
WHERE id = $3 AND source_updated_at < $2;- Or re-fetch the object. For state that really matters, treat the webhook as a notification that something changed and fetch the current object from the provider's API. You always end up with the latest state, at the cost of one API call per event (mind their rate limits).
When processing fails: retries and dead letters
Two failure modes need different responses. If verification fails or the payload is malformed, return a 4xx: retrying will not fix a bad signature. If you could not even persist the event (database down), return a 5xx and let the provider retry.
Once the event is safely stored, your worker owns retries. Provider retry windows vary and you do not control them, so do not rely on them for business logic failures. Retry with exponential backoff and jitter, as described in AWS's guide to retries and backoff, and after a fixed number of attempts move the row to a dead-letter status that an engineer can inspect:
-- Runs after the work transaction rolled back
UPDATE webhook_events
SET attempts = attempts + 1,
status = CASE WHEN attempts + 1 >= 8 THEN 'dead' ELSE 'pending' END,
next_attempt_at = now() + make_interval(secs => power(2, attempts) * 10),
last_error = $2
WHERE id = $1;A worker polling for status = 'pending' AND next_attempt_at <= now() covers most needs without a queue product. Alert on anything that lands in dead.
Finally, schedule a reconciliation job. Providers disable endpoints that keep failing, and events can be missed during long outages. A nightly job that lists recent objects through the provider's API and compares them to your records catches what webhooks missed. For payments this is not optional, and we cover it in depth in payment reconciliation for fintech apps.
Sending webhooks: what a good provider does
If your product sends webhooks to customers, you are now on the other side of every problem above. A good sender:
- Signs every request with HMAC-SHA256 over the raw body and a timestamp, using a per-endpoint secret the customer can rotate. Following the Standard Webhooks specification saves you from inventing a format, and gives customers existing libraries to verify with.
- Includes a unique event ID and the event type in every payload, so receivers can deduplicate.
- Uses a background queue, never sends webhooks inline in the user's request.
- Retries with exponential backoff over a period of hours to days, then disables the endpoint and emails the owner.
- Times out quickly, so one slow customer endpoint cannot exhaust your workers.
- Blocks private network targets. A customer-supplied URL pointing at
169.254.169.254orlocalhostturns your webhook sender into a server-side request forgery tool. Follow OWASP's SSRF prevention cheat sheet: resolve the hostname, reject private and link-local ranges, and do not follow redirects blindly. - Gives customers a delivery log with request, response and a "resend" button. It cuts your support load dramatically.
Things that save you at 3am
A few small habits pay off when something breaks:
- Store the raw payload, not just the fields you currently use. When a new bug appears you will want to replay events, and you cannot replay what you threw away. Prune old rows on a schedule if storage matters.
- Log the event ID and type on every request. When support says "the order did not update", you want to search for one ID and see the full path.
- Use separate endpoints per provider. Mixing Stripe and GitHub events through one handler with a big switch statement turns into a mess fast, and the signing secrets differ anyway.
- Build a replay tool early. A small script that resets a
webhook_eventsrow topendingturns a production incident from a panic into a chore. - Test with the provider's CLI or test events, including duplicate and out-of-order deliveries, before you go live.
A webhook receiver checklist
- The signature is verified against the raw request body, with the provider's library where one exists.
- Old timestamps are rejected to block replays.
- The handler stores the event and returns 2xx quickly; a worker does the real work.
- The event ID is unique in the database, so duplicates are ignored.
- Handlers cope with events arriving out of order.
- Failed events retry with backoff and land in a dead-letter state you can see.
- Raw payloads are stored and a replay tool exists.
- Duplicate and out-of-order deliveries were tested before launch.
Make your webhooks boring
Treat the webhook endpoint as an untrusted, at-least-once, out-of-order delivery channel, because that is exactly what it is. Verify the raw body, persist fast, return 2xx, and let an idempotent worker do the real work with the database enforcing uniqueness. Back it with reconciliation, and webhooks become boring, which is the goal. If they feed billing, our guide to implementing subscription billing shows how they fit into the bigger picture.
We build webhook pipelines for payments, CRMs and partner integrations as part of our API and backend engineering work. If you are wiring up payments or third-party sync and want it right before it ships, talk to us.
Sending email from your app is a close cousin of webhooks; see the best transactional email APIs in 2026.
FAQ ยท 05 questions
Frequently asked questions
What is a webhook?
A webhook is an HTTP request one system sends to another when something happens, such as Stripe calling your server when a payment succeeds. Instead of your app repeatedly asking whether anything changed, the provider pushes the event to a URL you register. Your endpoint verifies the request and reacts to it.
Why am I receiving the same webhook twice?
Most providers, including Stripe and GitHub, deliver webhooks at least once, not exactly once. If your endpoint timed out, returned an error, or the network dropped the response, the provider retries, and occasionally duplicates happen even when everything succeeded. Store each event ID and skip ones you have already processed.
Why does my webhook signature verification fail?
The most common cause is verifying against a parsed and re-serialised body instead of the raw bytes. JSON parsing changes whitespace and key order, so the signature no longer matches. Other causes are using the wrong signing secret for the environment, or a proxy that modifies the body before it reaches your code.
Should a webhook endpoint return 200 if processing fails?
Return 2xx once the event is verified and safely stored, even if the business logic has not run yet, and handle retries in your own worker. Return 4xx for invalid signatures or malformed payloads, since retrying will not fix them. Return 5xx only when you could not even store the event, so the provider tries again.
Webhooks or polling: which should I use?
Use webhooks when the provider offers them and you need to react quickly, because they avoid constant polling requests. Add a periodic reconciliation job that fetches recent changes via the provider's API anyway, since webhooks can be missed during outages or misconfiguration. The webhook is the fast path, the reconciliation job is the safety net.