Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

Lab: Two Sessions, Four Anomalies

Drive two PostgreSQL sessions by hand and reproduce the dirty read that cannot happen, the non-repeatable read, the phantom, the write skew and the lost update — then find the isolation level that stops each.

Contentsand lesson path

What you will learn

  • Reproduce non-repeatable reads, phantoms, lost updates and write skew, and state which PostgreSQL isolation level prevents each one.

Prerequisites: SQL Fundamentals

01. Goal and setup

The SQL standard names the ways concurrent transactions can surprise each other: dirty reads, non-repeatable reads, phantom reads — and practice adds two more, lost updates and write skew. You have learned why MVCC gives every transaction a snapshot; now you will feel where each snapshot ends. The lab runs two connections, A and B, and interleaves their statements by hand, so every anomaly appears on purpose, not by luck.

Why interleave by hand instead of hammering the server with threads? Because an anomaly you can reproduce on demand is an anomaly you understand: every demo below is a deterministic script you can rerun, edit and break. A stress test tells you something went wrong once, on a Tuesday; a two-session script tells you exactly which snapshot ended where — and the same skill of stepping through schedules is how you review a colleague's concurrent code.

You need: Docker, Python 3.12 and uv. Versions in this run: Python 3.12.13, psycopg 3.3.9, PostgreSQL 17.12. Use a throwaway database on its own port and delete it afterwards:

Terminal · scratch folder for the whole skill
mkdir txlab && cd txlab
docker run -d --name ti-pg -e POSTGRES_USER=lab -e POSTGRES_PASSWORD=lab \
  -e POSTGRES_DB=tilab -p 55436:5432 postgres:17-alpine

uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "psycopg[binary]==3.3.9"
Project layout
txlab/
└── anomalies.py   two connections, one demo per anomaly

Here is the whole script. Each demo first recreates two small tables, accounts and doctors, so every step starts from the same rows. A and B run in one Python thread, and the order of the lines is the interleaving: the script never relies on timing, so the output is the same on every run and every machine. Run one demo per step with python anomalies.py <demo>.

Python · anomalies.py
"""Two sessions, A and B, interleaved by hand: one demo per anomaly."""
import sys

import psycopg

DSN = "postgresql://lab:lab@localhost:55436/tilab"
COUNT_LOW = "SELECT count(*) FROM accounts WHERE balance < 1000"
COUNT_ON_CALL = "SELECT count(*) FROM doctors WHERE on_call"
SET_BALANCE = "UPDATE accounts SET balance = %s WHERE id = 1"


def connect() -> psycopg.Connection:
    # autocommit: the BEGIN each demo sends is the only BEGIN the server sees
    return psycopg.connect(DSN, autocommit=True)


def reset(conn: psycopg.Connection) -> None:
    """Fresh tables for every demo, so each one starts from the same state."""
    conn.execute("DROP TABLE IF EXISTS accounts, doctors")
    conn.execute("CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL)")
    conn.execute("INSERT INTO accounts VALUES (1, 100), (2, 50)")
    conn.execute("CREATE TABLE doctors (id int PRIMARY KEY, on_call bool NOT NULL)")
    conn.execute("INSERT INTO doctors VALUES (1, true), (2, true)")


def balance(conn: psycopg.Connection, account_id: int) -> int:
    sql = "SELECT balance FROM accounts WHERE id = %s"
    return conn.execute(sql, (account_id,)).fetchone()[0]


def on_call(conn: psycopg.Connection) -> int:
    return conn.execute(COUNT_ON_CALL).fetchone()[0]


def dirty(a, b) -> None:
    a.execute("BEGIN ISOLATION LEVEL READ COMMITTED")
    print("A> BEGIN ISOLATION LEVEL READ COMMITTED")
    b.execute("BEGIN")
    b.execute("UPDATE accounts SET balance = balance + 500 WHERE id = 1")
    print("B> BEGIN; UPDATE ... +500  (not committed)")
    print("A> SELECT balance ->", balance(a, 1), "(the uncommitted 600 is invisible)")
    b.rollback()
    print("B> ROLLBACK")
    print("A> SELECT balance ->", balance(a, 1))
    a.commit()


