StoicBuilder

HandbookXI the TabulariumTransactions

XIthe Tabularium, Model the data

Transactions

1 min readUpdated 28 November

In plain words

A transaction groups several database changes so they succeed or fail together: if any step fails, the database undoes the others, so nothing is left half done.

Where you see it

Upgrading a Harbor team writes three things: the old subscription marked ended, a new subscription row, and an invoice. Without a transaction, a crash after the first write leaves a team with no active plan and no invoice; inside one, the crash undoes all three.

lib/billing/upgrade.tsserver
await db.transaction(async (tx) => { await tx.update(subscriptions).set({ status: "ended" }).where(eq(subscriptions.id, oldId)); await tx.insert(subscriptions).values({ teamId, planId: "pro", status: "active" }); await tx.insert(invoices).values({ teamId, amountCents: 3000, status: "open" });});// if any line throws, Postgres rolls back all three
Drizzle shown here; Prisma has $transaction, and plain SQL has begin and commit.

What goes wrong

  1. Calling Stripe inside the transaction

    A rollback undoes database writes, not a card charge. If the charge succeeds and the commit then fails, the customer has paid for nothing, so keep outside calls out of the transaction and record their results in a way you can reconcile.

  2. Using the outer client inside the callback

    A query sent through db instead of tx runs outside the transaction and isn't rolled back. Every query inside must use the transaction's own handle.

    await db.insert(invoices).values(row); // inside the callback, outside the transaction
  3. Expecting a transaction to stop every race

    Two requests can both read a seat count of 4, both add a member and both commit, leaving 6 members on a 5-seat plan. Lock the row with select ... for update, or let a constraint refuse the second write.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Wrap every multi-step write in the upgrade flow in a single database transaction, using the transaction handle for each query inside it. Keep the Stripe call outside the transaction, and tell me exactly what happens if the process crashes between the charge and the commit.

Quick check

Sign in to earn +10 XP for it

Harbor's upgrade code charges the card through Stripe, then saves the new subscription in a transaction. The save fails. What does the rollback undo?

Got a prompt that touches transactions?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.