Interview Question: "Explain the difference between READ COMMITTED and REPEATABLE READ. What anomalies can occur at each isolation level? How does MVCC prevent dirty reads?" â Asked at JPMorgan, Goldman Sachs, Bloomberg for Senior Database roles
âšī¸
Difficulty: Advanced | Companies: JPMorgan, Goldman Sachs, Bloomberg, Citadel, Two Sigma | Time: 60-75 minutes
Isolation Levels Hierarchy
The SQL standard defines four isolation levels with increasing consistency:
| Level | Dirty Read | Non-Repeatable Read | Phantom Read | Serialization Anomaly |
|---|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible | Possible |
| READ COMMITTED | Prevented | Possible | Possible | Possible |
| REPEATABLE READ | Prevented | Prevented | Possible* | Possible |
| SERIALIZABLE | Prevented | Prevented | Prevented | Prevented |
*PostgreSQL prevents phantoms at REPEATABLE READ via predicate locking.
Four anomalies define that table. A dirty read observes a value that was never committed, so it can report money that does not exist. A non-repeatable read re-runs the same statement inside one transaction and gets a different answer because another session committed in between. A phantom changes the set of rows a predicate matches â the count moves even though no single row was rewritten. Write skew, which the SQL standard does not name, is the one that survives REPEATABLE READ: two transactions read disjoint rows and write disjoint rows, yet together they violate a rule neither could see.
PostgreSQL implements none of these levels with two-phase locking. Every statement reads a snapshot and writers leave the old row version in place, so readers never block writers and writers never block readers; the levels differ only in when the snapshot is taken and what happens when a transaction writes a row that changed after that snapshot. Keep that in mind when you compare manuals â MySQL's REPEATABLE READ is built on next-key locks while PostgreSQL's is built on snapshots, and the anomaly table above is the only part the two agree on.
-- Create banking example
CREATE TABLE accounts (
account_id INT PRIMARY KEY,
customer_name VARCHAR(100),
balance DECIMAL(15,2),
version INT DEFAULT 1
);
INSERT INTO accounts VALUES
(1, 'Alice', 10000.00, 1),
(2, 'Bob', 15000.00, 1),
(3, 'Charlie', 8000.00, 1);
-- Transaction isolation level settings
-- PostgreSQL default is READ COMMITTED
SHOW default_transaction_isolation;
-- Set isolation level for session
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- Or for next transaction only
BEGIN ISOLATION LEVEL SERIALIZABLE;
Dirty Read Demonstration
-- Session 1: READ UNCOMMITTED
BEGIN ISOLATION LEVEL READ UNCOMMITTED;
UPDATE accounts SET balance = 5000.00 WHERE account_id = 1;
-- Not committed yet
-- Session 2: READ UNCOMMITTED
BEGIN ISOLATION LEVEL READ UNCOMMITTED;
SELECT balance FROM accounts WHERE account_id = 1;
-- Returns 5000.00 (dirty read!)
-- Session 1: Rollback
ROLLBACK;
-- Session 2: Balance is now incorrect
-- Shows 5000.00 but actual is 10000.00
COMMIT;
Run that script against PostgreSQL and the surprising part is that it does not reproduce: the server accepts ISOLATION LEVEL READ UNCOMMITTED, reports it back from SHOW transaction_isolation, and then quietly implements it as READ COMMITTED. The second session reads the committed 10,000.00 because no uncommitted version is ever visible to another transaction. The demonstration above is what the SQL standard permits and what interviewers expect you to describe; engines that do implement dirty reads do it by reading the uncommitted tuple straight off the heap, and every anomaly that follows flows from that one design choice.
Non-Repeatable Read Demonstration
-- Session 1: READ COMMITTED
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT balance FROM accounts WHERE account_id = 1;
-- Returns 10000.00
-- Session 2: Update and commit
BEGIN;
UPDATE accounts SET balance = 12000.00 WHERE account_id = 1;
COMMIT;
-- Session 1: Same query, different result
SELECT balance FROM accounts WHERE account_id = 1;
-- Returns 12000.00 (non-repeatable read!)
COMMIT;
Under READ COMMITTED the snapshot belongs to the statement, not to the transaction, which is exactly why the second SELECT sees 12,000.00 while the first saw 10,000.00. The transaction is repeatable at the granularity of one query and not at the granularity of two. The same property is what lets a single query return rows that did not exist a moment earlier: nothing except the transaction's own writes is carried forward between statements, so every statement re-evaluates visibility against the current commit horizon.
Phantom Read Demonstration
-- Session 1: REPEATABLE READ
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT COUNT(*) FROM accounts WHERE balance > 9000;
-- Returns 2
-- Session 2: Insert new row
BEGIN;
INSERT INTO accounts VALUES (4, 'David', 11000.00, 1);
COMMIT;
-- Session 1: Same query, different count
SELECT COUNT(*) FROM accounts WHERE balance > 9000;
-- Returns 3 (phantom read!) in most databases
-- PostgreSQL returns 2 (prevents phantoms)
COMMIT;
PostgreSQL's REPEATABLE READ is snapshot isolation: one snapshot is taken when the first statement runs and held until COMMIT, so both counts come back as 2 no matter what other sessions committed in between. Read-only queries never fail at this level. The protection is not that conflicting writes are blocked â they are not â but that a write of our own to a row another transaction changed since our snapshot raises could not serialize access due to concurrent update with SQLSTATE 40001 instead of silently overwriting it. The application's only correct response to 40001 is to retry the whole transaction.
MVCC Implementation
Multi-Version Concurrency Control maintains multiple versions:
-- Check MVCC system columns
SELECT
ctid, -- Physical row location (page, offset)
xmin, -- Transaction ID that created this version
xmax, -- Transaction ID that deleted/updated this version (0 if not deleted)
account_id,
balance
FROM accounts
WHERE account_id = 1;
-- Update to create new version
UPDATE accounts SET balance = 11000.00 WHERE account_id = 1;
-- Check both versions
SELECT
ctid,
xmin,
xmax,
account_id,
balance
FROM accounts
WHERE account_id = 1;
-- Check transaction visibility
SELECT
txid_current() AS current_txid,
txid_visible_in_snapshot(xmin, txid_current_snapshot()) AS created_visible,
txid_visible_in_snapshot(xmax, txid_current_snapshot()) AS deleted_visible
FROM accounts
WHERE account_id = 1;
Visibility is decided by comparing transaction IDs against the snapshot taken when the query started: a row version is visible when its creating transaction had committed before the snapshot and its deleting transaction had not committed before it. Nothing is ever updated in place â UPDATE writes a new tuple with a fresh xmin and stamps the old one with an xmax â so a table where a hot row is rewritten two hundred times physically holds those versions side by side until vacuum removes the ones no live snapshot can reach.
That is the price of never blocking a reader, and it produces two operational consequences you will meet in production. Long-running transactions pin the oldest snapshot, which stops vacuum from reclaiming anything newer, so a forgotten session left open over a weekend can keep a fortnight of dead tuples alive and bloat every table it touched. And every transaction ID is eventually consumed, so age(datfrozenxid) in the monitoring query below is a countdown: when the oldest unfrozen ID approaches the 32-bit ceiling, autovacuum freezes aggressively to avoid wraparound, and if it cannot keep up the database refuses writes rather than risk losing visibility rules.
SERIALIZABLE with Serializable Snapshot Isolation (SSI)
PostgreSQL uses SSI for SERIALIZABLE:
-- SSI prevents write skew anomaly
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- Session 1: Check doctors on call
SELECT COUNT(*) FROM doctors
WHERE on_call = TRUE AND department = 'ER';
-- Returns 2
-- Session 2: Same check
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT COUNT(*) FROM doctors
WHERE on_call = TRUE AND department = 'ER';
-- Returns 2
-- Session 1: Remove one doctor (assuming another is on call)
UPDATE doctors SET on_call = FALSE
WHERE doctor_id = 1 AND department = 'ER';
COMMIT;
-- Session 2: Also removes a doctor (write skew!)
UPDATE doctors SET on_call = FALSE
WHERE doctor_id = 2 AND department = 'ER';
-- Serialization failure! Would violate constraint
COMMIT;
Write skew is the anomaly that survives REPEATABLE READ, and the doctors example shows precisely why. Each session reads a count of 2 and then decrements it; both commits succeed individually and the pair leaves 1 doctor on call when the rule required at least 2. Neither transaction wrote a row the other had read, so row-level locking never engages and snapshot isolation never notices. Serializable Snapshot Isolation closes the gap by recording read dependencies as edges between transactions and aborting one of them as soon as those edges would form a cycle in the serialization graph. PostgreSQL reports the abort as SQLSTATE 40001, the transaction's effects are rolled back, and the retry loop shown later in this lesson is the intended recovery. The practical cost is measurable: workloads that never conflict still pay for dependency tracking, which is why the comparison table later rates SERIALIZABLE as moderate rather than free.
Lock-Based Concurrency Control
-- Explicit locking
BEGIN;
-- Row-level lock
SELECT * FROM accounts WHERE account_id = 1 FOR UPDATE;
-- Other transactions block on this row
-- Share lock (allows reads, blocks writes)
SELECT * FROM accounts WHERE account_id = 1 FOR SHARE;
-- No-wait lock (fail immediately if locked)
SELECT * FROM accounts WHERE account_id = 1 FOR UPDATE NOWAIT;
-- Skip locked (skip rows that are locked)
SELECT * FROM accounts WHERE account_id = 1 FOR UPDATE SKIP LOCKED;
-- Advisory locks (application-level)
SELECT pg_advisory_lock(12345); -- Acquire
SELECT pg_try_advisory_lock(12345); -- Try acquire
SELECT pg_advisory_unlock(12345); -- Release
COMMIT;
NOWAIT and SKIP LOCKED are the two answers to contention on a shared queue, and they encode different policies. NOWAIT fails immediately with SQLSTATE 55P03 so the caller decides what happens next â useful when a lock that cannot be taken quickly means the request is already stale. SKIP LOCKED lets a hundred workers pull disjoint items from one table without any of them waiting, which is the standard PostgreSQL job-queue pattern and the reason queue tables rarely need a status column any more.
Advisory locks are different in kind: they protect something the database cannot see, such as a nightly import that must not run twice across replicas. The session-level form survives until it is explicitly released or the connection drops, the transaction-level form releases at COMMIT, and mixing the two on the same key is a common source of locks that appear never to expire â the transaction-level call returns, the session-level one quietly holds the key, and every later attempt blocks.
Deadlock Detection and Prevention
-- Create deadlock scenario
-- Session 1
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
-- Wait for session 2 to release lock on account 2
-- Session 2
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 2;
-- Wait for session 1 to release lock on account 1
-- DEADLOCK! One session will be rolled back
-- Check for deadlocks
SELECT * FROM pg_stat_activity WHERE wait_event_type = 'Lock';
-- Set deadlock timeout
SET deadlock_timeout = '1s';
Detection is graph-based rather than timer-based, and deadlock_timeout is easy to misread: it is not how long a deadlock lasts, it is how long a transaction must wait before the server bothers to look for a cycle at all. Once a wait crosses that threshold the lock manager walks the wait graph, and a cycle means one session is chosen as the victim and rolled back with SQLSTATE 40P01. Raising the timeout does not prevent deadlocks â it only delays the moment they are noticed, which usually makes p99 latency worse rather than better.
The prevention rule that removes the class entirely is lock ordering: if every code path acquires accounts in ascending account_id order, the cycle in the example cannot form, no matter how the sessions interleave. Where ordering is impractical, keep transactions short so lock hold times shrink, and treat a rising deadlocks counter in pg_stat_database as an application bug rather than a database tuning problem.
Optimistic Concurrency Control
-- Version-based OCC
CREATE TABLE products (
product_id INT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2),
version INT DEFAULT 1
);
-- Optimistic update pattern
WITH current_version AS (
SELECT version FROM products WHERE product_id = 1
)
UPDATE products
SET price = 29.99, version = version + 1
WHERE product_id = 1
AND version = (SELECT version FROM current_version)
RETURNING *;
-- If no rows updated, version changed by another transaction
The zero-row result is the whole signal: UPDATE reports how many rows matched, and a count of 0 means the version moved between the read and the write, so the caller simply retries against fresh state. Optimistic control suits read-heavy work where conflicts are rare â most attempts succeed on the first try, and no lock is ever held across a network call. It degrades badly once contention is genuine: a hot row updated a thousand times a second produces a thousand wasted reads before the winner is known, and pessimistic SELECT ... FOR UPDATE is cheaper overall. The deciding number is the conflict rate, not the transaction length.
Isolation Level Comparison Table
| Feature | READ COMMITTED | REPEATABLE READ | SERIALIZABLE |
|---|---|---|---|
| Lock Duration | Statement | Transaction | Transaction |
| MVCC Snapshot | Per statement | Per transaction | Per transaction |
| Phantoms | Allowed | Prevented | Prevented |
| Write Skew | Allowed | Allowed | Prevented |
| Performance | Best | Good | Moderate |
| Use Case | OLTP general | Reporting | Financial |
âšī¸
PostgreSQL REPEATABLE READ: Uses snapshot isolation, not traditional locking. Prevents phantoms via predicate locking, unlike MySQL/Oracle.
Advanced: Gap Locking
-- Gap locks prevent inserts in range
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- Lock gap between 100 and 200
SELECT * FROM accounts
WHERE account_id BETWEEN 100 AND 200 FOR UPDATE;
-- Other transactions cannot insert account_id in (100, 200)
-- This prevents phantom reads
INSERT INTO accounts VALUES (150, 'New', 5000.00, 1);
-- Blocks until first transaction commits
COMMIT;
Mathematical Formulation
For a set of transactions :
The serialization graph where:
- (transactions as vertices)
- if should come before
â ī¸
Performance Impact: SERIALIZABLE can cause up to 10% throughput reduction due to aborts. Monitor with pg_stat_database conflicts.
Monitoring and Diagnostics
-- Check current locks
SELECT
l.pid,
l.mode,
l.granted,
a.query,
a.state
FROM pg_locks l
JOIN pg_stat_activity a ON l.pid = a.pid
WHERE l.relation = 'accounts'::regclass;
-- Check transaction ID wraparound
SELECT
datname,
age(datfrozenxid) AS xid_age,
2^31 - age(datfrozenxid) AS transactions_until_wraparound
FROM pg_database;
-- Monitor serialization failures
SELECT
datname,
conflicts,
deadlocks,
conflicts_bet_rol
FROM pg_stat_database
WHERE datname = current_database();
âšī¸
Pro Tip: Use SET LOCAL to change isolation level for current transaction only. This is useful for mixed workloads.
Best Practices
- Use READ COMMITTED for most OLTP workloads
- Use SERIALIZABLE for financial transactions
- Implement retry logic for serialization failures
- Monitor lock contention with pg_stat_activity
- Avoid long-running transactions to reduce MVCC overhead
-- Retry pattern for serialization failures
DO $$
DECLARE
max_retries INT := 3;
retry_count INT := 0;
BEGIN
LOOP
BEGIN
-- Your transaction here
PERFORM transfer_funds(1, 2, 100);
EXIT; -- Success
EXCEPTION
WHEN serialization_failure OR deadlock_detected THEN
retry_count := retry_count + 1;
IF retry_count >= max_retries THEN
RAISE;
END IF;
PERFORM pg_sleep(random() * 0.1);
END;
END LOOP;
END $$;
A retry loop needs three properties to be safe in production. The retry must wrap the whole transaction, not just the statement that raised the error, because the snapshot it read against is already stale. The delay must include randomness, so two sessions that collided once do not wake together and collide again on the next attempt â a fixed 100 ms sleep converts one serialization failure into a repeating pattern of them. And the attempt count must be bounded, so a genuinely hot row fails loudly with a clear error instead of holding the request open until a proxy times it out.
Key Takeaways
- READ COMMITTED takes a fresh snapshot per statement, REPEATABLE READ takes one per transaction, and PostgreSQL accepts READ UNCOMMITTED but implements it as READ COMMITTED
- MVCC never rewrites a tuple in place, so every UPDATE leaves a version behind and a long-running transaction pins dead tuples until the oldest snapshot moves
- SERIALIZABLE layers Serializable Snapshot Isolation onto snapshots: read dependencies form a serialization graph, a cycle aborts one side with SQLSTATE 40001, and the only recovery is retrying
- Deadlocks are found by walking the wait graph after deadlock_timeout expires, which means consistent lock ordering in the application removes the entire class of failure