Skip to content

Transactions and what isolation levels stop

Deep diveConcept

Two requests run at the same time, both succeed, and the data ends up wrong. Isolation levels decide which of these accidents Postgres stops for you. Here are the four you will meet, drawn on two sessions, and the level that stops each one.

01 What a transaction promises

A transaction groups statements so that they all happen or none do. If a transfer debits one account and the app crashes before it credits the other, ROLLBACK (or the crash) undoes the debit. That part, atomicity, is the same at every level.

Isolation is about something else: what one transaction sees of another that is running at the same time. Perfect isolation would mean every transaction behaves as if it ran alone, one after another. That costs waiting or retries, so SQL defines weaker levels that allow some accidents, called anomalies, in return for less of both.

SQL
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- statements
COMMIT;
-- or, as the first statement inside BEGIN:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

02 Snapshots: how Postgres isolates

Postgres does not make readers wait for writers. An UPDATE writes a new version of the row and leaves the old one in place; each transaction reads using a snapshot, a note of which transactions had committed when it was taken. A version is visible to you only if the transaction that wrote it had committed by then. This is MVCC, multi-version concurrency control.

The levels differ in when the snapshot is taken, and in what extra checks run when you write.

The levels in Postgres 16
LevelSnapshotExtra on write
Read Uncommittedbehaves exactly as Read Committednone
Read Committed (default)a new one for every statementwaits for a row another transaction is changing, then uses the newest committed version
Repeatable Readone for the whole transactionfails if a row it changes was changed by someone else after its snapshot
Serializableone for the whole transactionalso tracks what it read, and fails when the reads and writes of concurrent transactions could not happen in any one-at-a-time order

03 Dirty and non-repeatable reads

A dirty read is seeing another transaction’s change before it commits. If that transaction rolls back, you acted on data that never existed. Postgres never allows it: a snapshot only includes committed work. You can ask for READ UNCOMMITTED, and SHOW transaction_isolation will say so, but you get Read Committed behaviour.

A non-repeatable read is reading the same row twice in one transaction and getting two answers, because someone committed in between. At Read Committed every statement takes a fresh snapshot, so it happens. Here, a second session sets the balance to 50 while the first one is between its two reads:

READ COMMITTED
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- 100
-- another session commits balance = 50
SELECT balance FROM accounts WHERE id = 1; -- 50
COMMIT;
REPEATABLE READ
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- 100
-- another session commits balance = 50
SELECT balance FROM accounts WHERE id = 1; -- 100
COMMIT;

At Repeatable Read the snapshot is fixed at the first statement, so the transaction keeps seeing 100. The same rule stops phantom reads, where a repeated WHERE query finds new rows. The SQL standard allows phantoms at this level; Postgres does not. Both listings are real runs on Postgres 16, with the output folded into comments.

04 Lost updates: read, then write back

The bug that costs money is the read-modify-write. The app reads a value, changes it in code, and writes the result. Two of those running at once can both start from the same value.

Lost update at READ COMMITTED
Step 1 of 7
Row: account 1, committed balance
100
Session A · balance it read
–
Session B · balance it read
–
Statements, in order
Empty
  • value read
  • written, not committed
  • just happened
  • final, wrong
  • nothing read yet

Account 1 holds 100. Two requests each withdraw 30, at the same moment, in two sessions at READ COMMITTED, the Postgres default. Each one reads the balance, subtracts in the app, and writes the result back.

40 expected end

Repeatable Read stops it. When B tries to update a row that changed after B’s snapshot was taken, Postgres refuses instead of overwriting. This is the same two sessions, run for real:

Text
-- session B, REPEATABLE READ, after A has committed 70
UPDATE accounts SET balance = 70 WHERE id = 1;
ERROR: could not serialize access due to concurrent update
COMMIT;
ROLLBACK

The balance stays at A’s 70, and B’s app must start again, read 70 and write 40. At Read Committed you have two other fixes that need no retry:

Let SQL do the sum
UPDATE accounts
SET balance = balance - 30
WHERE id = 1;
Lock while you decide
BEGIN;
SELECT balance FROM accounts
WHERE id = 1 FOR UPDATE;
-- app checks and computes
UPDATE accounts SET balance = 70
WHERE id = 1;
COMMIT;

On the left, B’s UPDATE waits for A’s lock, then re-reads the newest committed row and subtracts from 70: the real run ended at 40. On the right, FOR UPDATE takes the row lock at read time, so B’s SELECT waits until A commits and then reads 70.

05 Write skew: two right answers, one wrong result

