medium.com 11 min read Original Source

Database Isolation Levels Explained: Dirty Reads, Phantom Reads, and Locking in PostgreSQL

Wrap something in a transaction and the database handles consistency. That assumption works fine until you have concurrent users, and then it breaks in ways that are hard to reproduce because the bugs only appear when two operations hit the database at exactly the right moment.

READ COMMITTED sounds reassuring. It is not. This article goes through every anomaly, every isolation level, both locking strategies, and the PostgreSQL-specific behaviours that come up in production and in serious interviews. The same banking scenario runs throughout, because money is the domain where every one of these anomalies has a real cost.

The mental model first

A database with concurrent transactions has a choice: how much should each transaction know about what the others are doing right now?

The SQL standard defines four anomalies that can happen when transactions overlap. Two more come up at the senior level. All six are covered here.

The isolation levels are remedies for these anomalies. Understanding which level prevents which is the entire topic.

The schema

Everything in this article runs against this:

= 0),
version INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE transfers (
id BIGSERIAL PRIMARY KEY,
from_account_id BIGINT REFERENCES accounts(id),
to_account_id BIGINT REFERENCES accounts(id),
amount NUMERIC(15,2) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
INSERT INTO accounts (owner, balance) VALUES ('Alice', 1000.00);
INSERT INTO accounts (owner, balance) VALUES ('Bob', 500.00);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

CREATE TABLE accounts (
    id      BIGSERIAL PRIMARY KEY,
    owner   VARCHAR(100) NOT NULL,
    balance NUMERIC(15,2) NOT NULL CHECK (balance >= 0),
    version INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE transfers (
    id              BIGSERIAL PRIMARY KEY,
    from_account_id BIGINT REFERENCES accounts(id),
    to_account_id   BIGINT REFERENCES accounts(id),
    amount          NUMERIC(15,2) NOT NULL,
    created_at      TIMESTAMPTZ DEFAULT NOW()
);
INSERT INTO accounts (owner, balance) VALUES ('Alice', 1000.00);
INSERT INTO accounts (owner, balance) VALUES ('Bob',    500.00);
CREATE TABLE accounts (
    id      BIGSERIAL PRIMARY KEY,
    owner   VARCHAR(100) NOT NULL,
    balance NUMERIC(15,2) NOT NULL CHECK (balance >= 0),
    version INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE transfers (
    id              BIGSERIAL PRIMARY KEY,
    from_account_id BIGINT REFERENCES accounts(id),
    to_account_id   BIGINT REFERENCES accounts(id),
    amount          NUMERIC(15,2) NOT NULL,
    created_at      TIMESTAMPTZ DEFAULT NOW()
);
INSERT INTO accounts (owner, balance) VALUES ('Alice', 1000.00);
INSERT INTO accounts (owner, balance) VALUES ('Bob',    500.00);

The version column is for optimistic locking. The CHECK (balance >= 0) constraint is the one write skew will violate.

Anomaly 1: Dirty read

Transaction A reads data Transaction B wrote but has not committed. B rolls back. A made a decision based on data that never existed.

// Session B: writes but does not commit
connB.setAutoCommit(false);
PreparedStatement update = connB.prepareStatement(
    "UPDATE accounts SET balance = 0 WHERE id = 1"
);
update.executeUpdate();
// NOT committed yet

// Session A: tries to read uncommitted data
connA.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connA.setAutoCommit(false);
PreparedStatement read = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 1"
);
ResultSet rs = read.executeQuery();
rs.next();
System.out.println("Balance seen: " + rs.getBigDecimal("balance"));
// PostgreSQL: returns 1000.00, dirty read does NOT happen
// MySQL READ UNCOMMITTED: returns 0.00, dirty read happens
connB.rollback(); // balance was never really 0
// Session B: writes but does not commit
connB.setAutoCommit(false);
PreparedStatement update = connB.prepareStatement(
    "UPDATE accounts SET balance = 0 WHERE id = 1"
);
update.executeUpdate();
// NOT committed yet

// Session A: tries to read uncommitted data
connA.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connA.setAutoCommit(false);
PreparedStatement read = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 1"
);
ResultSet rs = read.executeQuery();
rs.next();
System.out.println("Balance seen: " + rs.getBigDecimal("balance"));
// PostgreSQL: returns 1000.00, dirty read does NOT happen
// MySQL READ UNCOMMITTED: returns 0.00, dirty read happens
connB.rollback(); // balance was never really 0

PostgreSQL-specific behaviour worth knowing: READ UNCOMMITTED in PostgreSQL is silently upgraded to READ COMMITTED. Dirty reads are impossible at any isolation level in PostgreSQL. The SQL standard allows them at READ UNCOMMITTED. MySQL with InnoDB actually implements them. This distinction comes up in interviews.

Anomaly 2: Non-repeatable read

Same row, same transaction, two reads, two different values. Another transaction committed a change between your first and second read.

connA.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
connA.setAutoCommit(false);
PreparedStatement read = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 1"
);
ResultSet rs1 = read.executeQuery();
rs1.next();
System.out.println("First read: " + rs1.getBigDecimal("balance")); // 1000.00
// Session B commits a change concurrently
connB.setAutoCommit(false);
connB.prepareStatement("UPDATE accounts SET balance = 800 WHERE id = 1").executeUpdate();
connB.commit();
ResultSet rs2 = read.executeQuery();
rs2.next();
System.out.println("Second read: " + rs2.getBigDecimal("balance")); // 800.00
// Same transaction. Same query. Different result.
connA.commit();
connA.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
connA.setAutoCommit(false);
PreparedStatement read = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 1"
);
ResultSet rs1 = read.executeQuery();
rs1.next();
System.out.println("First read: " + rs1.getBigDecimal("balance")); // 1000.00
// Session B commits a change concurrently
connB.setAutoCommit(false);
connB.prepareStatement("UPDATE accounts SET balance = 800 WHERE id = 1").executeUpdate();
connB.commit();
ResultSet rs2 = read.executeQuery();
rs2.next();
System.out.println("Second read: " + rs2.getBigDecimal("balance")); // 800.00
// Same transaction. Same query. Different result.
connA.commit();

