Sub topic 10
Snapshot isolation and repeatable read
This chapter assumes you know the four SQL standard isolation levels and the anomalies they allow, and that you have seen MVCC (multiversion concurrency control) described as keeping several versions of a row. It covers snapshot isolation, the model behind REPEATABLE READ in PostgreSQL and MySQL. It also covers what the model guarantees, how it handles two transactions writing the same row, and where engines differ in practice. Write skew gets its own chapter, so it appears here only as a boundary.
The idea: a frozen view of the database
Under snapshot isolation, a transaction reads from a snapshot. The snapshot is a consistent picture of the database as it stood at one moment. Everything committed before that moment is visible. Everything committed afterward is invisible, even if it happens while your transaction is still running. The transaction also sees its own writes.
Each row version carries bookkeeping about which transaction created it and which one deleted or replaced it. The engine compares that bookkeeping with the snapshot to decide which version you see. No read locks are needed, so two properties follow:
- Readers never block writers.
- Writers never block readers.
A long report can therefore run next to a busy write workload without slowing it down.
When the snapshot is taken
The snapshot is not necessarily taken at BEGIN.
- PostgreSQL takes it at the first statement that reads or writes data in the transaction. Time between
BEGINand that first statement does not count. - MySQL InnoDB takes it at the first consistent read, which is the first plain
SELECT.START TRANSACTION WITH CONSISTENT SNAPSHOTtakes it immediately.
This matters when you reason about a schedule. If Session B commits after Session A's BEGIN but before A's first query, A sees B's change.
Worked example: no non-repeatable reads, no phantoms
The following PostgreSQL script uses two sessions. Run the statements in the order of the comments.
-- Setup
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 100), (2, 200);
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- 100
SELECT count(*) FROM accounts; -- 2
-- Session B (autocommit, each statement commits at once)
UPDATE accounts SET balance = 50 WHERE id = 1;
INSERT INTO accounts VALUES (3, 300);
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- still 100
SELECT count(*) FROM accounts; -- still 2
COMMIT;
-- Session A, new transaction
SELECT balance FROM accounts WHERE id = 1; -- 50
SELECT count(*) FROM accounts; -- 3The second read of row 1 returns the same value, so there is no non-repeatable read. The second count does not include the new row, so there is no phantom read. The SQL standard permits phantoms at REPEATABLE READ, but a snapshot cannot show them, because rows inserted after the snapshot are invisible. PostgreSQL's REPEATABLE READ is therefore stronger than the standard requires.
Two writers on the same row: first updater wins
A snapshot protects what you read. It does not make a stale read safe to write from. If you read a row, someone else changes and commits it, and then you try to update it, your snapshot no longer matches reality. Snapshot isolation handles this by forbidding two concurrent transactions from both modifying the same row. The first one to write wins, and the other must not overwrite it.
PostgreSQL enforces this with an error:
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- 100
-- Session B
UPDATE accounts SET balance = balance + 20 WHERE id = 1; -- commits: 120
-- Session A
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- ERROR: could not serialize access due to concurrent update
ROLLBACK;Session A's snapshot says the balance is 100, but the newest committed version is 120. Applying A's change to the old version would discard B's deposit, which is a lost update. PostgreSQL aborts A with SQLSTATE 40001 instead. Your application must catch this error and rerun the whole transaction, which then takes a fresh snapshot.
Timing changes the behavior. If B has updated the row but not yet committed, A's UPDATE waits on B's row lock. When B commits, A fails with the error above. When B rolls back, A proceeds normally. The rule is first updater wins in PostgreSQL. SQL Server's SNAPSHOT level and Oracle's SERIALIZABLE level apply a similar rule. The literature calls it first-committer-wins.
Snapshot isolation therefore prevents lost updates by aborting one of the transactions. The cost is that the application must retry. See the chapter on serialization failures for retry patterns.
Repeatable read is not the same everywhere
The name REPEATABLE READ covers different behavior in different engines.
| Engine | What REPEATABLE READ does | Concurrent update of the same row |
|---|---|---|
| PostgreSQL | Pure snapshot isolation. Phantoms are not visible. | Second writer fails with `40001`. |
| MySQL InnoDB (default level) | Snapshot for plain `SELECT`. Locking statements read the latest data. | Second writer waits, then proceeds on the latest version. No error. |
| SQL Server | No snapshot. REPEATABLE READ uses shared locks held until commit. A separate SNAPSHOT level gives snapshot isolation. | SNAPSHOT: update conflict error 3960. |
| Oracle | No REPEATABLE READ level. SERIALIZABLE is snapshot isolation. | Second writer fails with `ORA-08177`. |
MySQL is the case that most often surprises people. UPDATE, DELETE, SELECT ... FOR UPDATE and SELECT ... FOR SHARE perform current reads. A current read ignores your snapshot and works on the newest committed row. This is the same schedule as above, but with the application doing the arithmetic:
-- MySQL, default REPEATABLE READ
-- Session A
START TRANSACTION;
SELECT balance FROM accounts WHERE id = 1; -- 100 (snapshot read)
-- Session B
UPDATE accounts SET balance = 120 WHERE id = 1; -- autocommit
-- Session A: application computed 100 + 10 from its stale read
UPDATE accounts SET balance = 110 WHERE id = 1; -- succeeds, no error
COMMIT;
-- Final balance is 110. B's deposit is lost.In InnoDB, REPEATABLE READ does not stop this lost update. The fixes are the same as at READ COMMITTED: write SET balance = balance + 10, or read with SELECT ... FOR UPDATE so that you read the latest value and hold the lock.
A second InnoDB oddity follows from the same rule. If your transaction updates a row that another transaction changed after your snapshot, you then see your own updated version of that row. Other rows still appear as of the snapshot, so your view can mix two points in time.
SQL Server needs one extra setup step before SNAPSHOT is available:
ALTER DATABASE shop SET ALLOW_SNAPSHOT_ISOLATION ON;
SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
BEGIN TRANSACTION;
SELECT balance FROM accounts WHERE id = 1;
COMMIT;What snapshot isolation still allows
Snapshot isolation blocks dirty reads, non-repeatable reads, phantoms (in PostgreSQL) and lost updates (in engines that detect write conflicts). It is not the same as serializable execution. The conflict check looks only at two transactions writing the same row. If two transactions each read a set of rows and then write different rows based on what they read, no write-write conflict occurs and both commit. This anomaly is write skew, covered in the next chapter. PostgreSQL's SERIALIZABLE level adds detection for this pattern on top of snapshots.
Costs to plan for
- Retries. Code that runs at REPEATABLE READ in PostgreSQL, SQL Server SNAPSHOT or Oracle SERIALIZABLE needs a retry loop around the whole transaction.
- Old versions pile up. The engine cannot remove row versions that an open snapshot may still need. A transaction left open for hours causes table bloat in PostgreSQL and a growing undo history in InnoDB. Keep snapshot transactions short, and watch for sessions stuck in "idle in transaction".
- Stale data by design. A snapshot transaction can act on information that is already out of date. This is acceptable for reports. For decisions based on current state, use locking reads or a stricter level.
Exercise
In PostgreSQL, Session A starts BEGIN ISOLATION LEVEL REPEATABLE READ and runs SELECT count(*) FROM orders, which returns 10. Session B inserts a new order and commits. Session A runs the same count again. What does it return, and which anomaly would the standard allow at this level that does not occur here?
Show answer
It returns 10. The standard permits phantom reads at REPEATABLE READ, but PostgreSQL's snapshot never includes rows committed after it was taken, so the phantom does not occur.
Exercise
The same schedule runs on PostgreSQL and on MySQL InnoDB, both at REPEATABLE READ. Session A reads balance 100. Session B sets it to 120 and commits. Session A then runs UPDATE accounts SET balance = balance + 10 WHERE id = 1. What happens on each engine, and what must the application do on PostgreSQL?
Show answer
PostgreSQL aborts Session A with "could not serialize access due to concurrent update" (SQLSTATE 40001). The application must roll back and retry the whole transaction. MySQL performs a current read, so the update succeeds and the balance becomes 130, with no error and no lost deposit. The atomic expression is what keeps it safe. If the application had written a value it computed from its snapshot read, the deposit would have been lost.