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.
The 60-second answer
Section titled “The 60-second answer”“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.”
ACID, precisely
Section titled “ACID, precisely”| 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.
Isolation levels and anomalies
Section titled “Isolation levels and anomalies”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 = 0begin Order.transaction(isolation: :serializable) { place_order! }rescue ActiveRecord::SerializationFailure attempts += 1 retry if attempts < 3 raiseendLost update, concretely
Section titled “Lost update, concretely”Three fixes, in increasing strength:
- Atomic update —
UPDATE accounts SET balance = balance - 10 WHERE id = 1; - Pessimistic lock —
SELECT ... FOR UPDATEserialises the read-modify-write. - Optimistic lock —
UPDATE ... WHERE id = 1 AND version = 7, retry if zero rows matched.
Row locks
Section titled “Row locks”SELECT * FROM accounts WHERE id = 1 FOR UPDATE; -- write lock, blocks other writersSELECT * FROM accounts WHERE id = 1 FOR NO KEY UPDATE; -- weaker: does not block FK checksSELECT * FROM accounts WHERE id = 1 FOR SHARE; -- shared: blocks writers, not readersLocks 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.
Deadlocks
Section titled “Deadlocks”-- A -- BBEGIN; 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 AThe database detects the cycle after a short timeout and aborts one transaction. It does not prevent the situation; you do:
- Acquire locks in a deterministic order — sort ids ascending before locking.
- Keep transactions short. No HTTP calls, sleeps or user interaction inside a transaction.
- Lock the fewest rows possible — a filtered
FOR UPDATE, not the whole table. - 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.
Optimistic vs pessimistic
Section titled “Optimistic vs pessimistic”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.
Follow-up questions
Section titled “Follow-up questions”- Which anomalies does PostgreSQL’s
READ COMMITTEDstill allow? - Why does
REPEATABLE READnot prevent write skew, and what does? - What does a serialization failure look like, and how should the application respond?
- Why is
UPDATE ... SET balance = balance - 10safer than read-then-write? - How do you avoid deadlocks, and what does the database do when one happens?
- When would you choose optimistic over pessimistic locking?
Common traps
Section titled “Common traps”- Assuming
READ COMMITTEDgives repeatable reads. TwoSELECTs in one transaction can disagree. - Assuming
REPEATABLE READis 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.