← back to databases

Concurrency Control

Wikipedia · wpConcurrency control · CC BY-SA 4.0

Concurrency control ensures that concurrent transactions produce correct results. The main techniques: locking (pessimistic: block conflicts before they happen), optimistic concurrency control (validate at commit time), and MVCC (each transaction sees a consistent snapshot).

Lock Compatibility Matrix Requested Held S X S Yes No X No No S = shared (read), X = exclusive (write).

Shared and exclusive locks

A shared lock (S-lock, read lock) allows concurrent reads. An exclusive lock (X-lock, write lock) blocks all other access. Multiple readers can hold S-locks simultaneously, but an X-lock is exclusive: no other lock (S or X) can coexist with it.

Scheme

Two-phase locking (2PL)

Two-phase locking guarantees serializability. Phase 1 (growing): acquire locks, never release. Phase 2 (shrinking): release locks, never acquire. Once a transaction releases any lock, it cannot acquire new ones. This prevents the interleaving patterns that cause anomalies.

Scheme

Deadlock detection

Deadlock occurs when two transactions each hold a lock the other needs. Detection: build a wait-for graph. If it has a cycle, one transaction must be aborted (the victim). Prevention strategies include timeout and wound-wait/wait-die schemes.

Python

MVCC — multiversion concurrency control

MVCC lets readers and writers run concurrently without blocking each other. Each write creates a new version of the data. Readers see a consistent snapshot from when their transaction started. PostgreSQL, MySQL/InnoDB, and Oracle all use MVCC.

Scheme
Neighbors

Cross-references

  • 🖥 OS Ch.5 — deadlock: same concept, different domain (OS resources vs database locks)

Foundations (Wikipedia)