def nonrepeatable(a, b) -> None:
    runs = [("READ COMMITTED", "two reads disagree"),
            ("REPEATABLE READ", "snapshot from the first read holds")]
    for n, (level, verdict) in enumerate(runs):
        if n:
            print()
        a.execute(f"BEGIN ISOLATION LEVEL {level}")
        print(f"A> BEGIN ISOLATION LEVEL {level}")
        print("A> SELECT balance ->", balance(a, 1))
        b.execute("UPDATE accounts SET balance = balance + 40 WHERE id = 1")
        print("B> UPDATE ... +40; COMMIT")  # autocommit: the UPDATE commits at once
        print("A> SELECT balance ->", balance(a, 1), "->", verdict)
        a.commit()


def phantom(a, b) -> None:
    runs = [("READ COMMITTED", 3, "a phantom appeared"),
            ("REPEATABLE READ", 4, "same snapshot, no phantom")]
    for n, (level, new_id, verdict) in enumerate(runs):
        if n:
            print()
        a.execute(f"BEGIN ISOLATION LEVEL {level}")
        print(f"A> BEGIN ISOLATION LEVEL {level}")
        first = a.execute(COUNT_LOW).fetchone()[0]
        print("A> SELECT count(*) ... balance < 1000 ->", first)
        b.execute("INSERT INTO accounts VALUES (%s, 10)", (new_id,))
        print(f"B> INSERT account {new_id}; COMMIT")
        second = a.execute(COUNT_LOW).fetchone()[0]
        print("A> SELECT count(*) ... ->", second, "->", verdict)
        a.commit()


def skew(a, b) -> None:
    for level in ("REPEATABLE READ", "SERIALIZABLE"):
        a.execute("UPDATE doctors SET on_call = true")  # both on call again
        print(f"-- both sessions at {level}")
        a.execute(f"BEGIN ISOLATION LEVEL {level}")
        b.execute(f"BEGIN ISOLATION LEVEL {level}")
        print("A> SELECT count(*) WHERE on_call ->", on_call(a))
        print("B> SELECT count(*) WHERE on_call ->", on_call(b))
        a.execute("UPDATE doctors SET on_call = false WHERE id = 1")
        print("A> UPDATE doctor 1 off call")
        b.execute("UPDATE doctors SET on_call = false WHERE id = 2")
        print("B> UPDATE doctor 2 off call")
        a.commit()
        print("A> COMMIT")
        try:
            b.commit()
            print("B> COMMIT -> accepted")
        except psycopg.errors.SerializationFailure as err:
            print(f"B> COMMIT -> SQLSTATE {err.sqlstate}")
            print(f"   {err.diag.message_primary}")
            print(f"   DETAIL: {err.diag.message_detail}")
        left = on_call(a)
        verdict = "write skew: nobody left" if left == 0 else "one update was refused"
        print("doctors still on call:", left, "->", verdict)
        if level == "REPEATABLE READ":
            print()


def lost(a, b) -> None:
    runs = [("READ COMMITTED", "one withdrawal lost, no error"),
            ("REPEATABLE READ", "B was refused and can retry")]
    for n, (level, verdict) in enumerate(runs):
        if n:
            print()
        a.execute(SET_BALANCE, (100,))  # both runs start from 100
        print(f"-- both sessions at {level}")
        a.execute(f"BEGIN ISOLATION LEVEL {level}")
        b.execute(f"BEGIN ISOLATION LEVEL {level}")
        seen_a, seen_b = balance(a, 1), balance(b, 1)
        print(f"A> SELECT balance -> {seen_a}   B> SELECT balance -> {seen_b}")
        a.execute(SET_BALANCE, (seen_a - 10,))  # new value computed in Python
        a.commit()
        print(f"A> UPDATE balance = {seen_a - 10}; COMMIT")
        try:
            b.execute(SET_BALANCE, (seen_b - 10,))
            b.commit()
            print(f"B> UPDATE balance = {seen_b - 10}; COMMIT -> accepted")
        except psycopg.errors.SerializationFailure as err:
            b.rollback()
            print(f"B> UPDATE -> SQLSTATE {err.sqlstate}")
            print(f"   {err.diag.message_primary}")
        print("final balance:", balance(a, 1), "->", verdict)


DEMOS = {"dirty": dirty, "nonrepeatable": nonrepeatable,
         "phantom": phantom, "skew": skew, "lost": lost}

if __name__ == "__main__":
    demo = DEMOS[sys.argv[1]]
    with connect() as a, connect() as b:
        reset(a)
        demo(a, b)

02. Step 1: the dirty read PostgreSQL refuses

