What it is
A transaction is a group of database statements that succeed or fail as one unit. The client opens it with BEGIN, sends its statements, and ends it with COMMIT (make everything permanent and visible) or ROLLBACK (discard everything). If the client disappears, or a statement fails, the database ends the transaction itself, and the transaction never commits.
Why it exists
Real operations are rarely one statement. A transfer debits one account and credits another; placing an order inserts the order, its lines and a stock reservation. Each statement can fail on its own: the process can crash between them, a constraint can reject one, the network can drop. Without a transaction, the statements that already ran stay committed, and the data ends up in a state nobody intended, such as money that left one account and never reached the other. Transactions turn "half done" into "not done at all", which is something an application can safely retry.
How it works
Autocommit. Most drivers run in autocommit mode by default: every statement is its own transaction and commits as soon as it returns. BEGIN switches this off until the next COMMIT or ROLLBACK.
Visibility at commit. Postgres uses multi-version concurrency control (MVCC). An UPDATE inside a transaction writes a new version of the row tagged with the transaction's id. Other sessions keep seeing the old version until the transaction commits. On commit, the transaction is marked committed in the commit log and all its new versions become visible at once. On abort, they are never visible and are removed later by vacuum. Other engines (MySQL InnoDB, Oracle) keep undo logs instead, with the same effect for the application.
Errors abort the transaction. In Postgres, any error inside a transaction puts it into an aborted state: further statements are refused until the client sends ROLLBACK. A SAVEPOINT lets an application roll back part of a transaction and continue.
Row locks. An UPDATE or DELETE locks the rows it changes until the transaction ends. A second transaction that wants to change the same row waits. Under the default READ COMMITTED level, once the first transaction commits, the waiting UPDATE re-reads the newest version of the row and applies its change to it, so balance = balance + 50 adds to the committed value. Plain reads do not wait for row locks: they read the last committed version.
Deadlocks. If transaction A holds row 1 and waits for row 2 while B holds row 2 and waits for row 1, neither can proceed. Postgres runs deadlock detection after a lock wait of deadlock_timeout (1 s by default), aborts one of them with SQLSTATE 40P01, and the other continues.
When to use it
- Whenever one logical change spans several statements or rows: transfers, orders with lines, moving an item between lists.
- When a read must be followed by a write based on it (read-modify-write); combine with the right isolation level or a locking read (see Isolation Levels).
- For bulk changes that must not be seen half-applied, such as migrations and backfills done in batches, each batch its own transaction.
When not to
- Single-statement changes are already atomic; wrapping them adds round trips but no safety.
- Do not span user think-time or external calls (HTTP requests, file uploads, message publishing) with a transaction.
- Very large single transactions (millions of rows) hold locks for a long time, bloat tables and make replication lag; batch them.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Explicit transaction | All-or-nothing changes | Extra BEGIN/COMMIT round trips; locks held until the end |
| Longer transaction | Fewer commits, simpler code | Connections and row locks held longer; more lock waits and deadlocks |
| Many small transactions | Short locks, less contention | Intermediate states are visible; failures must be resumable |
| Savepoints | Partial rollback inside a transaction | Extra overhead per savepoint; easy to overuse in ORMs |
Alternatives
- Single atomic statements:
UPDATE … SET balance = balance - 100 WHERE id = 7 AND balance >= 100changes and checks in one statement, with no explicit transaction. - Sagas: across services, a sequence of local transactions with compensating actions instead of one global transaction.
- Transactional outbox: commit the state change and an event row together, publish the event afterwards.
- Two-phase commit (XA,
PREPARE TRANSACTION): atomic commit across databases, at the cost of blocking when the coordinator fails. Rarely the right tool in application code.
Failure modes
- Half-done changes in autocommit mode when a process crashes between statements.
- Swallowed errors: application code catches an exception inside a transaction and carries on; in Postgres every following statement then fails, elsewhere the transaction may commit partial work.
- Lock waits and deadlocks when transactions touch the same rows in different orders.
- Long or idle transactions holding connections and locks: pool exhaustion, blocked writers, and in Postgres vacuum cannot remove dead row versions while an old transaction is open, so tables bloat.
- Assuming rollback undoes side effects in other systems (emails, payments, broker messages).
In production
Keep transactions short: gather input and call external services first, then BEGIN, write, COMMIT. Set idle_in_transaction_session_timeout, statement_timeout and lock_timeout so a stuck session cannot hold locks indefinitely. Retry transactions that fail with deadlock (40P01) or serialization (40001) errors, with a small random backoff, and make the retried code idempotent. Monitor long-running and idle-in-transaction sessions (pg_stat_activity) and lock waits (pg_locks, log_lock_waits).
Common misconceptions
- "Each statement is safe, so the operation is safe." Atomicity of single statements says nothing about a sequence of them.
- "ROLLBACK undoes everything the request did." Only database writes in that transaction.
- "Transactions make concurrent requests run one at a time." They only serialise writers to the same rows; what each transaction may see of others depends on the isolation level.
- "A deadlock is a database bug." It is a consequence of lock order in the application; the database just breaks the cycle.
Interview angle
Expect to be asked how you keep a multi-step write consistent: name the transaction boundary, what happens on failure, and which errors you retry. Strong answers mention keeping external calls outside the transaction (and an outbox for events), lock ordering to avoid deadlocks, and that a transaction stops at the database boundary, so cross-service workflows need sagas or idempotent retries.
Model assumptions
Steps 1–7 are scripted illustrations, not simulations: the engine does not model statements, row versions or locks. Packets are slowed down so the order of events is visible, balances are annotations, and the deadlock detection delay is shortened. Steps 8–9 and the sandbox are simulated: each transfer is one database operation whose duration stands for how long the transaction holds its connection (about 8 ms for two UPDATEs, about 300 ms when it also waits for a payment call). The database has 10 connections and gives up on a transfer that waits more than 1 s for one. Arrivals are random (Poisson) and durations lognormal. Numbers are illustrative orders of magnitude, not benchmarks.