Skip to content
Tech Interview Prep
Technical interview guide

Transactions & Isolation Levels

ACID guarantees, and the isolation-level trade-off between correctness and concurrent throughput.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the ACID properties, and which one is most often misunderstood.

Answer

The 90-second answer. ACID is four guarantees the transaction manager makes about a group of statements.

  • Atomicity: all statements commit, or none do. A crash or error mid-transaction leaves no partial work; uncommitted changes are undone.
  • Consistency: the transaction takes the database from one state satisfying your declared constraints to another. The database does not invent this property; your schema plus the other three do.
  • Isolation: concurrent transactions don't observe each other's uncommitted work. How much they can observe of each other's committed work is the isolation level; READ COMMITTED is PostgreSQL's default.
  • Durability: once commit returns, the change survives a crash. The WAL record is flushed before the client sees the acknowledgement.

The most misunderstood is consistency. It does not mean the data is correct in any business sense. It means no declared constraint (NOT NULL, UNIQUE, FOREIGN KEY, CHECK) is violated at commit. If your rule isn't declared, the database will let a transaction break it and consistency in the ACID sense still holds.

Here is that gap, on PostgreSQL 16 at the default READ COMMITTED:

SQL
CREATE TABLE orders (id int PRIMARY KEY, total numeric NOT NULL);
CREATE TABLE order_lines (order_id int REFERENCES orders(id), amount numeric NOT NULL);
INSERT INTO orders VALUES (1, 100);
INSERT INTO order_lines VALUES (1, 100);
-- Invariant we care about: orders.total = SUM(order_lines.amount).
-- It is not declared anywhere, so the database cannot enforce it.
A: BEGIN;
B: BEGIN;
A: SELECT total FROM orders WHERE id = 1;   -- 100
B: SELECT total FROM orders WHERE id = 1;   -- 100
A: INSERT INTO order_lines VALUES (1, 30);
A: UPDATE orders SET total = 130 WHERE id = 1;
A: COMMIT;
B: INSERT INTO order_lines VALUES (1, 50);
B: UPDATE orders SET total = 150 WHERE id = 1;   -- B's stale 100 + 50
B: COMMIT;

Final state: total = 150, SUM(amount) = 180. Every ACID property held. Atomicity: both transactions committed in full. Isolation: READ COMMITTED permits exactly this interleaving. Durability: both commits survived. Consistency: no declared constraint was violated. The invariant broke anyway.

What would have caught it: declare the rule where the database can see it. A single-row CHECK (total >= 0) makes the offending transaction abort with SQLSTATE 23514, and atomicity rolls back the whole transaction, line insert included. That is consistency doing its job. A cross-row invariant can't be declared, so you either lock (SELECT total FROM orders WHERE id = 1 FOR UPDATE before the read-modify-write, serialising the two transactions) or run at SERIALIZABLE, where PostgreSQL's SSI aborts one with SQLSTATE 40001 and the application retries.

The second confusion is the letter itself: the C in ACID is not the C in CAP. CAP's C is about distributed replicas agreeing on a value; ACID's C is about declared constraints on one node. They share a letter and nothing else.

Runner-up: durability. It is a configuration, not a constant. With synchronous_commit = off, commit returns before the WAL is flushed, so a crash can lose the last few hundred milliseconds of acknowledged transactions. With asynchronous replication, a commit acknowledged on the primary is gone if the primary dies before the replica receives it. "Durable" means durable under the settings you actually run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Walk me through the states a transaction passes through (active, partially committed, committed, failed, aborted) and what causes each transition?

Answer

The short version. A transaction is a state machine, and the state that carries the most weight is the one between "the last statement finished" and "the commit record is on disk." That is partially committed, and it is the only state where a crash gets to decide the outcome.

BEGIN | v active --statement error--> failed --ROLLBACK--> aborted | | | last statement done | ROLLBACK TO SAVEPOINT v +------> active partially committed | | | COMMIT | crash before the WAL flush v v committed aborted (decided during recovery)

The happy path, in psql 18:

BEGIN; UPDATE accounts SET bal = bal - 100 WHERE id = 1; UPDATE accounts SET bal = bal + 100 WHERE id = 2; COMMIT;

The failure path, which is where the interesting behaviour lives:

BEGIN; UPDATE accounts SET bal = bal - 100 WHERE id = 1; SELECT 1/0; ERROR: division by zero UPDATE accounts SET bal = bal + 100 WHERE id = 2; ERROR: current transaction is aborted, commands ignored until end of transaction block COMMIT; ROLLBACK

Two things to notice. The transaction is in failed, not aborted: it is still open, still holding the row lock on id = 1, and every statement except ROLLBACK and ROLLBACK TO SAVEPOINT is refused with SQLSTATE 25P02. And COMMIT on a failed transaction does not commit; psql prints ROLLBACK because the server converted it.

FromToCause
activepartially committedthe last statement returns without error
activefailedany statement raises: constraint violation, deadlock (40P01), serialization failure (40001), division by zero
failedactiveROLLBACK TO SAVEPOINT, only if a savepoint was taken before the error
failedabortedROLLBACK, or the session ends
partially committedcommittedthe commit record is flushed to WAL: synchronous_commit = on by default
partially committedabortedcrash or power loss before that flush; recovery finds no commit record
committed—terminal, visible to new snapshots

Why commit is a WAL flush, not a data write. The heap pages the transaction dirtied are still sitting in shared_buffers when COMMIT returns. The background writer and checkpoints write them out later. Durability comes entirely from the WAL record, which is why commit latency is roughly one fsync: on the order of 0.5–1 ms on a local SSD, and why group commit folds many concurrent commits into a single flush. If the machine dies in the partially committed state, recovery scans the WAL: commit record present, the change is replayed; absent, the transaction is aborted. That is atomicity, and it is decided at recovery time, not at COMMIT time.

Details an interviewer will pull on. PostgreSQL assigns the transaction ID lazily: BEGIN alone does not get one, the first statement that writes does, so a read-only transaction may never have an XID. Aborted tuples are not deleted; the XID is marked aborted in pg_xact and the dead row versions linger until vacuum. Two states outside the classic five are worth naming: prepared, after PREPARE TRANSACTION for two-phase commit, which survives the session and shows up in pg_prepared_xacts holding its locks; and implicit, where a bare statement outside BEGIN is its own transaction, committed on success.

Failure modes. 25P02 in the logs means an error path that never rolled back. idle in transaction in pg_stat_activity with an old xact_start is the same bug after the client returned the connection to the pool: locks held, vacuum horizon pinned. A forgotten prepared transaction holds locks indefinitely. And a retry loop that re-runs the failed statement instead of issuing ROLLBACK and starting a fresh transaction will spin on 25P02 forever.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Walk through the isolation levels and the anomalies each permits.

Answer

Assume PostgreSQL 16 unless stated. The standard's level names and what an engine actually does diverge in two places, and that divergence is usually the point of the question.

The mapping. Read uncommitted permits dirty reads; PostgreSQL accepts the syntax and silently runs read committed, so dirty reads are impossible there. Read committed is the default: each statement takes a fresh snapshot, so you never see uncommitted rows, but two statements in one transaction can see different data. Repeatable read takes one snapshot at the first statement and holds it for the whole transaction. Serializable adds read/write dependency tracking on top of that snapshot and aborts transactions whose outcome would not match any serial order.

LevelDirty readNon-repeatable readPhantomLost updateWrite skew
Read uncommitted (PG: read committed)noyesyesyesyes
Read committednoyesyesyesyes
Repeatable read (PG: snapshot isolation)nonononoyes
Serializablenonononono

Dirty read = seeing another transaction's uncommitted rows. Non-repeatable read = the same row returns different values across two reads. Phantom = the same query returns a different row set. Two notes on the table: the standard permits phantoms at repeatable read, PostgreSQL's snapshot isolation does not, because the whole transaction reads one snapshot; and "no lost update" at repeatable read is enforced by aborting, not by blocking.

Lost update, traced. Read committed, two sessions, counters(id, n) with n = 10:

A: BEGIN; SELECT n FROM counters WHERE id=1;   -- 10
B: BEGIN; SELECT n FROM counters WHERE id=1;   -- 10
A: UPDATE counters SET n = 11 WHERE id=1; COMMIT;
B: UPDATE counters SET n = 11 WHERE id=1; COMMIT;
-- final n = 11, not 12

