# Topic 44: Transactions
BEGIN, COMMIT, ROLLBACK, SAVEPOINT, nested transaction mechanics, and transaction error handling.
1. Definition
A database transaction is a logical unit of work comprising one or more SQL operations that execute with all-or-nothing atomicity.
2. Explain Like I'm 5
A transaction is an all-or-nothing promise. If you transfer $100 to a friend, step 1 takes $100 from you, and step 2 gives $100 to your friend. If step 2 fails, step 1 is cancelled completely so nobody loses money.
3. Animation & Visual Simulation
Interactive Engine TraceTransactions Visual Simulator
BEGIN;
UPDATE inventory SET stock = stock - 1 WHERE item_id = 99;
INSERT INTO order_log (item_id, sold_at) VALUES (99, NOW());
COMMIT;Active InputStep 1: Input & Parsing Stage
Initiating Transactions
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Transferring $500 between two bank accounts safely.
| Account | Initial | Step 1 (Deduct) | Step 2 (Credit) |
|---|---|---|---|
| Alice (Sender) | $1,000 | $500 | $500 |
| Bob (Receiver) | $200 | $200 | $700 |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectBEGIN; UPDATE accounts SET balance = balance - 500 WHERE id = 1; UPDATE accounts SET balance = balance + 500 WHERE id = 2; -- If all validations pass: COMMIT;
BEGIN; INSERT INTO orders (id, user_id) VALUES (101, 1); SAVEPOINT before_coupon; UPDATE coupons SET used = true WHERE code = 'INVALID_CODE'; -- Fails validation: ROLLBACK TO SAVEPOINT before_coupon; -- Order is still inserted and committed: COMMIT;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| All-or-Nothing | If an error occurs or ROLLBACK is issued, all changes made inside the transaction are completely undone. |
| Autocommit Mode | By default, standalone SQL statements outside a BEGIN block execute inside their own single-statement autocommit transaction. |
| Savepoint Nesting | Savepoints enable emulated nested transactions in PostgreSQL. |
| Write-Ahead Logging (WAL) protocol | WAL changes must be flushed to durable disk before dirty buffer pages can be written to the heap. |
| Savepoint partial rollback | ROLLBACK TO SAVEPOINT rolls back mutations made after the savepoint without aborting the parent transaction. |
7. Deep Dive: Write-Ahead Logging (WAL) and Durability
When COMMIT is issued, the database engine does NOT immediately write modified table pages to disk. Instead, it writes a compact record to the Write-Ahead Log (WAL) and flushes it to disk via fsync(). If power fails 1 millisecond later, the database replays WAL records to reconstruct the committed state (ARIES recovery).
-- WAL flow: -- 1. Mutate page in RAM buffer pool -- 2. Append change record to WAL buffer -- 3. On COMMIT: fsync() WAL buffer to disk -- 4. Later: Checkpointer flushes dirty RAM pages to table data files
8. Advantages & Disadvantages
Advantages
- •Guarantees mathematical consistency across multi-table writes.
- •Enables error recovery without leaving partial corrupted data.
Disadvantages & Trade-offs
- •Holding transactions open too long causes connection pool exhaustion and lock timeouts.
9. Common Interview Questions
Q1.What happens at the database storage engine level when you issue COMMIT?
When a client executes COMMIT, the database engine does NOT immediately flush all modified 8 KB data pages to table files (that would be slow random I/O). Instead, it appends a Commit Record to the sequential Write-Ahead Log (WAL) buffer and executes an fsync() system call, flushing the log to durable disk. Once WAL is on disk, the transaction is guaranteed durable and the engine acknowledges success.
Q2.How do SAVEPOINT and ROLLBACK TO SAVEPOINT work under the hood?
A SAVEPOINT marks an intermediate logical point within an active transaction block. If a subsequent statement fails (e.g. a foreign key violation or balance error), the application can issue ROLLBACK TO SAVEPOINT sp1; The engine invalidates all tuple mutations created after the savepoint without aborting the parent transaction, allowing subsequent statements to continue and commit.
Q3.What is the difference between an Implicit Transaction and an Explicit Transaction?
An Explicit Transaction starts with an explicit BEGIN or START TRANSACTION and ends with COMMIT or ROLLBACK. An Implicit Transaction (Autocommit mode) wraps every individual standalone SQL statement in its own automatic transaction: the statement begins, executes, and automatically commits immediately upon completion.
Q4.What is Transaction ID (XID) wraparound in PostgreSQL and how is it prevented?
PostgreSQL uses a 32-bit integer for transaction IDs, providing 4.2 billion unique IDs. Because comparison logic treats half the IDs as in the past and half in the future, if a database runs for 2 billion transactions without maintenance, old transaction IDs wrap around and appear to be in the future, causing historical data to suddenly disappear! Autovacuum freeze runs periodically to convert old XIDs into a special FrozenTransactionId.
Q5.Why are long-running open transactions dangerous in production databases?
1. They hold row and table locks, causing lock queues and application timeouts. 2. In MVCC, autovacuum CANNOT clean up dead tuples that were created after the oldest active transaction started, causing severe table and index bloat. 3. They prevent WAL logs from being recycled, filling up disk storage.
10. Interview-Ready Answer
“Transactions bundle multiple SQL operations into an atomic unit using BEGIN, COMMIT, and ROLLBACK. Changes are made durable via Write-Ahead Logging (WAL), with SAVEPOINTS enabling granular partial error recovery.”
11. Quick Test
What happens to changes made within a transaction if a server experiences a sudden power outage before COMMIT is issued?