LeepCast
Subscribe
All posts
Software

Transaction Isolation Levels Explained: Read Committed, Repeatable Read, and Serializable in PostgreSQL

What each PostgreSQL isolation level actually guarantees, how lost updates and write skew slip through the defaults, and how to use Serializable safely with a retry loop.

LeepCast7 min read

Most concurrency bugs in database-backed applications never show up in tests. Two requests arrive a few milliseconds apart, both read the same rows, both make a sensible decision based on what they saw, and together they leave the data in a state that no single request would ever produce. The database did exactly what it was asked to do. The problem is that the isolation level in use allowed that interleaving, and the code assumed it could not happen.

This guide walks through the isolation levels PostgreSQL offers, what each one really guarantees, the specific anomalies that get through the default setting, and a practical pattern for running transactions at Serializable without turning every conflict into a user-facing error.

The four standard levels and the phenomena they rule out

The SQL standard defines isolation levels by listing which read phenomena each level must prevent. A dirty read means seeing data written by a transaction that has not committed. A nonrepeatable read means reading the same row twice and getting different values because another transaction committed in between. A phantom read means re-running a query with a WHERE condition and getting a different set of rows. A serialization anomaly means the combined result of a group of committed transactions could not have been produced by running them one at a time in any order.

  • Read Uncommitted: the standard allows dirty reads. PostgreSQL accepts the setting but treats it exactly like Read Committed, so dirty reads never happen.
  • Read Committed: no dirty reads, but nonrepeatable reads, phantoms, and serialization anomalies are possible. This is PostgreSQL's default.
  • Repeatable Read: no dirty or nonrepeatable reads. The standard still permits phantoms here, but PostgreSQL's implementation prevents them too. Serialization anomalies remain possible.
  • Serializable: none of the four phenomena can occur. The outcome is guaranteed to match some serial ordering of the committed transactions.

So in practice PostgreSQL has three distinct behaviors, and the interesting question is not which phenomena a table says are possible but what each behavior means for the code you write.

Read Committed: a fresh snapshot for every statement

Under Read Committed, each statement sees a snapshot of the database taken at the moment that statement starts. Two SELECTs inside the same transaction can therefore return different results if another transaction committed between them. For many web workloads this is fine, because each request does a small amount of work and then commits.

Writes have an extra rule. When an UPDATE, DELETE, SELECT FOR UPDATE, or SELECT FOR SHARE finds a target row that a concurrent transaction is modifying, it waits for that transaction to finish. If the other transaction rolls back, the waiting statement proceeds with the original row. If it deleted the row, the row is skipped. If it updated the row, PostgreSQL re-checks the WHERE condition against the new version of the row and applies the change only if the row still matches. This is why a statement such as UPDATE accounts SET balance = balance - 100 WHERE id = 1 is safe under concurrency: the arithmetic always happens on the latest committed value.

The lost update

The danger appears when the calculation moves into application code. A handler reads a balance with SELECT, subtracts an amount in the application, and writes the result back with UPDATE SET balance = the computed number. Two handlers running at once both read 500, both compute 400, and both write 400. One withdrawal has vanished. Read Committed does nothing to stop this, because each statement is individually correct and the UPDATE is not re-checking any condition that changed.

There are three common fixes. The simplest is to keep the arithmetic in the database with an atomic UPDATE expression, as above. The second is to lock the row when reading it with SELECT ... FOR UPDATE, which makes the second handler wait until the first commits and then read the new value. The third is to run the transaction at a stricter isolation level, which turns the silent overwrite into an error the application can retry.

Repeatable Read: one snapshot for the whole transaction

Repeatable Read takes its snapshot at the first real statement of the transaction, not at BEGIN, and keeps using it until the transaction ends. Every query sees the database as it was at that point, which makes it a good fit for reports, exports, and any logic that reads several tables and needs them to agree with each other. This behavior is commonly known as snapshot isolation.

Because the snapshot is frozen, a transaction at this level cannot safely update a row that some other transaction changed and committed after the snapshot was taken. Instead of re-checking and continuing as Read Committed does, PostgreSQL aborts the statement with the error could not serialize access due to concurrent update. That is exactly what prevents the lost update in the previous section: the second handler fails instead of overwriting. The application is expected to roll back and run the whole transaction again from the start. Read-only transactions at this level never hit these conflicts.

Write skew: the anomaly snapshots allow

Snapshot isolation still permits a subtler problem called write skew. It happens when two transactions each read an overlapping set of data, each make a decision based on it, and then each write to different rows. Because neither one updates a row the other updated, there is no write conflict to detect, yet the combined result breaks a rule that both transactions checked.

Consider a clinic rule that at least one doctor must be on call. Alice and Bob are both on call and both ask to go off call at the same moment. Each transaction counts the on-call doctors, sees two, decides it is safe to leave, and updates its own row. The script below reproduces it with two psql sessions; run each step in the session it names, in order.

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

