Transactions, Concurrency Control, and Isolation Levels Questions
How a database engine manages concurrent access from multiple transactions: ACID guarantees (atomicity, consistency, isolation, durability), the standard isolation levels (read uncommitted, read committed, repeatable read, serializable) and the anomalies they permit or prevent (dirty reads, non-repeatable reads, phantom reads, lost updates, write skew), pessimistic locking versus optimistic concurrency control, deadlock detection and handling (including a single transaction that holds locks across more than one shard), and choosing an isolation level for a given workload (for example OLTP writes versus reporting reads). Also covers MVCC as the mechanism that delivers these guarantees, including snapshot isolation versus true serializability and the version cleanup (vacuum) MVCC requires to control table and index bloat from old row versions. Does not cover correctness across separate databases or services, such as two-phase commit, distributed consensus, or replication and sharding topology design.
Describe how PostgreSQL's MVCC mechanism works, including how transaction IDs and snapshots determine what a query can see, and why this design causes table and index bloat over time. How would you detect bloat in a production database, and what remediation options are available? Compare their operational trade-offs.
Sample Answer
Direct answer
PostgreSQL's MVCC (multi-version concurrency control) never updates a row in place: every UPDATE (and every DELETE) leaves the old row version on disk, marked dead, while a new version is written elsewhere. That old version has to stick around until no transaction's snapshot could possibly still need it, which is exactly why update- and delete-heavy tables accumulate dead tuples, bloat, over time. Detecting it is a matter of asking the engine directly how much of a table is live versus dead; remediating it means running VACUUM regularly enough that dead space never has the chance to build up in the first place.
Structured elaboration
Why MVCC causes bloat. Every row carries an xmin (creating transaction) and xmax (superseding transaction, if any). An UPDATE on Postgres 16, reproduced for real, physically relocates the row on every write (ctid, its physical address, changes each time) rather than editing bytes in place: a row updated twice moved from (0,7) to (0,14) to (0,15), leaving two dead versions behind. Nothing removes those dead versions automatically at write time, because another transaction's still-open snapshot might legitimately need to see the pre-update version; only a later cleanup pass can safely reclaim them, once no snapshot could possibly need them anymore.
Detecting bloat, with real numbers. A 50,000-row table, freshly created, measures 3320 kB on disk (pg_total_relation_size), reproduced directly against Postgres 16. With autovacuum (Postgres's background process that runs VACUUM automatically, without anyone scheduling it) disabled on that table to observe the raw state, a single bulk UPDATE touching every row (the shape of a routine nightly batch job) grows it to 6568 kB; the pgstattuple extension confirms why directly, reporting dead_tuple_count = 50000 (dead_tuple_percent = 39.04), exactly one dead version per live row, since the old version of every updated row is still sitting on disk next to its replacement. A second bulk update, still with no VACUUM run in between, grows the table further to 9032 kB, but pgstattuple measured right after that second update still reports dead_tuple_count = 50000, not 100,000. That is not a missing count: it is Postgres reclaiming part of the mess as it goes. The first update's transaction had already committed, so its dead row versions became invisible to every later snapshot immediately; when the second update needed room on a page that was now half-full of those dead versions, it opportunistically pruned them in place before writing its own new versions, reusing freed space rather than only ever adding to it. That pruning happens during ordinary reads and writes, with no VACUUM involved at all; it just does not return space to the operating system, which is what VACUUM and VACUUM FULL are for, covered next. On a comparable 20,000-row table, pgstattuple('bloat_demo2') reported dead_tuple_percent = 0 before any update and dead_tuple_percent = 38.25 after a single bulk update touching every row, real, measured numbers, not an estimate.
Remediation, with real behavior demonstrated. Plain VACUUM scans the table and marks dead tuple space reusable by future inserts and updates, without holding an exclusive lock and without shrinking the file on disk: running VACUUM (VERBOSE) on the bloated table reported tuples: 50000 removed, 50000 remain, matching the 50,000 dead tuples pgstattuple had just measured (the second update's dead versions only, since the first update's were already reclaimed in place by the mechanism above), and pg_total_relation_size immediately afterward was unchanged at 9032 kB, confirming that plain VACUUM frees space for the table to reuse internally but does not return it to the operating system. VACUUM FULL, by contrast, rewrites the entire table into a brand-new file with no wasted space (per the Postgres documentation, this "allows unused space to be returned to the operating system"), and running it on the same table dropped the size to 3288 kB, smaller than the original 3320 kB. The cost: VACUUM FULL requires an ACCESS EXCLUSIVE lock on the table for the duration, per the documentation, versus plain VACUUM, which "does not obtain an exclusive lock" and "can operate in parallel with normal reading and writing of the table."
Trade-offs & pitfalls
autovacuumshould be doing the routineVACUUMwork automatically; ifn_dead_tupis climbing steadily inpg_stat_user_tablesandlast_autovacuumis stale or null, that's the first thing to check, not a manualVACUUMschedule. A full maintenance plan also weighs autovacuum tuning,VACUUM FULLrisk and reindexing.VACUUM FULL's exclusive lock makes it an availability decision, not just a maintenance one: it is real, verified, downtime for that table for however long the rewrite takes. It should be an intentional, scheduled operation on a table that's already badly bloated, not a routine cron job.- A table with a high dead-tuple percentage isn't necessarily "broken"; a moderate, steady-state percentage that
autovacuumkeeps in check is normal MVCC behavior, not a defect. The problem is specifically when dead tuples accumulate faster than vacuuming reclaims them.
Snapshot isolation (SI) prevents some anomalies but can still allow write skew. Explain why, then walk through a concrete example with two concurrent transactions in a banking-like system where SI lets a business invariant get silently violated. Propose strategies to prevent or catch this when the invariant is critical.
Sample Answer
Direct answer
Snapshot isolation (SI, giving each transaction one fixed, consistent view of the database for its own duration) only detects conflicts between two transactions that write the same row. It says nothing about two transactions that each read a row, each base a decision on what they read, and then write two different rows, so if a business rule spans both rows, both transactions can independently confirm the rule holds, commit, and jointly violate it, with the engine never seeing anything resembling a conflict. The fix is either to make the guarantee explicit to the engine (true Serializable, or a lock that forces the transactions to see each other) or to accept the risk and catch it after the fact.
Structured elaboration and worked examples
Banking: a shared overdraft floor. Two sub-accounts of one joint account share a combined overdraft floor: balance(A) + balance(B) >= -50.00. Starting at 50.00 each (combined 100.00), two withdrawals of 100.00 happen concurrently under REPEATABLE READ (Postgres's snapshot isolation):
-- T1 (withdraws from A) -- T2 (withdraws from B)
BEGIN ISOLATION LEVEL REPEATABLE READ; BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT sum(balance) FROM accounts
WHERE id IN (1,2); -- 100.00 SELECT sum(balance) ... -- 100.00
-- 100 - 100 = 0, which is >= -50, looks safe
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance - 100 WHERE id = 2;
COMMIT; COMMIT;
Run for real against Postgres 16: both commit. Final combined balance: -100.00, past the -50.00 floor, even though each transaction's own check, at the moment it checked, was correct given what it could see.
Healthcare: on-call coverage. The same shape, a different domain: a nurse-scheduling invariant that at least one clinician must remain on call at all times. Two clinicians, both currently on call, each independently decide to go off call:
-- T1 (nurse A) -- T2 (nurse B)
SELECT count(*) FROM on_call WHERE on_call; -- 2 SELECT count(*) ... -- 2
UPDATE on_call SET on_call=false WHERE id=1; UPDATE on_call SET on_call=false WHERE id=2;
COMMIT; COMMIT;
Same result: both commit under REPEATABLE READ, final state has nobody on call, invariant silently violated. The mechanism is identical to the banking case; the only thing that changed is what the invariant means to the business.
Prevention: proactive and reactive
Proactive (stop it from ever committing): run the transactions under true SERIALIZABLE instead of snapshot isolation. Re-running either scenario above under SERIALIZABLE, the second COMMIT fails outright with ERROR: could not serialize access due to read/write dependencies among transactions, and only one withdrawal (or one clinician going off call) lands; the invariant holds because Postgres's Serializable Snapshot Isolation tracks the read-write dependency between the two transactions even though they wrote different rows. An alternative proactive fix that doesn't touch isolation level at all: an explicit constraint the database enforces directly, for example a trigger that re-checks the combined balance (or on-call count) after every write to either row and raises if it would go negative, or a lock on a single "invariant row" both transactions must acquire before proceeding, deliberately forcing them to see each other.
Reactive (catch it after the fact): if Serializable's abort-and-retry cost is unacceptable for the write volume, or the invariant only needs to be approximately held rather than never violated, run a periodic reconciliation query that checks the invariant directly (combined balance below floor, zero clinicians on call) and alerts or auto-compensates, page whoever's on call for the on-call table itself, or trigger a corrective transaction. This accepts a window where the invariant can be briefly false in exchange for never blocking or aborting a legitimate transaction.
Trade-offs & pitfalls
- Proactive Serializable is the only option that guarantees the invariant is never violated, even momentarily; it is also the only option that requires the application to handle a new failure mode (the serialization error) it didn't have before.
- Reactive detection is cheaper to add to an existing system and doesn't change any transaction's behavior, but it's fundamentally a "notice and fix" strategy, not a "prevent" strategy; it's appropriate when a brief invariant violation is embarrassing or costly to clean up, but not catastrophic (an over-withdrawn joint account can be clawed back; a hospital ward with zero coverage for even a few minutes is a different risk calculus, and that difference is exactly why the same technical anomaly gets a different prevention strategy depending on the domain).
List the four standard SQL isolation levels (read uncommitted, read committed, repeatable read, serializable) and for each, state which of the classic anomalies (dirty read, non-repeatable read, phantom read, write skew) it still permits. Which isolation level does PostgreSQL actually provide by default, and what does that guarantee in practice for a reader running concurrently with writers?
Sample Answer
Direct answer
Standard SQL (SQL-92) defines four isolation levels, weakest to strongest: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE. Each one is defined by which of the classic anomalies (dirty read, non-repeatable read, phantom read) it still permits; the stronger the level, the fewer anomalies survive, and the more the database has to work to rule them out. PostgreSQL's actual default is READ COMMITTED, and in practice that means every individual statement (not every transaction) sees a fresh snapshot of whatever was committed at the moment that statement started, so a reader never sees another transaction's uncommitted work, but two statements in the same transaction can legitimately see different data if a writer commits in between.
The four levels and what they permit
An anomaly here means a way concurrent transactions can produce a result that would be impossible if transactions ran strictly one at a time. Dirty read: seeing another transaction's uncommitted, possibly-about-to-be-rolled-back change. Non-repeatable read: re-reading the same row twice in one transaction and getting two different (both committed) answers because someone else's write landed in between. Phantom read: re-running the same filtered query twice in one transaction and getting a different set of rows, because someone else inserted or deleted a matching row in between.
| Level | Dirty read | Non-repeatable read | Phantom read | Typical use case |
|---|---|---|---|---|
| READ UNCOMMITTED | Permitted | Permitted | Permitted | Standard-allowed, but rarely implemented literally; see the PostgreSQL note below |
| READ COMMITTED | Prevented | Permitted | Permitted | Default for most OLTP (online transaction processing, the high-volume small-transaction workload behind typical apps) workloads: each statement sees committed-as-of-now data |
| REPEATABLE READ | Prevented | Prevented | Permitted (by the standard) | A multi-step read-then-write transaction that needs the data it reads to stay stable for the rest of the transaction, such as a batch job that reads a set of rows and later reconciles against that same set |
| SERIALIZABLE | Prevented | Prevented | Prevented | Correctness-critical multi-statement transactions where the combined effect of concurrent transactions must be equivalent to some one-at-a-time order, such as enforcing an invariant across more than one row (the write-skew anomaly) |
PostgreSQL's actual default, and what it guarantees
SHOW default_transaction_isolation; on a stock PostgreSQL 16 instance returns read committed. In practice that means: within one transaction, each new SQL statement gets its own fresh snapshot of the database as of the moment that statement begins, so a reader always sees a consistent, fully-committed view (never a partial or uncommitted write from another session), but it does not promise that two different statements in the same transaction see the same data, because a concurrent writer's commit lands between them.
-- T1
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT balance FROM accounts WHERE id = 1; -- returns 1000
-- T2 (runs to completion here)
BEGIN; UPDATE accounts SET balance = 900 WHERE id = 1; COMMIT;
-- back in T1
SELECT balance FROM accounts WHERE id = 1; -- returns 900: same transaction, different answer
COMMIT;
This was run against PostgreSQL 16.14 in a throwaway container and printed exactly 1000 then 900, which is the non-repeatable read that READ COMMITTED explicitly permits. Nothing in that sequence is a dirty read: T1 never saw T2's row while T2's transaction was still open; it only saw T2's value after T2 committed.
Trade-offs and pitfalls
One subtlety worth knowing cold: the SQL standard's table says REPEATABLE READ still permits phantom reads, but PostgreSQL's actual REPEATABLE READ is implemented as full-transaction snapshot isolation (the same mechanism SERIALIZABLE builds on, just without the extra conflict-detection layer), so in practice a PostgreSQL REPEATABLE READ transaction that re-runs the same filtered COUNT(*) twice gets the same answer both times, something a strictly standard-conforming engine would not guarantee. Do not assume this generalizes to every engine: MySQL's InnoDB storage engine also calls its default level REPEATABLE READ but achieves phantom protection for locking reads through gap locks, a different mechanism with different side effects (SQL Server is another engine that deviates from the standard's table in the other direction). The second pitfall is assuming READ UNCOMMITTED in PostgreSQL actually gives you dirty reads for a performance win: PostgreSQL accepts the READ UNCOMMITTED keyword but silently treats it exactly like READ COMMITTED (PostgreSQL has no genuinely lock-free dirty-read mode at all), so setting it buys nothing and should not be relied on for a "fast and loose" read path.
Analyze the performance and correctness trade-offs between running read-only transactions under snapshot isolation versus serializable isolation for a high-throughput analytical workload. Discuss MVCC snapshot management, stale reads, why serializable transactions need predicate locking or conflict tracking, and the runtime and memory overhead that adds. Recommend which isolation level to use, and when it is reasonable to relax the guarantee.
Sample Answer
Direct answer
For a high-throughput analytical workload that's read-only or nearly so, snapshot isolation (Postgres's Repeatable Read) is almost always the right default: it gives every query a consistent view at essentially the cost of an ordinary read, with no locking and no risk of the transaction itself being aborted. Reserve Serializable for the specific write paths that must actually prevent write skew (an invariant spanning more than one row); imposing it on read-only analytical queries buys a guarantee they don't need at a real, measurable cost.
Structured elaboration
Multiversion concurrency control (MVCC) snapshot management under Repeatable Read. A snapshot is not a data copy; it's a fixed rule for filtering row versions by transaction ID (visible in the xmin/xmax columns of any row: xmin is the id of the transaction that created that row version, xmax is the id of the transaction that superseded it, if any). Taking a snapshot at the start of a long analytical transaction costs essentially nothing extra per query: every read simply filters against the same fixed snapshot it already has. The price is paid elsewhere, on storage: any row version created after the snapshot but needed to satisfy it (because it's still visible to that old snapshot) cannot be vacuumed away until the snapshot's transaction ends, so a long-running analytical transaction under Repeatable Read can hold back cleanup of dead tuples that would otherwise be reclaimed, contributing to table bloat under concurrent writes elsewhere in the system.
Why Serializable costs more, concretely. True Serializable (Postgres's Serializable Snapshot Isolation) adds predicate locks on top of the same MVCC snapshot: as a transaction reads, the engine records what values it depended on (visible as SIReadLock entries in pg_locks), so it can detect at commit time whether another transaction's write invalidated that dependency. This bookkeeping has real memory cost, controlled by max_pred_locks_per_transaction (Postgres's own default is 64 objects per transaction, and the documentation says explicitly that this "might need to raise this value if you have clients that touch many different tables in a single serializable transaction"), meaning a wide analytical query touching many tables can exhaust the default predicate-lock budget before it even runs into a real conflict. Worse for a high-throughput workload: unlike Repeatable Read, a Serializable transaction can be aborted at commit time for a conflict it had no way to see coming. That's not hypothetical, it was reproduced directly: two transactions each read a shared invariant, each write a different row, and the second one to commit fails with ERROR: could not serialize access due to read/write dependencies among transactions, even though its own query was perfectly correct in isolation. At high throughput, that failure rate scales with contention, and every failure means a wasted execution plus a mandatory application-level retry, work that Repeatable Read never has to redo.
Worked example: what Repeatable Read never pays and Serializable sometimes does
Running the identical write-skew scenario (two transactions, shared invariant, disjoint writes) twice against Postgres 16, once under each level:
- Repeatable Read: both transactions commit successfully, zero retries, zero aborts, at the cost of the invariant silently breaking (this is the correctness gap; it's a real cost of choosing snapshot isolation, not a free lunch).
- Serializable: the second transaction's
COMMITis rejected outright with the reproduced error above; the invariant holds, but the application now has one failed execution to retry.
For a purely read-only analytical workload with no write-skew-sensitive invariant at all (the common case for reporting and analytics), Serializable's entire cost, predicate-lock bookkeeping and possible aborts, buys nothing, because there's no write for it to protect against. That's the core of the recommendation: match the level to what's actually being protected, not to "the strongest available option."
Trade-offs & pitfalls
- Recommendation, stated plainly: default read-only analytical transactions to Repeatable Read. Escalate specific, identified write paths (not the whole analytical workload) to Serializable only where a cross-row invariant genuinely needs protecting, and build the retry-on-serialization-failure path into those specific transactions, not everywhere.
- When it's reasonable to relax further, to plain Read Committed: only if the analytical query is a single statement that doesn't need to agree with any other statement in the same transaction, since Read Committed already gives per-statement consistency; the moment a report runs more than one query against related data, that guarantee stops being enough, as a two-session phantom-read test shows directly.
- Don't conflate "isolation level" with "performance knob" in the abstract; the actual cost differences above are structural (locking vs. non-locking, abort-and-retry vs. never-aborts), not a vague sense that "stronger is slower."
Explain how Multi-Version Concurrency Control (MVCC) works internally and how snapshot isolation differs from true serializability. Describe an example of a write-skew anomaly and how you would prevent it in a DBMS that provides snapshot isolation.
Sample Answer
Direct answer
Multi-version concurrency control (MVCC) works by never overwriting a row in place: every UPDATE writes a brand-new physical version of the row, tags it with the transaction ID that created it, and leaves the old version alone until nothing can possibly still need it. A transaction's "snapshot" is simply the rule it uses to decide, for any given row version, whether that version existed yet and wasn't since superseded, as of the moment the snapshot was taken. Snapshot isolation gives every transaction a single such consistent view for its whole duration; true serializability additionally guarantees the outcome is equivalent to running all transactions one at a time, which snapshot isolation alone does not guarantee, because of write skew.
Structured elaboration
Transaction IDs and snapshots, shown directly. Every row carries a hidden xmin (the ID of the transaction that created this version) and xmax (the ID of the transaction that superseded it, 0 if still current). Run for real against Postgres 16, updating the same row twice:
SELECT xmin, xmax, ctid, balance FROM accounts WHERE id = 1;
-- 770 | 774 | (0,7) | 500.00
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
SELECT xmin, xmax, ctid, balance FROM accounts WHERE id = 1;
-- 775 | 0 | (0,14) | 501.00
UPDATE accounts SET balance = balance - 1 WHERE id = 1;
SELECT xmin, xmax, ctid, balance FROM accounts WHERE id = 1;
-- 776 | 0 | (0,15) | 500.00
Each UPDATE produced a physically new row (ctid, the row's physical location, changes every time), stamped with a new xmin. Nothing was edited in place; the previous version simply became a dead tuple whose xmax now points at the transaction that replaced it. That dead tuple is not removed on the spot, MVCC keeps it around precisely because some other transaction's still-open snapshot might legitimately need to see it; VACUUM is the process that later scans the table and reclaims a dead tuple's space once no snapshot could possibly need it anymore. A snapshot is then just: "a row version is visible to me if its xmin committed before my snapshot was taken, and its xmax either doesn't exist or belongs to a transaction that hadn't committed yet when my snapshot was taken." That single rule is what makes a REPEATABLE READ transaction see a fixed picture of the database throughout its lifetime without ever taking a read lock: it's just filtering row versions by transaction ID, not blocking anyone.
Snapshot isolation vs. true serializability. Snapshot isolation (what Postgres implements at REPEATABLE READ) guarantees each transaction sees one consistent point-in-time view and detects genuine write-write conflicts (two transactions both trying to write the same row version) as a serialization failure. What it does not guarantee is that the combined outcome of several concurrently committed transactions is equivalent to some order of running them one at a time, because two transactions can each read a row, never write it, and separately write two different rows, and snapshot isolation's conflict detection never looks at reads at all, only at writes to the same row.
Write skew, concretely. Two on-call staff, an invariant that at least one must remain on call. Both transactions read the on-call count under REPEATABLE READ, both see 2 (safe), both then set themselves off-call and commit:
T1: SELECT count(*) WHERE on_call -> 2 T2: SELECT count(*) WHERE on_call -> 2
T1: UPDATE ... SET on_call=false WHERE id=1 COMMIT
T2: UPDATE ... SET on_call=false WHERE id=2 COMMIT
Both commits succeed under REPEATABLE READ (verified: final state has both rows on_call = false), because T1 wrote row 1 and T2 wrote row 2, never the same row, so there is no write-write conflict for snapshot isolation to catch, even though the invariant it was protecting is now violated.
Preventing it in an engine that provides snapshot isolation: use true SERIALIZABLE, which Postgres implements as Serializable Snapshot Isolation (SSI): it adds predicate locks that track which values a transaction's query depended on, not just which rows it wrote, and detects the read/write dependency cycle between T1 and T2 even though they never touched the same row. Re-running the identical scenario under SERIALIZABLE, the second transaction's COMMIT fails with the real error ERROR: could not serialize access due to read/write dependencies among transactions, DETAIL: Reason code: Canceled on identification as a pivot, during commit attempt., and the invariant holds.
Trade-offs & pitfalls
- Postgres's predicate locks (visible in
pg_locksasSIReadLock) are non-blocking by design, per the Postgres documentation: they never cause another transaction to wait, they only get checked at commit time, which is why SSI can catch write skew without turning reads into locking reads the way some other engines' Serializable implementations do. - A transaction that fails with a serialization error hasn't corrupted anything; it simply never committed. The application is expected to catch that specific error and retry the whole transaction, which is the price of getting true serializability instead of merely snapshot isolation.
Unlock Full Question Bank
Get access to all 25 Transactions, Concurrency Control, and Isolation Levels interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.