Sub topic 9
Isolation levels as snapshot timing
This chapter assumes you can run psql, open two sessions against one database, and use BEGIN, COMMIT and ROLLBACK. It also assumes you know what a snapshot is and what xmin and xmax mean on a row version. Here you will see that PostgreSQL's isolation levels differ mainly in one thing: when the snapshot is taken.
The core idea
A snapshot decides which row versions a query can see. An isolation level is a rule for when a transaction takes snapshots.
- Read Committed takes a new snapshot at the start of each statement.
- Repeatable Read takes one snapshot at the transaction's first query and keeps it until the transaction ends.
- Serializable uses the same snapshot rule as Repeatable Read and adds checks that can abort a transaction.
PostgreSQL accepts four level names in SQL, but it implements three. READ UNCOMMITTED behaves exactly like READ COMMITTED, because the engine never shows uncommitted row versions.
| Level | Snapshot taken | Dirty read | Non-repeatable read | Phantom read | Errors you must handle |
|---|---|---|---|---|---|
| Read Committed (default) | Per statement | No | Possible | Possible | Deadlocks |
| Repeatable Read | Once per transaction | No | No | No in PostgreSQL | Serialization failures, deadlocks |
| Serializable | Once per transaction, plus conflict tracking | No | No | No | Serialization failures, deadlocks |
The SQL standard allows phantom reads at Repeatable Read. PostgreSQL does not show them there, because the whole transaction reads from one snapshot. Some anomalies, such as write skew, can still occur at Repeatable Read.
Setup
The examples use the table from earlier chapters.
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);Open two psql sessions, called A and B. Run each step in the order shown.
Read Committed: a new snapshot per statement
Read Committed is the default level. Each statement sees every change committed before that statement began.
-- Session A
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT balance FROM accounts WHERE id = 1; -- 100
-- Session B
UPDATE accounts SET balance = balance + 10 WHERE id = 1; -- autocommits
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- 110, B's change is visible
COMMIT;Both queries ran inside one transaction, yet they returned different answers. The second SELECT took a fresh snapshot, and B's transaction was already committed by then. This is a non-repeatable read. It is allowed at this level.
The timing is per statement, not per transaction. A single statement never sees a change that commits while it is running. Within that statement the snapshot is fixed.
Repeatable Read: one snapshot for the transaction
Repeat the same steps, but start Session A with a different level.
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- 110
-- Session B
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- still 110
COMMIT;Session A's snapshot was taken at its first query, so B's later commit stays invisible to A. You can check this with pg_current_snapshot(). Inside a Repeatable Read transaction it returns the same value on every call.
SELECT pg_current_snapshot();
-- returns xmin:xmax:xip_list, for example 748:752:748,750The snapshot starts at the first query, not at BEGIN. If you open a transaction and wait, changes that commit before your first query are still visible. This matters for long pauses between BEGIN and the first SELECT.
Because that fence must name its type, here is the diagram in the required form.
What happens when you write
A snapshot only governs what you read. When you modify a row, PostgreSQL must act on the newest committed version, not the one in your snapshot. The two levels handle this differently.
At Read Committed, if a statement tries to update a row that another open transaction has already updated, it waits. If the other transaction commits, PostgreSQL re-evaluates the WHERE clause against the new version of the row. The statement then updates that new version. No error occurs.
At Repeatable Read, the same situation fails if the other transaction commits.
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;
-- Session B
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- Session A
UPDATE accounts SET balance = balance - 5 WHERE id = 1;
-- ERROR: could not serialize access due to concurrent update
ROLLBACK;The row changed and committed after A's snapshot. Applying A's update on top would silently discard B's change from A's point of view, so PostgreSQL aborts A. The application must catch this error and retry the whole transaction.
If B had rolled back instead, A's update would proceed, because the competing version never became visible.
Lost updates and how each level treats them
Consider the common pattern of reading a value, computing in the application, and writing it back.
SELECT balance FROM accounts WHERE id = 1; -- application reads 100
UPDATE accounts SET balance = 90 WHERE id = 1; -- application writes 100 - 10At Read Committed, two concurrent runs can both read 100 and both write 90, so one deduction is lost. The write does not fail, because the update just applies to the newest version. At Repeatable Read, the second writer gets a serialization failure, so the lost update cannot happen silently.
You can avoid the problem at Read Committed by writing the change as one statement, such as SET balance = balance - 10. Locking the row first with SELECT ... FOR UPDATE also works. The second session waits for the lock and then reads the newest committed value.
Write skew and Serializable
Repeatable Read still permits write skew. Two transactions read overlapping data, then each updates a different row based on what it read. Neither update touches a row the other changed, so no row-level conflict is detected. Each transaction was valid on its own, but together they break a rule.
For example, a rule says at least one doctor must stay on call. Two doctors each check that the other is on call, then each sets their own row to off. Both succeed at Repeatable Read, and nobody is on call.
Serializable adds Serializable Snapshot Isolation (SSI). PostgreSQL tracks read and write dependencies between concurrent transactions. If it finds a pattern that could not occur in any serial order, it aborts one transaction with:
ERROR: could not serialize access due to read/write dependencies among transactionsSSI can abort transactions that would have been safe, so expect some false positives. Retry logic is mandatory at this level. A later chapter covers the mechanism in detail.
Choosing a level
Use these rules as a starting point.
- Choose Read Committed for simple, short transactions where each statement stands alone. Write updates as single atomic statements or use
FOR UPDATEwhen you read before you write. - Choose Repeatable Read when a transaction runs several queries that must agree, such as a report. A read-only Repeatable Read transaction never fails with a serialization error because of other writers.
- Choose Serializable when correctness depends on invariants across several rows and you cannot easily lock them. Accept the retry cost.
You can set the level for one transaction, for a session, or as a default.
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- or, as the first statement after BEGIN:
-- SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SHOW default_transaction_isolation;SET TRANSACTION must run before the first query of the transaction. After that, the snapshot exists and the level can no longer change.
Common errors
- Assuming
BEGINtakes the snapshot. At Repeatable Read the snapshot starts with the first query. - Not retrying. Serialization failures (SQLSTATE
40001) are normal at the upper two levels. They are an expected signal, not a bug. Retry the entire transaction, not just the failed statement. - Reading, then writing based on the read at Read Committed. The read can be stale by the time of the write.
- Long Repeatable Read transactions. They hold an old snapshot, which holds back vacuum. A later chapter on the xmin horizon explains why this causes bloat.
- Expecting
READ UNCOMMITTEDto show dirty data. It does not in PostgreSQL.
Exercise
Session A runs BEGIN ISOLATION LEVEL REPEATABLE READ and then SELECT balance FROM accounts WHERE id = 1, which returns 100. Session B then updates that row to 150 and commits. Session A runs SELECT balance again, then UPDATE accounts SET balance = balance + 1 WHERE id = 1. What does each of the two statements do?
Show answer
The second SELECT returns 100, because A still uses the snapshot taken at its first query. The UPDATE fails with "could not serialize access due to concurrent update", because the row was changed and committed by B after A's snapshot. A must roll back and retry the transaction. At Read Committed, the SELECT would return 150 and the UPDATE would succeed, giving 151.
Exercise
Why does a single-statement UPDATE accounts SET balance = balance - 10 WHERE id = 1 avoid lost updates at Read Committed, while a separate SELECT followed by an UPDATE with a computed value does not?
Show answer
The single statement reads and writes the newest committed version of the row. If another transaction holds the row, it waits and then re-evaluates against the new version, so the subtraction applies to the current balance. In the two-step pattern, the application's SELECT can return a value that is stale by the time its UPDATE runs, so the computed value overwrites the other transaction's change.