PostgreSQL locks and isolation: snapshots, SSI and no gap locks

Row locks live in the tuple, repeatable read is snapshot isolation, serializable is SSI with retries, and DDL waits in the lock queue.

More on PostgreSQL

Keep learning

Overview

FOR KEY SHARE FOR SHARE FOR NO KEY UPDATE FOR UPDATE explicit SELECT … FOR SHARE UPDATE that leaves key columns alone DELETE, UPDATE of a key column, SELECT … FOR UPDATE READ UNCOMMITTED Same as READ COMMITTED. PostgreSQL never shows uncommitted data. none extra READ COMMITTED (default) New snapshot per statement. A blocked UPDATE re-checks its WHERE on the newest version. dirty reads REPEATABLE READ One snapshot per transaction: snapshot isolation. Updating a row changed since the snapshot fails with 40001. non-repeatable reads, phantoms, lost updates Snapshot isolation plus SSI: tracks read/write dependencies with SIRead locks and aborts one side of a dangerous cycle with 40001. all anomalies, including write skew 0 (wait forever) Give up on a lock after this long. Set it for migrations, e.g. 2s, and retry. 0 (off) Caps whole statements, including lock waits. Blunter than lock_timeout. Wait this long before running the deadlock check. Also the threshold for log_lock_waits. Logs every lock wait longer than deadlock_timeout. Cheap, and worth turning on. read committed Raise it per transaction with BEGIN ISOLATION LEVEL …, not globally. 400 million Every heavyweight lock: granted or waiting, mode, relation, transactionid. Which sessions a waiting pid is stuck behind. id=1, name=… One locker: SELECT … FOR UPDATE by xid 205 LOCK_ONLY · EXCL xid 205 still running waiters sleep on its xid Several lockers: xmax becomes a MultiXact id multi 17 IS_MULTI · LOCK_ONLY no lock table entry per row: locking writes the page Locking a million rows costs no lock memory, but it dirties every page they sit on and consumes MultiXact ids. Deadlock. Session A holds row 1 and waits for row 2. Session B holds row 2 and waits for row 1. The waits form a cycle. After deadlock_timeout, one second by default, the detector aborts one session with error 40P01. session A session B held by waits for after deadlock_timeout (1 s): ERROR: deadlock detected (40P01) for one of them The cure is ordering: lock rows in the same order everywhere, for example ORDER BY id … FOR UPDATE. chapters · postgresql PostgreSQL locks and isolation: snapshots, SSI and no gap locks Readers never block writers in PostgreSQL. The waits you do see come from row locks written into tuples, table locks taken by DDL, and the serialization errors that stand in for gap locks.

1. Row locks live in the tuple

Row lock modes: ✕ means the request waits requested ↓ / held → taken by A foreign-key check locks the parent row FOR KEY SHARE. A plain UPDATE of the parent’s other columns takes FOR NO KEY UPDATE, which does not conflict, so inserting order lines does not block updating the customer’s address. “Key” means columns of a unique index a foreign key could point at. Updating those, or deleting the row, takes the full FOR UPDATE. Row locks in general are in locks.

2. Table lock modes and the conflict matrix

Eight modes, from ACCESS SHARE (any SELECT) to ACCESS EXCLUSIVE (most ALTER TABLE, DROP, TRUNCATE, VACUUM FULL). Ordinary reads and writes only clash with each other at the row level. The names are historical: ROW EXCLUSIVE is a table lock that INSERT, UPDATE and DELETE take. Prefer CREATE INDEX CONCURRENTLY, which takes SHARE UPDATE EXCLUSIVE and lets writes continue.

3. DDL in the lock queue

ADD COLUMN without a volatile default is a catalog change that takes milliseconds. The danger is the wait for ACCESS EXCLUSIVE: while it waits, every new query on the table queues behind it. Run migrations with a short lock_timeout and a retry loop, and check for long transactions on the table first.

4. Isolation levels: snapshots, SSI and no gap locks

The four levels in PostgreSQL How PostgreSQL does it SERIALIZABLE never blocks on reads. It records what each transaction read as SIRead locks (mode SIReadLock in pg_locks) and aborts a transaction only when commits could not be put in any serial order. Every caller must retry on 40001. PostgreSQL has no gap or next-key locks. A range you read is not protected from inserts, except through SSI or a unique index. The anomalies themselves are in isolation anomalies and the levels in isolation levels.

5. Deadlocks, advisory locks and finding the blocker

A waiting session sleeps for deadlock_timeout, then checks the wait-for graph. Lock rows in a consistent order and most deadlocks disappear. Advisory locks are locks on numbers the application chooses: pg_advisory_xact_lock(42) for “only one worker runs the nightly job”, pg_try_advisory_lock to skip instead of wait. The database never takes them for you. Common misuse patterns are in transaction misuse.

Reference: settings and views

Defaults are PostgreSQL 16/17 Setting or view What it trades Compare: MySQL. InnoDB’s REPEATABLE READ blocks inserts into scanned ranges with next-key locks, where PostgreSQL uses snapshots and SSI: see gap locks.

Recap

Row locks are written into the tuple’s xmax (or a MultiXact for several lockers), not kept in memory. Foreign keys take FOR KEY SHARE, which only conflicts with FOR UPDATE: non-key parent updates do not block child inserts. No gap locks: use SERIALIZABLE, a unique constraint or an explicit lock to protect a range.

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.