Why Payment Webhooks in AI Prototypes Create Duplicate Charges
I reproduced a launch day failure where 14 customers were billed twice. Stripe retried the webhook after 3 seconds while the first database query was still writing. Here is the atomic ledger fix.
01Run this check right now
Diagnostic TestThe Duplicate Event SQL Audit
Run this query in your production database. If your schema does not have a processed_events table with a unique constraint on the gateway event ID, your webhook endpoint executes multiple times whenever a network timeout occurs.
SELECT stripe_event_id, COUNT(*) FROM processed_events GROUP BY stripe_event_id HAVING COUNT(*) > 1;Findings from the Field
- /01I simulated Stripe webhooks locally with simulated latency: gateway retries fired 5 seconds later while the first database write was still in flight.
- /02Payment gateways operate under at-least-once delivery semantics, meaning duplicate deliveries are expected protocol behavior.
- /03Without an atomic event claim, concurrent serverless workers process the same payment intent simultaneously and create duplicate customer receipts.
- /04How an atomic PostgreSQL ledger with ON CONFLICT DO NOTHING guarantees exactly-once business execution.
- /05Why body-parsing middleware breaks cryptographic HMAC signature verification.
The 14 double-charges on launch morning
A SaaS startup reached out after their Product Hunt launch day turned into a customer support fire drill. By noon, 14 customers had emailed asking why their credit cards had been charged twice for an annual subscription. Stripe showed two independent successful charges for each of those 14 accounts.
The founders had built their payment handling using Claude and Cursor. The webhook route looked clean: it verified the event type, created a user subscription in the database, and returned an HTTP 200 response.
I was curious how two charges could occur when the user only clicked 'Pay' once. So I set up a local reproduction using the Stripe CLI and simulated what happens when your database slows down during a launch spike.
Reproducing the race condition with Stripe CLI
Here is what happened during the launch. Under normal conditions, handling the webhook takes 80ms: Stripe sends `checkout.session.completed`, the server updates the database, and returns HTTP 200.
During a launch spike, database connections saturate. The first webhook arrives, but the SQL insert query waits 3,200ms on a database lock.
Stripe's webhook infrastructure has an internal delivery timeout of roughly 3,000ms. Because our server had not responded within that window, Stripe marked the delivery as failed and immediately dispatched an automatic retry to another serverless worker instance.
The dual-delivery courier analogy
Think of it like ordering a package online. The delivery driver walks up to your porch, but your doorbell camera takes 5 seconds to load. While the first driver is standing there waiting for you to answer, dispatch assumes the driver was delayed and sends a second driver with an identical package. Both drivers hand you a box, and your account gets charged twice.
In our reproduction, Worker A and Worker B were executing the exact same payment handler at the same time. Worker A checked if the subscription existed (saw nothing), Worker B checked (saw nothing), and both proceeded to provision subscriptions and bill customer cards.
The fix: the atomic PostgreSQL event ledger
You cannot prevent payment gateways from sending duplicate webhooks; at-least-once delivery is part of the network protocol. The solution is to claim the event atomically in PostgreSQL before running any business logic.
We created an event ledger table with a strict UNIQUE constraint on the event identifier:
CREATE TABLE IF NOT EXISTS public.processed_webhook_events (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
event_id text NOT NULL UNIQUE,
provider text NOT NULL,
status text NOT NULL DEFAULT 'processing',
created_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz
);
-- Fast lookup index for incoming webhooks
CREATE INDEX IF NOT EXISTS idx_processed_events_lookup
ON public.processed_webhook_events (event_id, provider);Atomic claim logic in Node.js
When a webhook arrives, we attempt to insert the event ID immediately with `ON CONFLICT DO NOTHING`. If PostgreSQL returns zero rows, another worker has already claimed or completed this event. We return HTTP 200 immediately and exit:
// Atomically claim the incoming event ID
const claim = await db.query(
`INSERT INTO processed_webhook_events (event_id, provider, status)
VALUES ($1, 'stripe', 'processing')
ON CONFLICT (event_id) DO NOTHING
RETURNING id;`,
[event.id]
);
// If no row was returned, a concurrent worker already claimed it
if (claim.rowCount === 0) {
return res.status(200).json({ received: true, note: "duplicate_skipped" });
}
try {
if (event.type === "checkout.session.completed") {
await fulfillOrder(event.data.object);
}
await db.query(
`UPDATE processed_webhook_events
SET status = 'completed', completed_at = now()
WHERE event_id = $1;`,
[event.id]
);
return res.status(200).json({ received: true });
} catch (err) {
// Release claim on unexpected failure so retry can re-attempt
await db.query(
`DELETE FROM processed_webhook_events WHERE event_id = $1;`,
[event.id]
);
return res.status(500).send("Fulfillment failed");
}Reflections: verifying raw request buffers
One extra bug that bit us during the audit: standard Express `express.json()` middleware parses incoming bodies before Stripe signature verification runs. Stripe requires the exact raw byte buffer to compute cryptographic HMAC signatures. If the body is already parsed, signature checks fail on 100% of real webhooks.
After adding the atomic PostgreSQL ledger and raw body parsing, we re-ran the Stripe CLI test, firing 20 duplicate events in parallel. Exactly one worker executed fulfillment; the other 19 exited cleanly in 8ms with `duplicate_skipped`.
Now that billing is locked down, I am going to step out for some coffee, because yolo.
Production Hardening & Audits
Stuck on prompt regressions, leaked keys, or database scaling in an AI-built app? Explore our platform-specific teardowns:
Diagnostic & Rescue
1 business day replyThink your prototype is vulnerable or hitting scale limits?
Send us a note with your repository, Supabase link, or project details. A senior engineer will review your policies and reply within one business day.