-- Step 1, session A:
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM doctors WHERE on_call;  -- returns 2

-- Step 2, session B:
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM doctors WHERE on_call;  -- returns 2

-- Step 3, session A:
UPDATE doctors SET on_call = false WHERE name = 'alice';
COMMIT;

-- Step 4, session B:
UPDATE doctors SET on_call = false WHERE name = 'bob';
COMMIT;

-- Both commits succeed, and nobody is on call:
SELECT * FROM doctors WHERE on_call;  -- 0 rows

The same thing happens under Read Committed. No serial order of these two transactions could produce zero doctors on call, because whichever ran second would have counted only one and refused. That is the definition of a serialization anomaly, and only the Serializable level is guaranteed to catch it. Under Repeatable Read or Read Committed, the usual workaround is an explicit lock, for example reading the on-call rows with SELECT name FROM doctors WHERE on_call FOR UPDATE so that the second transaction waits and then re-reads.

Serializable: snapshot isolation plus conflict detection

PostgreSQL implements Serializable with a technique called Serializable Snapshot Isolation. A Serializable transaction reads from a snapshot just like Repeatable Read, but the server also tracks what each transaction has read using predicate locks, which appear in pg_locks with the mode SIReadLock. These locks never block anyone and cannot cause deadlocks. They exist only so the server can notice a pattern of read and write dependencies among concurrent transactions that could not have happened in any serial order.

Rerun the clinic example with BEGIN ISOLATION LEVEL SERIALIZABLE in both sessions and one of them will fail with could not serialize access due to read/write dependencies among transactions. The other commits normally. When the failed transaction is retried, it counts only one doctor on call and the application refuses the request, which is the correct behavior.

Both kinds of serialization failure, the one from Repeatable Read and the one from Serializable, are reported with SQLSTATE 40001. That single code is what retry logic should look for.

Running Serializable safely: retry the whole transaction

Serializable is only useful if failures are retried automatically. The retry must re-run the entire transaction, including every read, because any decision made on data from the aborted attempt may be wrong. The example below uses psycopg 3, which maps SQLSTATE 40001 to the SerializationFailure exception class. It sets the isolation level on the connection, runs the work inside a transaction block that commits on success and rolls back on any exception, and retries with a short randomized backoff.

python
import random
import time

import psycopg
from psycopg import errors


def run_serializable(conninfo, work, attempts=5):
    with psycopg.connect(conninfo, autocommit=True) as conn:
        conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
        for attempt in range(1, attempts + 1):
            try:
                with conn.transaction():
                    return work(conn)
            except errors.SerializationFailure:
                if attempt == attempts:
                    raise
                time.sleep(random.uniform(0, 0.05 * 2 ** attempt))


def go_off_call(conn, name):
    on_call = conn.execute(
        "SELECT count(*) FROM doctors WHERE on_call"
    ).fetchone()[0]
    if on_call < 2:
        raise RuntimeError("at least one doctor must stay on call")
    conn.execute(
        "UPDATE doctors SET on_call = false WHERE name = %s", (name,)
    )


run_serializable("dbname=clinic", lambda conn: go_off_call(conn, "alice"))

Note that the business rule check lives inside the retried function. Moving the count outside the transaction, or caching it between attempts, would bring the write skew straight back.

Setting the level and keeping conflicts rare

The level can be chosen per transaction with BEGIN ISOLATION LEVEL SERIALIZABLE or SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, per session with SET SESSION CHARACTERISTICS AS TRANSACTION, or as a default through the default_transaction_isolation setting, which can also be applied per database with ALTER DATABASE. It must be set before the first query or data-modification statement of the transaction; after that it cannot be changed.

The PostgreSQL documentation also lists habits that keep the rate of serialization failures low:

  • Declare transactions READ ONLY when they do not write. For long reports that must see consistent data, SERIALIZABLE READ ONLY DEFERRABLE waits for a safe snapshot and then runs without any risk of a serialization failure.
  • Keep transactions as short as correctness allows, and do not leave sessions idle in transaction. The idle_in_transaction_session_timeout setting can disconnect sessions that do.
  • Limit the number of active connections, using a connection pool if needed.
  • Remove explicit locks and SELECT FOR UPDATE once the transaction runs at Serializable, since the isolation level already provides the protection.
  • Prefer index scans for hot queries. A sequential scan takes a predicate lock on the whole table, which makes false-positive conflicts more likely.

Choosing a level

A reasonable default is to stay on Read Committed for simple, single-statement writes and atomic UPDATE expressions, use Repeatable Read for read-heavy work that must be internally consistent, and use Serializable with a retry wrapper for any transaction that reads data, checks a rule, and then writes based on that check. The last category is where write skew lives, and it is far easier to pay for a few retries than to debug a constraint that was quietly violated in production.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments