Question

When should I use a database transaction?

Vault Verified
Curated Intelligence
Definitive Source
Answer

The rule is simple to state: use a transaction whenever two or more writes must either all succeed or all fail. If a partial result would leave your data in a state that should never exist, those writes belong in one transaction.

The classic example is moving a value between two records. Deducting from one and adding to the other are individually valid, but a failure between them destroys or invents value. Wrapping both in a transaction means a crash rolls back to the state before either happened.

Less obvious cases are just as important. Creating a record and its dependent rows together, updating a row and writing an audit entry, or consuming a queue item and recording the result all share the property that half of it is worse than none of it.

A transaction is not needed for a single statement, because individual statements are already atomic. It is also not the right tool for coordinating with systems outside the database. A transaction cannot roll back an email that has been sent or a payment provider that has been called, and holding one open across a network request is actively harmful, since it keeps locks and a connection occupied for the duration of something you do not control. The usual pattern is to commit first and record intent, then perform the external action separately with its own retry handling.

Two practical cautions apply. Long transactions increase lock contention and can block other writers, so keep them as short as correctness allows. And under concurrency the isolation level determines what a transaction can observe from others running at the same time; the default is often weaker than people assume, so operations that read a value and then write based on it may need explicit locking or a stricter level to be correct.

Related Questions