Lesson 13 of 13 · 16m
MVCC, Transactions, and Pipeline Safety
MVCC's snapshot rules make check-then-write a race; atomic UPDATEs, FOR UPDATE, retry loops on 40001/40P01, and short transactions keep pipelines correct.
Postgres never updates a row in place. UPDATE writes a new tuple version and marks the old one dead; DELETE marks without writing. Readers consult tuple xmin/xmax against their transaction snapshot to decide which versions they're allowed to see — which is the entire trick behind MVCC: readers never block writers, writers never block readers, and "the database" is actually a pile of coexisting row versions being filtered per-transaction. The dead versions stick around until autovacuum reclaims them — and vacuum can only reclaim tuples no open transaction could still see.
The wrong model: SELECT then UPDATE is fine
Read the balance, check it in code, then write the deduction — the pattern that produces double-spend bugs. Under the default READ COMMITTED, each statement gets its own snapshot: your SELECT balance sees commit-time values, and a concurrent transaction can update the row between your read and your write. Two withdrawals both see 100, both subtract 80, both commit — the account went to -60 and neither transaction errored.
The fixes, in order of preference: do the check in the write itself (UPDATE accounts SET balance = balance - 80 WHERE id = 1 AND balance >= 80 RETURNING balance — zero rows returned is the rejection, atomic by construction); take the row lock explicitly (SELECT ... FOR UPDATE serializes the read-modify-write on that row); or run the whole transaction at SERIALIZABLE and let SSI abort one of them. "Validate then write in two statements" is the bug, at any isolation level below serializable.
Isolation levels are three different machines
READ COMMITTED (default): snapshot per statement. Non-repeatable reads and phantoms are legal inside one transaction — the same SELECT run twice sees newly committed rows. For most OLTP this is right: you want fresh data per statement.
REPEATABLE READ: snapshot per transaction. Every statement sees the world as of BEGIN. Concurrent updates to a row you touch raise 40001 could not serialize — retryable, but you must build the retry.
SERIALIZABLE: predicate locking via SSI. Postgres tracks read-write dependencies and aborts transactions whose interleaving couldn't be serialized — again 40001. The wrong-model claim "serializable means literally one-at-a-time slow" is wrong: SSI lets transactions run in parallel and kills the ones that formed a dangerous cycle. The cost is real (tracking overhead, aborts under contention) and the guarantee is the strongest ANSI offers.
Deadlocks: the 40P01 retry loop
Two transactions take locks in opposite orders — A holds row 1 wants row 2, B holds row 2 wants row 1 — and Postgres's deadlock detector fires after deadlock_timeout (default 1s), kills one with SQLSTATE 40P01, and lets the other through. In pipeline workers, deadlocks are normal concurrency weather, not a bug report: the correct response is a bounded retry loop with jitter, plus lock-order discipline — always grab rows in a canonical order (ORDER BY id before the batch FOR UPDATE) so opposite-order lock graphs can't form.
The vacuum pin: long transactions are the silent killer
Autovacuum's horizon is the oldest open xmin. A transaction that stays open for six hours — or worse, idle in transaction, holding a snapshot while the application thinks it's done — pins every dead tuple created in those six hours. Table bloat compounds: scans read dead versions, indexes grow, EXPLAIN slows down, and nobody connects it to the monitoring query somebody left in a psql tab. idle_in_transaction_session_timeout (PG9.6+) is the config-level backstop; pg_stat_activity filtered on state = 'idle in transaction' and xact_start is the query-level check. Pipeline jobs need the same discipline: transactions are commit-fast units of work, not session-long contexts.
For worker-style job queues, pg_advisory_xact_lock and FOR UPDATE SKIP LOCKED are the two tools — SKIP LOCKED lets N workers each claim different rows from one SELECT ... FOR UPDATE LIMIT k without blocking each other, which is the entire mechanism behind Postgres-backed pull queues like River — the same claim-a-batch shape RabbitMQ-style brokers implement over their own storage.
What to actually do
- Read-modify-write money/state changes: atomic
UPDATE ... WHERE ... RETURNINGorSELECT FOR UPDATE— never bare check-then-write. SERIALIZABLEcode paths ship with a retry loop for40001;40P01deadlocks get retries plus canonical lock ordering.- Alert on
idle in transactionsessions and setidle_in_transaction_session_timeout— every pinned xmin is vacuum debt. - Worker queues on Postgres:
FOR UPDATE SKIP LOCKED, short transactions, commit-and-acknowledge.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
PHP API Performance: N+1 Queries, cURL, and Connection Pools
A PHP API case study: fixing an N+1 query, twenty serial cURL calls, missing connection pooling, and stats recalculated on every request with Redis caching.