B's write overwrites A's. Note that UPDATE counters SET n = n + 1 does not lose the update in PostgreSQL: when B's update blocks on A's row lock and A commits, B re-reads the latest row version and computes 12. The bug is the read-modify-write in the application, not the UPDATE. Fix it with the atomic increment, or SELECT ... FOR UPDATE to take the lock before reading.

Under repeatable read the same sequence fails loudly: B's UPDATE targets a row version newer than B's snapshot, so PostgreSQL raises ERROR: could not serialize access due to concurrent update (SQLSTATE 40001). The transaction must be retried from the start.

Write skew. The on-call table: on_call(name, shift, on_call boolean), invariant "at least one doctor on call per shift". Alice and Bob are both on call. Each transaction runs SELECT count(*) FROM on_call WHERE shift='x' AND on_call (sees 2), then UPDATE on_call SET on_call = false WHERE name = <self>. Both commit under repeatable read; the invariant is now violated with zero doctors on call. Neither transaction wrote the row the other read, so no lock or snapshot conflict fires. Serializable detects the read/write cycle and aborts one with 40001.

Failure modes to name. Serialization failures are expected traffic, not bugs: the retry loop must re-run the entire transaction including the reads, and under contention the abort rate can be high enough that serializable is the wrong choice for a hot path. Long repeatable-read or serializable transactions hold an old snapshot, which delays vacuum and grows table bloat: a batch job that opens one at the start and runs for an hour is a real operational hazard. And read committed's per-statement snapshot means a single long analytical query is consistent, but the transaction around it is not.

What to actually choose. Read committed plus atomic updates or explicit row locks covers most OLTP. Reach for serializable when the invariant spans rows no single lock covers, the on-call case, and you can afford retries. Repeatable read is the right pick for read-only reporting transactions that need one consistent view.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Explain how MVCC lets readers avoid blocking writers.

Answer

The 90-second answer. Assume PostgreSQL-style MVCC (heap tuples stamped with xmin/xmax) unless stated otherwise. A write never overwrites a row in place. UPDATE writes a new tuple version and stamps the old one with the updater's transaction id in xmax; DELETE only stamps xmax and leaves the bytes. So every version records who created it (xmin) and who removed it (xmax).

A reader takes a snapshot: the set of transaction ids committed at some instant, plus the ids still in flight, and for each version asks two questions: was xmin committed and visible in my snapshot, and is xmax unset or not visible? If both hold, that version is the row. The reader never touches the writer's new version and takes no row lock, so it cannot block the writer; the writer only appends, so it cannot block the reader. The only waiting is writer-versus-writer on the same row.

Trace it. Row t(id=1, v=10) was created by xid 100 and committed.

stepsession A (xid 200)session B (xid 201)tuple state
1BEGIN; UPDATE t SET v=20 WHERE id=1;—new (1,20) xmin=200, xmax=0; old (1,10) xmin=100, xmax=200
2(uncommitted)BEGIN; SELECT v FROM t WHERE id=1;snapshot = committed {100}, in flight {200}. Old tuple: xmin=100 visible, xmax=200 in flight → not deleted → returns 10, no lock, no wait
3COMMIT;—xid 200 now committed
4—next SELECT (read committed)fresh snapshot {100, 200}: old tuple's xmax=200 is now visible → invisible; new tuple xmin=200 visible → returns 20
5—same SELECT under repeatable readsnapshot fixed at step 2 → still returns 10 for the rest of the transaction

When the snapshot is taken is what the isolation level controls:

levelsnapshotreader sees
read committed (PostgreSQL default)per statementlatest committed state at statement start
repeatable readper transaction, at first statementone fixed point for the whole transaction
serializablesame as repeatable read, plus SSI conflict trackingaborts on dangerous read/write structures

Writer-writer is the only real wait. If B updates the row A already updated, B blocks on A's xid until A ends. On A's commit, read committed re-evaluates B's update against the new version; repeatable read instead raises ERROR: could not serialize access due to concurrent update (SQLSTATE 40001) and the application must retry. That ordering is genuinely required: one update has to be applied after the other.

Failure modes worth naming.

  • Bloat. Hypothetically, 10M rows at 100 B is 1 GB live; 10 updates per row per day leaves 100M dead tuples/day, roughly 10 GB/day of dead space that only vacuum reclaims. Detect with pg_stat_user_tables.n_dead_tup and the oldest xmin in pg_stat_activity.
  • Long transactions pin the horizon. Vacuum cannot remove any version whose xmax is at or above the oldest snapshot's xmin. One session left idle in transaction for eight hours freezes cleanup database-wide. Detect with SELECT pid, state, xact_start FROM pg_stat_activity ORDER BY xact_start LIMIT 5; and cap it with idle_in_transaction_session_timeout.
  • Write skew. Snapshot isolation is not serializable: two transactions can read the same rows and write disjoint ones, both commit, and break an invariant. Detect by running SERIALIZABLE (SSI) and retrying on 40001.

Contrasts. Lock-based two-phase locking has readers take shared locks and writers exclusive ones, so reads and writes contend directly: no version accumulation, far worse for mixed workloads. Undo-based engines (InnoDB, Oracle) keep old versions in an undo log or rollback segment with a purge thread; bloat shows up as undo tablespace growth and InnoDB history list length rather than table bloat, but a long transaction pins cleanup the same way. One caveat even in PostgreSQL: SELECT holds an AccessShareLock on the table, and ALTER TABLE needs AccessExclusiveLock, so a long-running query can block DDL even though it never blocks a row write.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

What is snapshot isolation, how does it relate to repeatable read and serializable, and what anomaly does it still permit?

Answer

Snapshot isolation means every statement in a transaction reads from one consistent snapshot of committed data, taken when the transaction's first query starts, not at BEGIN. Writers create new row versions instead of overwriting, so readers never block writers and writers never block readers. The only write-write conflict is two transactions touching the same row: the second to try gets could not serialize access due to concurrent update (SQLSTATE 40001) and must retry. That is first-updater-wins.

In PostgreSQL, REPEATABLE READ is snapshot isolation. It is stronger than the SQL standard's minimum for repeatable read, it also prevents phantoms, but weaker than serializable. SERIALIZABLE in PostgreSQL is Serializable Snapshot Isolation: the same snapshots, plus tracking of read-write dependencies (SIREAD predicate locks) to detect cycles, aborting a transaction with 40001 when committing would produce a non-serializable outcome. It does not block; it aborts.

LevelRead snapshotSame-row write conflictStill possible
Read committednew snapshot per statementsecond waits, then re-readsnon-repeatable read, phantom, write skew
Repeatable read (= snapshot isolation)one snapshot per transactionfirst updater wins, 40001write skew
Serializable (SSI)one snapshot + rw-dependency tracking40001 on a dangerous cyclenothing: false positives abort, they don't corrupt

The anomaly snapshot isolation still permits is write skew: two transactions read overlapping data, write disjoint rows, and each write is individually valid but the pair is not. The on-call example from the PostgreSQL docs:

sql -- doctors(id, name, on_call); Alice and Bob are on call -- T1 and T2, both BEGIN ISOLATION LEVEL REPEATABLE READ SELECT count() FROM doctors WHERE on_call; -- both see 2 UPDATE doctors SET on_call = false WHERE name = 'Alice'; -- T1 UPDATE doctors SET on_call = false WHERE name = 'Bob'; -- T2 COMMIT; -- both succeed, no row conflict, no error -- count() WHERE on_call is now 0

Neither transaction wrote the row the other wrote, so first-updater-wins never fires. Under SERIALIZABLE, SSI sees the rw-antidependency cycle and aborts one with 40001.

Operational consequences worth stating. A repeatable-read transaction holds its snapshot for its whole life, which pins the xmin horizon and delays vacuum: a long-running report at repeatable read causes bloat, not just latency. SSI aborts are expected traffic, not bugs, so the retry loop is mandatory and the retried work must be idempotent. And the level name is not portable: Oracle's SERIALIZABLE is snapshot isolation without the conflict detection, so code relying on serializable semantics there can write-skew.

Use repeatable read when you need a stable view and can tolerate write skew: reports, read-mostly work, or writes that only ever touch rows they read. Use serializable when the invariant spans rows you read but do not write, and you can afford retries. Read-only serializable transactions can be declared DEFERRABLE to wait for a safe snapshot instead of aborting.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does Two-Phase Locking (2PL) differ from Multi-Version Concurrency Control (MVCC) in managing transaction concurrency?

Answer

