Overview

Engines keep concurrent transactions from corrupting each other with locks, with multi-version concurrency control (MVCC), or both. MVCC keeps several versions of a row so that readers see a consistent snapshot while writers create new versions; readers do not wait for writers.

Core concepts

Where old versions liveCleaned up byTypical symptom when it goes wrong
PostgreSQLIn the table itself (each row has xmin/xmax transaction ids)VACUUMTable and index bloat; long transactions block cleanup
OracleIn undo segments, used to rebuild the old image of a blockUndo retentionORA-01555: snapshot too old
SQL ServerRow versions in a version store, only when RCSI/snapshot is enabled: in tempdb, or in the database’s persistent version store when Accelerated Database Recovery is on (2019+)Version cleanupVersion store growth from a long-open transaction

Lock vocabulary:

  • Shared (S) for reads, exclusive (X) for writes; S and X conflict, S and S do not. SQL Server also has update (U) locks to avoid conversion deadlocks, and intent locks (IS, IX) on higher-level objects to signal finer locks below.
  • Granularity: row, page, table. SQL Server may escalate many row locks to a table lock.
  • PostgreSQL row locks: FOR UPDATE, FOR SHARE, plus SKIP LOCKED and NOWAIT, which make queue-style workers simple.
  • Deadlock: two transactions each hold a lock the other needs. The engine detects the cycle and aborts one victim.

Worked example

A job queue without contention between workers (PostgreSQL, also supported by Oracle and SQL Server with READPAST):

WITH next AS (
  SELECT id FROM jobs WHERE status = 'new'
  ORDER BY id LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs SET status = 'running' FROM next WHERE jobs.id = next.id
RETURNING jobs.*;

Pitfalls and production notes

  • Always acquire locks in a consistent order (for example by primary key) to reduce deadlocks.
  • A forgotten open transaction is the most common cause of blocking and of MVCC cleanup stalls; monitor transaction age.
  • Lock timeouts keep migrations from queueing behind long queries and blocking everything behind them (safe-schema-migrations).
  • Under MVCC an update is effectively an insert plus a delete of a version, so very hot rows create churn.

Practice questions

  1. Why does a long SELECT in PostgreSQL not block an UPDATE, but can still hurt?
  2. How would you find the blocking session in each engine?
  3. When is SKIP LOCKED the right tool, and when is a real queue better?

References

isolation-levels · transactions-acid · indexing-theory · pg-mvcc · pg-vacuum-bloat · sqlserver-locking-blocking-deadlocks · oracle-locking-concurrency