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.
Compare optimistic and pessimistic concurrency control for a high-traffic inventory system with frequent stock transfers and purchases, such as a flash-sale checkout or a ticket-booking platform. Which strategy would you choose and why? Discuss version checks and retry loops, locking and the deadlock risk it introduces, and what each approach does to the user experience under contention.
Sample Answer
Direct answer
For a high-traffic inventory system, the right default is optimistic concurrency control (OCC) for the general case: most SKUs in a catalog have low per-item contention, so checking a version on write and retrying the rare conflict is cheap and keeps the system fully non-blocking. The one place to switch to pessimistic concurrency control (PCC), an explicit row lock, is the specific hot item: a single flash-sale SKU or a single ticket-booking event where thousands of requests target the exact same row in the same second, because at that level of contention, optimistic retries stop being rare and start being a self-inflicted retry storm.
Structured elaboration
Optimistic concurrency control. Each row carries a version number (or a updated_at timestamp). A worker reads the row including its version, computes the new state, then writes it conditioned on the version being unchanged: UPDATE inventory SET qty_available = qty_available - 1, version = version + 1 WHERE sku = $1 AND version = $2. If another worker committed a change in between, that WHERE clause matches zero rows, the write silently fails to apply, and the application must detect "0 rows affected" and retry (re-read, recompute, re-attempt). No lock is held between the read and the write; the cost of a conflict is entirely on the loser, who has to redo the round trip.
Pessimistic concurrency control. A worker takes an explicit row lock before reading, SELECT qty_available FROM inventory WHERE sku = $1 FOR UPDATE, and every other transaction that tries to touch the same row simply waits until the first one commits or rolls back. There is no conflict to detect and no retry logic to write; contention shows up as latency (queued waiters) rather than as failed attempts.
Locking's deadlock risk. The moment a transaction holds a lock on row A and then tries to acquire a lock on row B, while a second transaction holds B and tries to acquire A, the engine detects the cycle and aborts one of them with a real error (Postgres: ERROR: deadlock detected, naming the two blocked processes and the two locks each is waiting on). OCC has no equivalent failure mode: nothing is held between transactions, so there is nothing to deadlock on. This is a structural argument in OCC's favor whenever the write pattern touches more than one row, which most checkout flows do (decrement inventory, then write an order row).
Worked example
The version-conflict mechanic, run for real against Postgres 16: inventory('SKU-100', qty_available=3, version=1). A worker (call it B) already sold one unit and committed, moving the row to version=2. Worker A, still holding the stale version=1 it read earlier, attempts its own decrement:
UPDATE inventory SET qty_available = qty_available - 1, version = version + 1
WHERE sku = 'SKU-100' AND version = 1;
Actual result: UPDATE 0. Zero rows matched, because the row's real version is now 2. That's the entire conflict-detection mechanism: no exception, no lock wait, just a row count the application must check. Worker A's retry logic re-reads (qty_available=2, version=2), recomputes, and re-issues the same conditional update, which now succeeds.
For the pessimistic side, taking a row lock and having a second transaction queue behind it is the same underlying mechanism you can observe directly in the lock views: pg_locks shows the second session's request in granted = f with pg_blocking_pids() naming the first session's process id, and the second transaction's wall-clock latency is exactly however long the first one holds the lock.
Trade-offs & pitfalls
- Retry storms under extreme contention. OCC's cost model assumes conflicts are rare. On one specific hot row (a flash-sale item selling out in the first second, or the last few seats on a popular flight), that assumption breaks: hundreds of workers can all read the same version simultaneously, all attempt to write, and all but one lose, immediately re-read, and race again. That amplifies load on the exact row that's already the bottleneck. PCC avoids this by making excess demand wait in an orderly queue instead of retry in a storm, at the cost of every waiter's latency going up and the deadlock exposure noted above the moment more than one resource is locked per transaction.
- User experience under contention differs in kind, not just degree. OCC surfaces as a retry that's invisible to the user if it resolves in milliseconds, or as a visible "someone else grabbed this, try again" message if the application chooses not to auto-retry (common in collaborative-editing UIs, where silently overwriting a conflicting edit is worse than telling the user). PCC surfaces as the request simply taking longer, with no distinct "conflict" state at all, until a lock-wait timeout is hit.
- Recommendation, stated plainly: OCC as the default across the catalog; a targeted pessimistic lock (or a queue in front of the hot row entirely, decoupling the write from the request) for the handful of SKUs an ops team can identify in advance as flash-sale hot items. Don't pick one strategy database-wide; the right choice is a property of the contention level on a specific row, not of the schema.
Multiple worker processes need to increment a shared counter concurrently, for example a daily_user_counts(day, user_count) table. A naive read-then-update (SELECT the count, then UPDATE it to count + 1) loses updates under load. Walk through why that happens, propose a safe way to perform the increment, and discuss the performance and consistency trade-offs of your approach.
Sample Answer
Direct answer
The naive pattern loses updates because "read the value, compute a new value, write it back" is three separate steps with a gap between the read and the write, and the database has no idea those three steps are supposed to be atomic together. Two workers can both read the same starting value, both compute the same "correct" next value from it, and both write that value back, so instead of two increments you get one. The fix is to never let application code hold a value in memory across the gap: push the increment itself into a single statement the database executes atomically.
Structured elaboration
Why it breaks. SELECT count FROM daily_user_counts WHERE day = ... then, in application code, count + 1, then UPDATE ... SET count = <the number you computed> gives the database three independent operations. Under Read Committed (the common default), nothing stops two sessions from both executing the SELECT before either executes the UPDATE.
Three fixes, in order of preference:
- Atomic in-place update, the simplest and usually correct default:
UPDATE daily_user_counts SET user_count = user_count + 1 WHERE day = $1. The arithmetic happens inside the database's own read-modify-write of the row, under a row lock the engine takes automatically, so a concurrent identical statement simply waits for the first to commit and then reads the already-incremented value. - Upsert via
ON CONFLICT DO UPDATE, needed when the row fordaymay not exist yet:INSERT INTO daily_user_counts (day, user_count) VALUES ($1, 1) ON CONFLICT (day) DO UPDATE SET user_count = daily_user_counts.user_count + 1. This requires a unique index ondayas the conflict target (here, the primary key already provides one); without it Postgres has nothing to detect the conflict against. - Explicit row lock (
SELECT ... FOR UPDATE), useful when the read-then-write logic is more than a single arithmetic expression (for example, the new value depends on a lookup elsewhere first):SELECT user_count FROM daily_user_counts WHERE day = $1 FOR UPDATE;thenUPDATE ... SET user_count = $2 WHERE day = $1;in the same transaction.FOR UPDATEtakes the row lock at read time, so a second session'sSELECT ... FOR UPDATEon the same row blocks until the first transaction commits, closing the same gap the naive version left open.
Worked example
Reproducing the bug, run for real against Postgres 16: starting user_count = 0, two sessions both SELECT the row (both see 0), both compute 0 + 1 = 1 in application code, both UPDATE ... SET user_count = 1:
T1: SELECT user_count -> 0 T2: SELECT user_count -> 0
T1: UPDATE ... SET user_count = 1 COMMIT
T2: UPDATE ... SET user_count = 1 COMMIT
Final value: 1. Two increments happened; one was lost.
Fix 1 confirmed, same starting value, both sessions instead run UPDATE daily_user_counts SET user_count = user_count + 1 WHERE day = $1:
T1: UPDATE ... SET user_count = user_count + 1 (row lock acquired)
T2: UPDATE ... SET user_count = user_count + 1 (blocks on T1's row lock)
T1: COMMIT (T2 unblocks, reads the just-committed value, adds 1)
T2: COMMIT
Final value: 2, run and verified against the live database, both increments preserved.
Fix 2 confirmed, run twice in sequence on a fresh row:
INSERT INTO daily_user_counts (day, user_count) VALUES ('2026-09-25', 1)
ON CONFLICT (day) DO UPDATE SET user_count = daily_user_counts.user_count + 1;
-- run again --
Result after two calls: user_count = 2, matching the atomic-update result exactly.
Trade-offs & pitfalls
- Performance: the atomic
UPDATEand the upsert both serialize writers on the same row through a brief row lock, which is fine at the throughput of a per-day counter but becomes a real bottleneck if the same row is hit by thousands of concurrent workers per second (a single hot row can only accept one committing writer at a time). At that scale, the standard mitigation is sharding the counter (N sub-rows summed on read, or an in-memory/Redis-backed counter flushed periodically to the row) rather than fighting row-lock contention directly. - Consistency: the atomic update and
SELECT FOR UPDATEare both immediately consistent, every committed read sees the true count. If a shard-and-sum approach is adopted for throughput, reads become eventually consistent within the flush interval, a real trade-off to state explicitly rather than gloss over. - The naive read-then-write pattern is not "slightly wrong under heavy load," it silently loses data under any concurrent load, including two workers running a few milliseconds apart; do not treat it as a rare-edge-case risk.
An analytical job needs to read operational tables while writes are continuously happening against them. Which isolation level would you choose for the read job, and why? What goes wrong if you pick the wrong one, and what alternatives exist to get a consistent view without blocking the OLTP writers?
Sample Answer
Direct answer
For an analytical job reading operational (OLTP, online transaction processing) tables while writes continue, the floor is a snapshot: Repeatable Read at minimum, giving the read job one consistent point-in-time view of the data for its entire run. Read Committed is not enough, because a report that touches the same rows more than once, which any non-trivial aggregation does, can see a different value or a different row set on each pass. Picking the wrong level doesn't just risk incorrect numbers; on some engines it can also mean the report itself starts blocking the OLTP writers it's supposed to leave alone.
Structured elaboration
Why Read Committed breaks a long-running report. Read Committed gives each individual statement a fresh snapshot, not the whole transaction. A report that runs several queries, or one query that scans a large table over many seconds while the planner processes it, can see different committed states at different points within the same logical report. Concretely, this shows up as a phantom: an aggregate count taken at the start of a report and re-checked partway through can disagree with itself purely because an unrelated write landed in between, run for real against Postgres 16:
BEGIN ISOLATION LEVEL READ COMMITTED;
SELECT count(*) FROM on_call WHERE on_call = true; -- 2
-- concurrent INSERT of a new matching row commits here
SELECT count(*) FROM on_call WHERE on_call = true; -- 3, same transaction
COMMIT;
That's the mechanism behind "the report total doesn't reconcile," a symptom that shows up with no error and no obvious cause unless you already know to suspect the isolation level.
Why Repeatable Read fixes it (on Postgres specifically). Re-running the identical sequence under REPEATABLE READ, both counts return 2; the concurrent insert is invisible to the transaction's snapshot until that transaction commits and a new one starts. Worth stating precisely: Postgres's Repeatable Read blocks phantom reads too (stronger than the SQL standard, which only requires this at Serializable, the strongest standard isolation level: it guarantees the same result as if every transaction had run one at a time in some order, blocking every anomaly including phantoms); an engine that only implements the standard's minimum needs Serializable to get the same guarantee for a multi-query report.
Why the wrong choice can also hurt the writers, not just the reader. On engines whose stronger isolation levels are implemented with locking rather than pure multiversion concurrency control (MVCC) snapshots (a locking read under InnoDB's Serializable, for instance, converts plain SELECTs into shared-lock reads), reaching for the strongest available level "to be safe" can make the analytical query hold locks against rows the online transaction processing (OLTP) path needs to write, turning a read-only reporting job into a source of write contention. The safe, MVCC-only levels (Postgres's Repeatable Read, or a true snapshot-isolation read) avoid this entirely: a reader on a snapshot never blocks a writer and a writer never blocks that reader, because they're each looking at (or writing) a different row version.
Worked example
See above: the exact count(*) sequence was executed against a live Postgres 16 database, first under Read Committed (anomaly reproduced: 2 then 3) and then under Repeatable Read (anomaly prevented: 2 then 2), with no other change to the query or the schema.
Trade-offs & pitfalls
- If a consistent snapshot alone isn't enough (the report also can't tolerate any blocking on the primary, or needs to run for hours), the alternatives are architectural rather than a level bump: a read replica (the report runs entirely off a copy, at the cost of some replication lag, meaning the copy is always a little behind the primary because writes take a moment to propagate to it), or change-data-capture into a separate read-optimized store. Those trade consistency freshness and infrastructure complexity for zero interference with the primary, and each carries its own cost and complexity trade-offs.
- Don't default to Serializable for a read-only report "to be extra safe." Serializable adds real overhead (predicate-lock bookkeeping, and the possibility the transaction gets aborted and must retry) for a guarantee, true serializability among concurrent writers, that a pure read job doesn't need; Repeatable Read already gives it the one thing it actually requires, a fixed, self-consistent view.
Production is showing an increasing frequency of deadlocks between two tables during nightly batch jobs. Describe how you would diagnose the root cause using DB diagnostics and logs, how to reproduce and test in staging, short-term mitigations to stop the incident, and long-term fixes including transaction redesign or indexing improvements.
Sample Answer
Direct answer
Diagnose from the engine's own deadlock report first (it names the exact transactions, locks, and queries involved, so there's no guessing), stop the immediate incident with a fast, low-risk mitigation that doesn't require a code deploy, reproduce the exact interleaving in staging to confirm the real cause before changing anything permanent, and then fix the root cause: almost always inconsistent lock acquisition order across the two jobs, sometimes compounded by transactions that hold locks longer than they need to.
Structured elaboration
1. Diagnose from real evidence, not guesswork. Postgres logs every deadlock to the server log with the exact detail needed to reconstruct it. Reproduced for real: two sessions each update accounts rows 1 and 2 in opposite order (T1: row 1 then row 2; T2: row 2 then row 1). The second conflicting statement from whichever session loses returns:
ERROR: deadlock detected
DETAIL: Process 69 waits for ShareLock on transaction 772; blocked by process 70.
Process 70 waits for ShareLock on transaction 771; blocked by process 69.
HINT: See server log for query details.
CONTEXT: while updating tuple (0,8) in relation "accounts"
That DETAIL line is the diagnosis: two processes, each waiting on the other's transaction, over the same relation. In production, the server log (with log_lock_waits enabled) captures this automatically for every real deadlock, including the actual queries each side was running, which table and tuple, and how long each side had already been waiting, exactly the information needed to identify which two jobs collide and in what order they touch the shared tables.
2. Reproduce in staging before changing anything. Take the two real query patterns from the log and run them as two literal interleaved sessions against a staging copy with the same schema and comparable data volume, in the same order the log shows. If the deadlock reproduces on the first or second attempt (as it does with a genuinely opposite lock order, deadlocks like this aren't rare timing flukes, they're near-certain once two jobs regularly touch the same two tables in reverse order under load), that confirms the root cause before you touch production code.
3. Short-term mitigation to stop the incident. Nothing here requires a schema change or a deploy: (a) if the two colliding nightly jobs can be sequenced instead of run in parallel, even temporarily, do that first, it removes the concurrent access entirely; (b) make sure the application already retries on Postgres's deadlock SQLSTATE (40P01), since one side of a deadlock is always safely rolled back by the engine and is a normal candidate for a retry, not a data-loss event; if it doesn't retry yet, that's the fastest real fix to ship.
4. Long-term fix. The two most durable options: (a) transaction redesign for consistent lock order, have every job that touches both tables acquire them in the same order (for example, always sort the rows being updated by primary key before issuing the updates), which makes the specific cycle structurally impossible regardless of timing; (b) shrink the transaction's lock-holding window, batch the nightly job into smaller transactions so each one holds its locks for less time, reducing the odds two jobs overlap on the same rows at all. Indexing matters here too, but indirectly: a missing index can force a wider scan (and therefore more rows locked, for longer) than the logical update actually needs, so confirming the query plans for both jobs aren't taking broader locks than necessary is worth checking alongside the lock-order fix, not instead of it.
Trade-offs & pitfalls
- Postgres's automatic deadlock resolution (abort one transaction, let the other proceed) is not a bug to eliminate; it's the correct behavior. The actual production problem is an increasing frequency, which means treat the deadlock detector's rollback as safe and expected, and focus effort on lock order and transaction scope, not on trying to prevent every deadlock from ever occurring.
- Sequencing the two jobs (short-term) trades throughput (how many jobs the system can get through per unit time) for safety; it buys time, it is not the long-term fix, because it doesn't scale and reintroduces risk the moment a third job starts touching the same tables.
Walk through the SQL isolation levels: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE. For each level, describe which anomalies it prevents (dirty reads, non-repeatable reads, phantom reads), and give a short SQL snippet or scenario that demonstrates one anomaly.
Sample Answer
Direct answer
The SQL standard defines four isolation levels, each one permitting fewer of three named anomalies than the last: Read Uncommitted (may allow dirty reads, non-repeatable reads, and phantom reads), Read Committed (blocks dirty reads only), Repeatable Read (also blocks non-repeatable reads), and Serializable (blocks all three, and write skew besides). Higher isolation buys correctness at the cost of more blocking or more aborted-and-retried transactions, so the right level is the weakest one that still protects the invariant your transaction actually depends on.
Structured elaboration
A dirty read is seeing another transaction's uncommitted write. A non-repeatable read is reading the same row twice in one transaction and getting two different values because another transaction committed a change in between. A phantom read is re-running the same filtered query twice and getting a different set of rows because another transaction inserted or deleted a matching row in between.
| Isolation level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| Read Uncommitted | Possible (by the standard) | Possible | Possible |
| Read Committed | Prevented | Possible | Possible |
| Repeatable Read | Prevented | Prevented | Possible (by the standard) |
| Serializable | Prevented | Prevented | Prevented |
One caveat worth stating out loud in an interview: Postgres never actually implements Read Uncommitted as written. Running BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; and updating a row from one session, then reading it uncommitted from a second session at that level, still returns the last committed value, not the dirty one, because Postgres silently upgrades Read Uncommitted to Read Committed internally. The standard permits an engine to offer stronger guarantees than a level requires, and Postgres does that here; engines built on multiversion concurrency control (MVCC, keeping multiple versions of a row instead of overwriting it in place) in general tend to make dirty reads hard to produce even when asked for.
Worked example
A concrete non-repeatable read, run against Postgres 16 with two real interleaved sessions:
-- T1 (READ COMMITTED) -- T2
BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;
SELECT balance FROM accounts WHERE id = 1; -- returns 500.00
BEGIN;
UPDATE accounts SET balance = 750.00 WHERE id = 1;
COMMIT;
SELECT balance FROM accounts WHERE id = 1; -- returns 750.00 (!)
COMMIT;
Two SELECTs in the same transaction, same row, no write from T1 in between, and the value changed underneath it, that is the anomaly by definition. Re-running the identical sequence with REPEATABLE READ instead of READ COMMITTED on T1, both reads returned 500.00; T1's snapshot was fixed at the start of the transaction and did not move even though T2's write committed in between.
A second, less obvious point the anomaly table doesn't capture: isolation strength is not an all-or-nothing choice for a whole system. A single application often mixes levels deliberately: an inventory-and-purchase path (decrementing stock on checkout) needs strong protection because a lost decrement means overselling a physical item, while a page-view or "active users today" counter on the same schema can tolerate a much weaker level, because losing an occasional increment under load costs nothing but a slightly-off vanity metric. Treating every table in the schema as if it needed Serializable is a common overcorrection.
Trade-offs & pitfalls
- Write skew is real and none of the three named anomalies cover it. Two transactions can each read a consistent snapshot, each individually satisfy a business invariant based on what they saw, and still jointly violate the invariant when both commit, because neither transaction wrote a row the other read. Repeatable Read (even Postgres's stronger version) does not catch this; only true Serializable does. The fix is Serializable isolation or an explicit lock on the rows the invariant depends on.
- Detecting anomalies in a live production system is harder than in a two-session demo. A dirty read or lost update rarely throws an error; it shows up later as a number that's simply wrong (a report that doesn't reconcile, an inventory count that goes negative). Practically, that means instrumenting for it before it happens: log
pg_stat_activity.wait_eventand blocking chains during incidents, add a periodic reconciliation query for any invariant a transaction can't enforce directly, and treat "we changed nothing and the numbers moved" reports as a concurrency anomaly first, not a bug in the report.
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.