The 60-second answer. 2PL is pessimistic mutual exclusion on the current row: shared locks for reads, exclusive locks for writes, held until the transaction ends. MVCC is versioning: an update writes a new row version instead of overwriting, and each transaction reads a snapshot of the versions visible to it. The consequence is that 2PL makes readers and writers block each other, while MVCC makes reads non-blocking and moves the cost to storage, vacuum, and write-write conflicts.

2PL mechanics. Two phases: growing (acquire only) and shrinking (release only). Basic 2PL gives conflict serializability but permits cascading aborts. Strict 2PL holds exclusive locks to commit; rigorous 2PL holds all locks, shared and exclusive, to commit, which is what production engines actually implement. Lock compatibility is the whole story:

held \ requestedSX
Sokwait
Xwaitwait

Two shared locks coexist; anything involving X waits. Deadlock is structural, not a bug: T1 holds S on row 1 and wants X on row 2 while T2 holds S on row 2 and wants X on row 1. PostgreSQL's deadlock_timeout (default 1s) triggers a cycle check and aborts one with SQLSTATE 40P01. 2PL keeps no row versions, but it still writes WAL and undo: the saving is version storage, not logging.

MVCC mechanics (PostgreSQL). A tuple carries xmin (inserting xid) and xmax (deleting or locking xid). An UPDATE writes a new tuple with a new xmin and stamps the old tuple's xmax. A transaction's snapshot is (xmin, xmax, xip_list): the in-flight xids at snapshot time. Visibility is a pure function of that snapshot, so a reader takes no lock and never waits.

Trace: reader vs writer. Setup: CREATE TABLE accounts (id int PRIMARY KEY, balance int); INSERT INTO accounts VALUES (1,100);

Session A:

SQL
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;   -- 100

Session B:

SQL
UPDATE accounts SET balance = 200 WHERE id = 1;  -- UPDATE 1, no wait

Session A:

SQL
SELECT balance FROM accounts WHERE id = 1;   -- still 100
COMMIT;

A's next transaction reads 200. Under 2PL, B's UPDATE would have queued behind A's shared lock for the whole transaction.

Trace: writer vs writer. Both sessions run BEGIN; UPDATE accounts SET balance = balance + 10 WHERE id = 1;. B blocks on A's row lock. When A commits, B's outcome depends on isolation:

  • READ COMMITTED (PostgreSQL default): B re-evaluates the row against the new version and applies it, so 100 → 110 → 120.
  • REPEATABLE READ: B fails with ERROR: could not serialize access due to concurrent update (SQLSTATE 40001) and the application must retry the whole transaction.

Where each one hurts.

2PL: lock convoy and deadlock. A long analytics scan holding shared locks across a table stalls every writer behind it, and lock memory grows with concurrency. Detect with pg_locks or SHOW ENGINE INNODB STATUS; mitigate with shorter transactions, consistent lock ordering, or SELECT ... FOR UPDATE SKIP LOCKED for queue tables.

MVCC: bloat and the vacuum horizon. Dead tuples cannot be reclaimed while any snapshot can still see them, so one idle-in-transaction session pins the horizon and VACUUM reclaims nothing newer. Autovacuum fires at autovacuum_vacuum_threshold (50) + autovacuum_vacuum_scale_factor (0.2) × table rows: on a 100M-row table that is 20M dead tuples before it triggers, which is why large tables need per-table scale factors. Every non-HOT update also writes a new index entry; HOT applies only when no indexed column changes and the page has room, and with the default fillfactor of 100 that room usually appears only after pruning.

Isolation. 2PL gives serializability directly. MVCC gives snapshot isolation, which permits write skew; PostgreSQL's Serializable (SSI, 9.1+) adds SIREAD predicate locks that do not block but track rw-dependencies and abort dangerous cycles with 40001. Oracle's SERIALIZABLE is snapshot isolation, not serializable. MySQL InnoDB defaults to REPEATABLE READ and uses next-key locks for writes, so it blocks more than PostgreSQL does.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Explain what happens during a commit and what could make it fail.

Answer

The 90-second version. A commit is a durability operation, not a visibility one. The database appends a commit record to the write-ahead log, flushes the log to durable storage, and only after that flush returns does it tell the client "committed". The table pages the transaction touched are still dirty in the buffer pool and may not reach disk for minutes. That is the point of write-ahead logging: the log is the authority, and recovery replays it.

In PostgreSQL the path is:

  1. CommitTransaction() calls RecordTransactionCommit(), which inserts an XLOG_XACT_COMMIT record into the WAL buffers.
  2. XLogFlush() writes WAL up to that record's LSN and calls fsync() (or fdatasync, per wal_sync_method).
  3. Only after fsync returns does ProcArrayEndTransaction() clear the transaction's XID from the running-transactions array. Snapshots taken after this point no longer see the XID as in-progress.
  4. The commit status in pg_xact (clog) is set in memory and flushed lazily: it is not fsynced at commit. After a crash, recovery rebuilds clog from the WAL commit records.

A transaction that wrote nothing skips all of it: no WAL record, no flush, commit returns immediately.

Two things fall out of this. Group commit: backends that commit while a flush is already in flight wait on the same fsync, so throughput scales with batch size rather than with fsync count. And synchronous_commit decides how much of the above you wait for: off skips the local flush wait, local waits for local fsync, on (the default) also waits for a standby to fsync its copy, remote_apply waits for the standby to make it visible to queries.

What makes it fail.

FailureSurfaces atSQLSTATESafe to retry?
Deferred constraint violationCOMMIT23503, 23505, 23514, 23P01No: the data is wrong
Serialization failureCOMMIT40001Yes, always
Disk fullWAL flush53100No, until space is freed
fsync failureWAL flushPANIC, no SQLSTATENo: server crashes and recovers
Sync standby goneWAL flush waitblocks; client sees timeout or connection lossAmbiguous
Connection lost mid-commitclient08007Ambiguous

Deferred constraints. DEFERRABLE INITIALLY DEFERRED moves the check from the statement to the commit. Every statement returned success; the commit is the first place the violation is visible.

SQL
-- PostgreSQL 16
BEGIN;
INSERT INTO shifts (id, doctor_id) VALUES (1, 42);   -- INSERT 0 1
COMMIT;
-- ERROR:  insert or update on table "shifts" violates foreign key constraint
--         "shifts_doctor_id_fkey"
-- DETAIL:  Key (doctor_id)=(42) is not present in table "doctors".
-- SQLSTATE: 23503

Serialization failures. Under REPEATABLE READ and SERIALIZABLE, PostgreSQL runs SSI, and a dangerous structure may only be detectable when the transaction tries to commit. The transaction did nothing wrong. 40001 is a retry signal, not an error to report: the retry loop is mandatory, not defensive.

Disk and fsync. If the WAL flush cannot complete, the commit must fail; acknowledging a commit whose log record is not on disk is the one thing WAL exists to prevent. PostgreSQL escalates a failed fsync to a PANIC rather than a retryable error: it would rather crash and recover from WAL than keep serving on data it cannot prove is durable.

Synchronous replication. With synchronous_standby_names set, the commit waits for the standby. If the standby goes away, the commit blocks: there is no built-in timeout on that wait. The walsender notices the dead connection and exits, but the waiting backend re-evaluates, finds no synchronous standby, and keeps waiting. In practice the wait ends when the client's connection or statement_timeout kills it, or when the standby returns. This is the classic sync-rep outage: one standby's death stalls every write on the primary.

The ambiguous case. If the connection drops between the client sending COMMIT and receiving the acknowledgement, the client cannot know the outcome. SQLSTATE 08007 (transaction_resolution_unknown) is the protocol saying exactly that. Retrying may duplicate; not retrying may lose. No transaction machinery fixes this, because the uncertainty is in the network. The fix is application-level: a natural key or an idempotency token written in the same transaction, so the retry collides on a unique index instead of duplicating.

SQL
BEGIN;
INSERT INTO payments (idempotency_key, amount) VALUES ('ord-8812', 4200);
-- unique index on idempotency_key; a retry raises 23505 and the app returns the first result
COMMIT;

Two-phase commit adds a second failure point: PREPARE TRANSACTION flushes a prepare record and returns, then COMMIT PREPARED is a separate commit that can fail on its own, and the prepared transaction holds its locks until it resolves. max_prepared_transactions defaults to 0, so it is off unless you turn it on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

How should transaction boundaries be chosen in application code?

Answer

A transaction should span exactly one unit of work, the set of changes that must all happen or none happen, and nothing more.

