Course contents

04. Database Fundamentals Lesson 6 of 10

Transactions

See a transfer fail half-way without a transaction, how BEGIN, COMMIT and ROLLBACK fix it, how row locks and deadlocks work, and why long transactions hurt.

15 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Without a transaction each statement commits on its own, so a crash between statements leaves half-done changes.
  • BEGIN … COMMIT makes a group of writes visible together; an error, crash or ROLLBACK discards all of them.
  • Writers to the same row wait for each other’s row locks until COMMIT or ROLLBACK.
  • Deadlocks are detected and broken by aborting one transaction; lock in a consistent order and retry.
  • A transaction holds a connection and its locks for its whole duration: keep slow external work out of it.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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 >= 100 changes 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. A transfer is two writes

    Alice sends Bob $100. In the database that is two statements: UPDATE accounts SET balance = balance - 100 WHERE id = 'alice', then the same + 100 for Bob.

    Without an explicit transaction, Postgres runs each statement in its own tiny transaction (*autocommit*): the first UPDATE is committed and visible to everyone before the second one even starts. When both succeed nobody notices: Alice has 400, Bob 300, and the total is still $700.

    The moving packets in this and the next steps are a scripted illustration, slowed down so the order is visible; nothing here is simulated.

    Scene: Illustration: the Banking API sends two UPDATE statements to Postgres, one per account row. Each commits on its own. Alice goes from 500 to 400, Bob from 200 to 300.

    Key idea: A business operation is often several writes. The database only knows they belong together if you tell it.

  2. 2. The API crashes between the two writes

    Same transfer. The first UPDATE succeeds and, in autocommit mode, is committed immediately. Then the Banking API process dies (a deploy, an out-of-memory kill, a lost connection) before it sends the second statement.

    Alice has been debited, Bob was never credited. The total is now $600: $100 has vanished, and nothing in the database records that a transfer was half done.

    Scene: Illustration: the first UPDATE debits Alice and commits; then the Banking API crashes and the second UPDATE is never sent. Bob is not credited and $100 is missing.

    Key idea: Separate statements can fail separately. A crash in between leaves the data in a state no one intended.

  3. 3. Wrap both writes in one transaction

    Now the API sends BEGIN, the two UPDATEs, then COMMIT. Inside the transaction Postgres writes new versions of both rows, but other sessions keep seeing the old balances. Only COMMIT makes both changes visible, at the same instant.

    If COMMIT is acknowledged, both writes are permanent. If the transaction never commits, neither write ever becomes visible. There is no third outcome.

    Scene: Illustration: BEGIN, an UPDATE for Alice, an UPDATE for Bob, then COMMIT. Both new balances become visible together when the COMMIT is acknowledged.

    Key idea: A transaction is all or nothing: its writes become visible together at COMMIT, or not at all.

  4. 4. A crash inside the transaction rolls it back

    Replay the crash, this time inside a transaction. BEGIN, Alice’s UPDATE succeeds, and the API dies before sending Bob’s.

    Postgres sees the client connection drop and aborts the open transaction. Alice’s new row version was never committed, so it is simply never visible: everyone still sees 500 (vacuum cleans the dead version up later). Bob was never touched. The money did not move, and the transfer can safely be retried.

    The same happens on an explicit ROLLBACK, or when the database itself crashes before the commit.

    Scene: Illustration: BEGIN and Alice’s UPDATE succeed, then the Banking API crashes. Postgres aborts the transaction; Alice’s uncommitted change is discarded and she still has 500.

    Key idea: An unfinished transaction leaves no trace. Failure halfway is turned into “nothing happened”.

  5. 5. An error aborts the whole transaction

    Alice tries to send $600 but has only 500. The table has CHECK (balance >= 0). Bob’s credit happens first and succeeds; then Alice’s debit violates the constraint and the statement fails.

    In Postgres an error puts the transaction into an aborted state: every further statement is refused with “current transaction is aborted” until the client sends ROLLBACK. Bob’s +600 is undone with it. Constraints let the database guard invariants that the application might forget.

    Scene: Illustration: inside a transaction Bob is credited 600, then debiting Alice fails the balance check. The error comes back, the API sends ROLLBACK and Bob’s credit is undone.

    Key idea: A failed statement poisons the transaction; ROLLBACK undoes even the parts that had succeeded.

  6. 6. Two transactions want the same row

    A Payroll job pays Alice $50 while her transfer to Bob is still open. Both transactions update Alice’s row.

    An UPDATE takes a row lock that is held until the transaction ends. Payroll’s UPDATE therefore waits until the transfer commits, then applies its +50 to the committed 400: Alice ends at 450 and no change is lost. Readers are not blocked: a plain SELECT keeps seeing the last committed value meanwhile.

    What each transaction may see of the other’s changes is set by its isolation level (next lessons).

    Scene: Illustration: the transfer updates Alice’s row and holds its lock. The Payroll job’s update of the same row waits until the transfer commits, then applies its +50 to the committed balance; Alice ends at 450.

    Key idea: Writers to the same row queue behind each other’s locks until COMMIT or ROLLBACK.

  7. 7. Each holds what the other needs

    Now the transfer goes Alice → Bob while Payroll moves money Bob → Alice. The transfer locks Alice’s row, Payroll locks Bob’s. Then each asks for the other row and both wait forever: a deadlock.

    Postgres checks for lock cycles after waiting deadlock_timeout (1 s by default; shortened here) and aborts one of the transactions with error 40P01. The other proceeds and commits. The aborted one must be retried by the application.

    The standard fix is to take locks in a consistent order, for example always update the lower account id first.

    Scene: Illustration: the transfer locks Alice’s row and Payroll locks Bob’s. Each then waits for the other. Postgres detects the cycle, aborts Payroll with a deadlock error, and the transfer gets Bob’s lock and commits.

    Key idea: Lock cycles are detected and broken by aborting a victim. Lock rows in a fixed order to avoid them, and retry on 40P01.

  8. 8. A slow call inside the transaction

    Now real traffic: 60 transfers per second, simulated. Each transaction holds one of the database’s 10 connections from BEGIN to COMMIT, about 8 ms. Connections are mostly idle and latency is low.

    One and a half seconds in, a new release calls the payment provider inside the transaction (~300 ms). Each transfer now holds its connection, and its row locks, almost 40 times longer. Ten connections can only finish about 33 transfers per second, so transfers queue for a connection and, after waiting a second, fail with a pool timeout.

    Scene: Sixty transfers per second run against 10 database connections. When each transaction starts waiting 300 ms for a payment call, all connections stay busy, transfers queue and some fail with a pool timeout.

    Key idea: A transaction holds a connection and its locks for its whole duration. Never wait on slow external work inside one.

  9. 9. Do the slow work outside the transaction

    The fix is to keep only database work between BEGIN and COMMIT. The payment is authorised before the transaction starts, and anything that must follow the commit (emails, events) is written to an outbox table in the same transaction and sent afterwards.

    One second in, the fix ships: transactions are back to about 8 ms, the queue drains and the errors stop. Postgres can also enforce this: idle_in_transaction_session_timeout and statement_timeout end sessions that hold a transaction open too long.

    Scene: One second in, the payment call moves out of the transaction. Each transfer holds a connection for about 8 ms again, the waiting transfers drain and errors stop.

    Key idea: Short transactions: gather inputs first, then BEGIN, write, COMMIT. External side effects go before, or after via an outbox.

  10. 10. What a transaction gives you, and what it does not

    A transaction groups statements into one unit: COMMIT makes all of them visible and permanent, an error, crash or ROLLBACK makes it as if none ran. Writers to the same row wait for each other’s locks, deadlocks are broken by aborting one side, and the application retries.

    It does not cover anything outside the database: an HTTP call, a message sent to a broker or a write to another database is not undone by ROLLBACK. Keep transactions short and local, and use patterns like the transactional outbox for the rest.

    Scene: The Banking API sends short transactions to Postgres at 60 per second; nothing waits and nothing fails.

    Key idea: BEGIN … COMMIT gives all-or-nothing inside one database. Keep it short, retry aborts, and handle other systems separately.