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 4 of 6 · Worked example · 25 min · revision 3

Stopping Lost Updates: Locks, Versions, Serializable Retries

Reproduce a lost update with two concurrent transfer workers, then fix it three ways — row locks, optimistic version checks, SERIALIZABLE with retry — and prove 1,000 concurrent transfers conserve every unit.

Contentsand lesson path

What you will learn

  • Prevent lost updates with row locks (SELECT ... FOR UPDATE), optimistic version checks, or SERIALIZABLE with retry on serialization failure.

Prerequisites: SQL Fundamentals

01. The problem

The practice task for this skill: run two concurrent money-transfer workers against PostgreSQL, show a lost update under READ COMMITTED, fix it twice, and show the total balance unchanged after 1,000 concurrent transfers. This lesson solves it end to end on the lab container from the anomalies lab, with four worker threads and two accounts, so you can reuse the pattern at work.

Each worker does the natural thing — read both balances, compute new ones in Python, write them back. Every transfer function returns how many retries it needed, which is always 0 for the first two fixes:

Python · workers.py, imports and the naive transfer
import random
import time

import psycopg


def read_then_write(conn, src, dst, amount):
    with conn.transaction():
        debit = conn.execute("SELECT balance FROM accounts"
                             " WHERE id = %s", (src,)).fetchone()[0]
        credit = conn.execute("SELECT balance FROM accounts"
                              " WHERE id = %s", (dst,)).fetchone()[0]
        conn.execute("UPDATE accounts SET balance = %s"
                     " WHERE id = %s", (debit - amount, src))
        conn.execute("UPDATE accounts SET balance = %s"
                     " WHERE id = %s", (credit + amount, dst))
    return 0                       # no retries

02. Step 1: watch the updates vanish

The harness race.py recreates two accounts holding 5,000 each, then starts four threads together at a barrier. Each thread opens its own connection and performs 250 transfers of one unit from account 1 to account 2 — 1,000 transfers, total balance 10,000. It counts how many distinct debits landed: 5,000 minus the final balance of account 1. The command-line argument picks the transfer function from workers.py:

Python · race.py
import sys
import threading

import psycopg

import workers

DSN = "postgresql://lab:lab@localhost:55436/tilab"
name = sys.argv[1]                  # read_then_write, lock_rows or serializable
transfer = getattr(workers, name)
retries = []

with psycopg.connect(DSN) as conn:  # two accounts, 10,000 in total
    conn.execute("DROP TABLE IF EXISTS accounts")
    conn.execute("CREATE TABLE accounts (id int PRIMARY KEY, balance int)")
    conn.execute("INSERT INTO accounts VALUES (1, 5000), (2, 5000)")
barrier = threading.Barrier(4)


def worker():
    with psycopg.connect(DSN) as conn:
        if name == "serializable":
            conn.execute("SET SESSION CHARACTERISTICS AS TRANSACTION"
                         " ISOLATION LEVEL SERIALIZABLE")
            conn.commit()
        barrier.wait()              # all four threads start together
        retries.append(sum(transfer(conn, 1, 2, 1) for _ in range(250)))


threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
with psycopg.connect(DSN) as conn:
    (b1,), (b2,) = conn.execute("SELECT balance FROM accounts ORDER BY id")
print(f"{name}: total 10000 -> {b1 + b2}")
print(f"  debits applied {5000 - b1}/1000, retries {sum(retries)}")
Terminal · the naive worker
python race.py read_then_write
Illustrative output · counts vary per run and machine
read_then_write: total 10000 -> 10032
  debits applied 277/1000, retries 0

In the run shown, only 277 of the 1,000 debits landed. Your count will differ from run to run; any number below 1,000 is the bug. The rest were lost updates: two workers read the same balance, both computed 5000 - 1, and the second UPDATE overwrote the first with the identical value — one transfer silently evaporated. The total drifted as well, to 10,032 here, because a debit and a credit of the same transfer can be lost independently. Note the mechanism, because it is not obvious: the second UPDATE did wait for the row lock. But once the first worker committed, the second went ahead and wrote a number computed from its stale read. READ COMMITTED prevents nothing here; the write succeeds and the update is lost without a whisper.

03. Step 2: fix one — lock the rows you read

The pessimistic fix: take the row locks before reading, with SELECT ... FOR UPDATE. Any other worker reading the same rows now waits, and reads the values the previous writer committed — so the arithmetic starts from reality. Add this function to workers.py and run python race.py lock_rows:

Python · workers.py, add the locking fix
def lock_rows(conn, src, dst, amount):
    with conn.transaction():
        rows = conn.execute(
            "SELECT id, balance FROM accounts WHERE id = ANY(%s)"
            " ORDER BY id FOR UPDATE",
            ([src, dst],),
        ).fetchall()
        new = dict(rows)
        new[src] -= amount
        new[dst] += amount
        for id_, bal in new.items():
            conn.execute("UPDATE accounts SET balance = %s"
                         " WHERE id = %s", (bal, id_))
    return 0                       # no retries
Expected output
lock_rows: total 10000 -> 10000
  debits applied 1000/1000, retries 0

Every transfer landed and the total is untouched. Two details matter more than the lock itself. ORDER BY id makes every worker lock the pair in ascending order, which is also why two copies of this code cannot deadlock with each other — the next lesson shows what happens without it. And the whole read-and-write is one transaction, so the lock is held exactly as long as the invariant needs it: commit, and the next worker proceeds.

04. Step 3: fix two — optimistic version checks

Row locks fit workers that hold transactions briefly. For an HTTP API editing a note across two requests, holding a transaction open between the requests is unthinkable — so check instead of lock. Add a version column, bump it on every write, and make the WHERE clause refuse to match a row that has moved on. editors.py plays two editors on two autocommit connections: both load the note (request 1 of each edit), then both save (request 2):