That gives two rules pulling in opposite directions, and getting the balance right is the skill. Wide enough that related changes are atomic: creating an order and its lines belongs in one transaction, because an order with no lines is an invalid state. Narrow enough that nothing slow or external happens inside: no HTTP calls, no file uploads, no waiting for user input, no sending email.

The reason for the second is that transaction duration has costs entirely disproportionate to what the code appears to be doing: locks held, a connection occupied, vacuum blocked database-wide, and a wider window for conflicts. An external call inside a transaction means an unrelated service's latency becomes your database's problem, and its timeout becomes your outage.

The pattern I follow: do the external work first where possible, gathering everything needed; then open the transaction; write; commit; then perform side effects, or write an outbox row inside the transaction and let a worker handle them.

Structurally, the boundary belongs at a well-defined layer, a service method or a unit-of-work wrapper, rather than being started and committed at scattered call sites. Scattered boundaries produce nested-transaction confusion, functions that behave differently depending on whether a caller already opened one, and connection-mismatch bugs where part of the work runs outside the transaction entirely.

On nesting: most frameworks implement nested transactions with savepoints rather than genuine nesting, so an inner rollback does not necessarily do what a naive reading suggests. I would avoid relying on nesting and make the boundary explicit at one level.

The anti-pattern worth naming is the request-scoped transaction: opening one at the start of an HTTP request and committing at the end. It is convenient and it means transaction duration is request duration, including template rendering and any slow call anywhere in the handler. It works fine until traffic grows, and then it is a diffuse problem that is hard to attribute.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain what a savepoint is and when it is useful.

Answer

A savepoint marks a point within a transaction that you can roll back to without abandoning the whole transaction. Work after the savepoint is undone; work before it survives, and the transaction continues.

The genuinely useful case is attempting something that may fail without wanting the failure to destroy everything. In PostgreSQL specifically this matters more than elsewhere, because any error aborts the entire transaction: after an error, every subsequent statement fails with 'current transaction is aborted' until you roll back. So attempting an insert that might violate a unique constraint, and continuing afterwards, is only possible with a savepoint around it.

That is why most database libraries implement 'nested transactions' as savepoints: an inner block that fails rolls back to its savepoint while the outer transaction continues.

The uses I would accept: batch processing where individual item failures should be recorded and skipped rather than failing the whole batch; and a genuine try-alternative flow where the fallback needs the earlier work intact.

The caution is that savepoints are not free. Each has overhead, and creating one per row in a large loop is a common performance problem: it can dominate the cost of the batch. For bulk work, I would rather validate up front so failures do not happen, or process in chunks with a savepoint per chunk rather than per row.

The deeper caution is that reaching for savepoints often signals the transaction is doing too much. If a transaction contains work that might fail independently and should be independently retained, that is a hint it is really several units of work, and separate transactions express that more honestly than one transaction with partial rollbacks. I would ask that question before adding them.

And they do not change the transaction's overall duration or its effect on locks and vacuum: a long transaction with savepoints is still a long transaction.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Why should network calls and long-running non-database work be avoided inside an active database transaction?

Answer

An active database transaction reserves scarce physical and logical resources: an open client connection from the application pool, a backend worker process on the database host, row- or table-level locks, and an active MVCC transaction horizon (xmin). Introducing network calls or slow computation inside that window ties database resource duration directly to external latency, leading to three cascading failure modes.

1. Connection Pool Exhaustion

Connection pools (such as HikariCP or PgBouncer in transaction-pooling mode) are dimensioned for fast SQL query round-trips (typically 1–10 ms). If a transaction performs an HTTP call to a third-party payment gateway that takes 1,500 ms under a downstream degradation, that pooled connection is pinned in idle in transaction state for the entire duration.

Normal:   [Tx: SQL 5ms] -> Connection released back to pool
Degraded: [Tx: SQL 2ms -> HTTP 1500ms -> SQL 2ms] -> Connection held for 1504ms

If the connection pool size is 50, a throughput of just 35 requests/sec with a 1,500 ms call will exhaust the pool entirely ($50 / 1.5\text{s} \approx 33.3\text{ req/s}$). Unrelated requests waiting for a database connection time out, taking down the entire service.

2. Lock Contention and Cascading Queues

If the transaction executes an update, insert, or SELECT ... FOR UPDATE before the network call, PostgreSQL holds exclusive locks (such as RowExclusiveLock or row-level ExclusiveLock) until explicit COMMIT or ROLLBACK.

Any concurrent transaction attempting to read or write those rows under pessimistic locking, or modify foreign-key targets, queues behind the locked rows in LockManager. As waiting transactions stack up, active server threads multiply, triggering OS context switching, memory consumption, and eventual client timeouts.

3. MVCC Snapshot Retention and Table Bloat

PostgreSQL uses MVCC to determine row visibility. An open transaction retains an active xmin (the oldest transaction ID whose changes it may need to observe). Under Routine Vacuuming, autovacuum cannot purge dead row versions (tuples) whose deletion happened after that transaction's snapshot horizon.

A transaction held open by a slow external call prevents cleanup of dead tuples across all tables it touched or could observe. High-churn tables rapidly bloat, blowing out buffer cache hit rates and degrading sequential scans.

Architectural Remediation

  1. Shift external calls outside transaction boundaries: Execute the network call first, then open a short transaction only to persist results; or commit state transitions locally first and dispatch calls asynchronously.
  2. Database guardrails: Configure defensive timeouts to terminate rogue transactions:
SQL
-- Terminate transactions sitting idle inside application code
SET idle_in_transaction_session_timeout = '5s';
-- Bound lock waiting to fail fast rather than pile up queues
SET lock_timeout = '2s';

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Explain the difference between a transaction being slow and a transaction being long.

Answer

They are different problems with different consequences, and conflating them sends investigations in the wrong direction.

A slow transaction spends its time doing work: queries that take a long time. The cost is mostly borne by the caller waiting, and the remedy is query optimisation.

A long transaction is open for a long time, regardless of whether it is doing anything. Its cost is borne by the whole database: it pins the vacuum horizon so dead row versions accumulate everywhere, it holds any locks it has taken, it occupies a connection, and at higher isolation levels it accumulates a larger conflict window and is more likely to fail at commit.

The distinction matters most because a transaction can be long without being slow at all. The most damaging case in practice is idle-in-transaction: the application issued BEGIN, ran a fast query, and then never committed, because of an error path that returned early, a connection returned to a pool without rollback, or a developer's psql session left open. Every individual query was fast. The transaction is doing nothing. And it is blocking vacuum database-wide for as long as it lives.

That case is invisible to query-performance monitoring, which looks at statements. Nothing is slow. You only see it by looking at transaction age, which is why xact_start in pg_stat_activity and an alert on the oldest transaction are worth having specifically.

The reverse also occurs: a genuinely slow query in autocommit is not a long transaction at all, so it harms the caller and nobody else.

The practical consequences differ accordingly. For slow, optimise the query. For long, find why the transaction is open (usually a code path, not a query) and set idle_in_transaction_session_timeout so the database defends itself rather than relying on every code path being correct.

And for a legitimately long-running read, such as a large report, the answer is to run it somewhere its snapshot does not matter, a replica, rather than trying to make it shorter.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Why are long-running transactions dangerous, and how would you find them?

Answer

Under MVCC an update writes a new row version and leaves the old one; a delete only marks a row dead. Those old versions can only be reclaimed once no transaction might still need them. So an open transaction pins the cleanup horizon, and vacuum cannot remove anything newer than its snapshot: database-wide, not just for tables it touched.

The consequence is bloat: tables and indexes grow with dead versions, scans read more pages, and cache efficiency falls. Because the effect is proportional to how much churn happens while the transaction is open, one transaction left open overnight on a busy database can cause bloat that takes a rebuild to recover.

The crucial and counterintuitive part is that the transaction does not need to be doing anything. An idle-in-transaction session: a connection where the application issued BEGIN, did some work, and never committed or rolled back: is just as damaging as a running one. It is idle, invisible in query monitoring, and holding the whole database's cleanup hostage.

Other harms: locks held for the duration block conflicting writes, and at repeatable read or serializable a long transaction has a larger conflict window and is more likely to fail on commit after doing a lot of work.

Finding them: query pg_stat_activity for backends whose xact_start is old, paying particular attention to state = 'idle in transaction'. I would alert on the oldest transaction age: this is one of the highest-value database alerts available, because the fix is trivial and the damage is not.

