
A Stripe webhook is a message that says "something happened". It can arrive twice, late, or before the event that logically precedes it. If your code treats every message as a fresh, ordered fact, you will eventually grant access twice, miss a payment or show a wrong balance. This guide covers the patterns that prevent that. The code is TypeScript on Node and is an example to adapt, not a drop-in module.
The failure modes to design for
- Duplicates: the same event is delivered more than once, because your endpoint timed out or because a retry crossed your response.
- Out-of-order delivery: Stripe does not guarantee the order of events, so an update can land before the creation it refers to.
- Slow or failing handlers: if your endpoint does heavy work before answering, it times out and Stripe retries.
- Silent loss: an event that kept failing and was never looked at again.
- Money bugs: floats, missing currencies and balances that nobody can explain.
1. Verify the signature on the raw body
Signature checking needs the exact bytes Stripe sent. If a JSON parser runs first and you re-serialize the body, the check fails or, worse, gets disabled "temporarily". Use the raw body and the endpoint secret for that specific webhook endpoint.
// Example to adapt (Express + stripe-node)
app.post(
"/webhooks/stripe",
express.raw({ type: "application/json" }), // raw body, not express.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! // endpoint secret, never in code
);
} catch {
return res.sendStatus(400); // not from Stripe, or tampered
}
// ...store, then acknowledge (next section)
}
);
A handler generated quickly by an AI tool often skips this step. It is one of the first things to check, as in our production-readiness checklist for vibe-coded apps.
2. Acknowledge fast, process later
Stripe expects a 2xx response quickly. Do the minimum in the request: verify, store, answer. Do the real work in a separate worker. The insert-or-skip on the event id is also your deduplication.
CREATE TABLE webhook_events (
event_id text PRIMARY KEY, -- evt_... from Stripe
type text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'received', -- received | processed | failed | dead
attempts int NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
last_error text,
received_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz
);
// Example to adapt: insert-or-skip, then answer
await db.query(
`INSERT INTO webhook_events (event_id, type, payload)
VALUES ($1, $2, $3)
ON CONFLICT (event_id) DO NOTHING`,
[event.id, event.type, event]
);
return res.sendStatus(200); // duplicate or not, Stripe is satisfied
If the insert fails because your database is down, return a 500 and let Stripe retry. The unique constraint on event_id makes a second delivery harmless.
3. Do not trust event order: fetch current state
Do not build state from the sequence of events. Treat each event as a signal to look, then ask Stripe for the current object and act on that.
// Example to adapt: the event says "look at this PaymentIntent"
async function handle(event: Stripe.Event) {
if (event.type.startsWith("payment_intent.")) {
const id = (event.data.object as Stripe.PaymentIntent).id;
const pi = await stripe.paymentIntents.retrieve(id); // current truth
if (pi.status === "succeeded") await markOrderPaid(pi);
}
}
Make markOrderPaid idempotent too: set the order to paid only if it is not already paid, inside one database transaction.
4. Retries with backoff and a dead-letter state
The worker picks up rows that are received or failed and due, locks them so two workers do not take the same one, and processes them.
SELECT event_id FROM webhook_events
WHERE status IN ('received', 'failed') AND next_attempt_at <= now()
ORDER BY received_at
LIMIT 10
FOR UPDATE SKIP LOCKED;
On failure, increment attempts, store last_error and set next_attempt_at with exponential backoff (for example 1 minute, 5, 30, 2 hours, plus a little random jitter). After a fixed number of attempts, set status = 'dead' and alert a human. A dead row is not lost: it is a visible to-do item, and you can replay it after the fix.
5. Money: minor units, integers and a currency
Store amounts as integers in the currency's smallest unit (cents for euros and dollars) together with the ISO currency code. Never use floating point for money. Stripe already sends integers in minor units, so keep them that way end to end.
Do not assume two decimals everywhere: some currencies, such as the Japanese yen, have no minor unit, and some have three decimals. Keep a currency table or use a library, and convert only at the display layer.
6. Idempotency keys on outgoing calls
The mirror problem: your server calls Stripe, the network drops, and you do not know if the charge or refund happened. Send an idempotency key with each create request so a retry returns the original result instead of repeating the action.
// Example to adapt: derive the key from YOUR business operation
await stripe.refunds.create(
{ payment_intent: pi.id, amount: 1500 },
{ idempotencyKey: `refund-order-${order.id}-${refundRequest.id}` }
);
Derive the key from the business action (this refund request), not from a random value generated per attempt. Otherwise every retry looks new.
7. A simple double-entry ledger
A balance column that you overwrite is hard to audit. A small append-only ledger answers "why is this the balance?": every movement is a transaction made of lines that sum to zero.
CREATE TABLE ledger_accounts (
id bigserial PRIMARY KEY,
name text NOT NULL, -- e.g. 'customer:42', 'platform:revenue', 'stripe:clearing'
currency char(3) NOT NULL
);
CREATE TABLE ledger_transactions (
id bigserial PRIMARY KEY,
source_event_id text UNIQUE, -- the Stripe event: same event cannot post twice
description text,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE ledger_lines (
id bigserial PRIMARY KEY,
transaction_id bigint NOT NULL REFERENCES ledger_transactions(id),
account_id bigint NOT NULL REFERENCES ledger_accounts(id),
amount bigint NOT NULL, -- minor units; debit positive, credit negative
currency char(3) NOT NULL
);
-- Rule enforced in code (and checked by a nightly query):
-- for each transaction_id and currency, SUM(amount) = 0
Never edit or delete lines. A refund or correction is a new, reversing transaction. The UNIQUE on source_event_id is a second safety net behind the processed-events table.
8. Reconcile every day
Even with all of this, your records and the provider's can drift. Run a daily job that lists the provider's payments and payouts for the period, compares them with your ledger by id, amount and currency, and reports differences: missing on your side, missing on theirs, or different amounts. Output a short report to a human. A reconciliation job turns a silent bug into a ticket within a day.
9. Test before real money moves
Use test mode and the Stripe CLI to replay the hard cases:
stripe listen --forward-to localhost:3000/webhooks/stripeforwards events to your machine and prints the signing secret to use locally.stripe trigger payment_intent.succeededcreates a sample event.- Resend the same event twice, and stop your worker mid-processing, to prove nothing posts twice.
- Deliver two related events in reverse order and check the final state is still correct.
Add these cases to your MVP launch checklist before going live.
FAQ
Does Stripe guarantee webhooks arrive once and in order? No. Treat delivery as at-least-once with no ordering guarantee. Deduplicate by event id and read the current object state instead of relying on the sequence of events.
What is the difference between a webhook idempotency check and an idempotency key? The webhook check protects you from receiving the same event twice, using the event id. An idempotency key protects the opposite direction: when you send a request to the API and retry it, the key makes the provider treat the retry as the same operation.
Do I need a ledger for a first release? Not always. If you only sell a subscription, an orders table and a daily reconciliation may be enough. As soon as you hold balances, split payments or pay out to others, a ledger is much cheaper to start with than to add later. Our fintech MVP guide covers what to include first.
Get a second pair of eyes on your payment flows
We build payment and billing flows for fintech products: webhook handling, ledgers, payouts and reconciliation. When using a hosted checkout, card data never touches your server, which keeps your own surface small. If you want a review of your current handlers or a design for a new product, see our fintech app development service and tell us about your flow.
Have a project idea?
Get a rough estimate in 5 minutes with our Project Scoper.
Scope Your ProjectReady to discuss?
30 minutes. No pitch deck. Just an honest conversation about your project.
Book a Free Call





