Isolation Levels
Dirty reads, non-repeatable reads, phantoms, lost updates and write skew; the SQL isolation levels and what PostgreSQL and MySQL really do; snapshot isolation and serializability.
Perfect isolation — every transaction behaving as if it ran alone — is expensive. Databases offer weaker isolation levels that allow certain anomalies in exchange for more concurrency. Many real bugs (double-booked seats, negative balances, oversold inventory) come from not knowing which anomalies your level permits.
The anomalies
| Anomaly | What happens |
|---|---|
| Dirty read | T1 reads T2's uncommitted change; T2 rolls back, so T1 saw data that never existed |
| Non-repeatable read | T1 reads a row twice and gets different values because T2 committed an update in between |
| Phantom read | T1 runs the same range query twice and gets different rows because T2 inserted or deleted matching rows |
| Lost update | T1 and T2 both read a value, both compute a new one, both write; one update is silently overwritten |
| Write skew | T1 and T2 read overlapping data, make decisions, and write different rows; each write is fine alone, but together they break an invariant |
Lost update
Write skew
Rule: at least one doctor must be on call. Alice and Bob are both on call; both request leave at the same moment.
No row was written by both transactions, so row locks or "first committer wins" checks don't catch it.
The SQL standard levels
| Level | Dirty read | Non-repeatable read | Phantom |
|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible |
| Read Committed | ✗ | Possible | Possible |
| Repeatable Read | ✗ | ✗ | Possible (per the standard) |
| Serializable | ✗ | ✗ | ✗ — and no write skew: equivalent to some serial order |
What real databases do
| Database | Default | Notes |
|---|---|---|
| PostgreSQL | Read Committed | Repeatable Read is snapshot isolation (no phantoms; write skew possible). Serializable is SSI: true serializability with aborts on conflict |
| MySQL InnoDB | Repeatable Read | Consistent snapshot for plain reads; locking reads (FOR UPDATE) see the latest data and take gap/next-key locks to block phantoms |
| Oracle | Read Committed | "Serializable" is snapshot isolation |
| SQL Server | Read Committed (locking) | Optional snapshot isolation (READ_COMMITTED_SNAPSHOT) |
| CockroachDB | Serializable | Distributed SSI |
Fixing the anomalies in practice
Lost updates
-- 1. Atomic update: let the database do the read-modify-write
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock > 0;
-- 2. Pessimistic: lock the row while deciding
BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE;
UPDATE products SET stock = 9 WHERE id = 42;
COMMIT;
-- 3. Optimistic: version column, retry if someone else won
UPDATE products SET stock = 9, version = version + 1
WHERE id = 42 AND version = 7; -- 0 rows updated → reload and retryWrite skew
- Run the transaction at SERIALIZABLE and retry on serialisation failure (the cleanest fix in PostgreSQL and CockroachDB).
- Or lock the rows the decision depends on:
SELECT … FROM doctors WHERE on_call FOR UPDATE. - Or materialise the conflict: create a row both transactions must update (a per-shift row), or use a constraint (a unique index on bookings for the same room and time slot).
for (int attempt = 1; ; attempt++) {
try {
tx.execute(status -> { bookSeat(userId, seatId); return null; });
break;
} catch (CannotSerializeTransactionException | DeadlockLoserDataAccessException e) {
if (attempt == 5) throw e;
Thread.sleep((long) (Math.random() * 50 * attempt)); // jittered backoff
}
}from psycopg import errors
for attempt in range(5):
try:
with conn.transaction():
conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
book_seat(conn, user_id, seat_id)
break
except (errors.SerializationFailure, errors.DeadlockDetected):
time.sleep(random.random() * 0.05 * (attempt + 1))
else:
raise RuntimeError("could not book seat")for (let attempt = 1; ; attempt++) {
try {
await db.tx({ isolation: "serializable" }, (t) => bookSeat(t, userId, seatId));
break;
} catch (e: any) {
// 40001 = serialization_failure, 40P01 = deadlock_detected (PostgreSQL)
if (!["40001", "40P01"].includes(e.code) || attempt === 5) throw e;
await new Promise((r) => setTimeout(r, Math.random() * 50 * attempt));
}
}- Anomalies: dirty read, non-repeatable read, phantom, lost update, write skew.
- Levels: Read Uncommitted < Read Committed < Repeatable Read < Serializable.
- Postgres defaults to Read Committed, MySQL to Repeatable Read; "Repeatable Read" is often snapshot isolation.
- Snapshot isolation still allows write skew; Serializable (SSI) prevents it but requires retries.
- Fix lost updates with atomic updates, FOR UPDATE, or optimistic versioning.
QTwo users try to book the last seat at the same time. How do you prevent double booking?medium
Make the database enforce it: a unique constraint on (event_id, seat_id) in the bookings table, or a conditional atomic update (UPDATE seats SET booked_by = ? WHERE id = ? AND booked_by IS NULL and check the affected row count). Alternatively lock the seat row with SELECT … FOR UPDATE, or use SERIALIZABLE isolation with retries.
QWhat's the difference between repeatable read and serializable?hard
Repeatable read guarantees a row you've read won't change underneath you (typically via a snapshot). Serializable additionally guarantees the overall result equals some serial execution, which rules out phantoms (in the strict standard) and write skew, where transactions read overlapping data and write different rows.