Preventing them: set idle_in_transaction_session_timeout so the database terminates abandoned transactions itself rather than relying on application correctness. Set a statement timeout so a runaway query cannot run for hours. Keep transactions short, never open one across an external API call, and never open one and wait for user input.

The common causes worth checking are an application error path that returns without rolling back, a connection pool handing out a connection with an open transaction, and a developer's psql session left open after an investigation: that last one being genuinely frequent.

For legitimately long reads, such as a large report, the right approach is a read-only transaction on a replica, so the primary's cleanup is unaffected.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain deadlocks and how you would prevent and handle them.

Answer

The 90-second version. A deadlock is a cycle in the wait-for graph: T1 holds a lock T2 needs, T2 holds one T1 needs, neither can move. Every engine I'd use detects the cycle and aborts one transaction instead of waiting forever. So the answer splits in two: design the cycle out (consistent lock ordering, short transactions, no lock upgrades) and treat the abort as a retryable error sharing the retry loop you already have for serialization failures.

Assumptions: one database, row-level locking, READ COMMITTED or REPEATABLE READ, and no external side effects inside the transaction.

The trace. Two sessions, accounts(id, balance), both transferring between accounts 1 and 2:

S1: BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1;   -- holds row 1
S2: BEGIN; UPDATE accounts SET balance = balance + 100 WHERE id = 2;   -- holds row 2
S1: UPDATE accounts SET balance = balance + 100 WHERE id = 2;          -- blocks on S2
S2: UPDATE accounts SET balance = balance - 100 WHERE id = 1;          -- blocks on S1 -> cycle

PostgreSQL waits deadlock_timeout (default 1s) before running a deadlock check, so the victim sits blocked for about a second, then gets SQLSTATE 40P01 and is rolled back, releasing row 1. S1's blocked statement then completes. The loser's work is gone; the winner's is committed.

Prevention: lock in a fixed order. If every transaction takes locks in the same order, a cycle cannot form. A transaction holding the lower key never waits on one holding a higher key. In application code, sort the ids and lock one row at a time:

SQL
-- transfer(from_id, to_id, amount); ids sorted ascending in the caller
BEGIN;
SELECT id FROM accounts WHERE id = :lo FOR UPDATE;
SELECT id FROM accounts WHERE id = :hi FOR UPDATE;
UPDATE accounts SET balance = balance - :amount WHERE id = :from_id;
UPDATE accounts SET balance = balance + :amount WHERE id = :to_id;
COMMIT;

A single SELECT ... WHERE id IN (:a, :b) ORDER BY id FOR UPDATE also works in PostgreSQL, because the LockRows node sits above the Sort and locks rows as they come out, but that is a plan detail, so check EXPLAIN before relying on it.

Other real sources. Lock upgrades: two transactions each take FOR SHARE on a row and then both try to UPDATE it. Each waits for the other's share lock to drop. Take FOR UPDATE up front when you know you will write. Foreign keys: inserting a child row takes a key-share lock on the parent, so a concurrent parent update can deadlock with it. Bulk statements: UPDATE ... WHERE ... locks rows in plan order, so two such statements can deadlock even with no explicit ordering in the code. Add ORDER BY id in a subquery or process in batches.

Detection, per engine.

EngineDetectorErrorVictim
PostgreSQLwait-for graph, checked after deadlock_timeout (1s)SQLSTATE 40P01the transaction whose check found the cycle
MySQL/InnoDBcycle detection on by default (innodb_deadlock_detect=ON)error 1213the smaller transaction, fewest rows modified
SQL Serverlock monitor, every 5serror 1205a chosen victim, usually the cheapest to roll back

With InnoDB detection off, you fall back to innodb_lock_wait_timeout (default 50s): a 50-second stall instead of a fast abort.

Handling: retry the whole transaction.

Python
# psycopg 3, PostgreSQL 16
import random, time, psycopg

RETRYABLE = {"40P01", "40001"}  # deadlock_detected, serialization_failure

def with_retry(fn, attempts=5):
    for i in range(attempts):
        try:
            return fn()          # fn opens, runs and commits one transaction
        except psycopg.errors.Error as e:
            if e.sqlstate not in RETRYABLE or i == attempts - 1:
                raise
            time.sleep(random.uniform(0, 0.05 * 2 ** i))  # jittered backoff

Retry the transaction, not the statement: the aborted transaction's earlier statements are gone. Jitter matters: synchronized retries re-collide and turn one deadlock into a retry storm. And the precondition is the same as for serialization failures: nothing outside the database may have happened yet, or the retry duplicates it.

Diagnosis. PostgreSQL logs deadlock detected with both statements and the PIDs; log_lock_waits plus a lower deadlock_timeout surfaces the waits before they cycle. MySQL's SHOW ENGINE INNODB STATUS has a LATEST DETECTED DEADLOCK section listing each transaction's statement and the locks held and waited on. That usually names the two code paths on the first read.

Failure mode to watch. A steady deadlock rate absorbed by retries is a design signal, not noise: either lock ordering is inconsistent on one path, or a transaction is holding locks far longer than it needs to. Retries hide the cost while contention keeps growing. Across services there is no global detector at all: a distributed cycle just looks like two hung requests, so bound it with lock timeouts and idempotent operations.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Explain optimistic versus pessimistic concurrency control.

Answer

The 90-second answer. Both mechanisms solve the same problem: two transactions read the same row and both try to change it. Pessimistic control stops the second one before it does any work, by locking the row. Optimistic control lets both proceed and rejects the loser at write time, by checking a version. Choose pessimistic when the critical section is short and contention is high; choose optimistic when the work spans a user's think time or conflicts are genuinely rare. The constraint that usually decides it is hold time, not contention: you cannot hold a database lock across a form submission.

Pessimistic, concretely.

SQL
BEGIN;
SELECT balance FROM accounts WHERE id = 42 FOR UPDATE;  -- row lock held until COMMIT
UPDATE accounts SET balance = balance - 100 WHERE id = 42;
COMMIT;

A second session running the same SELECT ... FOR UPDATE blocks. Under Postgres READ COMMITTED, when the first commits, the waiter re-evaluates its WHERE clause against the new row version, so it sees the updated row rather than a stale one, and gets zero rows if the row no longer matches. In MySQL InnoDB (default REPEATABLE READ) the same statement takes next-key locks that can also lock the gap after the row, which is where a lot of surprise deadlocks come from. Readers using plain SELECT are never blocked in either engine; MVCC means pessimistic locking blocks writers only.

Optimistic, concretely.

SQL
-- read
SELECT balance, version FROM accounts WHERE id = 42;   -- (500, 7)
-- write: version bumped in the same statement as the change
UPDATE accounts SET balance = balance - 100, version = version + 1
 WHERE id = 42 AND version = 7;
-- 0 rows affected → someone else committed first; re-read and retry

Trace it with two sessions. A and B both read (500, 7). A runs the update: 1 row affected, row is now (400, 8), A commits. B runs the same update with version = 7: 0 rows affected. B re-reads (400, 8) and retries with version = 8: 1 row affected, row is (300, 9). No lock was ever held, and B learned about the conflict instead of silently overwriting A.

pessimisticoptimistic
lock heldSELECT ... FOR UPDATE → COMMITnone
conflict costwait, while holding a connectionwasted work, then retry
safe across user think timenoyes
surfaces the conflict to the userno: it prevents ityes: you can show a diff
degrades whenlock waits and deadlocks pile upcontention rises, retries multiply

Failure modes. Pessimistic: a transaction held open for five minutes pins Postgres's xmin horizon, so autovacuum cannot remove any dead tuple created after it started, in any table. That is table bloat, not just a blocked writer. Waiting transactions each hold a pool connection, so a hot row can exhaust the pool. Lock waits surface as lock_timeout errors (default 0, meaning wait forever) and deadlocks are detected after deadlock_timeout (default 1s). Detect with pg_locks joined to pg_stat_activity where wait_event_type = 'Lock', plus log_lock_waits = on.

Optimistic: retry storms. If 100 writers/s hit one row and each read-to-write window is 5 ms, roughly half of attempts collide (λw = 0.5), so expected attempts are 1/(1−0.5) = 2: double the work, and throughput can fall as load rises. Detect by counting rows-affected = 0 per endpoint. Two implementation traps: bumping the version in a separate statement from the change makes the check itself racy, and not checking rows-affected at all gives you silent last-write-wins, which users experience as lost edits.

