In short
A database transaction is a group of read and write operations executed as one unit: either every operation is applied, or none is, and the database moves from one consistent state to another without other users seeing the half-finished middle. Transactions provide the ACID guarantees: atomicity, consistency, isolation and durability. Use one whenever a change touches more than one row or table that must agree, such as an order and its items, a transfer between accounts, or an inventory decrement with a sale. Keep transactions short, retry on conflicts, and never hold one open across a network call or user input.
The example everyone uses
Moving money from account A to account B is two operations: subtract from A, add to B. If the server crashes between them, the money has vanished. If two transfers run at the same time and both read A's balance before either writes, one of the subtractions is lost. Neither outcome is acceptable, and preventing them is what transactions are for.
Wrapped in a transaction, the two operations are one: the database applies both or neither, and it ensures that concurrent transfers see a consistent balance. The bank example is a cliché because it is the clearest possible statement of the problem, and because every application has its own version of it.
The four guarantees
Transactions are defined by the ACID properties:
Atomicity. All or nothing. If any operation in the transaction fails, or the transaction is rolled back, none of its changes remain. The database undoes the partial work.
Consistency. The transaction moves the database from one valid state to another; constraints such as foreign keys, uniqueness and checks hold at the end. A transaction that would violate them fails entirely.
Isolation. Concurrent transactions do not see each other's intermediate state. Each behaves as if it were running alone, to a degree set by the isolation level.
Durability. Once the database confirms a transaction has committed, the changes survive a crash or power loss; they are written to durable storage before the confirmation.
Relational databases such as PostgreSQL and MySQL provide all four; the choice between them does not change this. Many NoSQL stores provide weaker or per-document guarantees, which is one of the trade-offs in choosing a database.
Isolation and what it costs
Full isolation, where every transaction behaves exactly as if serialised one after another, is expensive, so databases offer levels. Read Committed, the default in PostgreSQL, lets a transaction see changes other transactions have committed while it runs, which is fine for most work. Repeatable Read and Serializable give stronger guarantees at the cost of more conflicts, where the database aborts a transaction that would break the guarantee and the application must retry.
The practical rules: use the default unless a specific problem demands more; understand that under the default, two transactions can both read a value and then both write based on it, and use explicit locking (SELECT … FOR UPDATE) or a stronger level where that matters, such as decrementing stock or reserving a booking slot; and write code that retries a transaction that fails from a serialisation conflict or a deadlock, because those are expected outcomes rather than bugs.
Where web applications need them
Creating an order with its line items and the stock adjustment. Recording a payment and updating the account it pays. Transferring anything between two records. Applying a multi-step data change from an admin action. Registering a user and creating their initial related records. Any schema migration that changes several things. In each case, partial completion leaves data that disagrees with itself, and someone later spends a day working out why an order exists with no items.
Where they are not needed: single-row reads and writes, which are atomic by themselves; analytics queries; and logging.
The mistakes
No transaction at all around multi-step writes. The most common and the most damaging; it works until the day it does not, and then the data is inconsistent in ways that are hard to repair.
Long transactions. A transaction held open while the code calls an external API, sends an email, or waits for a user. It holds locks for seconds or minutes, blocks other transactions, and if the external call hangs, the whole database queues behind it. Do the external work outside the transaction, or after commit, or through a background job.
Ignoring failures. Catching the exception and continuing as if the transaction succeeded. The rollback happened; the code did not notice.
Not retrying conflicts. Under stronger isolation, or under contention, transactions are aborted by design. Code that treats an abort as a fatal error fails under load.
Deadlocks from inconsistent ordering. Two transactions each locking two rows in opposite order wait for each other forever until the database kills one. Acquire locks in a consistent order.
Assuming the ORM does it. ORMs and frameworks provide transaction helpers, and most single-model saves are atomic, but a sequence of saves across models is not a transaction unless wrapped in one. Check what the ORM actually does.
In practice
Most frameworks expose a transaction block: everything inside commits together or rolls back on exception. Wrap multi-step writes in it, keep the block small and free of network calls, handle the exception, and retry on conflict. That discipline is most of what separates applications whose data can be trusted from applications whose data needs an occasional cleanup script. If you have inherited a system with orders that do not add up, book a call; the missing transaction is usually easy to find.
Common questions
What does ACID mean in databases?
Atomicity: all of a transaction's operations apply or none do. Consistency: the database moves between valid states that satisfy its constraints. Isolation: concurrent transactions do not see each other's intermediate changes. Durability: a committed transaction survives crashes. Relational databases provide all four; many NoSQL stores provide weaker guarantees.
When should you use a database transaction?
Whenever a change involves more than one write that must agree: an order and its items, a payment and the balance it affects, a transfer between records, a multi-step admin action, or a migration touching several tables. Single-row writes are atomic on their own and do not need one.
What happens if a transaction fails?
The database rolls back every change the transaction made, leaving the data as it was before it started. The application receives an error and must handle it, usually by reporting the failure or, for conflicts and deadlocks, retrying the whole transaction. Ignoring the error and continuing is a common bug.
What is a deadlock in a database?
A situation where two transactions each hold a lock the other needs, so neither can proceed. The database detects it and aborts one, which the application should retry. Deadlocks usually come from transactions acquiring locks on the same rows in different orders; locking in a consistent order and keeping transactions short prevents most of them.
Why should transactions be short?
Because a transaction holds locks until it commits, and everything else that needs those rows waits. A transaction held open across an external API call, an email send or user input can block the database for seconds or minutes. Do the slow work outside the transaction, commit quickly, and hand follow-up work to a background job.