A dirty read is seeing another transaction's uncommitted work. Session B adds 500 to account 1 and does not commit; session A, at the default READ COMMITTED level, reads the row. Both connections are opened with autocommit=True, so the BEGIN ... lines you type are the only BEGIN the server receives and every demo states its own isolation level; commit() and rollback() still end the transaction you opened. (On a default psycopg connection the driver opens a transaction before your first statement, so a typed BEGIN ISOLATION LEVEL ... draws a warning, or fails once a query has run.)

Terminal · the dirty-read demo
python anomalies.py dirty
Expected output
A> BEGIN ISOLATION LEVEL READ COMMITTED
B> BEGIN; UPDATE ... +500  (not committed)
A> SELECT balance -> 100 (the uncommitted 600 is invisible)
B> ROLLBACK
A> SELECT balance -> 100

A reads 100, not 600. MVCC visibility, not a lock, keeps B's version hidden: a version becomes visible only when its creating transaction commits. This is worth internalising because the SQL standard allows dirty reads at its weakest level — PostgreSQL simply never permits them, at any level. One anomaly crossed off without any work.

03. Step 2: the non-repeatable read

Now A reads the same row twice, with B committing a change in between. At READ COMMITTED every statement takes a fresh snapshot (as the MVCC lesson showed), so the two reads can disagree. The demo runs the same schedule twice, first at READ COMMITTED and then at REPEATABLE READ:

Terminal · the non-repeatable-read demo
python anomalies.py nonrepeatable
Expected output · same schedule, two levels
A> BEGIN ISOLATION LEVEL READ COMMITTED
A> SELECT balance -> 100
B> UPDATE ... +40; COMMIT
A> SELECT balance -> 140 -> two reads disagree

A> BEGIN ISOLATION LEVEL REPEATABLE READ
A> SELECT balance -> 140
B> UPDATE ... +40; COMMIT
A> SELECT balance -> 140 -> snapshot from the first read holds

Raise the level to REPEATABLE READ and rerun the identical schedule: A's second read returns the value from its first read, because the whole transaction now uses one snapshot taken before B committed. The weakest level that prevents a non-repeatable read in PostgreSQL is therefore REPEATABLE READ. Note the price is symmetry: A's view of the world is frozen, so A must end its transaction to see B's change.

04. Step 3: the phantom

A phantom is the same anomaly aimed at a set of rows: re-run a range query and new matching rows have appeared. A counts accounts with a balance under 1,000 while B inserts one, again at both levels:

Terminal · the phantom demo
python anomalies.py phantom
Expected output
A> BEGIN ISOLATION LEVEL READ COMMITTED
A> SELECT count(*) ... balance < 1000 -> 2
B> INSERT account 3; COMMIT
A> SELECT count(*) ... -> 3 -> a phantom appeared

A> BEGIN ISOLATION LEVEL REPEATABLE READ
A> SELECT count(*) ... balance < 1000 -> 3
B> INSERT account 4; COMMIT
A> SELECT count(*) ... -> 3 -> same snapshot, no phantom

At READ COMMITTED the count grows; at REPEATABLE READ it does not. The SQL standard permits phantoms at REPEATABLE READ — PostgreSQL's snapshot isolation is stricter and hides them anyway, because the snapshot covers rows that did not exist when it was taken. If you arrive from another database, do not transfer the gap-lock folklore: PostgreSQL needs no gap locks to suppress phantoms, and uses none.

05. Step 4: write skew, and SERIALIZABLE stopping it

The last anomaly survives snapshots. Two doctors are on call; the rule is "never fewer than one". Both doctors open a transaction, each correctly reads two doctors on call, and each takes themselves off call:

Terminal · the same schedule at REPEATABLE READ, then at SERIALIZABLE
python anomalies.py skew
Expected output · REPEATABLE READ, then SERIALIZABLE
-- both sessions at REPEATABLE READ
A> SELECT count(*) WHERE on_call -> 2
B> SELECT count(*) WHERE on_call -> 2
A> UPDATE doctor 1 off call
B> UPDATE doctor 2 off call
A> COMMIT
B> COMMIT -> accepted
doctors still on call: 0 -> write skew: nobody left

-- both sessions at SERIALIZABLE
A> SELECT count(*) WHERE on_call -> 2
B> SELECT count(*) WHERE on_call -> 2
A> UPDATE doctor 1 off call
B> UPDATE doctor 2 off call
A> COMMIT
B> COMMIT -> SQLSTATE 40001
   could not serialize access due to read/write dependencies among transactions
   DETAIL: Reason code: Canceled on identification as a pivot, during commit attempt.