Alternatives worth naming. For a counter or balance, skip the read entirely: UPDATE accounts SET balance = balance - 100 WHERE id = 42 AND balance >= 100 is atomic and needs no version. For queue-style work distribution, SELECT ... FOR UPDATE SKIP LOCKED hands each worker a different row. Postgres SERIALIZABLE (SSI) gives database-level optimistic control that aborts with SQLSTATE 40001, and you retry the whole transaction. At the HTTP layer, ETag plus If-Match is the same version check applied to a request body.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

A counter is undercounting under load. Diagnose and fix it.

Answer

This is almost certainly a lost update. The code reads the current value, adds one in the application, and writes it back. Two concurrent requests both read 10, both compute 11, both write 11: two increments, one recorded, no error anywhere.

The tell is that undercounting scales with concurrency: barely visible in testing, obvious under load. If someone says 'it's only wrong sometimes, and more often when busy', that is this.

The simplest fix, and the one I would use, is to make the read and write a single statement: UPDATE counters SET value = value + 1 WHERE id = :id. There is no window between reading and writing because the database does both atomically while holding the row lock it takes for the update. No isolation level change, no locking clause, no retry logic.

The alternatives, and when they apply. SELECT ... FOR UPDATE before the read-modify-write serialises it, and is the right answer when the new value genuinely cannot be computed in SQL: it depends on an external call, or on complex application logic. Repeatable read turns the conflict into a serialization failure that you retry, which works but needs a retry loop for something a single statement solves. Optimistic concurrency with a version column detects the conflict and retries, which suits a form-based edit where a user held the record for minutes.

So my rule: if the new value is a function of the old that SQL can express, use one statement. Reach for locking only when it genuinely cannot be.

One caution: a single hot counter row serialises every writer on that row, so at high rates it becomes a bottleneck regardless of correctness. If that bites, the answer is sharding the counter into several rows summed on read, or aggregating from an append-only event table: both of which trade read cost for write concurrency.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

What happens if two transactions update the same row at read committed?

Answer

The second transaction's update blocks until the first commits or rolls back. Writers conflict on the same row; that is the one case MVCC cannot make non-blocking, because one write must be ordered after the other.

What happens next depends on the first transaction's outcome. If it rolls back, the second proceeds against the original row as though nothing happened. If it commits, PostgreSQL does something specific and worth knowing: the second transaction re-reads the updated row and re-evaluates its WHERE clause against the new version. If the row still matches, the update applies to the new version. If it no longer matches, the row is skipped.

This is unusual and it has real consequences. It means an UPDATE ... WHERE status = 'pending' will not update a row that another transaction just moved to 'complete', even though it matched when the statement began, which is generally the behaviour you want, and prevents a class of lost update.

But it also means a statement can behave inconsistently with its own snapshot: the update sees a newer version than a SELECT in the same transaction would. And the re-evaluation only helps for the rows the statement is updating: it does nothing for a value read earlier in the transaction and used to compute the new one. So the classic read-then-write lost update is still fully possible: both transactions read 10, the first writes 11, the second blocks, then writes its own 11 computed from the stale read. The re-evaluation does not save you, because the WHERE clause on the id still matches.

That distinction is the practically important one. Read committed protects a single self-contained UPDATE statement quite well, and protects a read-then-write across statements not at all.

So: UPDATE counters SET value = value + 1 is safe, and SELECT value then UPDATE counters SET value = :computed is not. If the value must be computed outside SQL, SELECT ... FOR UPDATE takes the lock at read time and closes the window, or use repeatable read and retry the serialization failure.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do transactions interact with connection pooling?

Answer

A transaction lives on exactly one connection. Everything the pool does (when it hands a connection out, when it takes it back, what state it resets) either preserves that or breaks it.

The core answer. Three rules. Every statement in a transaction must run on the connection that opened it. A connection must never go back to the pool with a transaction open. And the pooling mode decides which session state survives between transactions: transaction pooling silently drops most of it.

Rule 1, in code. A helper that reaches for the pool independently gets a different session:

Python
# psycopg 3.1 + psycopg_pool, PostgreSQL 16
def transfer(pool, src, dst, amount):
    with pool.connection() as conn:                 # connection A
        with conn.transaction():                    # BEGIN ... COMMIT / ROLLBACK
            conn.execute("UPDATE accounts SET bal = bal - %s WHERE id = %s", (amount, src))
            audit(pool, src, dst, amount)           # takes connection B
            conn.execute("UPDATE accounts SET bal = bal + %s WHERE id = %s", (amount, dst))

def audit(pool, src, dst, amount):
    with pool.connection() as conn:                 # connection B, different session
        conn.execute("INSERT INTO audit_log (src, dst, amount) VALUES (%s, %s, %s)",
                     (src, dst, amount))
        conn.commit()

Trace it. t0 conn A begins and debits id=1, holding a row lock. t1 conn B inserts the audit row and commits: it cannot see the uncommitted debit, so any balance it recomputes is the pre-debit value. t2 conn A credits id=2. If that credit fails (id=2 missing, constraint violation), conn.transaction() rolls back: the debit is undone, the audit row from t1 stays. The log now records a transfer that never happened. Nothing in the pool reports an error: the two connections were used correctly, just not together.

Rule 2: return clean. A connection handed back mid-transaction gives the next borrower an open transaction it knows nothing about, plus the row locks and the snapshot that blocks vacuum. HikariCP rolls back on return when autoCommit is false and a statement has run; its defaults are maximumPoolSize=10 and connectionTimeout=30000 ms. That is a client-side guard, not a guarantee: a crashed process returns nothing. PostgreSQL's backstop is idle_in_transaction_session_timeout, which defaults to 0 (disabled) and has existed since 9.6; set it to something like 30s on the server or per role. Find leaks with:

SQL
SELECT pid, now() - state_change AS idle_for, left(query, 60)
FROM pg_stat_activity
WHERE state IN ('idle in transaction', 'idle in transaction (aborted)')
ORDER BY idle_for DESC;

Rule 3: pooling mode.

modeconnection held forwhat breaks
sessionthe client's whole sessionnothing; multiplexing is poor
transactionone transactionsession state: prepared statements, session-level SET, session advisory locks (pg_advisory_lock; pg_advisory_xact_lock is fine), LISTEN, temp tables
statementone statementevery multi-statement transaction

PgBouncer defaults to pool_mode = session and default_pool_size = 20. Transaction mode is the usual choice for many short-lived clients, and it is where these bugs live. PgBouncer 1.21.0 added max_prepared_statements (default 0, off) so protocol-level prepared statements can work in transaction mode; before that they failed outright. LISTEN does not survive transaction mode because the listening connection goes back to the pool: NOTIFY itself is fine.

Pool size. Little's law: concurrency = rate × duration. At 500 transactions/s with 20 ms transactions you need 500 × 0.020 = 10 connections. Add one report query that runs 200 ms and the same 500/s now needs 100: the whole of PostgreSQL's default max_connections = 100, for one workload. The symptom is connectionTimeout expiries in the application, which points at the pool rather than at the slow query that caused it. More connections than the server can run makes throughput worse, not better.

What I would do. Make the transaction boundary and the connection boundary the same object: a unit of work that owns one connection and hands it to every repository inside the scope, so there is no API that lets a helper acquire its own. Then set idle_in_transaction_session_timeout and alert on the pg_stat_activity query above, so a leak shows up as a metric rather than as a support ticket.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

When would you choose serializable over read committed?

Answer

I default to read committed, because it is PostgreSQL's default, it never aborts a transaction for a conflict, and for most work (reading data, writing rows that do not depend on other rows' current values) it is entirely adequate.

I reach for serializable when there is an invariant spanning rows that a transaction reads but does not write, and where violating it matters. That is precisely the write-skew shape: the on-call rota, a booking system enforcing capacity, an account balance that must not go negative when several concurrent withdrawals each check it separately, or any 'at most N of these may be true' rule.

The reason those cases need it is that no row lock helps. Each transaction writes a different row, so there is no write-write conflict to detect, and locking the rows you read is what serializable does for you automatically and correctly.

What I would try before escalating the isolation level:

Express the invariant as a constraint if it can be: an exclusion constraint for overlapping bookings, a check constraint, a unique index. The database then enforces it at any isolation level, and it holds regardless of how the writing code behaves. This is the most robust option when available.

Restructure so the conflict materialises. If all the transactions contend on one row (locking the shift, the account, the resource) then ordinary row locking serialises them and read committed suffices.

Express the change as a single atomic statement, which removes the window entirely for read-modify-write cases.