The fix is REPEATABLE READ. PostgreSQL takes a snapshot at the first data-access statement of the transaction. Every subsequent read sees the snapshot, not the live data.

connA.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
// Now the second read returns 1000.00 regardless of what B committed
connA.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
// Now the second read returns 1000.00 regardless of what B committed

One clarification on the name: REPEATABLE READ means rows you have already read will not change within your transaction. It does not mean all queries return the same result set. New rows inserted by other transactions can still appear at the ANSI standard level. That is the phantom read problem.

Anomaly 3: Phantom read

Same query, same transaction, different rows. Another transaction inserted or deleted matching rows between your two executions. The key distinction from non-repeatable read: a non-repeatable read is about a row changing. A phantom read is about rows appearing or disappearing.

500"
);
ResultSet rs1 = count.executeQuery();
rs1.next();
System.out.println("First count: " + rs1.getInt(1)); // 1
// Session B inserts a new account
connB.setAutoCommit(false);
connB.prepareStatement(
"INSERT INTO accounts (owner, balance, version) VALUES ('Charlie', 900.00, 0)"
).executeUpdate();
connB.commit();
ResultSet rs2 = count.executeQuery();
rs2.next();
System.out.println("Second count: " + rs2.getInt(1));
// PostgreSQL REPEATABLE READ: still 1, snapshot prevents phantom
// SQL standard REPEATABLE READ: could be 2
connA.commit();” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

connA.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connA.setAutoCommit(false);
PreparedStatement count = connA.prepareStatement(
    "SELECT COUNT(*) FROM accounts WHERE balance > 500"
);
ResultSet rs1 = count.executeQuery();
rs1.next();
System.out.println("First count: " + rs1.getInt(1)); // 1
// Session B inserts a new account
connB.setAutoCommit(false);
connB.prepareStatement(
    "INSERT INTO accounts (owner, balance, version) VALUES ('Charlie', 900.00, 0)"
).executeUpdate();
connB.commit();
ResultSet rs2 = count.executeQuery();
rs2.next();
System.out.println("Second count: " + rs2.getInt(1));
// PostgreSQL REPEATABLE READ: still 1, snapshot prevents phantom
// SQL standard REPEATABLE READ: could be 2
connA.commit();
connA.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connA.setAutoCommit(false);
PreparedStatement count = connA.prepareStatement(
    "SELECT COUNT(*) FROM accounts WHERE balance > 500"
);
ResultSet rs1 = count.executeQuery();
rs1.next();
System.out.println("First count: " + rs1.getInt(1)); // 1
// Session B inserts a new account
connB.setAutoCommit(false);
connB.prepareStatement(
    "INSERT INTO accounts (owner, balance, version) VALUES ('Charlie', 900.00, 0)"
).executeUpdate();
connB.commit();
ResultSet rs2 = count.executeQuery();
rs2.next();
System.out.println("Second count: " + rs2.getInt(1));
// PostgreSQL REPEATABLE READ: still 1, snapshot prevents phantom
// SQL standard REPEATABLE READ: could be 2
connA.commit();

