Transactions, MVCC and locking
Real apps have many users changing data at the same time. Two people buy the last ticket; a transfer debits one account but crashes before crediting the other. Transactions are how PostgreSQL keeps data correct in that chaos.
ACID in one table
| Letter | Promise |
|---|---|
| Atomic | All statements in a transaction happen, or none do |
| Consistent | Constraints hold before and after |
| Isolated | Concurrent transactions don't see each other's half-finished work |
| Durable | Once committed, it survives a crash (it's in the write-ahead log on disk) |
BEGIN, COMMIT, ROLLBACK
Every statement runs in a transaction. Normally each one is its own ("autocommit"). BEGIN groups several:
CREATE TABLE accounts (
id integer PRIMARY KEY,
owner text NOT NULL,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Rahul', 100);ROLLBACK throws all the changes away:
Errors abort the whole transaction
If any statement fails, Postgres refuses to run anything else in that transaction until you roll back. This protects you from committing half a change:
Notice the COMMIT reports ROLLBACK: nothing from the failed transaction was saved.
Savepoints: partial rollback
A savepoint is a checkpoint inside a transaction that you can roll back to:
MVCC: how Postgres handles concurrency
PostgreSQL uses Multi-Version Concurrency Control. An UPDATE doesn't overwrite a row in place: it writes a new version and marks the old one as expired. Each transaction sees the versions that were committed when it started (or when its statement started). The result:
- Readers never block writers, and writers never block readers.
- Only two writers changing the same row wait for each other.
You can peek at the hidden system columns: xmin is the transaction that created the row version, and ctid is its physical location:
Asha's row moved to a new ctid with a new xmin: it's a new version. The old one is now a dead tuple. VACUUM (run automatically by autovacuum) cleans dead tuples up so the space can be reused. If autovacuum can't keep up on a busy table, the table bloats, so it's worth monitoring.
Isolation levels
How much do concurrent transactions see of each other? SQL defines isolation levels:
| Level | Each statement sees… | Prevents | Default? |
|---|---|---|---|
| Read Committed | Everything committed before the statement started | Dirty reads | ✅ Postgres default |
| Repeatable Read | A snapshot from the transaction's first query | + non-repeatable reads, phantoms | |
| Serializable | As if transactions ran one at a time | + all anomalies (may abort with a serialization error) |
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- ...
COMMIT;With Repeatable Read and Serializable, Postgres may abort a transaction with could not serialize access. Your app must then retry it. That's normal, not a bug.
The lost-update problem
Two requests run this at the same time, in two sessions (the editor has a single session, so here's the timeline):
Session A Session B
SELECT stock FROM products WHERE id=10;
→ 1 SELECT stock FROM products WHERE id=10;
→ 1
UPDATE products SET stock = 0 …; UPDATE products SET stock = 0 …;
-- both think they sold the last monitor! One sale is lost.Fix 1: do the maths in SQL, so the check and the change are one atomic statement:
Fix 2: lock the row with SELECT … FOR UPDATE. A second session's FOR UPDATE on the same row waits until the first commits:
A job queue with SKIP LOCKED
FOR UPDATE SKIP LOCKED lets many workers pull jobs from one table without ever grabbing the same job. Each worker skips rows another worker has locked:
Deadlocks
If session A locks row 1 then wants row 2, while session B locks row 2 then wants row 1, both wait forever. Postgres detects this after a second and aborts one of them with deadlock detected. Prevent it by always locking rows in the same order (for example, by id), and keep transactions short.
Rules for healthy transactions
- Keep them short. Never wait for user input or call a slow external API inside a transaction.
- Don't leave sessions "idle in transaction": they hold locks and block VACUUM.
- Let the database check rules atomically (
UPDATE … WHERE stock >= 1, constraints,ON CONFLICT). - Be ready to retry on serialization failures and deadlocks.
Practice
- In one transaction, move 50 from Rahul to Asha, but
ROLLBACKinstead of committing. Confirm nothing changed. - Write a transfer that should fail (move 10,000) and confirm both balances are unchanged afterwards.
- Use a savepoint to insert two accounts, where the second one fails, and keep the first.
1.A statement inside BEGIN … COMMIT fails. What happens at COMMIT?
2.In PostgreSQL's MVCC, do readers block writers?
3.What's the safest way to decrement stock without overselling?