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.
For each of the following anomalies: lost update, write skew, read skew, and phantom read, give a short example (SQL or pseudocode) with two concurrent operations that demonstrates it. For each anomaly, propose at least one way to prevent or mitigate it in a managed cloud database where you may not control every isolation-level or locking knob, and discuss the operational trade-offs of your approach.
Sample Answer
Direct answer
All four of these anomalies can be demonstrated with two ordinary concurrent transactions, and all four have a practical mitigation that does not depend on the database offering a knob you may not control: version-checked (optimistic) writes for lost update, an explicit contended row to force real conflict for write skew, combining multiple reads into one statement for read skew, and either accepting eventual consistency for a range check or app-level idempotency for phantom read. The common thread across a managed cloud database (where SERIALIZABLE might be unavailable, discouraged for cost reasons, or simply not offered as a tunable) is: push the correctness requirement into something the database does guarantee atomically (a single statement, a conditional write, a unique constraint) rather than relying on an isolation-level promise you cannot ask the vendor for.
Lost update
Two transactions read the same row, each computes a new value, and the second commit silently overwrites the first instead of compounding it.
-- T1 -- T2
SELECT qty FROM inventory WHERE id=1; SELECT qty FROM inventory WHERE id=1; -- both see 10
UPDATE inventory SET qty=8 WHERE id=1;
COMMIT;
UPDATE inventory SET qty=7 WHERE id=1;
COMMIT; -- final qty=7, T1's write lost
Run for real against PostgreSQL at READ COMMITTED: final qty was 7, confirming the loss. Mitigation: an optimistic version check, which works identically whether the managed service exposes tunable isolation levels or not, because it relies only on an ordinary conditional UPDATE:
UPDATE inventory SET qty = 8, version = version + 1
WHERE id = 1 AND version = 0; -- the version the app originally read
Run for real: when a second session ran the equivalent statement with the same stale version = 0 after the first had already committed and bumped it, the UPDATE matched zero rows instead of silently overwriting. Trade-off: this trades silent data loss for a visible, retryable no-op, but under high contention on one row it produces a retry storm; that is the point at which pessimistic locking (SELECT ... FOR UPDATE, if the managed engine supports session-held locks) becomes the better trade, accepting blocking latency instead of wasted retries.
Write skew
Two transactions each read an overlapping set of rows, each write is individually valid given what it read, but the combined effect violates an invariant spanning both rows (here: at least one doctor must be on call).
-- invariant: at least one of doctor 1, doctor 2 must be on call
-- T1 -- T2
SELECT oncall FROM on_call WHERE id IN (1,2); SELECT oncall FROM on_call WHERE id IN (1,2); -- both see (true,true)
UPDATE on_call SET oncall=false WHERE id=1;
UPDATE on_call SET oncall=false WHERE id=2;
COMMIT; COMMIT;
Run for real at REPEATABLE READ (PostgreSQL's snapshot-isolation level, the level most managed relational services do expose): both commits succeeded, leaving both doctors off call, because neither transaction's write touched a row the other one wrote, so ordinary row-level conflict detection never fires. Mitigation: since SERIALIZABLE may not be available or may be too expensive to run everywhere in a managed environment, materialize the invariant into something the database will enforce mechanically: either force both transactions through a shared contended row (for example, SELECT ... FOR UPDATE on a single on_call_lock row before touching either doctor row, so the second transaction blocks instead of racing), or use a real constraint if the engine has one, such as a check that runs at commit. Trade-off: the shared-lock-row approach serializes every on-call change through one hot row, which is fine for a rarely-changed roster but would be a bottleneck for a high-frequency invariant.
Read skew
A transaction reads two related values as two separate statements, and a concurrent transfer commits between them, so the transaction's own two reads are individually correct but jointly inconsistent.
-- true invariant: balance(A) + balance(B) is always 1000+1000=2000
-- T1 (reader) -- T2 (transfer)
SELECT balance FROM accounts_pair WHERE name='A'; -- 1000
UPDATE accounts_pair SET balance=balance-100 WHERE name='A';
UPDATE accounts_pair SET balance=balance+100 WHERE name='B';
COMMIT;
SELECT balance FROM accounts_pair WHERE name='B'; -- 1100
Run for real at READ COMMITTED: T1's own two remembered values, 1000 for A and 1100 for B, sum to 2100, not the true 2000 invariant; each individual read was accurate as of when it ran, but combined they describe a moment that never existed. Mitigation for a managed engine where you cannot force transaction-wide snapshot isolation (every read in the transaction sharing one fixed, consistent view of the database taken at the transaction's start): fold the two reads into one statement, since even READ COMMITTED guarantees a single statement's own snapshot is internally consistent. Run for real: SELECT sum(balance) FROM accounts_pair WHERE name IN ('A','B') issued mid-transfer, before T2 committed, returned exactly 2000, the correct pre-transfer total, from one atomic read. Trade-off: this only works when the two values live in the same table reachable by one query; if they are genuinely in different services or different databases, the honest fallback is accepting a bounded staleness window and documenting it, not pretending a cross-service read is atomic.
Phantom read
A transaction re-runs the same filtered query twice within one transaction and gets a different row count because a match was inserted in between.
-- T1 -- T2
SELECT count(*) FROM orders
WHERE customer_id=42 AND status='open'; -- 2
INSERT INTO orders (customer_id, status) VALUES (42,'open');
COMMIT;
SELECT count(*) FROM orders
WHERE customer_id=42 AND status='open'; -- 3: a phantom row appeared
Run for real at READ COMMITTED: the count went from 2 to 3 within one open transaction. Mitigation for a managed service without predicate-range locking: either read the count once and cache it for the rest of the transaction instead of re-querying (avoids the anomaly by avoiding the repeated read entirely, which is often all the business logic actually needs), or, if uniqueness matters more than a count (for example, "at most one open order per idempotency key"), enforce it with a unique constraint so a conflicting insert fails loudly at write time instead of silently changing a later read. Trade-off: caching the count sidesteps the anomaly but can go stale if the transaction runs long; a unique constraint is airtight but only applies to a uniqueness invariant, not an arbitrary count or aggregate.
Trade-offs and pitfalls, across all four
The pattern across all four fixes is the same: replace a promise you have to ask the vendor for (an isolation level) with a promise the vendor already always keeps (a single statement's atomicity, or a constraint enforced at write time). The failure mode to watch for is over-applying optimistic concurrency control everywhere out of caution: on a genuinely hot row, OCC's retry cost under contention can exceed what a short-held pessimistic lock would have cost, so the choice should be driven by measured conflict rate, not a blanket policy.
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability). For each property give a concrete example of a database operation that would break if that property were not guaranteed, and briefly describe how a typical RDBMS enforces that property.
Sample Answer
Direct answer
ACID is the contract a database makes about what a transaction guarantees: Atomicity (all of a transaction's writes happen or none do), Consistency (a transaction can only move the database from one state that satisfies its declared rules to another such state), Isolation (concurrent transactions don't see each other's half-finished work), and Durability (once committed, a write survives a crash). Each one protects against a distinct, concrete way an application can corrupt its own data.
Structured elaboration
| Property | What breaks without it (concrete example) | How a typical RDBMS enforces it |
|---|---|---|
| Atomicity | A funds transfer debits account A but the process crashes before crediting account B: money vanishes. Same failure mode in a nightly signup load: an INSERT batch dies on row 3 of a batch-load job and rows 1-2 are left permanently committed with no record the batch didn't finish. | The engine logs every write to a transaction (undo/redo information, in Postgres this is the write-ahead log, or WAL) before applying it, and on ROLLBACK or a crash mid-transaction, replays that log backward to erase the partial writes. |
| Consistency | A CHECK (balance >= 0) constraint exists specifically because, without it, a withdrawal that overdraws an account would silently leave a negative balance in the table with nothing to stop it. Run for real against Postgres: ALTER TABLE accounts ADD CONSTRAINT balance_nonneg CHECK (balance >= 0); then UPDATE accounts SET balance = -50 WHERE id = 1; returns ERROR: new row for relation "accounts" violates check constraint "balance_nonneg" and the row is never written. | Declared constraints (CHECK, NOT NULL, UNIQUE, foreign keys) are evaluated as part of every write inside the transaction; if any fails, the whole transaction is forced to abort rather than commit an invariant-violating row. |
| Isolation | Two transactions read the same row, each computes a new value from what they read, and one write silently overwrites the other (a lost update: both read the old value, both write back, one change vanishes). At larger scale, a BI dashboard summing revenue while an order-processing transaction is mid-flight can double-count a row it read once as pending and once, moments later, as a different in-flight state, or miss rows entirely, producing a report total that never existed in the database at any single instant. | Locking and/or multiversion concurrency control (MVCC): the engine either blocks a second writer until the first commits, or gives each transaction a consistent snapshot of the data as of some point in time so it never sees another transaction's uncommitted intermediate state. The isolation level you choose controls exactly which of these anomalies are still possible: the weaker the level, the more of these anomalies it permits. |
| Durability | A transaction commits, the client is told "success," and a second later the server loses power. If durability weren't guaranteed, that acknowledged write could simply be gone on restart, which is catastrophic for anything the caller might have already acted on (shipped an order, sent a receipt). | Before acknowledging COMMIT, the engine forces the change to a durable log on disk (fsync), not just to memory. Postgres exposes this directly: SELECT pg_current_wal_lsn(); returns the current write position in the WAL (for example 0/3738C00 on a fresh database), and every committed transaction has a WAL record at or before that position that crash recovery will replay. |
Worked example
The atomicity and consistency rows above are not hypothetical: both ERROR messages were produced by running the exact statements shown against a live Postgres 16 instance, not paraphrased from documentation. That distinction matters for an interview answer: a candidate who can show the actual constraint-violation error text is demonstrating they've watched the engine enforce the rule, not just recited the definition.
Trade-offs & pitfalls
- Full ACID is not free, and some systems deliberately relax it for specific data paths. The common shorthand for the alternative is BASE (Basically Available, Soft state, Eventually consistent): an online feature store (a database holding the input values, called features, that a machine-learning model reads to make a live prediction) serving a live ML prediction path, for instance, will often keep strict consistency for feature values that directly decide a yes/no business outcome (for example, a fraud-risk value that blocks a payment) but relax it (accept a few seconds of staleness) for aggregate features, values computed by summarizing many past events, like a rolling seven-day average, that only nudge a ranking score (the number a model uses to order results, rather than to gate them outright), because blocking the prediction path on a strict read would cost more in latency than the staleness costs in accuracy. Similarly, an SRE running a mixed online transaction processing (OLTP, the day-to-day inserts and updates that keep an application running) plus analytics pipeline might intentionally let the analytics side read slightly stale or eventually-consistent data (via a replica) while keeping the OLTP writes themselves fully ACID, and catch the gap operationally: an alerting rule on replication lag, a periodic reconciliation job, or a checksum comparison between primary and replica, rather than relying on the database to prevent the staleness at all.
- Don't confuse "the database enforces consistency" with "the database enforces business consistency." The C in ACID only enforces the rules you actually declared (constraints); an invariant that only lives in application code, never expressed as a
CHECKorUNIQUEconstraint, gets no protection from the database at all, however carefully atomicity and isolation are otherwise honored.
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.
A high-throughput OLTP database had its isolation level raised from READ COMMITTED toward REPEATABLE READ or SERIALIZABLE, and write throughput dropped noticeably afterward. Explain why raising isolation level can cause this kind of regression, and walk through how you would diagnose and mitigate it without simply reverting the isolation change.
Sample Answer
Direct answer
Raising isolation level doesn't slow the database down by making individual statements do more work; it slows the database down by turning previously-independent transactions into ones that now wait on each other, or that now sometimes fail outright and have to be retried. Both effects reduce effective write throughput even though the hardware's doing the same amount of underlying work. Diagnosing and fixing it without reverting means narrowing the isolation bump to the specific transactions that actually need it, rather than treating it as a single database-wide setting.
Structured elaboration
Why the regression happens. At Read Committed, two transactions writing to unrelated or lightly-overlapping rows almost never interact; each one takes only the row locks it needs, momentarily, and releases them on commit. Moving to Repeatable Read or Serializable changes that in two distinct ways depending on the engine and level: (a) a transaction's snapshot is now fixed for its whole duration, so if two transactions running concurrently happen to touch the same row, one of them may now be forced into a wait or a conflict it wouldn't have hit under per-statement Read Committed snapshots; (b) at true Serializable specifically, the engine has to track read-write dependencies between transactions (Postgres's predicate locks) and can abort a transaction at commit time for a conflict that was undetectable earlier, meaning some fraction of transactions now do all their work and then get thrown away and have to be retried from scratch, pure wasted throughput. On engines whose Repeatable Read or Serializable is lock-based rather than pure-MVCC (unlike Postgres's snapshot-based Repeatable Read), raising the level can additionally mean writes now take broader locks: a gap lock blocks other transactions from inserting into a range of not-yet-existing rows, and a next-key lock combines that with a lock on the existing row right after the gap (or shared locks on reads under Serializable), and any of these can block other writers outright, not just abort them later.
How to diagnose it, rather than assume. Look for the specific fingerprint of each mechanism: a rising rate of aborted transactions with a serialization-failure SQLSTATE (the five-character error code the database returns with every error, 40001 for a serialization failure) in application logs or pg_stat_database.xact_rollback climbing relative to xact_commit points at (b), retry-driven waste; a rising count of sessions in pg_stat_activity with wait_event_type = 'Lock' points at (a), genuine blocking. Those are different problems with different fixes, so confirm which one is actually happening before changing anything.
Mitigating without simply reverting:
- Scope the isolation bump to the transactions that actually need it, using
SET TRANSACTION ISOLATION LEVELper-transaction rather than a database- or session-wide default. Most of a typical online transaction processing (OLTP) workload doesn't need the stronger guarantee at all; if the change was made broadly "to be safe," narrowing it to the specific write paths with a real cross-row invariant (write-skew risk: two transactions each read a shared condition and write different rows) removes the regression from everything else without giving up the protection where it matters. - Shrink the transactions that do need the stronger level, so each one holds its snapshot and any locks for less time: split a large multi-statement transaction into the smallest unit that still needs to be atomic, and make sure nothing unrelated (an external API call, an unrelated read) is happening inside the transaction boundary and extending how long it's exposed to conflict.
- Add the indexes the affected queries are missing. A query without a good index scans (and, on lock-based engines, locks) a wider range of rows than the logical operation requires; a targeted index can shrink both the work done and the surface area for conflict.
- Add application-level retry with backoff for the (b) failure mode. If Serializable's abort rate under real contention isn't zero, that's expected; the fix is making sure every write path that can hit it retries automatically and transparently, not treating each abort as an incident.
Trade-offs & pitfalls
- Reverting the isolation change entirely trades away whatever correctness problem it was meant to fix; the mitigations above are worth doing specifically because they let the team keep that protection where it's actually needed while giving it back everywhere else.
- Don't assume the regression is caused by locking without checking; on Postgres specifically, Repeatable Read and Serializable are MVCC-based and non-blocking for reads, so a throughput drop after raising isolation there is more likely retry-driven (mechanism b) than genuinely blocking-driven (mechanism a), which points the investigation at
pg_stat_database.xact_rollbackbefore it points atpg_locks.
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).
Unlock Full Question Bank
Get access to all 24 Transactions, Concurrency Control, and Isolation Levels interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.