If none of those apply, serializable is the correct tool, and its costs are honest: more aborts under contention, dependency-tracking overhead, and a mandatory retry loop. I would apply it to the specific transactions that need it rather than globally: the level is per transaction, and making everything serializable to protect one invariant taxes work that never needed it.

The judgement I would offer: the failure mode of choosing read committed wrongly is silent data corruption discovered much later, while the failure mode of serializable is visible aborts you must handle. Where an invariant genuinely matters, the visible cost is the better trade.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How would you implement retry logic for serializable transactions?

Answer

In the first 90 seconds. Retry is part of the contract at REPEATABLE READ and SERIALIZABLE, not an optimisation. The engine aborts a transaction that lost a race and expects you to run it again. So I wrap the whole transaction (BEGIN, every statement, COMMIT) in a loop that catches only the serialization and deadlock codes, backs off with jitter, and stops after a bounded number of attempts or a wall-clock deadline. The precondition that makes it safe is that the body has no external side effects: anything that must happen exactly once goes into an outbox row written inside the transaction, or runs after the commit.

Catch the specific codes, not "any error". A unique violation or a syntax error fails identically on every attempt; retrying it multiplies work and delays the real error.

EngineIsolationRetryableNote
PostgreSQLSERIALIZABLE (SSI), REPEATABLE READSQLSTATE 40001, 40P0140001 can be raised by COMMIT, so the retry must wrap the commit
MySQL / InnoDBSERIALIZABLE1213 deadlock, 1205 lock wait timeout1205 usually means the transaction is too long, not that you need more attempts
SQL ServerSERIALIZABLE, SNAPSHOTerror 1205 (deadlock victim)error number, not SQLSTATE
OracleSERIALIZABLEORA-08177raised on the first statement that cannot serialize
Python
# psycopg 3.1, PostgreSQL 16
import random, time
import psycopg
from psycopg import errors

RETRYABLE = (errors.SerializationFailure,   # SQLSTATE 40001
             errors.DeadlockDetected)       # SQLSTATE 40P01

def run_serializable(conn, body, *, max_attempts=5, base=0.02,
                     cap=1.0, deadline=10.0):
    started = time.monotonic()
    for attempt in range(max_attempts):
        try:
            with conn.transaction():                 # BEGIN; ROLLBACK on exception
                conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
                return body(conn)                    # COMMIT on clean exit
        except RETRYABLE:
            if attempt == max_attempts - 1 or time.monotonic() - started >= deadline:
                raise
            delay = min(cap, base * 2 ** attempt)
            time.sleep(random.uniform(0, delay))     # full jitter

What the database does. Two sessions each read a set and write based on it: classic write skew:

StepT1T2
1SELECT count(*) FROM on_call WHERE shift='night' → 2
2same SELECT → 2
3INSERT INTO on_call ...; COMMIT → ok
4INSERT ...; COMMIT → ERROR 40001 could not serialize access due to read/write dependencies
5ROLLBACK, sleep 13 ms, re-run: SELECT → 3, INSERT, COMMIT → ok

What the loop does. With body raising SerializationFailure on attempts 0 and 1 and returning on attempt 2, and one draw from the jitter distribution:

attemptbody outcomeelapsed at catchdelay = min(1.0, 0.02·2^attempt)sleep
0400010.004 s0.020 s0.013 s
1400010.048 s0.040 s0.031 s
2returns row———

The sleep is uniform in [0, delay]; the bound and the doubling are what matter, not the sample draw.

Failure modes.

  • Side effects inside the body. An email, a card charge or a published message is not recalled by ROLLBACK, so a retry sends it twice. Write an outbox row inside the transaction and let a separate worker deliver it.
  • Retrying the statement, or retrying inside a savepoint. After 40001 the transaction is aborted and the snapshot is stale. Savepoints do not help: the whole transaction restarts.
  • Retrying non-retryable errors. 23505 unique violation, 42601 syntax error: identical on every attempt.
  • Unbounded or immediate retries. Under sustained contention they add load to the thing causing the contention, and synchronised clients produce a thundering herd. Jitter breaks the synchronisation.
  • Retrying past the caller's deadline. If the request already timed out, the retry is work nobody wants. Cap wall-clock time, not just attempts.
  • Stale ORM state. SQLAlchemy's identity map and Hibernate's session keep objects from the aborted attempt; roll back and expire/clear before re-running.
  • Long transactions. A climbing retry rate is a symptom. The fix is a shorter transaction or a different isolation level, not a higher limit.

Detection. Emit a counter per transaction type on retry and on exhaustion, and alert on the retry rate. If it climbs, look at the hot path.

Testing. Force the conflict rather than trusting the loop: two connections, a barrier between their reads and their writes, then assert the body ran twice and the committed state is correct. Untested retry paths are routinely broken until a busy day.

One escape hatch. Read-only reporting transactions can use BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE in PostgreSQL: they may block when taking their snapshot, but they then cannot be cancelled by a serialization failure.

Placement. The loop lives outside the transaction and outside anything with effects, a service method or unit-of-work wrapper, not sprinkled at call sites.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Explain write skew with an example, and how you would prevent it.

Answer

Write skew is two transactions each reading an overlapping set of rows, each checking a condition that holds, and each writing different rows, where the combination violates an invariant that neither transaction could observe being broken.

The standard example is an on-call rota with a rule that at least one doctor must remain on duty. Two doctors both try to sign off simultaneously. Each transaction reads the rota, sees the other is on duty, concludes signing off is fine, and updates its own row. Both checks were valid against their snapshots. Both writes touch different rows so no row lock conflicts. Both commit. Nobody is on call.

Snapshot isolation cannot prevent this, because each transaction's reads were consistent and their writes did not conflict. The invariant spans rows that each transaction read but did not write, and snapshot isolation only detects write-write conflicts.

The remedies, in order of preference:

Serializable isolation. It tracks read/write dependencies, detects that the two transactions form a cycle, and aborts one. This is the correct general answer and the reason the level exists. It requires a retry loop.

Materialising the conflict. Lock a row that represents the invariant (the shift, or the rota) so both transactions contend on the same row and one waits. This works at lower isolation levels but requires recognising every such invariant and remembering to lock, which is exactly the discipline that fails.

Making the invariant a constraint. Sometimes it can be expressed declaratively (an exclusion constraint for overlapping bookings, for instance) and then the database enforces it regardless of isolation level. When possible this is the most robust option, because it does not depend on how the writing code behaves.

What does not work is SELECT ... FOR UPDATE on the rows you write, since those are already disjoint. You would need to lock the rows you read, which is what serializable effectively does for you.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

A booking system occasionally double-books a room. How do you fix it?

Answer

The existing implementation almost certainly queries for conflicting bookings and inserts if none are found. That is check-then-insert, and it is a race: two requests both find no conflict, both insert, and the room is double-booked. It passes every sequential test, which is why it reached production.

Read committed does not help, because neither transaction sees the other's uncommitted row. Nor does SELECT ... FOR UPDATE on the conflicting bookings: there are none to lock, which is precisely the problem. Locking rows that do not exist yet is not something row locking can do.

The right fix is an exclusion constraint. It expresses the invariant declaratively: no two bookings for the same room may have overlapping time ranges.

SQL
ALTER TABLE bookings ADD CONSTRAINT no_overlap
  EXCLUDE USING gist (room_id WITH =, during WITH &&);

The database enforces it atomically, so one insert succeeds and the other fails with a constraint violation the application turns into 'that slot was just taken'. It holds regardless of isolation level, and regardless of which code path writes: a migration, an admin tool, a future service. That last property is what makes it the right answer rather than merely a working one.

It requires the range as a range type rather than separate start and end columns, so there may be a migration, and the existing data must be checked for overlaps first, since adding the constraint will fail if any exist. That cleanup is a real piece of work and needs decisions about which of two overlapping bookings survives.

Alternatives, and why they are weaker. Serializable isolation would also catch it, since this is a write-skew-shaped problem, but it needs a retry loop and does not protect against a writer that uses a different isolation level. Materialising the conflict by locking a room row serialises all bookings for that room, which works but is coarse and depends on every writer remembering to take the lock.

So: exclusion constraint as the primary fix, and I would keep the application-level check too, not for correctness, but so the common case gives a good error message before hitting the constraint.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How would you reduce lock contention in a hot part of the schema?

Answer

First I would confirm it is genuinely lock contention rather than slow queries, by looking at lock waits rather than at durations. The signature is that execution time is unchanged while total time grows: the work is fine, the waiting is not.

Then the remedies, roughly from cheapest to most invasive.

