· 5 min read
A Stripe webhook retry that could not repair what it found
A checkout webhook wrote a workspace, its roles and its subscription as separate commits. If it failed half-way, Stripe retried, the handler saw the workspace and skipped it, and the buyer kept a paid workspace with no owner. The merged fix in Kan is one database transaction.
Stripe webhooks come with two promises that shape how you write the handler. If your endpoint does not answer with a 2xx, Stripe tries again later, for days. And any event can arrive more than once. So a webhook handler has to be safe to run twice, and safe to run again after it failed half-way.
Most handlers get the first part right. The second part is where this bug lived. I fixed it in Kan, the open-source Trello alternative (kanbn/kan#768, merged 1 December 2026).
What the handler did
When someone pays for a new workspace, Stripe sends checkout.session.completed. Kan's handler for it, onCheckoutCompleted, did this:
- Look up the workspace by its public id. If it does not exist, create it. Creating a workspace writes three things: the workspace row, its system roles, and the buyer's owner membership.
- Find the subscription row for this Stripe subscription. Update it if it exists, otherwise create it.
Each write was committed on its own. A recent change (#759) had already made step 2 retry-safe: if the subscription insert failed, the retry found no row and created it.
The guard in step 1 looked retry-safe too:
const existing = await workspaceRepo.getByPublicId(db, meta.workspacePublicId);
if (!existing)
await workspaceRepo.create(db, { publicId: meta.workspacePublicId, /* ... */ });If the workspace is already there, do not create it again. That is the usual way to make a handler idempotent.
Where it broke
The guard checks whether the workspace row exists. It does not check whether the workspace is complete.
Say the connection drops after the workspace row is written but before its roles are. The handler throws, Kan answers with an error, and Stripe schedules a retry. On the retry, getByPublicId finds the row, so create is skipped. The handler moves on, writes the subscription and answers 200. Stripe marks the event as delivered and never sends it again.
The result: a paid workspace with no roles and no owner. The buyer paid and cannot use what they paid for, and nothing in the system will ever fix it, because the only process that could have fixed it just reported success.
The problem was reported by another contributor in #697, for the case where the subscription insert fails after the workspace commits. Once #759 covered that case, the same window was still open one step earlier, inside workspace creation.
The fix: one transaction
The answer is to make the partial state impossible: either every write commits, or none does. Kan uses Drizzle on PostgreSQL, and its Trello import already wraps its writes in db.transaction, so the fix follows the same pattern:
// One transaction: if any write fails, nothing is committed and Stripe's
// retry starts from scratch. Without it, a failure after the workspace
// row is written leaves it without roles or an owner, and the retry
// skips it because the workspace already exists. See #697.
await db.transaction(async (tx) => {
const txDb = tx as unknown as typeof db;
if (newWorkspace) {
const existing = await workspaceRepo.getByPublicId(txDb, workspacePublicId);
if (!existing) await workspaceRepo.create(txDb, newWorkspace);
} else {
await workspaceRepo.update(txDb, workspacePublicId, { plan });
}
const row = await findRow(sub, txDb);
const values = { ...fields, plan, referenceId: workspacePublicId };
if (row) await subscriptionRepo.updateById(txDb, row.id, values);
else await subscriptionRepo.create(txDb, values);
});Now if creating the roles fails, the workspace row rolls back with it. The retry finds nothing, creates everything, and the existence check is honest again: if the row exists, so does everything else.
Three smaller choices made the change safe to merge:
- Pass the connection, do not swap the global. The helper
findRownow takes an optional connection that defaults todb. Inside the transaction it getstxDb, so it reads rows the transaction has written. Every other caller is unchanged. - Keep network calls outside the transaction. The handler calls Stripe's API (
subscriptions.retrieve) to load the subscription. That call stays before the transaction starts. Holding a database connection and a transaction open while waiting on another company's API is how you run out of connections on a bad day. - Build the input first. The workspace input is built from the event metadata before the transaction starts. This keeps TypeScript's narrowing of the metadata fields, and keeps the transaction body to database work only.
Testing against a real database
A transaction bug cannot be tested with mocked repositories, because the mock has no idea what was committed. The PR adds a test file that runs the real handler against a real PostgreSQL: PGlite, an in-memory Postgres, with all of Kan's migrations applied. Each test delivers an event and then reads back what was actually committed.
The test for this bug makes role creation fail once, the way a dropped connection would:
it("commits nothing when workspace setup fails part-way (#697)", async () => {
// The workspace row is written, then creating its roles fails.
vi.spyOn(permissionRepo, "createRole").mockRejectedValueOnce(
new Error("connection reset"),
);
await expect(deliver()).rejects.toThrow("connection reset");
const { ws, subs } = await committed();
expect(ws).toBeUndefined();
expect(subs).toHaveLength(0);
});The five tests together cover the cases a webhook handler meets in real life:
- A normal delivery creates the workspace, its owner and one linked subscription.
- The same event delivered twice changes nothing the second time.
- A retry after the subscription insert failed completes the subscription.
- A failure part-way through workspace setup commits nothing.
- After that failure and a retry, the buyer is an admin of their workspace.
On the old code the last two fail. With the change all five pass, and the full API suite (429 tests) stays green.
What is still not covered
Two deliveries of the same event at the same moment can both see "no workspace" and both try to create it. The fix does not add locking for that. It relies on the unique publicId column: one insert wins, the other fails, and Stripe retries the loser, which then finds a complete workspace. I wrote that limit in the PR description instead of leaving it for a reviewer to find.
A checklist for webhook handlers
What I check now in any handler that Stripe, or any provider with retries, calls:
- Can it run twice? Deliver the same event twice in a test and compare the database.
- Can it fail half-way and recover? Make each write fail once, then deliver again. This is the test most handlers do not have.
- Are related writes in one transaction? If an existence check guards a multi-step create, the steps must commit together.
- Is there network I/O inside the transaction? Move it before or after.
- Does it return 2xx only when the work is done? A 200 tells the provider to stop retrying. Send it only when there is nothing left to repair.
Retries are a gift from the provider: a free second chance at every failure. They only help if the second attempt can see what the first one left behind, and with one transaction there is nothing left behind to see.