Stripe delivers webhooks at least once, not exactly once. The same checkout.session.completed event can reach your server twice. It happens when your endpoint times out, when it returns a 500 and Stripe retries, or when someone clicks "resend" in the dashboard.
If the handler is not ready for that, the customer gets credits twice or two receipt emails. This article shows how I handle it in Warpkit, my SaaS starter.
There are two problems
It looks like one problem, but it's two:
- The database write must not happen twice.
- The side effects (an email, a background job) must not happen twice.
Fixing the first one does not fix the second, so each one gets its own check.
Check one: a marker row in the same transaction
For a one-time purchase I use the payment intent ID, because Stripe keeps it the same on every delivery. I save it as a marker row, and I write the marker and the credits in one transaction:
let granted = false;
db.transaction(tx => {
const existing = tx.query.purchases
.findFirst({ where: eq(purchases.stripePaymentIntentId, paymentIntentId) })
.sync();
if (existing) return; // replay, nothing to do
tx.insert(purchases).values({ /* marker row */ }).run();
tx.update(users)
.set({ credits: sql`credits + ${amount}` })
.where(eq(users.id, userId))
.run();
granted = true;
});
if (granted) {
await emit('credits.purchased', { userId, amount });
}
Both writes commit together. If the server crashes in the middle, you don't end up with a marker and no credits, or credits and no marker. The event only fires when granted is true, so a second delivery stops before it.
Check two: a replay flag for upserts
A subscription upsert is already safe to run twice, because the second write changes nothing. The receipt email is not safe.
So I read the row first, inside the transaction, and keep a flag that says if I have seen this subscription before:
let isReplay = false;
db.transaction(tx => {
const existing = tx.query.subscriptions
.findFirst({ where: eq(subscriptions.userId, userId) })
.sync();
isReplay = existing?.stripeSubscriptionId === subId;
tx.insert(subscriptions)
.values({ /* ... */ })
.onConflictDoUpdate({ /* ... */ })
.run();
});
if (!isReplay) {
await emit('subscription.activated', { /* ... */ });
}
The race in most examples
Most examples I see online look like this:
// WRONG: the check and the write are not atomic
const existing = await db.query.purchases.findFirst({ /* ... */ });
if (existing) return;
await db.insert(purchases).values({ /* marker row */ });
await db.update(users).set({ credits: sql`credits + ${amount}` });
This passes if you send the event twice, one after the other. It fails when two deliveries arrive at almost the same time. Both read "no marker" before either one writes, so both grant the credits.
The check has to be inside the same transaction as the write.
The Bun problem
This one is easy to miss. If you use Bun with SQLite, db.transaction() only works with a synchronous callback. If you pass an async function, Bun calls it, gets a promise back, and commits right away at the first await. The rest of your code runs outside the transaction. There is no error and no warning.
That is why the examples above use .sync() for reads and .run() for writes, with no await inside the callback.
One more thing if you run several server processes. A transaction that reads and then writes should start with BEGIN IMMEDIATE. In the default mode it takes a read lock first and upgrades later. If another process commits in between, SQLite fails right away with database is locked and does not wait for the busy timeout. When I tested this with 12 processes, 2,037 of 2,400 handler transactions failed. After I made immediate the default, they passed.
Checklist
- Write down what must not happen twice in the database, and which side effects must not fire twice.
- Protect the write with a marker row or an upsert, inside one transaction.
- Read a replay flag in that same transaction and use it to skip the side effects.
- Test with two deliveries at the same time, not one after the other.
- Verify the Stripe signature against the raw request body before any of this.