Stripe webhooks notify your application about subscriptions, invoices and payments. Delivery can be repeated or out of order, and your processing can fail after acceptance. Design for each case explicitly.
Before you start
A Stripe sandbox and an installed, authenticated Stripe CLI using test credentials only.
An HTTP POST endpoint you own; local examples assume localhost:4242/webhook.
Access to a durable database or queue and a worker for production processing.
Scope
This guide covers how to design a reliable webhook pipeline and test it locally. Stripe's starter code verifies signatures but doesn't store events durably, so add that before going live.
Step 1
What a webhook actually is
STRIPE
event POST
↓→HTTPS + signature
ENDPOINT
/webhook
verify sig
ack after persist
↓→persist, then ack
QUEUE
durable inbox
↓→async, retryable
WORKER
apply event / current state
↓→idempotent write
DATABASE
On non-2xx → Stripe retries with same event id
up to 3 days in live mode · exponential backoff · same payload
Stripe → verify → durable acceptance → retryable worker → idempotent effects. Acknowledge only after persistence.
Stripe sends an HTTP POST describing an event to your configured URL. Your endpoint verifies and durably stores the event; a worker applies business changes later. If your endpoint doesn't answer 2xx, Stripe retries the same event for up to 3 days in live mode; in a sandbox it retries 3 times over a few hours.
Step 2
Verify the signature on every request
Stripe signs every webhook with a secret. If you don't verify the signature, anyone on the internet can POST to your endpoint and forge events. Use Stripe's official SDK: stripe.webhooks.constructEvent(rawBody, signature, secret). If this throws, return 400 immediately — don't process unverified events.
Express webhook route: verify, store, acknowledge
import express from "express";
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const app = express();
// Raw body on this route only: register express.json() AFTER it, or on other routes.
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
req.body,
req.headers["stripe-signature"] as string,
process.env.STRIPE_WEBHOOK_SECRET!,
);
} catch {
return res.sendStatus(400); // invalid or missing signature
}
try {
// Duplicate deliveries keep the existing row; the worker retries it if unfinished.
await db.query(
`INSERT INTO stripe_events (event_id, type, payload, status, received_at, next_retry_at)
VALUES ($1, $2, $3, 'pending', now(), now())
ON CONFLICT (event_id) DO NOTHING`,
[event.id, event.type, event],
);
} catch {
return res.sendStatus(500); // not stored: let Stripe retry
}
res.sendStatus(200); // stored durably; processing happens in the worker
});
db stands for your own Postgres client. In a Next.js App Router route handler, pass await req.text() to constructEvent instead of calling req.json().
Signature verification needs the raw request body. A global express.json(), or reading req.json() in Next.js, parses it first and breaks verification. Keep the raw body on the webhook route only. When the body was parsed, the SDK throws "No signatures found matching the expected signature for payload".
Step 3
Subscribe to the events you actually need
In Workbench → Webhooks → Create event destination, choose snapshot event payloads when your integration reads event.data.object. Select the events your integration handles, for example customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, invoice.paid, invoice.payment_failed and customer.updated. Document each handler and avoid selecting all events without a defined handling policy.
Sandbox only: check the CLI account and test credentials first; never add --live. Start your local server at this route, or change the address to match it. Use the listener's signing secret in your server environment, not a Dashboard endpoint secret. Keep that secret private and leave this terminal running.
Step 4
Persist before acknowledging, then process asynchronously
Verify the signature, persist the event in a durable inbox (a table or queue where each event is saved before you reply), then respond promptly with 2xx after durable acceptance. If persistence fails, do not acknowledge success. A worker takes pending work with an atomic claim (only one worker can take an event at a time), applies the changes and retries failures. Each claim is a lease (the claim expires if the worker crashes), so a crash doesn't leave an event stuck. An in-memory task started before returning 200 is not durable acceptance.
Tip
A pending-event table can replace a queue if you implement atomic claims, expiring leases, retry scheduling and error monitoring. Keep received_at separate from processed_at.
Worker: claim one pending event
UPDATE stripe_events
SET status = 'processing',
claim_expires_at = now() + interval '5 minutes',
attempt_count = attempt_count + 1
WHERE event_id = (
SELECT event_id FROM stripe_events
WHERE ((status = 'pending' AND next_retry_at <= now())
OR (status = 'processing' AND claim_expires_at < now()))
AND attempt_count < 10
ORDER BY received_at
LIMIT 1
FOR UPDATE SKIP LOCKED
)
RETURNING *;
On success set status = 'processed' and processed_at = now(). On failure set status = 'pending', next_retry_at = now() + backoff and last_error; after the 10th attempt set status = 'failed' instead, so it shows up as stuck work (step 8). FOR UPDATE SKIP LOCKED lets several workers run without picking the same event.
Step 5
Handle idempotency
DELIVERY #1
evt_1ABC123
invoice.paid
DELIVERY #2 (RETRY)
evt_1ABC123
same id
↓→
INSERT INTO stripe_events
(event_id, type, payload)
ON CONFLICT (event_id) DO NOTHING
↓→
FIRST WRITE
✓ row created
pending work created
DUPLICATE
reuse existing row
retry if unfinished
A unique event_id deduplicates storage, not business effects. Mark processed only after success.
Use a unique event_id to prevent duplicate inbox rows, but successful insertion is NOT successful processing. On duplicate delivery, reuse the existing pending record rather than discarding unfinished work. Workers atomically claim it and keep business effects idempotent, including external calls with appropriate idempotency keys. Set processed_at only after successful processing; failed work remains retryable. Coordinate database writes and external effects so a crash between them cannot repeat a charge or notification.
Step 6
Handle out-of-order and concurrent events
Events can arrive out of order and concurrent workers can race. Retrieve current state from Stripe when synchronising a current-state view, but preserve the immutable event for historical or accounting effects. A latest API response cannot replace what happened at the event's time. Use per-object serialisation and version or reconciliation rules appropriate to each handler; arrival order is not causal order.
Watch out
Test reversed delivery order and concurrent processing for the same object, not only duplicate event IDs.
Step 7
Build a controlled replay path
Replay from your durable event records. A redelivery must reuse the pending record and retry unfinished processing, not disappear behind event-ID deduplication. Require authorised access, keep an audit trail and preserve idempotent business effects. Make deliberate reprocessing of completed events a separate, reviewed operation. For a single event, you can also resend it from the Stripe Dashboard or with stripe events resend evt_…. Stripe keeps events for 30 days, so you can list recent events through the API to reconcile gaps.
Step 8
Monitor delivery and processing separately
Monitor non-2xx responses, queue age, expired claims, processing failures and reconciliation gaps. A 200 only proves acceptance, not completion. Store structured status, attempt count, next retry time and last error; alert on stuck work and provide an authorised repair path. Define retention, payload access and redaction rules for personal data and secrets rather than keeping raw logs indefinitely.
Sandbox failure fixture
stripe trigger invoice.payment_failed
In a second terminal using the same sandbox, trigger this fixture while the listener runs. It creates test objects; it is not a real charge or a replay of an existing event. Check both the HTTP response and durable worker completion. Test duplicates, ordering and crash recovery separately.
Verify signatures, accept durably, process idempotently and distinguish current-state synchronisation from historical effects. Monitor unfinished work and test replay after failure.
Connect Stripe to FlowMRR for billing-data synchronisation and recurring-revenue metrics. Check connection status and the last sync rather than treating configuration as proof of processing.
No. Subscribe only to the events your app cares about. Unsubscribed events aren't delivered, which keeps your endpoint quiet and your code focused.
What's the right database design for webhooks?+
Use a durable inbox with unique event_id, type, payload, received_at, processed_at, status, claim expiry, attempt count, next retry time and last error. Atomic claims prevent concurrent work; the unique ID prevents duplicate storage, not duplicate business effects. Set processed_at only after success and enforce retention and access controls.
Should I expose webhooks behind a CDN or directly?+
Either can work if the route preserves the raw request body and signature header, accepts requests without interactive challenges and does not cache responses. Test signature verification through the deployed CDN or proxy. There is no universal special Cloudflare setting required for Stripe webhooks.
How long does Stripe retry a failed webhook?+
In live mode, Stripe retries an event for up to 3 days with exponential backoff until your endpoint returns 2xx; in a sandbox it retries 3 times over a few hours. Every retry carries the same event id and payload, so a durable inbox with a unique event_id absorbs them.
Why does Stripe webhook signature verification fail?+
Usually because the body was parsed before verification: "No signatures found matching the expected signature for payload" means constructEvent did not receive the exact raw bytes. Use express.raw() on the webhook route, or await req.text() in Next.js. Also check the signing secret: the Stripe CLI listener has its own, different from the Dashboard endpoint's.
How do I handle duplicate Stripe webhook events?+
Store each event with a unique event_id using INSERT … ON CONFLICT (event_id) DO NOTHING. A duplicate then reuses the existing row: the worker retries it if unfinished and skips it once processed. Keep business effects idempotent as well, because deduplicating storage does not deduplicate effects.
Can I resend a Stripe webhook event?+
Yes. Resend a single event from the Stripe Dashboard or with stripe events resend evt_…. Stripe keeps events for 30 days, so you can list recent events through the API to find gaps. For larger repairs, replay from your own durable event records.