Skip to content
Visual explainer 3h to learn 4 steps

MVCC & isolation levels

Explain read committed, repeatable read and serializable and the anomalies each prevents.

By Invicly Tech, , in SQL & PostgreSQL. About 12 minutes to read.

Topic 22 of 30

In short

MVCC lets readers and writers work at the same time: every transaction sees a snapshot, and updates create new row versions instead of overwriting. Isolation levels decide how fresh that snapshot is and which anomalies can occur.

Explained simply

A busy database runs many transactions at the same time. Isolation decides what each one can see of the others while they are still running. Too little isolation and you read numbers that are changing under your feet. Too much and transactions get in each other's way.

Postgres solves most of this with MVCC (multi-version concurrency control). When a row is updated, Postgres does not overwrite it. It writes a new version and keeps the old one for a while. Each transaction looks at a snapshot: a picture of which versions were committed when it started looking.

Because readers look at old versions and writers create new ones, readers never wait for writers and writers never wait for readers. That is why Postgres stays fast under mixed reading and writing.

Isolation levels set how long a snapshot lasts. Read Committed (the default) takes a new snapshot for each statement. Repeatable Read keeps one snapshot for the whole transaction. Serializable adds checks so the result is as if transactions ran one after another.

Press Play on a diagram to walk through it one step at a time.

SequenceRead Committed: a non-repeatable read
Session A
Postgres
Session B
  1. 1BEGIN; SELECT stock → 10
    Session A to Postgres: BEGIN; SELECT stock → 10
  2. 2UPDATE stock = 4; COMMIT
    Session B to Postgres: UPDATE stock = 4; COMMIT
  3. 3SELECT stock again
    Session A to Postgres: SELECT stock again
  4. 44 (new snapshot per statement)
    Postgres to Session A: 4 (new snapshot per statement)
  5. 5Under Repeatable Read: still 10
    Session A to Postgres: Under Repeatable Read: still 10
ComparePostgres isolation levels
Read Committed (default)
  • New snapshot per statement
  • No dirty reads
  • Values can change mid-transaction
Repeatable Read
  • One snapshot per transaction
  • Stable reads, no phantoms
  • Conflicting update: error, retry
Serializable
  • As if run one at a time
  • Prevents write skew
  • Must retry on serialization failure
SequenceWrite skew: two doctors leave on-call at once
Session A (Alice)
Postgres
Session B (Bob)
  1. 1count on-call doctors: 2
    Session A (Alice) to Postgres: count on-call doctors: 2
  2. 2count on-call doctors: 2
    Session B (Bob) to Postgres: count on-call doctors: 2
  3. 3UPDATE Alice off-call; COMMIT
    Session A (Alice) to Postgres: UPDATE Alice off-call; COMMIT
  4. 4UPDATE Bob off-call; COMMIT
    Session B (Bob) to Postgres: UPDATE Bob off-call; COMMIT
  5. 5Repeatable Read: ok, now 0 on call
    Postgres to Session B (Bob): Repeatable Read: ok, now 0 on call
  6. 6Serializable: ERROR 40001, retry
    Postgres to Session B (Bob): Serializable: ERROR 40001, retry

In depth

MVCC under the hood: xmin, xmax and snapshots

Every transaction that writes gets a transaction ID (XID). Every row version stores two hidden columns: xmin, the XID that created it, and xmax, the XID that deleted or replaced it (0 if still current). An UPDATE is really "mark the old version with xmax, insert a new version with xmin". You can see them yourself: SELECT xmin, xmax, * FROM accounts.

A snapshot records which XIDs had committed at the moment it was taken. A row version is visible to you if its xmin committed before your snapshot, and its xmax is either empty or not yet committed in your snapshot. pg_current_snapshot() shows the current one.

The cost: old versions pile up as dead rows. They stay until no running snapshot could still need them, and then VACUUM removes them. That is why a single transaction left open for hours causes table bloat everywhere.

