Topic 1 of 5 · 5 min read
Drawing transaction boundaries correctly
Goal: Mark where a multi-step write should begin and commit, and move slow external calls outside the transaction.
A transaction should wrap exactly the writes that must succeed or fail together, and nothing slower than the database. Atomicity means all statements inside commit, or none do. It says nothing about work outside the database.
Check yourself · 1 of 3
What does atomicity guarantee for a transaction?
Why it matters
Take an order. You insert the order row, insert its items and reduce stock. If the server crashes after the second statement, a half-written order exists and stock is wrong. Put the three writes in one transaction and a crash rolls back all of them. Two bugs follow from drawing the line badly: too small (related writes in separate transactions) and too big (slow work inside).
How to draw the line
- List the invariants. "An order always has items." "Stock never goes negative." Each invariant tells you which writes share a transaction.
- Begin late, commit early. Do validation, parsing and reads that need no consistency before
BEGIN. Commit as soon as the last write is done. - Keep the transaction to database work. Do not call a payment API, send an email or wait for a model response while it is open.
- Check the connection. Every statement must use the same connection or session. In an ORM, use the transaction object it hands you, not the global client.
Why slow calls hurt
Rows you have written stay locked until COMMIT or ROLLBACK. If you call an LLM for 8 seconds inside the transaction, every other request that touches those rows waits 8 seconds, and the connection stays checked out of the pool. A traffic spike then exhausts the pool and the whole service stalls. The session also shows as idle in transaction while it waits.
Before and after
# Before: the model call holds a transaction open
with db.transaction() as tx:
order = tx.insert_order(cart)
summary = llm.summarize(cart) # 5-10 seconds
tx.update_order(order.id, summary=summary)
# After: slow work first, short transaction after
summary = llm.summarize(cart)
with db.transaction() as tx:
order = tx.insert_order(cart, summary=summary)
tx.reserve_stock(cart.items)
If the call must happen after the commit (you need the order id), commit first, call the API, then write the result in a second short transaction. Accept that the two steps can fail separately and design for it (see idempotent writes).
What goes wrong
- Autocommit by accident. Each statement commits alone, so a failure between them leaves partial data. AI-written scripts often do this.
- Swallowed errors inside the block. A
try/exceptthat catches the error and continues commits a half-done change. In PostgreSQL a failed statement aborts the whole transaction anyway. - One giant transaction for a batch job. Updating a million rows at once holds locks and bloats the log. Commit in batches of a few thousand.
Examples
Payment call inside a transaction
A generated checkout handler opens a transaction, inserts the order, calls the payment provider (about 2 seconds, sometimes 30), then updates the order to paid. During that time the order row and the stock rows are locked. Move the provider call out: create the order as pending in a short transaction, call the provider, then mark it paid in a second short one.
Two writes on two connections
await db.transaction(async (tx) => {
await tx.insert(orders).values(order);
await db.insert(items).values(items); // global db, not tx
});
The items insert uses the global client, so it runs on another connection and commits immediately. If the order insert rolls back, the items stay. The fix is tx.insert(items).
Key points
- Atomicity means all the writes in a transaction commit or none do, and it covers only database work.
- Choose the writes for a transaction from the invariants that must always hold together.
- Begin the transaction late and commit as soon as the last write is done.
- Calling an external API or a model inside a transaction holds row locks and a pooled connection for the whole call.
- Every statement of a transaction must use the same connection or transaction object.
Common mistakes
- Assuming a transaction also rolls back an email, a webhook call or a file write.
- Wrapping a whole request handler in one transaction, including validation and network calls.
- Catching a database error inside the transaction block and carrying on.
- Using the global database client inside a transaction callback instead of the transaction object.
Check yourself · 2 of 3
A handler opens a transaction, writes an order, calls a payment API that takes 3 seconds, then updates the order. What is the best change?
Check yourself · 3 of 3
Inside db.transaction(tx => ...), a generated function inserts the parent row with tx and the child rows with the global db client. What happens?
Practice items, not counted towards your mastery.
Start here
- Transaction Isolation (PostgreSQL documentation) (opens in a new tab)DocsFree
What read committed, repeatable read and serializable allow, and why serialization failures must be retried.
- PostgreSQL: Explicit locking (opens in a new tab)DocsFree
Row and table lock modes, FOR UPDATE, and the section on deadlocks and lock ordering.
- Jepsen: Consistency models (opens in a new tab)ArticleFree
A map of isolation and consistency models and which anomalies each one allows.
More for this topic
- PostgreSQL: Transactions tutorial (opens in a new tab)DocsFree
A short worked example of BEGIN, COMMIT and atomic multi-statement changes.