← blog · November 28, 2026

Transaction Isolation Levels: Read Committed, Repeatable Read, Serializable and Write Skew

Each transaction is correct alone, together they break the rule. What the default isolation level permits, write skew, choosing between constraints, locks and Serializable, and how to write the retry loop correctly.

Two requests arrive at the same moment. Both check a business rule, both see "allowed", both write. Each transaction is correct on its own, yet the data they leave behind breaks the rule. There is no bug in the code, it never shows up in staging, and in production it happens about once a month. The usual cause is the transaction isolation level: a setting everyone assumes they understand, and few people have checked what its default actually permits.

The default is weaker than you think

PostgreSQL defaults to Read Committed. MySQL InnoDB defaults to Repeatable Read. The names come from the SQL standard, but every engine implements them differently, so "we run Repeatable Read, we are safe" means nothing until you say which engine.

In PostgreSQL the levels behave like this in practice:

  • Read Committed: each statement sees data committed before that statement began. Two SELECTs in the same transaction can return different results. An UPDATE that hits a row changed by a concurrent transaction waits, then re-evaluates its WHERE clause against the newest version of the row.
  • Repeatable Read: a snapshot is taken at the first statement of the transaction (not at BEGIN) and used throughout. If you try to update a row that someone else modified after your snapshot, the transaction fails with could not serialize access due to concurrent update.
  • Serializable: everything Repeatable Read does, plus tracking of read/write dependencies between transactions. If the outcome cannot be explained by some serial order, one transaction is aborted.

InnoDB's Repeatable Read is a different animal. Plain SELECT reads from the snapshot, but SELECT ... FOR UPDATE and UPDATE read the latest committed row and take gap locks. That is why a plain read and a locking read inside the same transaction can see different data.

Write skew: both are right, the result is wrong

A lost update is two transactions overwriting the same row, and an atomic UPDATE or a version column fixes it. Write skew is subtler: two transactions write different rows, but base their decision on the same shared data.

The textbook case is an on-call roster with the rule "at least one person stays on call per shift". Two people request leave at once:

BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM on_call WHERE shift_id = 7 AND active;   -- both see 2
UPDATE on_call SET active = false WHERE shift_id = 7 AND person_id = 1;
COMMIT;

The second transaction does the same for person_id = 2. The rows differ, no conflict is detected, both commit, and the shift is empty. Snapshot isolation allows this freely. The pattern is everywhere: overlapping room bookings, two uploads that together exceed a quota, a username claimed twice through check-then-insert, payments validated against the sum of several accounts.

Three fixes and where each fits

1. Serializable plus retry. PostgreSQL's Serializable level (SSI, serializable snapshot isolation) aborts one of the two transactions above with SQLSTATE 40001. It needs the fewest code changes and does not require you to know where the rule lives; the engine finds the dependency. The price is that the application must be ready to retry every transaction. For business logic with many scattered invariants, this is the approach I would pick: reasoning about locks by hand means forgetting one of the rules eventually.

2. Lock what you read. If you lock the rows that drive the decision with SELECT ... FOR UPDATE, the second transaction waits and then sees current data. In the roster example, locking all active rows of the shift is enough. But this cannot lock a row that does not exist: "insert if no booking overlaps this slot" has nothing to lock. In that case you materialize the conflict by locking a shared parent row (the room, the user's account row). If lock order is inconsistent this produces deadlocks, so always lock in the same order.

3. Turn the rule into a constraint. When the database can express the rule, this is the strongest option, because it holds regardless of isolation level, code path, or a hand-written query in a console. UNIQUE for uniqueness, an exclusion constraint for overlapping ranges:

CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE booking
  ADD CONSTRAINT no_overlap
  EXCLUDE USING gist (room_id WITH =, period WITH &&);

Here period is a tstzrange column, and btree_gist is needed so a plain column can use equality inside a GiST index. For rules a constraint cannot express (counts, sums) you fall back to the first two options.

Writing the retry correctly

If you choose Serializable, the real work is in the application. A minimal version with Python and psycopg 3:

import random, time
import psycopg
from psycopg import errors

def serializable(conn, work, attempts=5):
    conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
    for i in range(attempts):
        try:
            with conn.transaction():
                return work(conn)
        except (errors.SerializationFailure, errors.DeadlockDetected):
            if i == attempts - 1:
                raise
            time.sleep(random.uniform(0, 0.05 * 2 ** i))

What matters:

  • Rerun the whole transaction, reads included. Retrying only the failed UPDATE means writing again based on a stale read, which defeats the protection.
  • Keep side effects outside. If the function sends an email or calls another service, every attempt sends it again. Do those after a successful commit, or through an outbox row written in the same transaction.
  • Retry on 40001 (serialization failure) and 40P01 (deadlock). Retrying anything else just hides a real error behind a delay.
  • Add random backoff between attempts; two transactions that failed together and return together will collide again.
  • The error can arrive at COMMIT. Do not consider the work done until commit returns successfully.

Traps

Set the level per transaction, not per connection. With a transaction-mode connection pooler, a session-level SET leaks into another client's request or silently disappears. Use BEGIN ISOLATION LEVEL SERIALIZABLE explicitly, or pin it for the whole database with default_transaction_isolation.

Mixed levels give no protection. SSI only sees dependencies between transactions running at Serializable. If a batch job touching the same invariant runs at Read Committed, your Serializable transactions will not notice the conflict.

Sequential scans cause false positives. At Serializable, PostgreSQL tracks what you read with predicate locks. With an index scan the lock stays narrow; with a full table scan the whole relation counts as read, and unrelated transactions start aborting each other. If your retry rate is unexpectedly high, look at the plans first.

Long transactions make everything expensive. The longer a Serializable transaction stays open, the more likely it conflicts. Never hold a transaction open while waiting for user input. For read-only reports, SERIALIZABLE READ ONLY DEFERRABLE waits briefly at the start for a safe snapshot and then can never be aborted.

Measure the retry rate. Export the count of 40001 errors as a metric. Near zero is healthy; a sudden jump points to a hot row or a query that lost its index, and users feel it as latency.

When not to use Serializable

Where a single hot row (a counter, a balance, stock level) takes heavy writes, Serializable aborts and retries most of the traffic. An atomic UPDATE ... SET stock = stock - 1 WHERE stock > 0 is faster and more correct there, and Read Committed is enough. If the rule fits a constraint, write the constraint first. And turning on Serializable in a codebase that cannot retry cleanly (side effects scattered inside transactions) only converts silent data corruption into user-visible errors; separate the side effects first.

The short rule: know which anomaly your default level allows, push invariants into constraints first, and for the ones that do not fit, use Serializable with a properly written retry loop.