SequenceTwo row versions, two different readers
Txn 100 (writer)
Table
Txn 101 (reader)
  1. 1Snapshot taken: 100 still running
    Txn 101 (reader) to Table: Snapshot taken: 100 still running
  2. 2UPDATE: old row xmax=100
    Txn 100 (writer) to Table: UPDATE: old row xmax=100
  3. 3New row xmin=100
    Txn 100 (writer) to Table: New row xmin=100
  4. 4COMMIT
    Txn 100 (writer) to Table: COMMIT
  5. 5SELECT in same snapshot
    Txn 101 (reader) to Table: SELECT in same snapshot
  6. 6Old version: 100 was not committed in my snapshot
    Table to Txn 101 (reader): Old version: 100 was not committed in my snapshot

The anomalies, and which level stops which

The SQL standard describes problems that concurrency can cause. A dirty read sees another transaction's uncommitted data; Postgres never allows this, and even READ UNCOMMITTED behaves as Read Committed. A non-repeatable read reads the same row twice and gets different values. A phantom read runs the same query twice and gets new rows. A lost update is two read-then-write transactions where one write overwrites the other. Write skew is two transactions that each read overlapping data, make decisions, and write different rows, together breaking a rule neither broke alone.

In Postgres, Read Committed stops dirty reads only. Repeatable Read is implemented as snapshot isolation, which is stronger than the standard asks: it also stops non-repeatable reads and phantoms, and detects lost updates by failing with a serialization error. Only Serializable also stops write skew.

CompareWhat each Postgres level allows
Read Committed
  • Dirty read: never
  • Non-repeatable read: possible
  • Phantom: possible
  • Write skew: possible
Repeatable Read
  • Non-repeatable read: no
  • Phantom: no (in Postgres)
  • Lost update: error 40001
  • Write skew: possible
Serializable
  • All of Repeatable Read
  • Write skew: error 40001
  • Result equals some serial order
  • Needs retry logic

How Read Committed handles concurrent UPDATEs

Read Committed is not as weak as it sounds for simple writes. When your UPDATE finds a row that another transaction is changing, it waits. If the other one commits, Postgres re-reads the newest version of that row, checks your WHERE again, and applies your change to that version. So UPDATE accounts SET balance = balance - 30 WHERE id = 1 is safe: two of these in parallel subtract 60 in total.

The danger is the read-modify-write pattern done in application code: SELECT the balance, compute a new number in the app, then UPDATE SET balance = 70. The second writer's computed value is based on an old read, so one change is lost. Fix it by doing the math in SQL, by locking with SELECT ... FOR UPDATE, or by using Repeatable Read, which raises an error instead of losing data.

Also note that in Read Committed two SELECTs in one report can see different data, so totals may not add up. Run reports in Repeatable Read.

  • UPDATE ... SET x = x - 1 is safe under Read Committed
  • SELECT, compute in app, UPDATE is not
  • Reports that need consistent totals: Repeatable Read

Serializable and retries

Postgres implements Serializable with Serializable Snapshot Isolation (SSI). Transactions still run in parallel with snapshots, but Postgres tracks what each one read (shown as SIReadLock entries in pg_locks) and what it wrote. If it finds a pattern of read and write dependencies that could not happen in any one-at-a-time order, it aborts one transaction with SQLSTATE 40001, serialization_failure.

That means your application must retry: catch 40001, roll back, and run the whole transaction again, including the reads, a few times with a short random backoff. Treat 40P01 (deadlock detected) the same way. Retry logic belongs in one helper so every transaction uses it.

Tips: keep serializable transactions short; declare read-only ones with READ ONLY, which helps SSI; and for a long report use SERIALIZABLE READ ONLY DEFERRABLE, which waits for a safe snapshot and then can never fail. You can also set default_transaction_isolation for a role or database.

  • Retry on SQLSTATE 40001 and 40P01
  • Retry the whole transaction, not just the last statement
  • BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE for long reports

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Explain how MVCC works~45m
  2. 2
    Compare read committed and repeatable read~45m
  3. 3
    Use serializable and handle retries~45m
  4. 4
    Reproduce an anomaly in two sessions~45m

Key points

  • Readers never block writers and writers never block readers under MVCC.
  • Postgres never shows uncommitted data, at any isolation level.
  • Repeatable Read and Serializable can fail with error 40001; the app must retry.
  • Set the level per transaction: BEGIN ISOLATION LEVEL SERIALIZABLE.

Key terms

Tap a card to flip it. 0/6 known

Examples

sql
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT stock FROM products WHERE id = 1;  -- 10

