Transactions

Which operations belong in one atomic unit, why a network call inside a transaction is a resource problem, and what to do when a commit and a message must both happen.

Transactions from Application Code

BEGIN, COMMIT and ROLLBACK as things your code controls: bound to one connection, ended by an error you did not expect, and retried when the database says so.

Q · What does a transaction actually give my handler, and what do I have to do to get it?
Where the Transaction Boundary Goes

Which operations must commit together, which merely happen nearby, and why "the whole handler" is almost never the right answer.

Q · Which of these operations belong inside the same transaction, and which are just adjacent in time?
One Transaction or Two

Splitting a unit of work trades an atomicity guarantee for shorter locks — and buys you an intermediate state you now have to design.

Q · Should this be one long transaction or two short ones, and what do I owe the state in between?
External Calls Inside a Transaction

A five-second payment call between BEGIN and COMMIT holds a pooled connection and every lock the transaction took, for five seconds, on every request.

Q · What does it actually cost to call another system while a database transaction is open?
The Dual Write Problem

The commit succeeds and the publish fails, or the publish succeeds and the commit rolls back. Two systems, no shared transaction, and no ordering that fixes it.

Q · How do I make a database write and a message publish either both happen or neither?
The Transactional Outbox

Write the event as a row in the same transaction as the state change, then publish it from a background reader — at-least-once, by design.

Q · How do I guarantee that an event is published for every committed change, exactly as reliably as the change itself?
Deadlocks in Application Code
▶ lab

Two transactions take the same two locks in opposite orders, each waits for the other, and the database kills one of them — with an error your code has to expect.

Q · Why does one of my transactions get aborted with "deadlock detected", and whose fault is it?