PostgreSQL prevents phantom reads at REPEATABLE READ because its MVCC snapshot covers new rows too. This is stronger than the SQL standard requires. The standard only guarantees phantom prevention at SERIALIZABLE. In PostgreSQL you get it one level earlier.

Anomaly 4: Lost update

This one is not in the SQL standard’s four anomaly list, which is why it catches people off guard. It is the most common real-world concurrency bug in financial applications.

Two transactions read a value, both compute a new value, and one overwrites the other. No error is raised. No lock fails. One update simply disappears.

// This is the broken pattern, read-modify-write without locking
public void withdraw(long accountId, BigDecimal amount) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(false);
// Read
    PreparedStatement read = conn.prepareStatement(
        "SELECT balance FROM accounts WHERE id = ?"
    );
    read.setLong(1, accountId);
    ResultSet rs = read.executeQuery();
    rs.next();
    BigDecimal balance = rs.getBigDecimal("balance");
    // Application-level compute
    BigDecimal newBalance = balance.subtract(amount);
    // Write - overwrites whatever happened between read and write
    PreparedStatement write = conn.prepareStatement(
        "UPDATE accounts SET balance = ? WHERE id = ?"
    );
    write.setBigDecimal(1, newBalance);
    write.setLong(2, accountId);
    write.executeUpdate();
    conn.commit();
}
// This is the broken pattern, read-modify-write without locking
public void withdraw(long accountId, BigDecimal amount) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(false);
// Read
    PreparedStatement read = conn.prepareStatement(
        "SELECT balance FROM accounts WHERE id = ?"
    );
    read.setLong(1, accountId);
    ResultSet rs = read.executeQuery();
    rs.next();
    BigDecimal balance = rs.getBigDecimal("balance");
    // Application-level compute
    BigDecimal newBalance = balance.subtract(amount);
    // Write - overwrites whatever happened between read and write
    PreparedStatement write = conn.prepareStatement(
        "UPDATE accounts SET balance = ? WHERE id = ?"
    );
    write.setBigDecimal(1, newBalance);
    write.setLong(2, accountId);
    write.executeUpdate();
    conn.commit();
}

Every concurrent call to this method is a race condition. The fix is either pessimistic or optimistic locking, covered in full below.

Anomaly 5: Read skew

A transaction reads two related rows and sees them from different points in time. Each individual read is consistent, but together they represent a state the database was never in.

