Skip to content

Transactions and Concurrency ​

Pick an isolation level on purpose, and stop the lost update that read-committed will not stop for you.

In this chapter: what ACID actually promises · the four isolation levels and their anomalies · optimistic against pessimistic locking · deadlocks · transactions in application code

💡 The Core Idea ​

A transaction turns several statements into one indivisible operation: all of them happen, or none of them do. That is the easy half, and it is not what interviews are about.

The hard half is concurrency. Your transaction is not running alone, and the isolation level decides what it may see of everyone else's in-flight work. The default in Postgres and most engines is READ COMMITTED. It prevents dirty reads but permits lost updates. So read-modify-write logic written without care is silently wrong under load, and correct in every test that runs one request at a time.

What ACID Promises ​

PropertyPromiseDelivered by
AtomicityAll statements commit or none doThe write-ahead log and rollback
ConsistencyConstraints hold at commitYour constraints — the database only enforces what you declared
IsolationConcurrent transactions do not corrupt each otherMVCC and locks, to the degree the isolation level specifies
DurabilityA committed write survives a crashfsync of the write-ahead log

Consistency is the one people misstate. The database does not know your business rules. It enforces the constraints you wrote. An AND you forgot in a CHECK is not an isolation problem.

Isolation Levels ​

LevelDirty readNon-repeatable readPhantom readLost update
READ UNCOMMITTEDPossiblePossiblePossiblePossible
READ COMMITTED (default)NoPossiblePossiblePossible
REPEATABLE READNoNoNo (in Postgres)Detected — the transaction aborts
SERIALIZABLENoNoNoNo
  • Dirty read — seeing another transaction's uncommitted write. Postgres never allows this at any level.
  • Non-repeatable read — reading the same row twice inside one transaction and getting different values, because someone committed in between.
  • Phantom read — re-running a query and finding new rows. Postgres's snapshot isolation prevents this at REPEATABLE READ, which the SQL standard does not require.
  • Lost update — two transactions read the same value, both compute from it, and the second write overwrites the first.

Postgres implements REPEATABLE READ as snapshot isolation: your transaction sees the database as of its first statement. A conflicting write is detected when it runs and raises a serialisation failure. So any application using it must be prepared to retry.

The Lost Update ​

sql
-- Two concurrent transactions, READ COMMITTED. Stock starts at 10.
-- T1: SELECT stock FROM products WHERE id = 1;   -- 10
-- T2: SELECT stock FROM products WHERE id = 1;   -- 10
-- T1: UPDATE products SET stock = 9 WHERE id = 1;
-- T2: UPDATE products SET stock = 9 WHERE id = 1;  -- one sale vanished

Three fixes, in increasing order of cost:

1. Do the arithmetic in the database. Correct, cheapest, and the answer whenever the new value is a function of the old one.

sql
UPDATE products SET stock = stock - 1 WHERE id = $1 AND stock >= 1;
-- Zero rows affected means insufficient stock. The row lock is held only for this statement.

2. Optimistic locking — a version column. No lock is held, so it scales. The loser retries.

sql
UPDATE products SET stock = $1, version = version + 1
WHERE id = $2 AND version = $3;
-- Zero rows affected means someone else committed first: re-read and retry.

3. Pessimistic locking — SELECT … FOR UPDATE takes a row lock until the transaction ends.

sql
BEGIN;
SELECT stock FROM products WHERE id = $1 FOR UPDATE; -- other writers block here
UPDATE products SET stock = $2 WHERE id = $1;
COMMIT;
ApproachUse whenCost
In-database arithmeticThe new value derives from the old oneNone — always prefer it
Optimistic (version column)Conflicts are rare; a long think-time between read and writeRetry logic, and a user-visible conflict
Pessimistic (FOR UPDATE)Conflicts are common; the work between read and write is shortBlocked writers; deadlock risk

FOR UPDATE SKIP LOCKED is the variant worth knowing. It is how you build a work queue on a SQL table. Each worker claims rows nobody else holds, instead of queueing behind them.

Deadlocks ​

Two transactions each hold what the other needs. The database detects the cycle and kills one with a deadlock error.

text
T1: locks row A → waits for row B
T2: locks row B → waits for row A

The prevention is boringly effective: always take locks in a consistent order. If every transfer locks the lower account id first, the cycle cannot form.

typescript
const [first, second] = [fromId, toId].sort(); // Deterministic order, no cycle possible.
await tx.query('SELECT 1 FROM accounts WHERE id = $1 FOR UPDATE', [first]);
await tx.query('SELECT 1 FROM accounts WHERE id = $1 FOR UPDATE', [second]);

Keep transactions short for the same reason. A long transaction holds locks longer, widening every window for conflict. And never do anything slow inside one.

Transactions in Application Code ​

typescript
async function transfer(fromId: string, toId: string, amount: number): Promise<void> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const { rowCount } = await client.query(
      'UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1',
      [amount, fromId],
    );
    if (rowCount === 0) throw new AppError('Insufficient funds', 409, 'insufficient_funds');

    await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, toId]);
    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release(); // Without this, the pool leaks a connection per call.
  }
}

Three rules this shows:

  • One client for the whole transaction. Statements issued through the pool land on different connections and are therefore different transactions.
  • ROLLBACK in catch, release in finally. A missing release exhausts the pool, and the symptom is the whole service hanging.
  • Never await an HTTP call inside a transaction. A 30-second timeout becomes a 30-second lock.

⚠️ Retrying a serialisation failure is mandatory at REPEATABLE READ and SERIALIZABLE. Retry the whole transaction, not the failed statement, and cap the attempts.

Savepoints give partial rollback inside a transaction. They help when one optional step may fail without invalidating the rest. In Postgres, any error aborts the whole transaction unless a savepoint was set. So a try/catch around one statement without a savepoint does not let you continue.

🔑 Key Takeaways ​

  • READ COMMITTED is the default and it permits lost updates, so read-modify-write needs explicit protection.
  • Prefer arithmetic in the UPDATE statement. It is correct and free.
  • Optimistic locking scales and needs retry logic. Pessimistic locking blocks and needs short transactions.
  • Take locks in a deterministic order and deadlocks cannot form.
  • Any code at REPEATABLE READ or above must retry serialisation failures.

Interview Questions ​

Q: What is a lost update, and does the default isolation level prevent it?

Two transactions read the same value, each computes a new one from it, and the second write overwrites the first. One update disappears. READ COMMITTED does not prevent it: both reads are legal and both writes are legal. You need in-database arithmetic, a version check, or a row lock.

Q: Optimistic or pessimistic locking?

Optimistic when conflicts are rare or the gap between read and write is long. An edit form open for ten minutes should not hold a lock. Pessimistic when conflicts are frequent and the work between read and write is short, because retry storms cost more than brief blocking. Optimistic pushes the conflict to the user. Pessimistic pushes latency onto other writers.

Q: How do you prevent deadlocks?

Take locks in a consistent order across all code paths, keep transactions short, and touch as few rows as possible. The database detects a deadlock and kills one transaction, so the application still needs to retry. Lock ordering is what stops the cycle forming in the first place.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.