← Back to Backend, page 2

backend-0030 · Medium mid

What are the transaction isolation levels and the anomalies they prevent (dirty read, non-repeatable read, phantom), and how does PostgreSQL behave at READ COMMITTED and REPEATABLE READ?

Isolation levels trade correctness for concurrency. READ COMMITTED (the PostgreSQL default) shows each statement the data committed before that statement began, so the same query can return different results inside one transaction (non-repeatable read). REPEATABLE READ uses one snapshot for the whole transaction, so reads are stable, and PostgreSQL aborts a transaction that tries to update a row changed since its snapshot (serialization failure 40001). SERIALIZABLE adds detection of other anomalies such as write skew. PostgreSQL never allows dirty reads.

Full answer

Anomalies

  • Dirty read: reading data another transaction has not committed. PostgreSQL does not allow it at any level (READ UNCOMMITTED behaves like READ COMMITTED).
  • Non-repeatable read: reading the same row twice and seeing a changed value because another transaction committed in between.
  • Phantom read: running the same range query twice and seeing new rows. (PostgreSQL REPEATABLE READ prevents this too, because it uses a snapshot.)
  • Lost update and write skew: two transactions read, then write based on stale reads. Need locks, atomic updates, version checks or SERIALIZABLE.

Levels in PostgreSQL (MVCC, readers do not block writers)

  • READ COMMITTED: a new snapshot per statement. UPDATE waits for a conflicting row lock, then re-checks the row.
  • REPEATABLE READ: one snapshot per transaction. A write to a row that changed after the snapshot fails with SQLSTATE 40001, and the application retries the transaction.
  • SERIALIZABLE: guarantees results as if transactions ran one at a time, using predicate tracking. It can abort transactions with 40001, so every write path needs retry logic.

Choosing: READ COMMITTED with explicit locking or atomic SQL is common. Use REPEATABLE READ for consistent reports. Use SERIALIZABLE when invariants span several rows and you accept retries.

javascript
const { Client } = require('pg');

(async () => {
  const a = new Client(), b = new Client();
  await Promise.all([a.connect(), b.connect()]);
  const reset = () => a.query('DROP TABLE IF EXISTS bk30_acct; CREATE TABLE bk30_acct (id int PRIMARY KEY, balance int); INSERT INTO bk30_acct VALUES (1, 100)');
  const read = async (c) => (await c.query('SELECT balance FROM bk30_acct WHERE id = 1')).rows[0].balance;

  // 1. No dirty reads: B does not see A's uncommitted update.
  await reset();
  await a.query('BEGIN'); await a.query('UPDATE bk30_acct SET balance = 10 WHERE id = 1');
  console.log('1. B reads while A is uncommitted :', await read(b), '(no dirty read)');
  await a.query('ROLLBACK');

  // 2. READ COMMITTED: a non-repeatable read.
  await reset();
  await a.query('BEGIN ISOLATION LEVEL READ COMMITTED');
  const first = await read(a);
  await b.query('UPDATE bk30_acct SET balance = 70 WHERE id = 1');                 // B commits (autocommit)
  const second = await read(a);
  await a.query('COMMIT');
  console.log('2. READ COMMITTED reads           :', first, 'then', second, '(non-repeatable read)');

  // 3. REPEATABLE READ: the snapshot is stable, and a conflicting write fails.
  await reset();
  await a.query('BEGIN ISOLATION LEVEL REPEATABLE READ');
  const r1 = await read(a);
  await b.query('UPDATE bk30_acct SET balance = 70 WHERE id = 1');
  const r2 = await read(a);
  console.log('3. REPEATABLE READ reads          :', r1, 'then', r2, '(same snapshot)');
  try { await a.query('UPDATE bk30_acct SET balance = balance + 1 WHERE id = 1'); console.log('   update succeeded'); }
  catch (err) { console.log('   update after a concurrent change  :', err.code, '-', err.message); }
  await a.query('ROLLBACK');

  await a.query('DROP TABLE bk30_acct');
  await Promise.all([a.end(), b.end()]);
})();

Two connections are interleaved by hand against the local PostgreSQL server. The order of statements is fixed, so the anomalies appear every time. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. B reads while A is uncommitted : 100 (no dirty read) 2. READ COMMITTED reads : 100 then 70 (non-repeatable read) 3. REPEATABLE READ reads : 100 then 100 (same snapshot) update after a concurrent change : 40001 - could not serialize access due to concurrent update

Key points

  • Higher isolation means fewer anomalies and more aborts or waiting.
  • PostgreSQL has no dirty reads at any level.
  • READ COMMITTED can show different data to two statements in one transaction.
  • REPEATABLE READ gives a stable snapshot and may raise 40001.
  • Applications must retry serialization failures.

Common mistakes

  • Assuming the default level protects against lost updates.
  • Not retrying after SQLSTATE 40001.
  • Running long reports at READ COMMITTED and expecting a consistent view.
  • Using SERIALIZABLE without retry code.
  • Believing that the SQL standard names describe every database in the same way.

Follow-ups

  • What is MVCC?
  • How does READ COMMITTED treat an UPDATE that waits on a locked row?
  • When would you use SERIALIZABLE?

Tips

  • Name the anomalies with one-line examples.
  • State PostgreSQL's default and its behaviour.
  • Mention retries.