connA.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
connA.setAutoCommit(false);
// Read Alice's balance before a transfer
PreparedStatement readAlice = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 1"
);
ResultSet rsAlice = readAlice.executeQuery();
rsAlice.next();
BigDecimal aliceBalance = rsAlice.getBigDecimal("balance"); // 1000
// Session B transfers 200 from Alice to Bob
connB.setAutoCommit(false);
connB.prepareStatement("UPDATE accounts SET balance = balance - 200 WHERE id = 1").executeUpdate();
connB.prepareStatement("UPDATE accounts SET balance = balance + 200 WHERE id = 2").executeUpdate();
connB.commit();
// Read Bob's balance after the transfer
PreparedStatement readBob = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 2"
);
ResultSet rsBob = readBob.executeQuery();
rsBob.next();
BigDecimal bobBalance = rsBob.getBigDecimal("balance"); // 700 (post-transfer)
// A sees: Alice=1000, Bob=700. Total appears to be 1700.
// Real total is 1500. The database was never in the state A is reporting.
System.out.println("Total (skewed): " + aliceBalance.add(bobBalance)); // 1700
connA.commit();
connA.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
connA.setAutoCommit(false);
// Read Alice's balance before a transfer
PreparedStatement readAlice = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 1"
);
ResultSet rsAlice = readAlice.executeQuery();
rsAlice.next();
BigDecimal aliceBalance = rsAlice.getBigDecimal("balance"); // 1000
// Session B transfers 200 from Alice to Bob
connB.setAutoCommit(false);
connB.prepareStatement("UPDATE accounts SET balance = balance - 200 WHERE id = 1").executeUpdate();
connB.prepareStatement("UPDATE accounts SET balance = balance + 200 WHERE id = 2").executeUpdate();
connB.commit();
// Read Bob's balance after the transfer
PreparedStatement readBob = connA.prepareStatement(
    "SELECT balance FROM accounts WHERE id = 2"
);
ResultSet rsBob = readBob.executeQuery();
rsBob.next();
BigDecimal bobBalance = rsBob.getBigDecimal("balance"); // 700 (post-transfer)
// A sees: Alice=1000, Bob=700. Total appears to be 1700.
// Real total is 1500. The database was never in the state A is reporting.
System.out.println("Total (skewed): " + aliceBalance.add(bobBalance)); // 1700
connA.commit();

REPEATABLE READ prevents this because both reads come from the same snapshot.

Anomaly 6: Write skew

Two transactions each read overlapping data, each verify a business constraint, each write a change that is individually valid, but together they violate the constraint.

This is the hardest anomaly to reason about and the main reason SERIALIZABLE exists.

The constraint: total balance across all accounts must remain non-negative.

0, so withdrawal is safe
// Both withdraw everything

// Transaction A withdraws Alice's 1000
connA.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connA.setAutoCommit(false);
BigDecimal totalA = readTotalBalance(connA); // 1500
if (totalA.compareTo(new BigDecimal("1000")) >= 0) { // valid
connA.prepareStatement(
"UPDATE accounts SET balance = 0 WHERE id = 1"
).executeUpdate();
connA.commit(); // succeeds
}

// Transaction B withdraws Bob's 500 (concurrently)
connB.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connB.setAutoCommit(false);
BigDecimal totalB = readTotalBalance(connB); // still sees 1500 from its snapshot
if (totalB.compareTo(new BigDecimal("500")) >= 0) { // valid
connB.prepareStatement(
"UPDATE accounts SET balance = 0 WHERE id = 2"
).executeUpdate();
connB.commit(); // also succeeds
}
// Result: both accounts are 0. Total balance is 0.
// Each individual transaction was valid. Together they violated the invariant.” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// Both transactions run concurrently
// Both read: Alice=1000, Bob=500, total=1500
// Both verify: total > 0, so withdrawal is safe
// Both withdraw everything

// Transaction A withdraws Alice's 1000
connA.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connA.setAutoCommit(false);
BigDecimal totalA = readTotalBalance(connA); // 1500
if (totalA.compareTo(new BigDecimal("1000")) >= 0) { // valid
    connA.prepareStatement(
        "UPDATE accounts SET balance = 0 WHERE id = 1"
    ).executeUpdate();
    connA.commit(); // succeeds
}

// Transaction B withdraws Bob's 500 (concurrently)
connB.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connB.setAutoCommit(false);
BigDecimal totalB = readTotalBalance(connB); // still sees 1500 from its snapshot
if (totalB.compareTo(new BigDecimal("500")) >= 0) { // valid
    connB.prepareStatement(
        "UPDATE accounts SET balance = 0 WHERE id = 2"
    ).executeUpdate();
    connB.commit(); // also succeeds
}
// Result: both accounts are 0. Total balance is 0.
// Each individual transaction was valid. Together they violated the invariant.
// Both transactions run concurrently
// Both read: Alice=1000, Bob=500, total=1500
// Both verify: total > 0, so withdrawal is safe
// Both withdraw everything

// Transaction A withdraws Alice's 1000
connA.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connA.setAutoCommit(false);
BigDecimal totalA = readTotalBalance(connA); // 1500
if (totalA.compareTo(new BigDecimal("1000")) >= 0) { // valid
    connA.prepareStatement(
        "UPDATE accounts SET balance = 0 WHERE id = 1"
    ).executeUpdate();
    connA.commit(); // succeeds
}

