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 live | Cleaned up by | Typical symptom when it goes wrong | |
|---|---|---|---|
| PostgreSQL | In the table itself (each row has xmin/xmax transaction ids) | VACUUM | Table and index bloat; long transactions block cleanup |
| Oracle | In undo segments, used to rebuild the old image of a block | Undo retention | ORA-01555: snapshot too old |
| SQL Server | Row 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 cleanup | Version 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, plusSKIP LOCKEDandNOWAIT, 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
- Why does a long
SELECTin PostgreSQL not block anUPDATE, but can still hurt? - How would you find the blocking session in each engine?
- When is
SKIP LOCKEDthe right tool, and when is a real queue better?
References
- PostgreSQL manual, Concurrency Control: https://www.postgresql.org/docs/current/mvcc.html
- Microsoft Learn, Transaction locking and row versioning guide
- Oracle Database Concepts, Data Concurrency and Consistency
Related
isolation-levels · transactions-acid · indexing-theory · pg-mvcc · pg-vacuum-bloat · sqlserver-locking-blocking-deadlocks · oracle-locking-concurrency