doctors still on call: 1 -> one update was refused

At REPEATABLE READ both transactions commit and nobody is on call. Neither saw anything stale: each read a true fact, each wrote a different row, so no row-level conflict exists. This is write skew, and of the isolation levels only SERIALIZABLE stops it (the other fix is to lock the rows the decision reads, with SELECT ... FOR UPDATE). That level tracks what each transaction read and wrote; B's commit is refused with SQLSTATE 40001 because B's decision depended on a state that A changed and committed first. When the error arrives depends on the schedule: here both UPDATEs ran before either COMMIT, so the conflict is found at B's COMMIT ("during commit attempt"). Had A committed before B even sent its UPDATE, PostgreSQL would already have cancelled B at that UPDATE ("during write") — same protection, earlier. The error is not a failure of your SQL — it is the database declining to pretend the two transactions could have run one after the other. Applications must expect it and retry, which the next lesson builds into a loop.

06. Step 5: the lost update

Practice adds one more anomaly, and it is the one most likely to hit application code. A and B both withdraw 10 from account 1 the natural way: read the balance, compute the new value in Python, write it back. Predict the final balance at each level before you run it:

Terminal · the lost-update demo
python anomalies.py lost
Expected output · same schedule, two levels
-- both sessions at READ COMMITTED
A> SELECT balance -> 100   B> SELECT balance -> 100
A> UPDATE balance = 90; COMMIT
B> UPDATE balance = 90; COMMIT -> accepted
final balance: 90 -> one withdrawal lost, no error

-- both sessions at REPEATABLE READ
A> SELECT balance -> 100   B> SELECT balance -> 100
A> UPDATE balance = 90; COMMIT
B> UPDATE -> SQLSTATE 40001
   could not serialize access due to concurrent update
final balance: 90 -> B was refused and can retry

At READ COMMITTED both writes succeed, and two withdrawals of 10 leave 90. B's UPDATE came after A had committed, so it did not even wait; it simply wrote a value computed from a read that was already stale. No error was raised anywhere. At REPEATABLE READ the same schedule fails loudly: B's snapshot was taken before A committed, so PostgreSQL refuses to let B overwrite a row version B never saw, and answers SQLSTATE 40001. B must then retry its whole transaction from fresh reads.

07. Step 6: the map you just earned

Everything the lab showed, on one card. Read each row as "possible at this level in PostgreSQL":

Anomalies by isolation level (PostgreSQL)
Anomaly                READ        REPEATABLE   SERIALIZABLE
                       COMMITTED   READ
dirty read             never       never        never
non-repeatable read    yes         no           no
phantom read           yes         no (*)       no
lost update            yes         no (40001)   no (40001)
write skew             yes         yes          no (40001)

(*) stricter than the SQL standard, which allows phantoms at REPEATABLE READ

Read the two "no (40001)" cells with care: "no" means the database refuses the second write with an error, not that your code is done. Silent versus loud is the difference that matters. Turning the loud error into a correct retry, and fixing lost updates without raising the isolation level, is the subject of the next lesson and the practice task for this skill.

08. Troubleshooting

09. Check your understanding

Practice check · 3 questions

Reading the outputs

Three questions on what each demo proved.

Q1. In Step 1, what actually kept B's uncommitted +500 invisible to A?
Q2. In the SERIALIZABLE rerun of Step 4, when exactly did B's transaction fail?
Q3. An end-of-day report reads several tables and must see one consistent cut of all of them. What is the weakest PostgreSQL level that guarantees that?
Practice only: not graded, not saved, not evidence.

10. Apply it: stretch tasks

Extend anomalies.py with two more demos:

  1. The relative write: copy lost to a new demo in which both sessions write SET balance = balance - 10 instead of a value computed in Python. Predict the final balance at READ COMMITTED and at REPEATABLE READ, then run it and explain any difference from Step 5.
  2. Skew with three doctors: seed three on-call doctors and let each of three sessions go off call when at least two are on call. Predict how many end up on call at REPEATABLE READ before you run it, then check yourself against the output.

11. Review prompt

Without looking back: which of the four phenomena can happen at READ COMMITTED, and which single level prevents all of them? Why did the phantom disappear at REPEATABLE READ without any gap locks? In the doctors demo, why did REPEATABLE READ accept both updates — what was not in conflict? And what must an application do when it receives SQLSTATE 40001?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check