Sub topic 1
MVCC: why readers do not block writers
PostgreSQL lets a SELECT and an UPDATE run against the same row at the same time, and neither waits for the other. The mechanism is multiversion concurrency control (MVCC). This chapter explains how MVCC works, what a snapshot is, and which cases MVCC does not cover. Those cases are why the rest of this tutorial exists.
Prerequisites
This chapter assumes you already know:
- Basic SQL:
SELECT,INSERT,UPDATE,DELETE. - Transactions:
BEGIN,COMMIT,ROLLBACK. - How to open two concurrent sessions, for example two
psqlwindows connected to the same database. - What primary keys and foreign keys are.
All examples use this table. Create it once:
CREATE TABLE accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100), (2, 100);The core idea: many versions of one row
A database that kept a single copy of each row would have to make readers and writers take turns. Otherwise a reader could see a half-written change. PostgreSQL avoids this by never changing a row in place. An UPDATE writes a new version of the row and marks the old version as replaced. A DELETE marks the current version as removed and writes nothing new.
Each row version carries bookkeeping in hidden system columns:
| Column | Meaning |
|---|---|
| `xmin` | ID of the transaction that created this version |
| `xmax` | ID of the transaction that deleted or replaced this version, or 0 if none has |
| `ctid` | Physical location of this version as (page, item) |
You can select these columns like any other:
SELECT xmin, xmax, ctid, * FROM accounts ORDER BY id;Right after the INSERT, both rows have xmax = 0 and a ctid such as (0,1) and (0,2). The xmin value is the transaction ID of the insert. Exact numbers differ on your server.
Now run an update in an open transaction and look at the row again:
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SELECT xmin, xmax, ctid, * FROM accounts WHERE id = 1;Inside this transaction you see the new version. Its ctid has typically moved to something like (0,3), and its xmin is your own transaction ID. The old version at (0,1) is still on disk, and its xmax now holds your transaction ID. Leave the transaction open for the next section.
Snapshots decide which version you see
A snapshot is a record of which transactions had committed at a particular moment. When a query reads a row, PostgreSQL checks each version against the snapshot and returns the one that is visible:
- A version is visible if its
xmintransaction is committed in the snapshot (or is your own transaction), and itsxmaxis 0, aborted, still in progress, or not visible to the snapshot. - A version is invisible if its creator has not committed, or if a transaction visible to the snapshot has already deleted or replaced it.
While your transaction from the previous section is still open, switch to a second session and run:
SELECT xmin, xmax, ctid, * FROM accounts WHERE id = 1;The query returns immediately. It shows the old version, with balance 100, because your uncommitted update is not visible in the second session's snapshot. The xmax column shows your transaction ID, but the version is still visible because that transaction has not committed. The reader did not wait, and it did not see uncommitted data.
Now commit in the first session:
COMMIT;Repeat the SELECT in the second session. It returns the new version, with balance 90.
Isolation levels choose when the snapshot is taken
How long a snapshot lives depends on the transaction isolation level.
- Read Committed (the default) takes a new snapshot at the start of every statement. Two identical
SELECTstatements in one transaction can return different results if another transaction commits between them. - Repeatable Read takes one snapshot at the first statement of the transaction and keeps it. Every statement in the transaction sees the same data, apart from your own changes.
- Serializable uses the same kind of snapshot as Repeatable Read and adds checks that abort transactions whose combined effects could not have happened in any serial order.
You can see the Repeatable Read behavior directly. In session A:
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 2;In session B, change the row and commit:
UPDATE accounts SET balance = 500 WHERE id = 2;In session A, select again. It still returns 100, because the snapshot was fixed at the first query. Finish with COMMIT; in session A, and the next query sees 500.
Where MVCC stops: locks are still needed
MVCC removes read/write blocking. It does not remove the need for locks, for four reasons.
Two writers cannot both replace the same row
If two transactions both try to update the same row, only one can create the next version. The second one waits for a row-level lock held by the first. The wait lasts until the first transaction commits or rolls back:
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session B (blocks until session A commits or rolls back)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;
-- Session A
COMMIT;What session B does after the wait depends on the isolation level. Under Read Committed, session B re-reads the newest version of the row, checks that it still matches the WHERE clause, and applies its change to that version. The final balance reflects both updates. Under Repeatable Read, the newest version is not part of B's snapshot, so PostgreSQL aborts B with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001). The application must retry the whole transaction.
Plain reads still take a table lock
Every statement takes a lock on each table it touches, including SELECT. A plain SELECT takes the weakest table lock, ACCESS SHARE. You can see it in pg_locks:
BEGIN;
SELECT * FROM accounts WHERE id = 1;
SELECT locktype, relation::regclass AS relation, mode, granted
FROM pg_locks
WHERE pid = pg_backend_pid()
AND locktype = 'relation'
AND relation = 'accounts'::regclass;
COMMIT;The result has a row with mode = AccessShareLock and granted = t. This lock conflicts only with ACCESS EXCLUSIVE, which is what commands like DROP TABLE and most forms of ALTER TABLE take. So readers do not block writers, but a schema change can block both, as a later chapter shows.
MVCC alone does not stop lost updates in application logic
Consider code that reads a balance, computes a new value in the application, and writes it back:
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- application sees 90
-- application computes 90 - 10
UPDATE accounts SET balance = 80 WHERE id = 1;
COMMIT;If another transaction changed the balance between the SELECT and the UPDATE, the write overwrites that change. The SELECT took no row lock, and the snapshot gave no protection. Two fixes work. You can write SET balance = balance - 10 so the arithmetic happens against the latest version. Or you can read with SELECT ... FOR UPDATE, which takes a row lock. Row locks are covered in a later chapter.
Constraints and explicit locking need coordination
Unique indexes, foreign keys, and explicit commands such as LOCK TABLE all depend on locks. Two sessions inserting the same primary key value, for example, cannot both succeed. The second waits to learn whether the first commits.
The cost of MVCC: dead tuples and vacuum
Old row versions that no snapshot can see anymore are called dead tuples. They take up space until VACUUM removes them. Autovacuum runs this in the background. Two consequences matter for locking:
- A long-running transaction holds its snapshot open, so vacuum cannot remove any version that snapshot might still need. A forgotten open transaction makes tables grow even if it holds no row locks.
- A transaction left open after a write holds its locks too. This is why
idle_in_transaction_session_timeoutappears later in this tutorial.
You can see the counts per table:
SELECT relname, n_live_tup, n_dead_tup
FROM pg_stat_user_tables
WHERE relname = 'accounts';The statistics update with a short delay, so the numbers may lag behind your last statement.
Common errors and misconceptions
- "A SELECT never takes locks." It takes
ACCESS SHAREon the table. That lock rarely matters, but it does conflict withACCESS EXCLUSIVE. - "Read Committed means my transaction sees one consistent state." It does not. Each statement gets its own snapshot, so a multi-statement transaction can see changes committed between statements.
- "Uncommitted updates make other readers wait." They do not. Readers get the last committed version. Only other writers (and explicit lockers) wait.
- Ignoring serialization failures. Under Repeatable Read and Serializable,
40001errors are normal and expected. Treat them as a signal to retry the transaction. - Leaving transactions open. An open transaction keeps locks and a snapshot. Both cause trouble that is hard to trace to the cause.
What comes next
The next chapter looks at how long locks live: every lock taken inside a transaction is held until the transaction ends, which is the root of most blocking problems. Later chapters build on that to cover table lock modes, row locks, deadlocks, and diagnosis.
Exercise
Session A runs BEGIN; UPDATE accounts SET balance = 0 WHERE id = 1; and leaves the transaction open. Session B then runs (1) SELECT balance FROM accounts WHERE id = 1; and (2) UPDATE accounts SET balance = balance + 1 WHERE id = 1;. Which of these two statements waits, what does the other return, and what happens to the waiting one if session A rolls back?
Show answer
Statement (1), the SELECT, does not wait. It returns the last committed balance, because session A's new row version is not visible to session B's snapshot. Statement (2), the UPDATE, waits for session A's row lock. If session A rolls back, its new version is discarded and the lock is released, so session B's update proceeds against the original committed row and adds 1 to the original balance.
Exercise
In a Repeatable Read transaction, you read row 2 and then another session updates and commits that row. You then try to UPDATE row 2 in your transaction. What happens, and what should the application do?
Show answer
Your snapshot was fixed at your first query, and the committed change is newer than it. PostgreSQL aborts the statement with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001). The application should roll back and retry the entire transaction, which then gets a fresh snapshot.