Overview
A transaction groups statements into one unit of work that either fully happens or does not happen at all. ACID names the guarantees:
- Atomicity: all or nothing. A failure rolls back partial changes.
- Consistency: a transaction takes the database from one valid state to another (constraints hold).
- Isolation: concurrent transactions do not see each other’s partial work, to a degree set by the isolation level.
- Durability: once committed, data survives a crash.
Core concepts
- Durability is implemented with a write-ahead log (WAL in PostgreSQL, the transaction log in SQL Server, redo log in Oracle): changes are written to the log and flushed before
COMMITreturns; data pages are written later. After a crash the engine replays the log. - Atomicity uses the log (or undo information) to reverse uncommitted changes.
- Autocommit: most clients run each statement in its own transaction unless you open one explicitly (
BEGIN, orBEGIN TRANin SQL Server). Oracle starts a transaction implicitly on the first change and ends it atCOMMIT/ROLLBACK. - Savepoints allow partial rollback inside a transaction.
Worked example
Verified on PostgreSQL 17 with acct(id, bal CHECK (bal >= 0)), balances 100 and 0:
BEGIN;
UPDATE acct SET bal = bal - 60 WHERE id = 1; -- 40
SAVEPOINT s;
UPDATE acct SET bal = bal - 60 WHERE id = 1; -- ERROR: violates check constraint
ROLLBACK TO s; -- back to the state after the first update
UPDATE acct SET bal = bal + 60 WHERE id = 2;
COMMIT;Final balances: 40 and 60. A later UPDATE ... SET bal = bal - 500 fails the check and leaves the table unchanged. Without the savepoint, PostgreSQL would mark the whole transaction as aborted after the error and refuse further statements until ROLLBACK. (SQL Server and Oracle behave differently here: a failed statement is rolled back but the transaction stays open, unless XACT_ABORT is on in SQL Server.)
Pitfalls and production notes
- Keep transactions short. A long transaction holds locks or old row versions, blocks maintenance, and in PostgreSQL stops vacuum from removing dead rows (locking-and-mvcc).
- Never wait on a user, an HTTP call or a message broker inside a transaction.
- Retry on serialization failures and deadlocks (PostgreSQL SQLSTATE
40001/40P01, SQL Server error 1205, Oracle ORA-00060). Make the retried work idempotent. - Cross-system consistency (database plus message broker) needs patterns such as the outbox, not a bigger transaction.
Practice questions
- What exactly is flushed to disk at
COMMIT, and what is not? - A transfer updates two rows in two statements. Which ACID property protects against a crash between them?
- Why is
autocommitrisky for multi-statement business operations?
References
- PostgreSQL manual, Transactions: https://www.postgresql.org/docs/current/tutorial-transactions.html
Related
isolation-levels · locking-and-mvcc · safe-schema-migrations · pg-wal-checkpoints · oracle-redo-undo · ch-when-not-to-use