Overview
Curated: · Written: · Reviewed:
Transactions & Isolation Levels
In one line
A transaction makes a group of statements commit or roll back together, and the isolation level decides which concurrent changes each statement can see. Reach for it whenever several statements must agree, and choose the weakest level whose anomalies your invariant can survive.
Key definitions
- Atomicity: all statements take effect or none do. A rollback leaves no partial work.
- Consistency: the commit moves the database between states that satisfy its declared constraints. Business rules the schema does not declare are not enforced.
- Durability: a commit is acknowledged only after the change reaches the write-ahead log.
- Lost update: two read-modify-write cycles where the second write silently discards the first.
- Write skew: two transactions read overlapping rows, each check passes, and their disjoint writes break an invariant neither saw.
- Serialization failure (SQLSTATE 40001): the database aborted the transaction because it lost a race. Re-run the whole transaction.
Formulas and complexity
Worked example for the 25 MCQ, hypothetical figures: let be first attempts per second. Retries are , so and . Every retry commits, so committed throughput is 4,000 per second, not 5,000.
How it works
- Under read committed, each statement reads a snapshot taken when that statement starts. Repeatable read and serializable use one snapshot, taken at the first statement.
- At repeatable read, updating a row that another transaction committed after your snapshot raises 40001. It does not overwrite.
- Serializable tracks read/write dependencies and aborts one transaction in any cycle that no serial order would produce.
- A row lock from
UPDATEorSELECT ... FOR UPDATEis held until commit or rollback. Other writers wait for it. ROLLBACK TO SAVEPOINTundoes only the work after that savepoint. The rest of the transaction still commits.
When to use and when not to
| Situation | Choice | Why |
|---|---|---|
| Counter or balance change | One atomic UPDATE ... SET x = x + n | No read-modify-write window |
| Read-modify-write on one row, read committed | SELECT ... FOR UPDATE first | Serializes the read and the write |
| Invariant across rows nobody locks (on-call rota, room capacity) | SERIALIZABLE with retry | Snapshots alone allow write skew |
| Multi-statement read over a stable snapshot | REPEATABLE READ | One snapshot for the whole transaction |
| Work queue | FOR UPDATE SKIP LOCKED | Workers claim different rows without queueing |
| External API call | Do not hold the transaction open | The call holds locks and blocks vacuum |
Traps interviewers probe
- Using a savepoint for atomicity. In the MCQ 1 case,
ROLLBACK TO SAVEPOINT after_debitkeeps the debit and undoes the credit, so the money leaves A and never reaches B. Fix: roll back the whole transaction, and use savepoints only to skip work you can afford to lose. - Read in application code, write later. Under read committed, two workers both read 100 and write 90. Fix:
UPDATE counters SET value = value + 1 WHERE id = $1, or lock the row withFOR UPDATEbefore computing. - Retrying a transaction that already did external work. A charge or email sent inside the block repeats on every retry. Fix: move the call after commit, or into an outbox worker that runs once per committed row.
- Assuming repeatable read prevents write skew. The on-call rota passes both checks and leaves nobody on duty. Fix: serializable with a retry loop, or lock the rows the check reads.
- Treating a rejected update as a business guarantee. A
CHECK (balance >= 0)stops overdraft, but a second-approver rule enforced only in code is not protected. Fix: declare every rule the schema can express, and enforce the rest deliberately.
Interview tips
Opening: "A transaction gives atomicity, consistency against declared constraints, isolation at the chosen level, and durability through the write-ahead log. Which anomaly matters depends on the invariant I am protecting."
Follow-ups to expect:
- Why does read committed lose updates? A blocked
UPDATEre-reads the row after the other commit and re-evaluates itsWHEREagainst the new value, so a condition likebalance >= 100can match nothing. - How does serializable retry work? Re-run the whole body, bound the attempts, and back off between them.
- Why are long transactions dangerous? An open transaction stops vacuum from removing old row versions. Find them with
pg_stat_activityandxact_start. - How do deadlocks get prevented? Acquire locks in one fixed order, and retry on 40P01.
- When is a savepoint useful? To recover from one failed statement without aborting the whole transaction.
30-second answer: "Transactions make a set of statements atomic and durable, and the isolation level decides which anomalies I accept. For a counter I use one atomic UPDATE. For an invariant spanning rows, I use serializable and retry the whole transaction on 40001 with bounded backoff, with side effects after commit. I keep transactions short and never hold one open across a network call."
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.