Shorten the transactions holding the locks. Contention is the product of lock hold time and arrival rate, so halving the hold time halves the queue. Moving external calls out of transactions is usually the biggest single win, and it is often available because the call did not need to be there.

Acquire the contended lock later. If a transaction locks a hot row and then does other work, reordering so the lock is taken last shortens the hold dramatically for the same total work.

Remove read-modify-write windows. UPDATE ... SET value = value + 1 holds the row lock for the duration of one statement rather than a round trip, which for a hot counter is a large difference.

Shard the hot row. A single counter row serialises every writer regardless of how efficient each one is. Splitting it into N rows written at random and summed on read trades read cost for write concurrency, and it is the standard answer when one row is genuinely the bottleneck.

Replace synchronous updates with an append-only log, aggregated later. Inserts do not contend with each other the way updates on one row do, so this converts a contention problem into a read-time aggregation problem, which is often a much better trade.

Batch. Aggregating many small updates into one periodic update reduces both lock acquisitions and total work, at the cost of staleness.

And if the contention is on a queue rather than a counter, FOR UPDATE SKIP LOCKED is the specific fix, since the default behaviour of every worker queueing on the same row is what causes it.

The framing I would offer: lock contention is a queueing problem, so it responds to reducing service time or arrival rate, and it degrades non-linearly. A system at 80% contention gets dramatically worse at 90%, which is why it appears to fall over suddenly rather than gradually. That non-linearity is why acting on a rising trend matters more than reacting to the incident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How would you implement a job queue in the database?

Answer

The core mechanism is SELECT ... FOR UPDATE SKIP LOCKED:

SQL
UPDATE jobs SET status = 'running', started_at = now(), worker_id = :worker
WHERE id = (
  SELECT id FROM jobs
  WHERE status = 'pending' AND run_after <= now()
  ORDER BY priority DESC, run_after
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING *;

SKIP LOCKED is what makes it work with several workers. Without it, every worker locks the same highest-priority row and queues behind the first, so ten workers process jobs one at a time. With it, each worker passes over rows already locked and claims a different one.

FOR UPDATE without SKIP LOCKED is the most common mistake here, and it looks fine with one worker.

The surrounding design matters as much as the query.

A partial index on (priority DESC, run_after) WHERE status = 'pending' keeps the index small no matter how many completed jobs accumulate: otherwise the index grows forever while only its pending fraction is ever read.

Crash recovery: a worker that dies mid-job leaves a row stuck in running. So I record started_at and have a sweeper that returns jobs exceeding a timeout to pending, with an attempt counter and a dead-letter state after too many failures. Without this, a crash silently loses work.

Retries with backoff via run_after, so a failing job does not spin.

Idempotent handlers, because at-least-once delivery is what this gives you: a worker can complete a job and die before marking it done, so it will run again.

Completed job retention: a table that only grows will eventually be the problem. Either delete after a window or partition by time and drop partitions.

The honest caveat: a database queue is excellent up to moderate throughput and has real advantages. Transactional enqueue with your business data, which a separate broker cannot give you without an outbox, plus one less system to operate. At high throughput the polling load and row contention become the bottleneck, and a purpose-built broker is the right answer. I would start here and move when measurement says so, rather than adding a broker pre-emptively.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do read replicas interact with transactional consistency?

Answer

The 90-second answer. A replica is a second copy of the database that applies the primary's write-ahead log (Postgres) or binlog (MySQL) after the fact. Replication is asynchronous by default: Postgres ships WAL as fast as it can whenever synchronous_standby_names is empty, which it is out of the box, and MySQL's semi-sync plugin is off unless you install it. So a replica is the primary as of some earlier point. The only guarantee it gives you is eventual consistency: it converges, and it never shows a state the primary never had. It does not give you read-your-writes, and it does not give you monotonic reads across replicas. Those are session-level properties you have to buy back yourself.

Read-your-writes is the one that produces user-visible bugs. A user saves their profile, the write lands on the primary, the redirect reads from a replica that has not replayed that WAL record yet, and they see the old value. They conclude the save failed and do it again. The trace is short:

t=0ms   UPDATE users SET email='a@b.c' WHERE id=7   -> primary, WAL LSN 0/3A2F118
t=1ms   replica replay position: 0/3A2F0C0   (lag 88 bytes)
t=2ms   SELECT email FROM users WHERE id=7          -> replica, returns old value
t=3ms   replica replay position: 0/3A2F118   (caught up, too late)

Monotonic reads is the second: two replicas sit at different replay positions, so request N+1 hitting replica B can show a state older than request N on replica A. The user sees time run backwards.

The remedies, and what each costs.

RemedyMechanismCostFails when
Route to primary for N seconds after a writesession flag with a TTLprimary absorbs the read loadlag exceeds N: a long vacuum or a bulk load
Wait for the replica to reach the write's positionpoll replay LSN / GTIDup to one lag interval per readyou wait on replica A and read from replica B
Sticky session to one replicahash session id to a replicanonethat replica is promoted or restarted
Return the written value in the write responseno read at allnonethe client needs server-computed fields on a later screen

The LSN wait is the precise one. In Postgres 15 with psycopg2:

Python
cur.execute("SELECT pg_current_wal_lsn()")
target = cur.fetchone()[0]          # e.g. '0/3A2F118'

while True:
    cur.execute("SELECT pg_last_wal_replay_lsn() >= %s::pg_lsn", (target,))
    if cur.fetchone()[0]:
        break
    if time.monotonic() > deadline:  # deadline = start + 2.0
        raise TimeoutError("replica lagged past 2s")
    time.sleep(0.005)
# read from THIS replica, not any other

MySQL 5.7+ has the equivalent as WAIT_FOR_EXECUTED_GTID_SET(gtid_set, timeout); MASTER_POS_WAIT() does the same against a binlog coordinate.

Failure modes worth naming. A long analytical query on a replica conflicts with replay of WAL that removes rows it is still reading. Postgres resolves this by cancelling the query once max_standby_streaming_delay elapses, default 30 s, so the report dies with canceling statement due to conflict with recovery. Setting hot_standby_feedback = on stops the cancellation but makes the primary hold dead rows for the replica's oldest snapshot, which shows up as table bloat. Pick your poison deliberately.

On MySQL, Seconds_Behind_Master is computed from the timestamp of the last executed event, so it reads 0 on a replica that is minutes behind whenever the primary is idle and no new events are arriving to timestamp against. Alert on the replay-position delta in seconds, not on that column.

Where replicas earn their place: reporting, analytics, search indexing, and any read where a few hundred milliseconds of staleness is invisible. Where they do not: a read immediately after a write in the same session, and any read that feeds a write decision. That decision is then made on a state the primary has already moved past.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How would you handle a transaction that must span several services?

Answer

My first response is to question the requirement, because a transaction spanning services is usually a sign the service boundary is in the wrong place. If two things must change atomically, that is strong evidence they belong to the same consistency domain and should live in one service with one database. Moving the boundary is often cheaper and always simpler than distributed coordination.

When that is genuinely not possible, the options:

Two-phase commit provides atomicity across resources, and I would avoid it in most architectures. It is a blocking protocol: if the coordinator fails after prepare, participants hold locks indefinitely awaiting resolution. It couples the availability of every participant, so the system is only as available as the least available member, which is usually the opposite of why the services were separated.

Sagas are the practical answer. The work is decomposed into local transactions, each committing independently, with a compensating action for each step. If a later step fails, earlier ones are compensated in reverse. Crucially, this gives eventual consistency, not atomicity: there is a window where some steps have happened and others have not, and that window is visible to users and to other services.

That visibility is the design work, and it is not primarily technical. Compensations are rarely perfect inverses: you can refund a charge but not un-send a notification; you can cancel a reservation but the customer may already have seen it confirmed. So the business has to define what a partially-completed flow means and how it should appear, and that conversation is the actual hard part.

The implementation requirements are demanding: every step idempotent, since retries are certain; every compensation idempotent for the same reason; the saga's state durably tracked so an orchestrator crash does not strand it mid-flight; and monitoring for stuck sagas, because they will occur and a stranded one is invisible without it.

And within each service, the outbox pattern makes the local commit and the message atomic, which is what keeps the saga's steps reliable.

So my ordering: reshape the boundary if you can; a saga with explicit compensations if you cannot; two-phase commit only in a tightly-coupled environment where its availability cost is genuinely acceptable.

Curated: · Written: · Reviewed:

Difficulty: Hard