Repeatable Read catches two transactions writing the same row. Write skew is when each reads something, decides, and writes a different row, and the decision each made is no longer true once both commit. A hotel double booking is the classic shape.

Write skew at REPEATABLE READ
Step 1 of 7
bookings: room 7, 24 Dec (committed)
Empty
Session A · its snapshot counts
–
Session B · its snapshot counts
–
Statements, in order
Empty
  • just happened
  • inserted, not committed
  • nothing read yet

Room 7 is free on 24 December. Ana and Ben try to book it at the same time. Each session runs at REPEATABLE READ, checks that the room is free, then inserts a booking.

Repeatable Read gives you nothing here: no row was written twice, so its write check never fires. Locking with FOR UPDATE does not help either, because the row that would prove the room is taken does not exist yet. There is nothing to lock.

06 Serializable stops it, and fails one side

At Serializable, Postgres also records what each transaction read: here, “bookings for room 7 that night”. When a concurrent transaction writes into a range another one read, it notes a dependency. If the dependencies form a pattern that no one-at-a-time order could produce, one transaction is cancelled. The same two sessions, run at Serializable:

Text
-- session B, SERIALIZABLE, after A has committed Ana
COMMIT;
ERROR: could not serialize access due to read/write dependencies
among transactions
DETAIL: Reason code: Canceled on identification as a pivot,
during commit attempt.
HINT: The transaction might succeed if retried.

Only Ana’s booking is stored. Serializable did not make anyone wait; it let both run and refused the one that would break the illusion of running alone. That makes retrying part of the deal. Both errors on this page share SQLSTATE 40001, so one handler covers them:

book.py
import sys, threading, time
import psycopg
from psycopg import errors
DSN = "postgresql://postgres:x@localhost:54329/postgres"
def book(room, night, guest, pause=0.0):
with psycopg.connect(DSN) as conn:
conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
for attempt in range(1, 4):
try:
with conn.transaction():
taken = conn.execute(
"SELECT count(*) FROM bookings WHERE room = %s AND night = %s",
(room, night),
).fetchone()[0]
Text
$ python3 book.py
Ana: serialization failure, retrying
Ana: room 7 is taken
Ben: booked on attempt 1

That is a real run against Postgres 16 with psycopg 3. The 0.5 second pause makes the race certain; which guest wins varies between runs. On the retry the losing side gets a new snapshot, sees the booking, and gives the right answer.

Which level stops which anomaly in Postgres
AnomalyRead CommittedRepeatable ReadSerializable
Dirty readstoppedstoppedstopped
Non-repeatable readhappensstoppedstopped
Phantom readhappensstoppedstopped
Lost update (read, then write)happensstopped: errorstopped: error
Write skewhappenshappensstopped: error

07 When it bites

Raising the isolation level without a retry loop turns silent data bugs into errors your users see. Code that runs at Repeatable Read or Serializable must catch SQLSTATE 40001 and run the whole transaction again, reads included.

BEGIN ISOLATION LEVEL SERIALIZABLE; -- in one service onlyMixing levelsSerializable only guarantees anything among transactions that all run at Serializable. A Read Committed writer elsewhere can still cause the anomaly. Set default_transaction_isolation for the database if you rely on it.
SELECT ... FOR UPDATE -- on rows that do not existLocking the absence of a rowFOR UPDATE locks rows it finds. A check for “no booking yet” finds none, so it locks nothing. Use a unique constraint on (room, night), an exclusion constraint for date ranges, or Serializable.
retry: only the failed UPDATERetrying half a transactionAfter a 40001 the transaction is aborted. Retrying just the last statement reuses values read from the old snapshot. Retry from BEGIN.
BEGIN; ... a slow API call ... COMMIT;Long transactionsA long transaction keeps its locks and its old snapshot, so others wait, more of them fail and must retry, and VACUUM cannot clean row versions it might still see. Keep network calls out of transactions.
Repeatable Read in MySQLSame name, other rulesLevel names come from the SQL standard, but behaviour is per database. MySQL InnoDB at Repeatable Read does not raise an error on the lost-update pattern; its plain UPDATE uses the latest committed row. Check the documentation of the database you run.

08 Check yourself

Question

At Read Committed, two sessions each run UPDATE stock SET qty = qty - 1 WHERE id = 5 at the same moment, starting from 10. What is qty after both commit?

Question

Two doctors are on call. Each transaction checks that at least two are on call, then takes itself off. Which level is the lowest that stops both leaving?

Question

Your code runs at Repeatable Read and gets could not serialize access due to concurrent update. What should it do?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?