Python · editors.py
import psycopg

DSN = "postgresql://lab:lab@localhost:55436/tilab"
editor1 = psycopg.connect(DSN, autocommit=True)
editor2 = psycopg.connect(DSN, autocommit=True)
editor1.execute("DROP TABLE IF EXISTS notes")
editor1.execute("CREATE TABLE notes (id int PRIMARY KEY, body text,"
                " version int NOT NULL)")
editor1.execute("INSERT INTO notes VALUES (1, 'first draft', 1)")

read = "SELECT version FROM notes WHERE id = 1"
v1 = editor1.execute(read).fetchone()[0]   # request 1 of each edit:
v2 = editor2.execute(read).fetchone()[0]   # both see version 1

update = ("UPDATE notes SET body = %s, version = version + 1"
          " WHERE id = 1 AND version = %s")
with editor1.transaction():
    n1 = editor1.execute(update, ("edited by editor 1", v1)).rowcount
with editor2.transaction():
    n2 = editor2.execute(update, ("edited by editor 2", v2)).rowcount
print(f"editor 1 read version {v1} -> rows updated: {n1}")
print(f"editor 2 read version {v2} -> rows updated: {n2}")
print("final row:", editor1.execute(
    "SELECT body, version FROM notes WHERE id = 1").fetchone())
Expected output · python editors.py
editor 1 read version 1 -> rows updated: 1
editor 2 read version 1 -> rows updated: 0
final row: ('edited by editor 1', 2)

Editor 1's update matched one row and moved it to version 2. Editor 2's update matched zero rows — the row it based its edit on no longer exists in that version. Zero rows updated is the conflict signal: the application must reload, merge or report, never assume success. Nobody waited on a lock; the check costs one column and one predicate. This is optimistic concurrency. It suits low contention and edits whose read and write happen in separate requests, with a person's think time in between, where no lock can stay held. The practice below asks when you would pick it over FOR UPDATE.

05. Step 4: fix three — SERIALIZABLE, with retries

The third fix changes the rules instead of the code shape: run the same naive transfer at SERIALIZABLE, and let the database refuse any outcome that no serial order of the transactions could produce. Refusal arrives as SQLSTATE 40001, so the worker retries the whole transaction, with backoff. Add this function to workers.py; for this run race.py also sets every worker connection to SERIALIZABLE with SET SESSION CHARACTERISTICS. Then run python race.py serializable:

Python · workers.py, add the serializable fix
def serializable(conn, src, dst, amount):
    for attempt in range(100):          # returns the retries it needed
        try:
            read_then_write(conn, src, dst, amount)  # same reads and writes
            return attempt
        except (psycopg.errors.SerializationFailure,
                psycopg.errors.DeadlockDetected):
            time.sleep(random.uniform(0, 0.005 * (attempt + 1)))
    raise RuntimeError("transfer failed after 100 serialization retries")
Illustrative output · retry counts vary per run and machine
serializable: total 10000 -> 10000
  debits applied 1000/1000, retries 101

All 1,000 transfers landed and the total is intact. In the run shown 101 attempts were refused and replayed; that count swings widely from run to run, because it depends on how the threads happen to overlap. That trade is the deal with SERIALIZABLE: correctness for retries. Two failure modes showed up while developing this snippet and are worth more than the happy path. Retrying only the failed statement is wrong — the transaction is gone, including its reads, so the decisions must be re-made from fresh data. And retrying without backoff wastes the database's work: the same workers keep cancelling each other. In four pairs of runs of this lab on one machine, the retry count was 74 to 109 with the sleep and 1,719 to 2,372 without it; with more workers, a transfer can then use up its whole attempt budget. Sleep, jitter, and a bounded attempt count are part of the algorithm, not decoration — and when the budget runs out the code must raise, as the last line does, so the caller can report or requeue the transfer. A loop that simply ends and returns would drop the transfer silently, which is the lost update all over again. DeadlockDetected (40P01) is caught alongside 40001 because both mean "roll back and run me again".

06. Pitfalls

07. Check your understanding

Practice check · 3 questions

Choosing and applying a fix

Three decisions from the code you just ran.

Q1. A colleague changes the last line of `serializable()` to log a warning and `return attempt` instead of raising. In a heavily loaded run, `python race.py serializable` prints `total 10000 -> 10000` and `debits applied 997/1000`. What happened to the three missing transfers?
Q2. A single statement `UPDATE accounts SET balance = balance - 100 WHERE id = 1` runs twice concurrently at READ COMMITTED. Can an update be lost?
Q3. A note-editing HTTP API: low contention, two requests per edit, no transaction spans them. Which fix fits best?
Practice only: not graded, not saved, not evidence.

08. Apply it

This is the skill's practice task, in full:

  1. Recreate the lab: two accounts at 5,000, four workers, 250 transfers each. Run the naive worker and record debits applied.
  2. Add both fixes and show total 10000 -> 10000, debits applied 1000/1000 for each, logging the retry count for the SERIALIZABLE run.
  3. Add a transfers ledger table that inserts one row per committed transfer, and assert count(transfers) = 1000 and sum(amounts) = balance change — the ledger turns a silent loss into a loud invariant failure.
  4. Push one run to eight workers and write two sentences on how each fix degrades.

09. Review prompt

Without looking back: why exactly did the naive worker lose updates at READ COMMITTED — what did the second UPDATE wait for, and what did it write? What does FOR UPDATE change about what the waiting worker reads? In the optimistic fix, what does "0 rows updated" mean and what must the application do? For SERIALIZABLE, what two errors are retryable, what must be replayed, and why does the retry need a pause?

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