Serializable Isolation: Two-Phase Locking and SSI

How databases make transactions behave as if run one by one: serial execution, two-phase locking and serializable snapshot isolation, and why you must retry.

In this chapter

Serializability: making concurrent transactions behave like a queue

More on Transactions: isolation

Keep learning

Overview

chapters · transactions, isolation and locks Serializability: making concurrent transactions behave like a queue Serializable means the outcome equals some one-at-a-time order, so the a/b swap (→ write anomalies) cannot happen. Snapshot isolation a a b b → b b a a (no serial order) a a b b → all a or all b

1. How to tell if a schedule is serializable

Ti op first conflicts with Tj op Arrow Ti → Tj No cycle serial order exists not serializable Every anomaly is a cycle Lost update and write skew: two-node cycles. No cycle? Read the serial order off the arrows.

2. The three strategies side by side

Actual serial execution One thread, one tx at a time. No concurrency bugs. Two-phase locking (2PL) Readers and writers block each other. You wait. Serializable snapshot isolation Snapshots + conflict tracking. You may be aborted.

3. Actual serial execution: take concurrency away

Cheap RAM and short OLTP transactions made it viable: no lock manager, no latches, no deadlocks. It only works if: Data fits in memory No transaction waits for disk. Whole tx submitted Writes partitioned One core is enough For your write throughput. ✓ Used by Redis, VoltDB, some in-memory stores ✕ Not for Interactive transactions that wait for users

4. Two-phase locking: grow, then shrink

Locks held over time: only grows, then only shrinks. Strict 2PL Holds all locks to commit/abort. No uncommitted reads. Deadlocks constantly Engine finds the waiter cycle, aborts one. → walkthrough Slowest transaction sets latency for everyone behind it.

Phantoms and 2PL

A new matching row has no lock, so engines lock the condition. Predicate locks (theory) Lock exactly the WHERE condition. Costly to check. Index-range locks (practice) Next-key / gap locks: a cheaper superset. → gap locks · → locks chapter

5. Serializable snapshot isolation: pessimistic is too slow, so be optimistic

SSI watches for a pivot: one rw dependency in, another out. snapshots: readers never block writers rw deps, even empty-range reads Pivot found rw in + rw out Abort one at commit False positives happen: retries mandatory. Not MySQL Its serializable uses 2PL. → PG chapter Who gets aborted Long read-write transactions Who is happy Short read-write, and long read-only queries (never a pivot)

6. In practice: the a/b swap, retried or locked

PostgreSQL, both sessions at SERIALIZABLE. Neither update blocks: they write different rows. no blocking ERROR 40001: cycle sees four b A failed commit is normal At SERIALIZABLE and PG REPEATABLE READ. Retry the whole transaction. Pessimistic alternative: stay at READ COMMITTED and lock first. T1 (READ COMMITTED) T2 (READ COMMITTED) locks all rows reads new values Nothing fails, but everyone queues behind the lock. Optimistic versus pessimistic Optimistic (detect, abort) Pessimistic (lock, wait) PostgreSQL SERIALIZABLE SELECT … FOR UPDATE, 2PL On conflict One tx fails at commit Your code must Retry the whole tx Lock right rows, consistent order Best when Conflicts are rare Conflicts common or retries costly → concurrency control

7. Choosing

Serializable strategies compared Readers block writers? Failure mode One slow tx stalls all Waits, deadlocks Serialization errors Application must Use stored procedures Retry deadlocks Retry any failure Low contention One core High contention One core, steady Poor (many aborts) VoltDB, Redis MySQL serializable, SQL Server PostgreSQL serializable

Remember

Same result as some serial order, or bust. SI ≠ serializable The a/b swap commits as b b a a. Serial execution Needs memory-sized data, short procs, partitions. Aborts a pivot with 40001. Retry whole tx. In practice RC/SI + FOR UPDATE on hot spots. Serializable is deliberate.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.