Skip to content

Transactions

A transaction promises that a group of statements either all happened or none did. Isolation is the separate promise about what other concurrent transactions see while yours is in flight. Most candidates can recite ACID; far fewer can say which anomaly READ COMMITTED still allows — the question that matters when two requests touch the same row.

“Atomicity is all-or-nothing, consistency means constraints hold at commit, isolation means concurrent transactions do not see each other’s partial work, durability means a commit survives a crash. Isolation is not free, so SQL defines four levels, each permitting different anomalies. PostgreSQL defaults to READ COMMITTED, which prevents dirty reads but allows non-repeatable reads, phantoms and lost updates. REPEATABLE READ gives a stable snapshot but still allows write skew; only SERIALIZABLE prevents it, by aborting conflicting transactions with a serialization failure you must retry. Locking is the manual tool: SELECT ... FOR UPDATE for a pessimistic read-modify-write, a version column for optimistic concurrency. Deadlocks come from acquiring locks in different orders and are resolved by killing one transaction.”

Property Guarantee What breaks it
Atomicity All statements commit or none Application-level multi-step logic outside a transaction
Consistency Constraints and invariants hold at commit Application invariants the database cannot see
Isolation Concurrent transactions behave as if serial Choosing a weak level and assuming otherwise
Durability Committed data survives a crash synchronous_commit = off, fsync disabled

The nuance interviewers like: consistency is mostly your job. The database enforces declared constraints; “the ledger sums to the balance” is only guaranteed if expressed as a constraint or checked inside the same transaction.

BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
COMMIT;
Anomaly What happens
Dirty read You read another transaction’s uncommitted write
Non-repeatable read You read the same row twice and it changed
Phantom read You run the same query twice and new rows appeared
Lost update Two transactions read, both write, one overwrites the other
Write skew Each transaction reads a set, writes based on it, an invariant breaks
Level Dirty read Non-repeatable Phantom Lost update Write skew
Read Uncommitted Treated as Read Committed in PostgreSQL — — — —
Read Committed No Yes Yes Yes Yes
Repeatable Read No No No in PostgreSQL No Yes
Serializable No No No No No

Two facts worth memorising: PostgreSQL defaults to READ COMMITTED; MySQL/InnoDB defaults to REPEATABLE READ. And PostgreSQL’s SERIALIZABLE uses Serializable Snapshot Isolation, so it does not block — it aborts with 40001 serialization_failure, and correct code retries the whole transaction.

attempts = 0
begin
Order.transaction(isolation: :serializable) { place_order! }
rescue ActiveRecord::SerializationFailure
attempts += 1
retry if attempts < 3
raise
end

Three fixes, in increasing strength:

  1. Atomic update — UPDATE accounts SET balance = balance - 10 WHERE id = 1;
  2. Pessimistic lock — SELECT ... FOR UPDATE serialises the read-modify-write.
  3. Optimistic lock — UPDATE ... WHERE id = 1 AND version = 7, retry if zero rows matched.
SELECT * FROM accounts WHERE id = 1 FOR UPDATE; -- write lock, blocks other writers
SELECT * FROM accounts WHERE id = 1 FOR NO KEY UPDATE; -- weaker: does not block FK checks
SELECT * FROM accounts WHERE id = 1 FOR SHARE; -- shared: blocks writers, not readers

Locks are held until COMMIT or ROLLBACK. FOR UPDATE on a row that does not exist locks nothing, so a concurrent insert is not prevented — that is what SERIALIZABLE or a unique index is for. Table locks (LOCK TABLE ... IN ACCESS EXCLUSIVE MODE) block everything including reads and belong in migrations, not application logic. Advisory locks (pg_advisory_lock) are application-defined and useful for “only one worker at a time”, but they are not tied to rows and leak if a session dies.

-- A -- B
BEGIN; BEGIN;
UPDATE accounts ... WHERE id = 1;
UPDATE accounts ... WHERE id = 2;
UPDATE accounts ... WHERE id = 2; -- waits for B
UPDATE accounts ... WHERE id = 1; -- waits for A

The database detects the cycle after a short timeout and aborts one transaction. It does not prevent the situation; you do:

  1. Acquire locks in a deterministic order — sort ids ascending before locking.
  2. Keep transactions short. No HTTP calls, sleeps or user interaction inside a transaction.
  3. Lock the fewest rows possible — a filtered FOR UPDATE, not the whole table.
  4. Retry on deadlock (40P01), exactly as you retry serialization failures.

In PostgreSQL a long transaction also blocks vacuum from cleaning dead rows, which bloats tables and degrades every query. “Keep transactions short” is a storage argument as well as a contention one.

Pessimistic (FOR UPDATE) Optimistic (version column)
Mechanism Database lock WHERE version = ?, retry on mismatch
Contention Waiters queue; throughput drops No waiting; conflicts surface as errors
Good for High contention, short critical sections, money Low contention, long user think-time
Cost Hold a lock for the whole transaction Application must retry conflicts

Rule of thumb: pessimistic when the window is short and contention is high; optimistic when the window includes a human. An edit form open for ten minutes must not hold a row lock for ten minutes.

  1. Which anomalies does PostgreSQL’s READ COMMITTED still allow?
  2. Why does REPEATABLE READ not prevent write skew, and what does?
  3. What does a serialization failure look like, and how should the application respond?
  4. Why is UPDATE ... SET balance = balance - 10 safer than read-then-write?
  5. How do you avoid deadlocks, and what does the database do when one happens?
  6. When would you choose optimistic over pessimistic locking?
  • Assuming READ COMMITTED gives repeatable reads. Two SELECTs in one transaction can disagree.
  • Assuming REPEATABLE READ is serializable. Write skew survives it.
  • Read-modify-write without a lock. The lost update above.
  • Long transactions in the request path. Locks held across a call to a payment provider.
  • Not retrying serialization or deadlock errors. They are normal outcomes, not bugs.
  • Locking rows in a user-dependent order. Two users clicking in different orders is a deadlock generator.