-- Session B (meanwhile)
UPDATE products SET stock = 4 WHERE id = 1;  -- autocommits

-- Session A
SELECT stock FROM products WHERE id = 1;  -- still 10 (same snapshot)
UPDATE products SET stock = stock - 1 WHERE id = 1;
-- ERROR: could not serialize access due to concurrent update
ROLLBACK;  -- then retry the whole transaction

Reproducing write skew in two psql windows

Rule: at least one doctor must stay on call. Step 1: create the table with two doctors on call. Step 2: in both sessions, begin a Repeatable Read transaction and count on-call doctors; both see 2. Step 3: each session takes itself off call and commits. Both succeed and nobody is on call: write skew. Step 4: repeat with SERIALIZABLE; the second COMMIT (or update) fails with 40001, and the retry sees only 1 doctor and refuses.

sql
CREATE TABLE doctors (name text PRIMARY KEY, on_call boolean NOT NULL);
INSERT INTO doctors VALUES ('alice', true), ('bob', true);

-- Session A                          -- Session B
BEGIN ISOLATION LEVEL SERIALIZABLE;   -- BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM doctors          -- SELECT count(*) FROM doctors
  WHERE on_call;          -- 2        --   WHERE on_call;          -- 2
UPDATE doctors SET on_call = false    -- UPDATE doctors SET on_call = false
  WHERE name = 'alice';               --   WHERE name = 'bob';
COMMIT;  -- ok                        -- COMMIT;
                                      -- ERROR: could not serialize access
                                      -- due to read/write dependencies ...

A retry helper for serializable transactions

Any serializable transaction may fail and must be retried from the start. Step 1: wrap the work in a function that receives the connection. Step 2: run it inside a transaction whose first statement sets the isolation level. Step 3: on SerializationFailure or DeadlockDetected, wait a short random time and try again. Step 4: give up after a few attempts so a real bug does not loop forever.

python
import random, time
from psycopg import errors

def run_serializable(conn, work, attempts=5):
    for attempt in range(attempts):
        try:
            with conn.transaction():
                conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
                return work(conn)
        except (errors.SerializationFailure, errors.DeadlockDetected):
            time.sleep(random.uniform(0, 0.05 * 2 ** attempt))
    raise RuntimeError("transaction failed after retries")

Quick reference

  • BEGIN ISOLATION LEVEL REPEATABLE READ; or SERIALIZABLE
  • SHOW transaction_isolation; current level (default: read committed)
  • SELECT xmin, xmax, * FROM t; see the MVCC version columns
  • SQLSTATE 40001 = serialization failure; 40P01 = deadlock: retry the whole transaction
  • Postgres never shows uncommitted data, even at READ UNCOMMITTED
  • BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE; long reports that never fail
  • ALTER ROLE app SET default_transaction_isolation = 'serializable';

Common mistakes

  • Using Serializable without retry logic in the application.
  • Assuming Read Committed values stay the same during a transaction.
  • Holding long transactions that keep old row versions alive.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Under Read Committed, two sessions run UPDATE stock SET qty = qty - 1 WHERE id = 5 at the same time. What happens?

Question 2

2Which anomaly can still happen under Repeatable Read in PostgreSQL?

Question 3

3What does the hidden column xmax on a row version hold?

Question 4

4A serializable transaction fails with SQLSTATE 40001. What should the app do?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Show that an UPDATE creates a new row version by comparing the hidden ctid and xmin columns before and after.

  2. Exercise 2medium

    In two psql sessions, show a non-repeatable read under Read Committed, then show that Repeatable Read prevents it.

  3. Exercise 3hard

    Under Repeatable Read, make a lost update attempt fail: both sessions read balance 100, then both run UPDATE ... SET balance = 70 and 50. Describe what each session sees.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I just use Serializable everywhere?
It is the safest level, but every transaction then needs retry logic and there is some overhead. Many teams use Read Committed with careful locking, and Serializable for the few flows with tricky invariants.
What is the difference between Repeatable Read and Serializable in Postgres?
Both use one snapshot per transaction. Serializable also tracks read and write dependencies and aborts transactions that would cause anomalies like write skew.
Does MVCC mean Postgres never locks?
No. Reads do not block writes, but two writers on the same row still wait for each other, and DDL takes table locks.

Go deeper

ShareXLinkedInWhatsApp