Concurrency Control

How databases implement isolation — two-phase locking, lock types and granularity, MVCC, optimistic concurrency control, serializable snapshot isolation, and deadlock handling.

Advanced 4 min readLesson 11 of 14

Isolation levels describe what guarantees you get; concurrency control is how the database provides them while letting many transactions run at once. There are three main families: locking, multi-version and optimistic schemes. Most production databases combine them.

Two-phase locking (2PL)

Transactions acquire locks before touching data:

LockHeld byCompatible with
Shared (S)ReadersOther shared locks
Exclusive (X)WritersNothing

Two-phase rule: a transaction has a growing phase (acquire locks, never release) and then a shrinking phase (release, never acquire). This guarantees serialisable schedules. Strict 2PL holds all exclusive locks until commit or abort, which prevents others from reading uncommitted data and avoids cascading aborts. That's what lock-based databases implement.

Granularity and intention locks

Locking every row of a 10-million-row update is costly; locking the whole table kills concurrency. Databases lock at several levels (table, page, row) and use intention locks (IS, IX) on parents, so "lock the whole table" can quickly check whether anyone holds locks on rows inside it. Some escalate many row locks into a table lock.

Predicate and gap locks

To stop phantoms, the database must lock not just existing rows but the range a query covered. InnoDB uses next-key locks (a row plus the gap before it in the index); true predicate locking is expensive, which is why index-range locks are used instead.

MVCC: multi-version concurrency control

Instead of overwriting data, writers create new versions. Each transaction reads the versions that were committed as of its snapshot, so readers never block writers and writers never block readers.

versionxminxmaxv1: balance=100created by T10deleted by T15v2: balance=70created by T15—
A transaction with a snapshot taken before T15 committed still sees v1; later ones see v2.
  • PostgreSQL stores versions in the table itself (xmin/xmax per tuple) and VACUUM removes versions no snapshot can see anymore.
  • InnoDB and Oracle update rows in place and reconstruct old versions from undo logs.
  • Write–write conflicts still need locks (or first-committer-wins checks).

Optimistic concurrency control (OCC)

Assume conflicts are rare. Run without locks, then validate at commit: if anything you read was changed by a concurrent committed transaction, abort and retry.

In applications this is the familiar version column:

@Entity
class Product {
    @Id Long id;
    int stock;
    @Version long version;     // JPA adds "WHERE version = ?" and increments it
}
// A concurrent change makes the UPDATE affect 0 rows → OptimisticLockException → retry

Pessimistic vs optimistic

Pessimistic (locking)Optimistic
AssumesConflicts are likelyConflicts are rare
Cost when there's no conflictLock overhead, blockingNearly free
Cost on conflictWaitingAbort and redo the work
Best forHot rows (inventory counters, seat booking)Most web edits, low contention, long "think time" (a user editing a form)

Serializable snapshot isolation (SSI)

PostgreSQL's SERIALIZABLE level (and CockroachDB's) runs on snapshots like MVCC but tracks read–write dependencies between concurrent transactions. When it detects a dangerous pattern (a cycle that would make the result non-serialisable, like write skew), it aborts one transaction. You get full serialisability with MVCC's non-blocking reads, at the cost of occasional retries.

Timestamp ordering

Each transaction gets a timestamp; operations that would violate timestamp order are rejected and the transaction restarts. Distributed databases (Spanner, CockroachDB) build on this with carefully synchronised clocks (Clocks & ordering).

Which databases use what

DatabaseReadsWritesSerializable via
PostgreSQLMVCC snapshotsRow locksSSI
MySQL InnoDBMVCC (undo logs)Row + next-key locksLocking reads (2PL)
SQL ServerLocks by default; optional snapshotsLocks2PL with range locks
CockroachDB / SpannerMVCCLocks/intents + timestampsSSI / strict 2PL + TrueTime
Key takeaways
  • Strict 2PL: hold locks until commit; serialisable but readers and writers block each other.
  • Intention locks enable multi-granularity locking; next-key/gap locks stop phantoms.
  • MVCC keeps versions so readers and writers don't block; old versions need cleanup.
  • Optimistic control validates at commit (version columns, ETags) and retries on conflict.
  • SSI gives serialisability on top of MVCC by aborting dangerous dependency cycles.