// Transaction B withdraws Bob's 500 (concurrently)
connB.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
connB.setAutoCommit(false);
BigDecimal totalB = readTotalBalance(connB); // still sees 1500 from its snapshot
if (totalB.compareTo(new BigDecimal("500")) >= 0) { // valid
    connB.prepareStatement(
        "UPDATE accounts SET balance = 0 WHERE id = 2"
    ).executeUpdate();
    connB.commit(); // also succeeds
}
// Result: both accounts are 0. Total balance is 0.
// Each individual transaction was valid. Together they violated the invariant.

REPEATABLE READ does not prevent this because each transaction’s snapshot was accurate when taken. Neither sees the other’s write. Only SERIALIZABLE prevents write skew by detecting the read/write dependency and aborting one transaction.

The full anomaly matrix

PostgreSQL default is READ COMMITTED. Most applications never change this and then wonder why they have lost update bugs under concurrent load.

Pessimistic locking

Pessimistic locking assumes conflicts will happen. It acquires locks before reading and holds them until commit. Other transactions that need the same rows block until the lock is released.

<button data-code="public void transfer(long fromId, long toId, BigDecimal amount) throws SQLException {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
try {
// Always lock in consistent order to prevent deadlock
// Lower ID first, regardless of which direction the transfer goes
long firstId = Math.min(fromId, toId);
long secondId = Math.max(fromId, toId);
PreparedStatement lockStmt = conn.prepareStatement(
"SELECT id, balance FROM accounts WHERE id = ANY(?) ORDER BY id FOR UPDATE"
);
Array ids = conn.createArrayOf("BIGINT", new Object[]{firstId, secondId});
lockStmt.setArray(1, ids);
ResultSet rs = lockStmt.executeQuery();
Map balances = new HashMap();
while (rs.next()) {
balances.put(rs.getLong("id"), rs.getBigDecimal("balance"));
}
BigDecimal fromBalance = balances.get(fromId);
if (fromBalance.compareTo(amount)

public void transfer(long fromId, long toId, BigDecimal amount) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(false);
try {
        // Always lock in consistent order to prevent deadlock
        // Lower ID first, regardless of which direction the transfer goes
        long firstId  = Math.min(fromId, toId);
        long secondId = Math.max(fromId, toId);
        PreparedStatement lockStmt = conn.prepareStatement(
            "SELECT id, balance FROM accounts WHERE id = ANY(?) ORDER BY id FOR UPDATE"
        );
        Array ids = conn.createArrayOf("BIGINT", new Object[]{firstId, secondId});
        lockStmt.setArray(1, ids);
        ResultSet rs = lockStmt.executeQuery();
        Map<Long, BigDecimal> balances = new HashMap<>();
        while (rs.next()) {
            balances.put(rs.getLong("id"), rs.getBigDecimal("balance"));
        }
        BigDecimal fromBalance = balances.get(fromId);
        if (fromBalance.compareTo(amount) < 0) {
            conn.rollback();
            throw new IllegalStateException("Insufficient funds: " + fromBalance);
        }
        PreparedStatement debit = conn.prepareStatement(
            "UPDATE accounts SET balance = balance - ? WHERE id = ?"
        );
        debit.setBigDecimal(1, amount);
        debit.setLong(2, fromId);
        debit.executeUpdate();
        PreparedStatement credit = conn.prepareStatement(
            "UPDATE accounts SET balance = balance + ? WHERE id = ?"
        );
        credit.setBigDecimal(1, amount);
        credit.setLong(2, toId);
        credit.executeUpdate();
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        throw e;
    }
}
public void transfer(long fromId, long toId, BigDecimal amount) throws SQLException {
    Connection conn = dataSource.getConnection();
    conn.setAutoCommit(false);
try {
        // Always lock in consistent order to prevent deadlock
        // Lower ID first, regardless of which direction the transfer goes
        long firstId  = Math.min(fromId, toId);
        long secondId = Math.max(fromId, toId);
        PreparedStatement lockStmt = conn.prepareStatement(
            "SELECT id, balance FROM accounts WHERE id = ANY(?) ORDER BY id FOR UPDATE"
        );
        Array ids = conn.createArrayOf("BIGINT", new Object[]{firstId, secondId});
        lockStmt.setArray(1, ids);
        ResultSet rs = lockStmt.executeQuery();
        Map<Long, BigDecimal> balances = new HashMap<>();
        while (rs.next()) {
            balances.put(rs.getLong("id"), rs.getBigDecimal("balance"));
        }
        BigDecimal fromBalance = balances.get(fromId);
        if (fromBalance.compareTo(amount) < 0) {
            conn.rollback();
            throw new IllegalStateException("Insufficient funds: " + fromBalance);
        }
        PreparedStatement debit = conn.prepareStatement(
            "UPDATE accounts SET balance = balance - ? WHERE id = ?"
        );
        debit.setBigDecimal(1, amount);
        debit.setLong(2, fromId);
        debit.executeUpdate();
        PreparedStatement credit = conn.prepareStatement(
            "UPDATE accounts SET balance = balance + ? WHERE id = ?"
        );
        credit.setBigDecimal(1, amount);
        credit.setLong(2, toId);
        credit.executeUpdate();
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        throw e;
    }
}

ORDER BY id before acquiring the lock is the deadlock prevention. If Transaction A tries to lock accounts 1 and 2, and Transaction B also tries to lock accounts 1 and 2, both lock 1 first. One succeeds and holds it. The other blocks. No circular dependency, no deadlock.

Without consistent ordering: A locks 1, B locks 2, A waits for 2, B waits for 1. PostgreSQL detects the cycle and rolls one back with ERROR: deadlock detected.

FOR UPDATE SKIP LOCKED for job queues:

PreparedStatement fetchJob = conn.prepareStatement(
    "SELECT id, payload FROM jobs WHERE status = 'pending' " +
    "ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"
);
PreparedStatement fetchJob = conn.prepareStatement(
    "SELECT id, payload FROM jobs WHERE status = 'pending' " +
    "ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED"
);

Multiple workers run this simultaneously. Each picks a different job because locked rows are invisible to the others. No job gets processed twice.

FOR UPDATE NOWAIT when waiting is worse than failing:

PreparedStatement lockStmt = conn.prepareStatement(
    "SELECT balance FROM accounts WHERE id = ? FOR UPDATE NOWAIT"
);
// Fails immediately with an exception if the row is locked
// Caller handles it and retries with its own backoff
PreparedStatement lockStmt = conn.prepareStatement(
    "SELECT balance FROM accounts WHERE id = ? FOR UPDATE NOWAIT"
);
// Fails immediately with an exception if the row is locked
// Caller handles it and retries with its own backoff

FOR SHARE when you need consistency but not exclusive access:

PreparedStatement readStmt = conn.prepareStatement(
    "SELECT balance FROM accounts WHERE id = ? FOR SHARE"
);
// Other transactions can also acquire shared locks on the same row
// But no transaction can modify or exclusively lock it
// Use when you need to read a row and guarantee it will not be deleted
// but you do not plan to modify it yourself
PreparedStatement readStmt = conn.prepareStatement(
    "SELECT balance FROM accounts WHERE id = ? FOR SHARE"
);
// Other transactions can also acquire shared locks on the same row
// But no transaction can modify or exclusively lock it
// Use when you need to read a row and guarantee it will not be deleted
// but you do not plan to modify it yourself

Optimistic locking

Optimistic locking assumes conflicts are rare. No locks on read. At write time, it checks whether the row changed since you read it. If it did, the update affects zero rows, you detect the conflict, and retry.

<button data-code="public void transfer(long fromId, long toId, BigDecimal amount)
throws SQLException, OptimisticLockException {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
try {
String readSql = "SELECT id, balance, version FROM accounts WHERE id = ?";
PreparedStatement fromRead = conn.prepareStatement(readSql);
fromRead.setLong(1, fromId);
ResultSet fromRs = fromRead.executeQuery();
fromRs.next();
BigDecimal fromBalance = fromRs.getBigDecimal("balance");
int fromVersion = fromRs.getInt("version");
if (fromBalance.compareTo(amount)

public void transfer(long fromId, long toId, BigDecimal amount)
        throws SQLException, OptimisticLockException {
Connection conn = dataSource.getConnection();
    conn.setAutoCommit(false);
    try {
        String readSql = "SELECT id, balance, version FROM accounts WHERE id = ?";
        PreparedStatement fromRead = conn.prepareStatement(readSql);
        fromRead.setLong(1, fromId);
        ResultSet fromRs = fromRead.executeQuery();
        fromRs.next();
        BigDecimal fromBalance = fromRs.getBigDecimal("balance");
        int fromVersion        = fromRs.getInt("version");
        if (fromBalance.compareTo(amount) < 0) {
            conn.rollback();
            throw new IllegalStateException("Insufficient funds");
        }
        PreparedStatement toRead = conn.prepareStatement(readSql);
        toRead.setLong(1, toId);
        ResultSet toRs = toRead.executeQuery();
        toRs.next();
        BigDecimal toBalance = toRs.getBigDecimal("balance");
        int toVersion        = toRs.getInt("version");
        // Only update if version has not changed since we read
        String updateSql =
            "UPDATE accounts SET balance = ?, version = version + 1 " +
            "WHERE id = ? AND version = ?";
        PreparedStatement debit = conn.prepareStatement(updateSql);
        debit.setBigDecimal(1, fromBalance.subtract(amount));
        debit.setLong(2, fromId);
        debit.setInt(3, fromVersion);
        if (debit.executeUpdate() == 0) {
            conn.rollback();
            throw new OptimisticLockException("Concurrent modification on account " + fromId);
        }
        PreparedStatement credit = conn.prepareStatement(updateSql);
        credit.setBigDecimal(1, toBalance.add(amount));
        credit.setLong(2, toId);
        credit.setInt(3, toVersion);
        if (credit.executeUpdate() == 0) {
            conn.rollback();
            throw new OptimisticLockException("Concurrent modification on account " + toId);
        }
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        throw e;
    }
}
public void transfer(long fromId, long toId, BigDecimal amount)
        throws SQLException, OptimisticLockException {
Connection conn = dataSource.getConnection();
    conn.setAutoCommit(false);
    try {
        String readSql = "SELECT id, balance, version FROM accounts WHERE id = ?";
        PreparedStatement fromRead = conn.prepareStatement(readSql);
        fromRead.setLong(1, fromId);
        ResultSet fromRs = fromRead.executeQuery();
        fromRs.next();
        BigDecimal fromBalance = fromRs.getBigDecimal("balance");
        int fromVersion        = fromRs.getInt("version");
        if (fromBalance.compareTo(amount) < 0) {
            conn.rollback();
            throw new IllegalStateException("Insufficient funds");
        }
        PreparedStatement toRead = conn.prepareStatement(readSql);
        toRead.setLong(1, toId);
        ResultSet toRs = toRead.executeQuery();
        toRs.next();
        BigDecimal toBalance = toRs.getBigDecimal("balance");
        int toVersion        = toRs.getInt("version");
        // Only update if version has not changed since we read
        String updateSql =
            "UPDATE accounts SET balance = ?, version = version + 1 " +
            "WHERE id = ? AND version = ?";
        PreparedStatement debit = conn.prepareStatement(updateSql);
        debit.setBigDecimal(1, fromBalance.subtract(amount));
        debit.setLong(2, fromId);
        debit.setInt(3, fromVersion);
        if (debit.executeUpdate() == 0) {
            conn.rollback();
            throw new OptimisticLockException("Concurrent modification on account " + fromId);
        }
        PreparedStatement credit = conn.prepareStatement(updateSql);
        credit.setBigDecimal(1, toBalance.add(amount));
        credit.setLong(2, toId);
        credit.setInt(3, toVersion);
        if (credit.executeUpdate() == 0) {
            conn.rollback();
            throw new OptimisticLockException("Concurrent modification on account " + toId);
        }
        conn.commit();
    } catch (SQLException e) {
        conn.rollback();
        throw e;
    }
}

The caller must handle the conflict with a retry loop:

<button data-code="public void transferWithRetry(long fromId, long toId, BigDecimal amount)
throws SQLException {
int maxRetries = 3;
long baseDelayMs = 50;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
try {
transfer(fromId, toId, amount);
return;
} catch (OptimisticLockException e) {
if (attempt == maxRetries) {
throw new SQLException("Transfer failed after " + maxRetries + " retries", e);
}
// Exponential backoff with jitter
// Without jitter, retrying threads synchronise and collide again
long delay = baseDelayMs * (1L <

public void transferWithRetry(long fromId, long toId, BigDecimal amount)
        throws SQLException {
    int maxRetries   = 3;
    long baseDelayMs = 50;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            transfer(fromId, toId, amount);
            return;
        } catch (OptimisticLockException e) {
            if (attempt == maxRetries) {
                throw new SQLException("Transfer failed after " + maxRetries + " retries", e);
            }
            // Exponential backoff with jitter
            // Without jitter, retrying threads synchronise and collide again
            long delay = baseDelayMs * (1L << attempt)
                + (long)(Math.random() * baseDelayMs);
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw new SQLException("Interrupted during retry", ie);
            }
        }
    }
}
public void transferWithRetry(long fromId, long toId, BigDecimal amount)
        throws SQLException {
    int maxRetries   = 3;
    long baseDelayMs = 50;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            transfer(fromId, toId, amount);
            return;
        } catch (OptimisticLockException e) {
            if (attempt == maxRetries) {
                throw new SQLException("Transfer failed after " + maxRetries + " retries", e);
            }
            // Exponential backoff with jitter
            // Without jitter, retrying threads synchronise and collide again
            long delay = baseDelayMs * (1L << attempt)
                + (long)(Math.random() * baseDelayMs);
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw new SQLException("Interrupted during retry", ie);
            }
        }
    }
}

The jitter matters. Without it, multiple threads that all fail at the same time all retry at the same time and collide again. The random component spreads them across a time window.

Pessimistic vs optimistic side by side

Use pessimistic when contention is high, transactions are long, or retry cost is expensive. Use optimistic when reads heavily outnumber writes and conflicts are genuinely infrequent. The rough threshold: if more than 20% of your transactions would hit an optimistic lock conflict, pessimistic locking is more efficient overall.

PostgreSQL-specific behaviour worth knowing

These come up in interviews and production debugging and are not obvious from the documentation.

READ UNCOMMITTED is silently upgraded. PostgreSQL treats it as READ COMMITTED internally. Dirty reads cannot happen at any isolation level.

REPEATABLE READ prevents phantoms. The SQL standard only requires this at SERIALIZABLE. PostgreSQL’s MVCC snapshot implementation prevents phantom reads at REPEATABLE READ as a side effect.

SERIALIZABLE uses SSI, not two-phase locking. Most databases implement SERIALIZABLE with locks that block everything. PostgreSQL uses Serializable Snapshot Isolation, which detects conflicts through dependency tracking. Transactions run concurrently and are aborted if PostgreSQL detects they cannot be serialized. Lower blocking, but requires retry handling.

Snapshots in REPEATABLE READ are taken at the first data-access statement, not at BEGIN. There can be a gap:

BEGIN;
-- snapshot not yet taken
SELECT pg_sleep(5); -- another transaction commits here
-- snapshot taken here, includes the commit
SELECT balance FROM accounts WHERE id = 1;
BEGIN;
-- snapshot not yet taken
SELECT pg_sleep(5); -- another transaction commits here
-- snapshot taken here, includes the commit
SELECT balance FROM accounts WHERE id = 1;

FOR UPDATE with REPEATABLE READ can still generate serialization errors. If two transactions both attempt to update the same row under REPEATABLE READ, the second blocks on the lock. When the first commits, the second gets a “could not serialize access” error that must be handled with a retry.

Which isolation level to actually use

READ COMMITTED is correct for most OLTP workloads. Each operation is a short transaction. Non-repeatable reads and phantom reads are acceptable. Combine with FOR UPDATE on any read-modify-write cycle.

REPEATABLE READ when a transaction reads the same data multiple times and needs a consistent view throughout. Prevents non-repeatable reads, read skew, and in PostgreSQL, phantom reads. Does not prevent write skew.

SERIALIZABLE when you have business invariants that span multiple rows: inventory allocation where a total must not go negative, seat booking where the same seat cannot be booked twice, on-call scheduling where at least one doctor must remain available. Use it with a retry loop for serialization failures.

READ UNCOMMITTED has no practical use in PostgreSQL.

The most common mistake is defaulting to READ COMMITTED and writing read-modify-write logic without FOR UPDATE. That is a lost update waiting to happen under load. The second most common mistake is assuming REPEATABLE READ prevents write skew. It does not.

Published under Systems Engineering.