Concurrency Control
How databases implement isolation — two-phase locking, lock types and granularity, MVCC, optimistic concurrency control, serializable snapshot isolation, and deadlock handling.
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:
| Lock | Held by | Compatible with |
|---|---|---|
| Shared (S) | Readers | Other shared locks |
| Exclusive (X) | Writers | Nothing |
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.
- PostgreSQL stores versions in the table itself (
xmin/xmaxper 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 → retryupdated = conn.execute(
"UPDATE products SET stock = %s, version = version + 1 WHERE id = %s AND version = %s",
(new_stock, pid, version),
).rowcount
if updated == 0:
raise ConflictError("modified concurrently; reload and retry")// HTTP equivalent: ETag + If-Match
const res = await fetch(`/api/products/${id}`, {
method: "PUT",
headers: { "If-Match": etag, "Content-Type": "application/json" },
body: JSON.stringify(product),
});
if (res.status === 412) { /* Precondition Failed: someone else changed it */ }Pessimistic vs optimistic
| Pessimistic (locking) | Optimistic | |
|---|---|---|
| Assumes | Conflicts are likely | Conflicts are rare |
| Cost when there's no conflict | Lock overhead, blocking | Nearly free |
| Cost on conflict | Waiting | Abort and redo the work |
| Best for | Hot 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
| Database | Reads | Writes | Serializable via |
|---|---|---|---|
| PostgreSQL | MVCC snapshots | Row locks | SSI |
| MySQL InnoDB | MVCC (undo logs) | Row + next-key locks | Locking reads (2PL) |
| SQL Server | Locks by default; optional snapshots | Locks | 2PL with range locks |
| CockroachDB / Spanner | MVCC | Locks/intents + timestamps | SSI / strict 2PL + TrueTime |
- 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.