Sub topic 8
Isolation levels and what each one prevents
This chapter assumes you know basic SQL, the meaning of BEGIN, COMMIT and ROLLBACK, and the concurrency anomalies from the previous chapter: dirty reads, non-repeatable reads, phantom reads, lost updates and write skew. The examples use PostgreSQL syntax. Where other databases behave differently, the text says so.
Why isolation comes in levels
Perfect isolation makes concurrent transactions behave as if they ran one at a time. That guarantee costs throughput, because the database must either block transactions or abort some of them. Isolation levels let you pick how much protection you want and how much you pay for it.
The SQL standard defines four levels by the anomalies each one allows. From weakest to strongest they are READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ and SERIALIZABLE. Each real database implements these names in its own way, so the name alone does not tell you what you get.
The standard's table
The standard describes the levels in terms of three anomalies.
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | Prevented | Possible | Possible |
| REPEATABLE READ | Prevented | Prevented | Possible |
| SERIALIZABLE | Prevented | Prevented | Prevented |
This table is a minimum. A database may prevent more than the standard requires, and most do. It also leaves out lost updates and write skew, which is why the standard's wording is a poor guide for real systems.
What PostgreSQL actually does
PostgreSQL uses multiversion concurrency control (MVCC), so each statement or transaction reads from a snapshot of committed data. That changes the picture.
| Level | Dirty read | Non-repeatable read | Phantom read | Lost update | Write skew |
|---|---|---|---|---|---|
| READ UNCOMMITTED | Prevented (behaves as READ COMMITTED) | Possible | Possible | Possible | Possible |
| READ COMMITTED (default) | Prevented | Possible | Possible | Possible | Possible |
| REPEATABLE READ | Prevented | Prevented | Prevented | Prevented (by error) | Possible |
| SERIALIZABLE | Prevented | Prevented | Prevented | Prevented | Prevented |
Two points stand out. PostgreSQL never allows dirty reads, so READ UNCOMMITTED is just an alias for READ COMMITTED. And PostgreSQL's REPEATABLE READ is snapshot isolation, which also blocks phantoms but still allows write skew.
Setting the level
You choose the level per transaction. It must be set before the first query of the transaction runs.
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- queries here
COMMIT;You can also use SET TRANSACTION ISOLATION LEVEL ... as the first statement after BEGIN. To change the default for a session, use SET default_transaction_isolation = 'repeatable read';.
READ COMMITTED
Each statement sees a snapshot of the data that was committed when that statement began. Two statements in the same transaction can therefore see different data.
-- Session A -- Session B
BEGIN; BEGIN;
SELECT balance FROM accounts WHERE id = 1;
-- returns 70.00
UPDATE accounts SET balance = 0 WHERE id = 1;
COMMIT;
SELECT balance FROM accounts WHERE id = 1;
-- READ COMMITTED: returns 0.00 (non-repeatable read)
-- REPEATABLE READ: still returns 70.00
COMMIT;This is fine for many workloads, such as single-statement updates like UPDATE accounts SET balance = balance - 30 WHERE id = 1. The database applies the change to the latest committed row, so that statement does not lose updates.
The danger appears when the application reads a value, computes a new one, and writes it back. Another transaction can change the row between your read and your write, and your write then overwrites its change. That is a lost update, and READ COMMITTED does not stop it.
REPEATABLE READ
The transaction takes one snapshot at its first query and uses it for every later statement. Repeated reads return the same rows and values, and no phantoms appear.
What happens when two transactions try to change the same row? The second one to write waits for the first to finish. If the first commits, the second fails with an error instead of overwriting.
ERROR: could not serialize access due to concurrent update
SQLSTATE: 40001The application must catch this error and retry the whole transaction. This is how PostgreSQL prevents lost updates at this level.
REPEATABLE READ still allows write skew. Two transactions read overlapping data, each updates a different row based on what it read, and both commit. Neither wrote the row the other one changed, so there is no write conflict to detect.
MySQL's InnoDB uses the same name for a different behavior. It is the default level there, it uses a snapshot for plain reads, and it uses locks for FOR UPDATE and for writes, which can read newer data than the snapshot shows. Check your database's manual before relying on a level's name.
SERIALIZABLE
At this level the database guarantees that the result of concurrent transactions equals the result of some serial order. PostgreSQL implements this with Serializable Snapshot Isolation (SSI). It runs on top of snapshots and tracks read-write dependencies between transactions. When it finds a pattern that could produce a non-serializable result, it aborts one transaction.
The doctors on call example shows this.
CREATE TABLE doctors (id integer PRIMARY KEY, on_call boolean NOT NULL);
INSERT INTO doctors VALUES (1, true), (2, true);
-- Session A (same steps in Session B, but with id = 2)
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM doctors WHERE on_call; -- 2, so it looks safe to leave
UPDATE doctors SET on_call = false WHERE id = 1;
COMMIT;
-- Under REPEATABLE READ in PostgreSQL both sessions can commit, leaving nobody on call (write skew).
-- Under SERIALIZABLE, one of them fails with SQLSTATE 40001 (serialization_failure) and must be retried.The failure can appear at the UPDATE or at COMMIT. Your code must handle it at either point. SSI can also abort transactions that would not actually have caused an anomaly (false positives), so a serializable workload needs retry logic by design.
Some databases implement SERIALIZABLE with locks instead. They block transactions rather than abort them, which trades retries for waiting and raises the risk of deadlocks.
How the levels differ in mechanism
Choosing a level
Use these criteria in order.
- Start with the anomalies your code can actually trigger. A transaction that runs one statement needs nothing beyond READ COMMITTED.
- If a transaction reads data and then writes based on what it read, decide how to protect that pattern. You can lock the rows with
SELECT ... FOR UPDATE, which works at any level, or raise the isolation level. - If the correctness rule spans several rows, such as "at least one doctor on call", use SERIALIZABLE, or lock a row that all competing transactions must touch.
- If you use REPEATABLE READ or SERIALIZABLE, add retry logic for SQLSTATE 40001 before you ship.
Higher levels cost more in three ways: more aborted transactions, more memory for tracking, and long transactions that hold old snapshots and delay cleanup of dead row versions. Run long reports at REPEATABLE READ for a consistent view, but keep write transactions short.
Common errors
- Reading a value, computing in application code, and writing it back at READ COMMITTED, which loses updates.
- Setting the isolation level after the first query, which PostgreSQL rejects with an error.
- Catching a serialization failure but retrying only the last statement. You must rerun the entire transaction, because its snapshot and earlier reads are no longer valid.
- Treating SERIALIZABLE as free. It needs retries, and under load it aborts more transactions than lower levels.
Exercise
Two sessions run at REPEATABLE READ in PostgreSQL. Each reads the count of on-call doctors, sees 2, and sets a different doctor's on_call to false. Both commit without error. Which anomaly occurred, why did PostgreSQL not detect it, and what is the smallest change that prevents it?
Show answer
Write skew occurred. The two transactions updated different rows, so no row was written by both and REPEATABLE READ found no write conflict. Running both transactions at SERIALIZABLE prevents it, because the database tracks the read-write dependency and aborts one transaction with SQLSTATE 40001. The application must then retry that transaction.
Exercise
A transaction at READ COMMITTED runs SELECT balance FROM accounts WHERE id = 1; twice and gets different results. Name the anomaly and give two ways to make the two reads agree.
Show answer
This is a non-repeatable read. Run the transaction at REPEATABLE READ (or SERIALIZABLE) so both reads use one snapshot. Alternatively, read the row once and keep the value in the application, or lock the row with SELECT ... FOR UPDATE so that no other transaction can change it between the reads.