Skip to content
Chethan Yadav_
Database Management Systems

DBMS/Lesson 7 of 9/6 min read

Concurrency Control

Read phenomena (dirty read, non-repeatable read, phantom, lost update), isolation levels, lock-based protocols, two-phase locking and its variants, deadlock handling, timestamp ordering, optimistic concurrency, and MVCC.


On this page

Why Concurrency Control

Running transactions concurrently improves throughput and response time, but uncontrolled interleaving breaks isolation. Concurrency control decides which interleavings are allowed.

Concurrency problems

Dirty Read

T2 reads a value written by T1 that is not yet committed. If T1 rolls back, T2 used garbage.

Non-Repeatable Read

T1 reads a row, T2 updates and commits it, T1 reads again and gets a different value.

Phantom Read

T1 runs SELECT ... WHERE salary > 50000 twice; between them T2 inserts a matching row, so the second result has a new "phantom" row. Affects sets of rows, not one row.

Lost Update

Both read X = 10, both add, both write. One update overwrites the other.

T1: read X (10)            write X = 15
T2:          read X (10)              write X = 12   -> T1's +5 is lost

Fixes: SELECT ... FOR UPDATE, atomic UPDATE x = x + 5, or optimistic version checks.

Write skew: two transactions read overlapping data, then write different rows based on what they read, breaking a constraint (two doctors both go off call because each saw the other on call). Prevented only by serializable isolation.

Isolation Levels

SQL standard levels, weakest to strongest:

LevelDirty readNon-repeatable readPhantom
Read UncommittedPossiblePossiblePossible
Read CommittedPreventedPossiblePossible
Repeatable ReadPreventedPreventedPossible (standard)
SerializablePreventedPreventedPrevented

Read Committed

Each statement sees only data committed before it began. Default in PostgreSQL, Oracle and SQL Server.

Repeatable Read

Rows read once will read the same again in that transaction. Default in MySQL InnoDB, which also blocks most phantoms with gap locks. PostgreSQL's Repeatable Read is actually snapshot isolation.

Higher isolation means more correctness but less concurrency (more blocking or aborts).

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Lock-based protocols

Shared Lock

Shared (S) lock for reading. Many transactions can hold S locks on the same item.

Exclusive Lock

Exclusive (X) lock for writing. Only one holder, and no S locks allowed at the same time.

Compatibility matrix:

Held \ RequestedSX
SYesNo
XNoNo

Locks alone do not guarantee serializability: unlocking too early lets other transactions see inconsistent states. A locking protocol defines when to lock and unlock.

Two-Phase Locking

Two-Phase Locking (2PL) has two phases per transaction:

  1. Growing phase: may acquire locks, may not release any.
  2. Shrinking phase: may release locks, may not acquire any.

The moment of the last lock acquired is the lock point. Ordering transactions by lock point gives an equivalent serial order, so 2PL guarantees conflict serializability.

Problems of basic 2PL: deadlocks are possible, and cascading rollbacks are possible.

Strict 2PL

Strict 2PL: hold all exclusive locks until commit or abort. Gives strict, cascadeless schedules. Used by most lock-based databases.

Rigorous 2PL: hold all locks (S and X) until commit. Transactions serialize in commit order.

Conservative (static) 2PL: acquire all locks before starting. Deadlock free, but needs to know the read/write set in advance.

Deadlock handling in databases

2PL can deadlock (T1 holds A wants B, T2 holds B wants A), exactly like OS deadlocks.

  • Detection: build a wait-for graph; on a cycle, abort a victim (youngest, least work). Used by PostgreSQL and MySQL.
  • Timeouts: abort a transaction that waits too long.
  • Prevention with timestamps (older = smaller timestamp):

Wait-Die

Non-preemptive. If an older transaction requests a lock held by a younger one, it waits. If a younger one requests a lock held by an older one, it dies (aborts, restarts later with the same timestamp).

Wound-Wait

Preemptive. If an older transaction requests a lock held by a younger one, it wounds (aborts) the younger. If a younger one requests, it waits.

In both, the older transaction never gets aborted for this reason, so there is no starvation.

Lock Granularity

Locks can be on a database, table, page or row. Fine granularity = more concurrency, more overhead. Multiple granularity locking uses intention locks (IS, IX, SIX) on ancestors so a table lock can quickly check for conflicting row locks.

Lock escalation: a database converts many row locks into one table lock to save memory.

Timestamp Ordering

Each transaction gets a unique timestamp TS(T) at start. Each item keeps R-TS(X) and W-TS(X) (largest timestamps that read and wrote it). Conflicts are resolved so the schedule is equivalent to the timestamp order.

  • T reads X: if TS(T) < W-TS(X), a younger transaction already wrote it, so abort T. Else read and update R-TS(X).
  • T writes X: if TS(T) < R-TS(X) or TS(T) < W-TS(X), abort T. Else write and update W-TS(X).

No locks, so no deadlocks, but there can be many restarts and cascading aborts.

Thomas Write Rule

Modification: if TS(T) < W-TS(X) on a write, just ignore the obsolete write instead of aborting. Allows some view-serializable schedules that are not conflict serializable.

Optimistic Concurrency Control

Optimistic Concurrency Control (OCC), also called validation-based: assume conflicts are rare.

  1. Read phase: execute, writing to private copies.
  2. Validation phase: at commit, check whether any concurrent committed transaction conflicted.
  3. Write phase: if validation passes, apply changes; otherwise abort and retry.

Great for read-heavy, low-contention workloads. Application-level version is a version column:

UPDATE product SET stock = 9, version = version + 1
WHERE id = 42 AND version = 7;   -- 0 rows updated means someone else changed it

MVCC

Multiversion Concurrency Control (MVCC) keeps several versions of each row. Each transaction reads a consistent snapshot as of its start time (or statement start).

  • Readers never block writers and writers never block readers.
  • Writers still conflict with writers on the same row.
  • Old versions are cleaned up later (PostgreSQL VACUUM, InnoDB purge of undo logs).

Used by PostgreSQL, MySQL InnoDB, Oracle, SQL Server (snapshot mode), CockroachDB.

Snapshot Isolation

Snapshot isolation reads from a snapshot and aborts a transaction on a write-write conflict ("first committer wins"). It prevents dirty reads, non-repeatable reads and lost updates, but allows write skew, so it is not fully serializable. PostgreSQL's Serializable level adds conflict tracking on top (SSI) to fix this.

Comparison

TechniqueDeadlocksBest for
Strict 2PLPossibleGeneral OLTP, high contention
Timestamp orderingNoneSystems avoiding locks
Optimistic (OCC)NoneLow contention, read heavy
MVCCOnly among writersMixed read/write workloads

Quick revision

  • Read Committed stops dirty reads; Repeatable Read stops non-repeatable reads; Serializable stops phantoms.
  • 2PL = growing then shrinking; guarantees conflict serializability; strict 2PL avoids cascading aborts.
  • Wait-die: old waits, young dies. Wound-wait: old wounds, young waits.
  • MVCC: readers and writers do not block each other.