PostgreSQL Transaction Isolation, MVCC, and Writing Secure Concurrent Programs

December 24, 2025

PostgreSQL Transaction Isolation, MVCC, and Writing Secure Concurrent Programs

Understanding transaction isolation levels and how PostgreSQL implements them through Multi-Version Concurrency Control (MVCC) is essential for writing correct, efficient, and secure concurrent database applications. This guide provides a comprehensive exploration of these concepts with practical examples.


The Problem: Concurrent Data Access

When multiple transactions access the same data simultaneously, several anomalies can occur:

AnomalyDescription
Dirty ReadReading data written by an uncommitted transaction
Nonrepeatable ReadRe-reading data and finding it was modified by another committed transaction
Phantom ReadRe-executing a query and finding the result set changed due to another committed transaction
Serialization AnomalyCommitting a group of transactions produces results inconsistent with any serial execution order

These anomalies can lead to data corruption, incorrect calculations, and security vulnerabilities in your application.


Transaction Isolation Levels: The SQL Standard

The SQL standard defines four isolation levels to protect against these anomalies:

Isolation LevelDirty ReadNonrepeatable ReadPhantom ReadSerialization Anomaly
Read UncommittedPossiblePossiblePossiblePossible
Read CommittedNot PossiblePossiblePossiblePossible
Repeatable ReadNot PossibleNot PossiblePossiblePossible
SerializableNot PossibleNot PossibleNot PossibleNot Possible

PostgreSQL's Implementation

PostgreSQL implements only three distinct levels internally:

Requested LevelActual PostgreSQL Behavior
Read UncommittedTreated as Read Committed (PostgreSQL never allows dirty reads)
Read CommittedRead Committed (default)
Repeatable ReadSnapshot Isolation (stronger than standardโ€”no phantom reads)
SerializableSerializable Snapshot Isolation (SSI)

Key Insight: PostgreSQL's Repeatable Read is actually stronger than the SQL standard requiresโ€”it prevents phantom reads, which the standard only requires Serializable to prevent.


Multi-Version Concurrency Control (MVCC) Deep Dive

PostgreSQL uses MVCC to provide transaction isolation without the heavy locking that traditional databases require. Unlike lock-based systems where readers block writers and vice versa, MVCC allows concurrent access by maintaining multiple versions of data.

The Core Idea: Versioned Rows

Traditional databases use a lock-based approach:

  • When Transaction A reads a row, it acquires a read lock
  • Transaction B wanting to write must wait
  • This leads to blocking and reduced concurrency

PostgreSQL's MVCC approach:

  • When Transaction A reads a row, no lock is acquired
  • Transaction B can write by creating a new version of the row
  • Transaction A continues seeing the old version
  • Both transactions proceed without blocking each other

How MVCC Works Internally

Each row (tuple) in PostgreSQL contains hidden system columns that track versioning:

ColumnTypePurpose
xminTransactionIdThe transaction ID that created this row version
xmaxTransactionIdThe transaction ID that deleted or updated this row (0 if still valid)
cminCommandIdCommand ID within the inserting transaction
cmaxCommandIdCommand ID within the deleting transaction
ctidItemPointerPhysical location of this or newer row version

You can actually see these columns:

SELECT xmin, xmax, ctid, * FROM your_table;

Row Lifecycle in MVCC

INSERT creates a new row:

Row Version 1: xmin=100, xmax=0 (valid, created by txn 100)

UPDATE creates a new version and "deletes" the old:

Row Version 1: xmin=100, xmax=200 (deleted by txn 200)
Row Version 2: xmin=200, xmax=0 (valid, created by txn 200)

DELETE marks the row as deleted:

Row Version 1: xmin=100, xmax=300 (deleted by txn 300)

Visibility Rules: Who Sees What?

When a transaction queries data, PostgreSQL applies visibility rules to determine which row version to show:

A row version is VISIBLE to transaction T if:
  1. xmin is committed AND xmin < T's snapshot
  2. xmax is either:
     - 0 (not deleted), OR
     - Not committed, OR
     - Committed but after T's snapshot

Visual Example:

Timeline:
  txn 100: INSERT row (xmin=100)
  txn 100: COMMIT
  txn 200: BEGIN (takes snapshot)
  txn 300: UPDATE row (creates new version, xmax=300 on old)
  txn 300: COMMIT
  txn 200: SELECT (still sees OLD version because xmax=300 committed after snapshot)

Snapshot Mechanics

When a transaction starts (or a statement begins, in Read Committed), PostgreSQL takes a snapshot containing:

struct SnapshotData {
    TransactionId xmin;      // All txns < xmin are visible (committed)
    TransactionId xmax;      // All txns >= xmax are invisible (in progress or future)
    TransactionId *xip;      // Array of in-progress txn IDs in [xmin, xmax)
    uint32 xcnt;             // Count of in-progress transactions
};
  • xmin: Oldest active transaction when snapshot was taken. Any transaction below this is definitely committed.
  • xmax: First unassigned transaction ID. Anything >= this doesn't exist yet.
  • xip: List of transactions that were in-progress at snapshot time (even if committed now, we don't see their changes)

MVCC Example: Concurrent Read and Write

-- Initial state
CREATE TABLE accounts (id INT PRIMARY KEY, balance INT);
INSERT INTO accounts VALUES (1, 1000);
COMMIT;

-- Timeline of operations:

-- T=0: Transaction 200 starts
BEGIN;  -- txn 200, snapshot: xmin=200

-- T=1: Transaction 200 reads
SELECT balance FROM accounts WHERE id = 1;
-- Sees: 1000 (row xmin=199 < 200, xmax=0)

-- T=2: Transaction 300 starts and updates
BEGIN;  -- txn 300
UPDATE accounts SET balance = 500 WHERE id = 1;
-- Creates: new row xmin=300, old row gets xmax=300
COMMIT;

-- T=3: Transaction 200 reads again
SELECT balance FROM accounts WHERE id = 1;
-- Still sees: 1000!
-- Why? xmax=300 committed AFTER txn 200's snapshot
-- The new row (xmin=300) is also invisible (300 > snapshot xmax)

MVCC vs Traditional Locking: Comparison

AspectLock-Based (e.g., SQL Server default)MVCC (PostgreSQL)
Read-ReadNo conflictNo conflict
Read-WriteReader blocks writerNo conflict
Write-ReadWriter blocks readerNo conflict
Write-WriteWriter blocks writerWriter blocks writer
Deadlock riskHigherLower
Space usageLowerHigher (multiple versions)
MaintenanceNoneRequires VACUUM

MVCC Benefits

BenefitDescription
No read locksSELECT never blocks other operations
No write-blocks-readWriters don't block readers
Consistent snapshotsEach transaction sees a stable view
No lock escalationNo risk of table-level lock contention
Time-travel queriesOld versions are available until vacuumed

MVCC Trade-offs

Trade-offDescription
Storage overheadOld row versions consume space until vacuumed
VACUUM requiredDead tuples must be periodically cleaned up
Transaction ID wraparoundRequires maintenance to prevent 32-bit XID exhaustion
Index bloatIndexes may point to dead tuples
HOT updates limitedHeap-Only Tuples only work if no indexed columns change

VACUUM: Cleaning Up Dead Tuples

Dead tuples (old row versions no longer visible to any transaction) must be cleaned up:

-- Manual vacuum
VACUUM accounts;

-- Vacuum with statistics update
VACUUM ANALYZE accounts;

-- Aggressive vacuum (reclaims more space, more I/O intensive)
VACUUM FULL accounts;  -- Warning: Locks table exclusively!

Autovacuum runs automatically based on these thresholds:

-- Check autovacuum settings
SHOW autovacuum_vacuum_threshold;       -- Default: 50 tuples
SHOW autovacuum_vacuum_scale_factor;    -- Default: 0.2 (20%)
-- Vacuum triggers when: dead_tuples > threshold + scale_factor * table_size

Monitoring MVCC Health

-- Check dead tuple count
SELECT
    schemaname,
    relname,
    n_live_tup,
    n_dead_tup,
    n_dead_tup::float / NULLIF(n_live_tup, 0) as dead_ratio,
    last_vacuum,
    last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC;

-- Check for transaction ID wraparound risk
SELECT
    datname,
    age(datfrozenxid) as xid_age,
    2^31 - age(datfrozenxid) as xids_remaining
FROM pg_database
ORDER BY age(datfrozenxid) DESC;

Read Committed: The Default Level

Read Committed is PostgreSQL's default isolation level. Understanding its behavior is critical because most applications use it.

Behavior Summary

  • Each statement (not transaction) sees a fresh snapshot
  • You see data committed before your statement began
  • Two successive SELECTs in the same transaction may see different data

Example: The Balance Transfer

This works correctly in Read Committed:

BEGIN;
UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 12345;
UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 7534;
COMMIT;

If another transaction modifies account 7534 concurrently:

  1. The second UPDATE waits for the concurrent transaction to commit or rollback
  2. If it commits, our UPDATE operates on the new version
  3. The WHERE clause is re-evaluated against the updated row

The DELETE Problem

Read Committed can produce surprising results with concurrent modifications:

-- Session 1
BEGIN;
UPDATE website SET hits = hits + 1;

-- Session 2 (concurrent)
DELETE FROM website WHERE hits = 10;

-- Session 1
COMMIT;

Scenario: Table has rows with hits = 9 and hits = 10

Result: The DELETE may delete nothing, even though a row with hits = 10 exists both before and after the UPDATE:

  • Before UPDATE: Row has hits = 10
  • DELETE locks the row, waits for Session 1
  • After UPDATE: Row now has hits = 11 (no longer matches WHERE)

When to Use Read Committed

Use CaseWhy
Simple CRUD operationsGood performance, adequate isolation
Short transactionsLess chance of conflicts
Operations that don't require consistency across multiple readsSnapshots refresh per-statement
High-concurrency OLTP workloadsMinimal blocking

When to Avoid Read Committed

Use CaseWhy
Complex analytical queriesResults may be inconsistent
Multi-statement reads that must be consistentDifferent statements see different snapshots
Operations enforcing business rulesConcurrent changes can violate invariants

Repeatable Read: Snapshot Isolation

Repeatable Read provides a transaction-level snapshot: all statements in the transaction see the same consistent view of the database.

Behavior Summary

  • Snapshot is taken at the first non-transaction-control statement
  • All queries see data committed before the transaction started
  • Cannot modify rows changed by other transactions after snapshot

The Serialization Error

In Repeatable Read, if you try to modify a row that was changed by another transaction after your snapshot:

ERROR: could not serialize access due to concurrent update

This is PostgreSQL telling you: "Your view of this row is stale. Please retry."

Example: Write Conflict

-- Session 1
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT * FROM products WHERE id = 1;  -- Takes snapshot
-- sees: price = 100

-- Session 2
UPDATE products SET price = 150 WHERE id = 1;
COMMIT;

-- Session 1
UPDATE products SET price = price * 1.1 WHERE id = 1;
-- ERROR: could not serialize access due to concurrent update

Handling Serialization Failures

Applications must be prepared to retry transactions:

def execute_with_retry(conn, operation, max_retries=3):
    for attempt in range(max_retries):
        try:
            with conn.cursor() as cur:
                cur.execute("BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ")
                result = operation(cur)
                cur.execute("COMMIT")
                return result
        except psycopg2.errors.SerializationFailure:
            cur.execute("ROLLBACK")
            if attempt == max_retries - 1:
                raise
            time.sleep(0.1 * (2 ** attempt))  # Exponential backoff

When to Use Repeatable Read

Use CaseWhy
Complex analytical queriesConsistent view across multiple statements
Reports requiring point-in-time consistencySame snapshot for entire transaction
Read-heavy workloads with occasional writesWrites rare, conflicts unlikely
Batch processing that reads data once, then updatesSnapshot prevents inconsistent intermediate states

Serializable: True Isolation

Serializable isolation guarantees that concurrent transactions produce results equivalent to running them one at a time in some serial order.

How PostgreSQL Implements Serializable

PostgreSQL uses Serializable Snapshot Isolation (SSI), which:

  1. Starts with Snapshot Isolation (like Repeatable Read)
  2. Adds predicate locks (SIRead locks) to detect dangerous patterns
  3. Aborts transactions that would cause serialization anomalies

Predicate Locks Are Not Real Locks

PropertyPredicate LocksRegular Locks
Block other transactions?NoYes
Cause deadlocks?NoYes
PurposeDetect anomaliesPrevent concurrent access
Visible in pg_locksYes (mode: SIReadLock)Yes

The Classic Serialization Anomaly Example

Consider this table:

CREATE TABLE mytab (class INT, value INT);
INSERT INTO mytab VALUES (1, 10), (1, 20), (2, 100), (2, 200);

Two concurrent transactions:

-- Transaction A
SELECT SUM(value) FROM mytab WHERE class = 1;  -- Returns 30
INSERT INTO mytab VALUES (2, 30);  -- Inserts sum of class 1 into class 2

-- Transaction B
SELECT SUM(value) FROM mytab WHERE class = 2;  -- Returns 300
INSERT INTO mytab VALUES (1, 300);  -- Inserts sum of class 2 into class 1

In Repeatable Read: Both commit successfully

Result:

  • Class 1 now has: 10, 20, 300
  • Class 2 now has: 100, 200, 30

Problem: No serial order produces this result:

  • If A ran first: B would see 30 in class 2, sum = 330, not 300
  • If B ran first: A would see 300 in class 1, sum = 330, not 30

In Serializable: PostgreSQL detects this read/write dependency cycle and rolls back one transaction.

Performance Considerations for Serializable

-- Optimize: Declare read-only when possible
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE;
-- This may block briefly at start, but guarantees no conflicts later
-- and can release predicate locks early
OptimizationBenefit
READ ONLYCan release locks early, never causes conflicts
DEFERRABLEWaits for conflict-free snapshot, then never blocks
Short transactionsLess opportunity for conflicts
Index scans over sequential scansFiner-grained predicate locks

When to Use Serializable

Use CaseWhy
Financial systemsCorrectness is paramount
Inventory managementPrevents overselling
Enforcing complex business rulesCan't be violated by concurrent transactions
When reasoning about correctness"If it works single-threaded, it works"

Locking Strategies: Pessimistic vs Optimistic

When multiple transactions need to modify the same data, you need a strategy to handle conflicts. There are two fundamental approaches: pessimistic locking (assume conflicts, lock preemptively) and optimistic locking (assume no conflicts, detect them later).

Understanding the Two Approaches

AspectPessimistic LockingOptimistic Locking
Philosophy"Someone might conflict, so I'll lock first""Conflicts are rare, I'll check at the end"
When to useHigh contention, short transactionsLow contention, longer transactions
ImplementationDatabase locks (SELECT FOR UPDATE)Version columns, timestamps, or checksums
BlockingYes, other transactions waitNo blocking, but may need retry
Deadlock riskHigherNone
Best forFinancial transactions, inventoryDocument editing, web forms

Pessimistic Locking in PostgreSQL

Pessimistic locking explicitly locks rows to prevent concurrent modifications.

SELECT FOR UPDATE

The most common pessimistic lock. It locks the selected rows until the transaction commits:

BEGIN;

-- Lock the row - other transactions wanting to UPDATE/DELETE this row will wait
SELECT * FROM accounts WHERE id = 12345 FOR UPDATE;

-- Safe to make decisions based on the value
-- No one else can modify this row until we commit
UPDATE accounts SET balance = balance - 100 WHERE id = 12345;

COMMIT;  -- Lock released

Lock Modes Comparison

Lock ModeBlocksUse Case
FOR UPDATEFOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, UPDATE, DELETEWill modify the row
FOR NO KEY UPDATEFOR UPDATE, FOR SHARE, UPDATE (on key columns), DELETEWill modify non-key columns only
FOR SHAREFOR UPDATE, FOR NO KEY UPDATE, UPDATE, DELETENeed to prevent changes, but won't modify
FOR KEY SHAREFOR UPDATE, UPDATE (on key columns), DELETEOnly need to prevent key changes (FK integrity)

Preventing Deadlocks with Lock Ordering

Deadlocks occur when two transactions wait for each other:

-- Transaction A
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;  -- Locks row 1
-- Meanwhile, Transaction B locks row 2...
SELECT * FROM accounts WHERE id = 2 FOR UPDATE;  -- Waits for B
-- DEADLOCK!

-- Transaction B
BEGIN;
SELECT * FROM accounts WHERE id = 2 FOR UPDATE;  -- Locks row 2
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;  -- Waits for A
-- DEADLOCK!

Solution: Always lock in consistent order:

-- Both transactions should lock in the same order (e.g., by ID)
BEGIN;
SELECT * FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
-- This locks both rows in consistent order, preventing deadlock

NOWAIT and SKIP LOCKED

Control what happens when a row is already locked:

-- NOWAIT: Fail immediately if row is locked
SELECT * FROM accounts WHERE id = 12345 FOR UPDATE NOWAIT;
-- ERROR: could not obtain lock on row in relation "accounts"

-- SKIP LOCKED: Skip locked rows (great for queues!)
SELECT * FROM job_queue
WHERE status = 'pending'
ORDER BY created_at
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- Returns next available unlocked row, or empty if all locked

Row-Level Lock Wait Diagram

Transaction A                    Transaction B
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
BEGIN;
SELECT * FROM t WHERE id=1
  FOR UPDATE;
  โœ“ Lock acquired
                                 BEGIN;
                                 SELECT * FROM t WHERE id=1
                                   FOR UPDATE;
                                   โณ Waiting for A...
UPDATE t SET x=1 WHERE id=1;
                                   โณ Still waiting...
COMMIT;
  โœ“ Lock released                  โœ“ Lock acquired
                                 UPDATE t SET x=2 WHERE id=1;
                                 COMMIT;

Optimistic Locking in PostgreSQL

Optimistic locking doesn't use database locks. Instead, it detects conflicts at update time using a version indicatorโ€”a column that changes with every update.

Strategy 1: Version Number Column

The most common approach. Each row has an integer version that increments on every update:

-- Schema
CREATE TABLE documents (
    id SERIAL PRIMARY KEY,
    title TEXT,
    content TEXT,
    version INT NOT NULL DEFAULT 1,
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Application reads document (remembers version)
SELECT id, title, content, version FROM documents WHERE id = 123;
-- Returns: id=123, title='My Doc', content='...', version=5

-- User edits... time passes...

-- Application updates with version check
UPDATE documents
SET
    title = 'Updated Title',
    content = 'New content',
    version = version + 1,
    updated_at = NOW()
WHERE id = 123 AND version = 5;  -- Only if version unchanged!

-- Check rows affected:
-- If 1 row: Success! We updated it.
-- If 0 rows: Conflict! Someone else updated it first.

Full Optimistic Locking Pattern

def update_document_optimistic(doc_id, new_title, new_content, expected_version):
    with connection.cursor() as cur:
        cur.execute("""
            UPDATE documents
            SET title = %s, content = %s, version = version + 1, updated_at = NOW()
            WHERE id = %s AND version = %s
            RETURNING version
        """, (new_title, new_content, doc_id, expected_version))

        result = cur.fetchone()

        if result is None:
            # No rows updated - version mismatch!
            connection.rollback()

            # Fetch current state for conflict resolution
            cur.execute("SELECT version, title, content FROM documents WHERE id = %s", (doc_id,))
            current = cur.fetchone()

            raise OptimisticLockError(
                f"Document was modified by another user. "
                f"Expected version {expected_version}, current version is {current[0]}"
            )

        connection.commit()
        return result[0]  # Return new version

Strategy 2: Timestamp-Based Versioning

Use updated_at timestamp as the version indicator:

-- Application reads (remembers timestamp)
SELECT id, content, updated_at FROM documents WHERE id = 123;
-- Returns: updated_at = '2024-01-15 10:30:00'

-- Update with timestamp check
UPDATE documents
SET content = 'New content', updated_at = NOW()
WHERE id = 123 AND updated_at = '2024-01-15 10:30:00';

Caveat: Timestamps have precision limits. If two updates happen within the same timestamp resolution, conflicts may not be detected. Version numbers are more reliable.

Strategy 3: Row Hash/Checksum

For tables where you can't add columns, compute a hash of the row:

-- Read and compute hash
SELECT id, content, md5(content::text) as content_hash
FROM documents WHERE id = 123;
-- Returns: content_hash = 'abc123...'

-- Update with hash check
UPDATE documents
SET content = 'New content'
WHERE id = 123 AND md5(content::text) = 'abc123...';

Strategy 4: PostgreSQL's System Columns

Use the xmin system column (transaction ID that created the row version):

-- Read the row and its xmin
SELECT id, content, xmin FROM documents WHERE id = 123;
-- Returns: xmin = 12345

-- Update only if xmin unchanged (no one else modified it)
UPDATE documents
SET content = 'New content'
WHERE id = 123 AND xmin = 12345;

Note: This works because any update creates a new row version with a new xmin. However, xmin values can wrap around, so this is best for short-lived operations.


Optimistic vs Pessimistic: When to Use Each

Use Pessimistic Locking When:

ScenarioWhy
High contentionMany users updating same rows
Short transactionsLock held briefly
Critical operationsMoney transfers, inventory
Sequential processingOrder matters
Database-only logicNo application-side state
-- Example: Money transfer with pessimistic locking
BEGIN;

-- Lock both accounts in consistent order to prevent deadlock
SELECT * FROM accounts WHERE id IN (sender_id, receiver_id) ORDER BY id FOR UPDATE;

-- Verify sufficient balance
-- If not, ROLLBACK

-- Perform transfer
UPDATE accounts SET balance = balance - amount WHERE id = sender_id;
UPDATE accounts SET balance = balance + amount WHERE id = receiver_id;

COMMIT;

Use Optimistic Locking When:

ScenarioWhy
Low contentionConflicts are rare
Long transactionsUser thinks for minutes
Read-heavy workloadsMany reads, few writes
Distributed systemsMultiple databases/services
Web applicationsStateless requests
-- Example: Document editing with optimistic locking
-- Request 1: User loads document
SELECT id, content, version FROM documents WHERE id = 123;
-- Returns version=5, store in session/hidden form field

-- Request 2: User saves (minutes later)
UPDATE documents
SET content = 'Edited content', version = version + 1
WHERE id = 123 AND version = 5;

-- If 0 rows affected: conflict! Show merge UI or error

Hybrid Approach: Optimistic with Pessimistic Fallback

For maximum performance with correctness guarantee:

def update_with_fallback(doc_id, new_content, expected_version, max_optimistic_retries=3):
    for attempt in range(max_optimistic_retries):
        try:
            # Try optimistic first
            result = update_optimistic(doc_id, new_content, expected_version)
            return result
        except OptimisticLockError:
            # Refresh version and retry
            expected_version = get_current_version(doc_id)

    # Too many conflicts - fall back to pessimistic
    with connection.cursor() as cur:
        cur.execute("BEGIN")
        cur.execute("SELECT version, content FROM documents WHERE id = %s FOR UPDATE", (doc_id,))
        current = cur.fetchone()

        # Conflict resolution logic here...

        cur.execute(
            "UPDATE documents SET content = %s, version = version + 1 WHERE id = %s",
            (resolved_content, doc_id)
        )
        cur.execute("COMMIT")

Advisory Locks: Application-Level Coordination

When you need locking at a logical level (not tied to specific rows):

-- Lock a logical resource (e.g., "report generation for tenant 42")
-- The lock ID is any bigint you choose
SELECT pg_advisory_lock(42);  -- Blocks until acquired

-- Do work...
-- This ensures only one connection runs this logic at a time for tenant 42

SELECT pg_advisory_unlock(42);  -- Release

-- Or use transaction-scoped version (auto-releases on commit/rollback)
SELECT pg_advisory_xact_lock(42);

Use cases:

  • Prevent duplicate cron job execution
  • Serialize expensive operations (report generation)
  • Coordinate across multiple tables without row locks

Lock Monitoring and Debugging

-- View all current locks
SELECT
    l.pid,
    l.locktype,
    l.mode,
    l.granted,
    a.usename,
    a.query,
    a.state
FROM pg_locks l
JOIN pg_stat_activity a ON l.pid = a.pid
WHERE l.locktype = 'relation' OR l.locktype = 'tuple'
ORDER BY l.granted, l.pid;

-- Find blocking chains
SELECT
    blocked.pid AS blocked_pid,
    blocked.query AS blocked_query,
    blocking.pid AS blocking_pid,
    blocking.query AS blocking_query
FROM pg_stat_activity blocked
JOIN pg_locks blocked_locks ON blocked.pid = blocked_locks.pid
JOIN pg_locks blocking_locks ON blocked_locks.locktype = blocking_locks.locktype
    AND blocked_locks.relation = blocking_locks.relation
    AND blocked_locks.pid != blocking_locks.pid
JOIN pg_stat_activity blocking ON blocking_locks.pid = blocking.pid
WHERE NOT blocked_locks.granted;

Writing Secure Concurrent Programs

Principle 1: Choose the Right Isolation Level

-- For most CRUD: Read Committed (default)
BEGIN;

-- For consistent multi-statement reads: Repeatable Read
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;

-- For correctness-critical operations: Serializable
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;

Principle 2: Always Handle Serialization Failures

Any isolation level above Read Committed can throw serialization errors:

# Python with psycopg2
import psycopg2
from psycopg2 import errors

def transfer_funds(from_account, to_account, amount):
    retries = 0
    max_retries = 5

    while retries < max_retries:
        try:
            with connection.cursor() as cur:
                cur.execute("""
                    BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;

                    UPDATE accounts SET balance = balance - %s
                    WHERE id = %s AND balance >= %s;

                    UPDATE accounts SET balance = balance + %s
                    WHERE id = %s;

                    COMMIT;
                """, (amount, from_account, amount, amount, to_account))
                return True
        except errors.SerializationFailure:
            connection.rollback()
            retries += 1
            time.sleep(0.01 * (2 ** retries))
        except Exception as e:
            connection.rollback()
            raise

    raise Exception("Max retries exceeded")

Principle 3: Use SELECT FOR UPDATE When Needed

Even in Read Committed, you may need to lock rows explicitly:

BEGIN;

-- Lock the row to prevent concurrent modifications
SELECT * FROM accounts WHERE id = 12345 FOR UPDATE;

-- Now safe to read and update based on the value
UPDATE accounts SET balance = balance - 100 WHERE id = 12345;

COMMIT;

FOR UPDATE vs FOR SHARE

ClauseBlocksUse Case
FOR UPDATEOther FOR UPDATE and modificationsWill modify the row
FOR SHAREOnly modificationsRead-only, but must prevent changes
FOR KEY SHAREOnly key modificationsForeign key integrity
FOR NO KEY UPDATEOnly FOR UPDATEUpdate non-key columns

Principle 4: Avoid Long Transactions

Long transactions cause problems:

ProblemDescription
Lock holdingRows locked for extended periods
MVCC bloatOld row versions can't be vacuumed
Increased conflict chanceMore opportunity for serialization failures
Connection holdingTies up database connections
-- Bad: Long transaction with locks
BEGIN;
SELECT * FROM orders FOR UPDATE;  -- Locks all orders
-- ... application does slow processing ...
UPDATE orders SET status = 'processed' WHERE ...;
COMMIT;

-- Better: Process in batches
DO $$
DECLARE
    batch_ids INT[];
BEGIN
    FOR i IN 1..10 LOOP
        SELECT array_agg(id) INTO batch_ids
        FROM orders
        WHERE status = 'pending'
        LIMIT 100
        FOR UPDATE SKIP LOCKED;  -- Skip already-locked rows

        UPDATE orders SET status = 'processed'
        WHERE id = ANY(batch_ids);

        COMMIT;
    END LOOP;
END $$;

Principle 5: Use SKIP LOCKED for Queue-Like Patterns

When multiple workers process items from a shared queue:

-- Worker grabs next available item, skipping locked ones
BEGIN;
SELECT * FROM job_queue
WHERE status = 'pending'
ORDER BY created_at
LIMIT 1
FOR UPDATE SKIP LOCKED;

-- Process the job...

UPDATE job_queue SET status = 'completed' WHERE id = ...;
COMMIT;

Principle 6: Understand Sequences and Serials

Sequences are not transactional:

CREATE TABLE orders (id SERIAL PRIMARY KEY, data TEXT);

-- Transaction A
BEGIN;
INSERT INTO orders (data) VALUES ('A');  -- Gets id=1
-- Transaction not yet committed

-- Transaction B (concurrent)
BEGIN;
INSERT INTO orders (data) VALUES ('B');  -- Gets id=2
COMMIT;

-- Transaction A
ROLLBACK;

-- Result: id=1 is "lost" (gap in sequence)
-- id=2 exists, id=1 does not

This is by design for performance. If you need gap-free sequences, you need additional locking (which hurts concurrency).

Principle 7: Be Careful with Unique Constraints

Even with SERIALIZABLE, unique constraint violations can occur:

-- Session 1
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT * FROM users WHERE email = '[email protected]';  -- Returns empty
-- Thinks: "Good, email is available"

-- Session 2
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT * FROM users WHERE email = '[email protected]';  -- Returns empty
INSERT INTO users (email) VALUES ('[email protected]');
COMMIT;  -- Success

-- Session 1
INSERT INTO users (email) VALUES ('[email protected]');
-- ERROR: duplicate key value violates unique constraint

Solution: Use ON CONFLICT:

INSERT INTO users (email, name) VALUES ('[email protected]', 'Test User')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name
RETURNING *;

Principle 8: Design for Idempotency

Make operations safe to retry:

-- Bad: Can't safely retry
INSERT INTO events (id, data) VALUES (gen_random_uuid(), 'event_data');

-- Good: Idempotent with client-provided ID
INSERT INTO events (id, data) VALUES ('client-uuid-123', 'event_data')
ON CONFLICT (id) DO NOTHING;

Common Patterns and Anti-Patterns

Anti-Pattern: Check-Then-Act Without Locking

-- WRONG: Race condition
BEGIN;
SELECT quantity FROM inventory WHERE product_id = 123;
-- Application checks: quantity >= order_amount
UPDATE inventory SET quantity = quantity - order_amount WHERE product_id = 123;
COMMIT;
-- CORRECT: Lock the row first
BEGIN;
SELECT quantity FROM inventory WHERE product_id = 123 FOR UPDATE;
-- Application checks: quantity >= order_amount
UPDATE inventory SET quantity = quantity - order_amount WHERE product_id = 123;
COMMIT;

-- ALSO CORRECT: Use conditional update
BEGIN;
UPDATE inventory
SET quantity = quantity - order_amount
WHERE product_id = 123 AND quantity >= order_amount
RETURNING quantity;
-- Check if row was updated (RETURNING returns result)
COMMIT;

Pattern: Optimistic Concurrency Control

Use version numbers for conflict detection:

-- Add version column
ALTER TABLE documents ADD COLUMN version INT DEFAULT 1;

-- Update with version check
UPDATE documents
SET content = 'new content', version = version + 1
WHERE id = 123 AND version = 5;

-- Check rows affected
-- If 0 rows: someone else modified the document (retry or fail)

Pattern: Advisory Locks for Application-Level Synchronization

When you need to coordinate beyond row-level:

-- Acquire an advisory lock (blocks until available)
SELECT pg_advisory_lock(12345);

-- Do work that needs coordination...

-- Release the lock
SELECT pg_advisory_unlock(12345);

-- Or use transaction-scoped locks (auto-release on commit/rollback)
SELECT pg_advisory_xact_lock(12345);

Pattern: Materialized View Refresh

For expensive queries, use materialized views with concurrent refresh:

CREATE MATERIALIZED VIEW sales_summary AS
SELECT product_id, SUM(quantity) as total_sold, SUM(amount) as total_revenue
FROM sales
GROUP BY product_id;

-- Refresh without blocking reads
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_summary;

Monitoring and Debugging Concurrency Issues

Check Current Locks

SELECT
    pid,
    locktype,
    relation::regclass,
    mode,
    granted,
    query
FROM pg_locks l
JOIN pg_stat_activity a ON l.pid = a.pid
WHERE NOT granted OR relation IS NOT NULL
ORDER BY pid;

Find Blocking Queries

SELECT
    blocked_locks.pid AS blocked_pid,
    blocked_activity.usename AS blocked_user,
    blocking_locks.pid AS blocking_pid,
    blocking_activity.usename AS blocking_user,
    blocked_activity.query AS blocked_statement,
    blocking_activity.query AS blocking_statement
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity
    ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks
    ON blocking_locks.locktype = blocked_locks.locktype
    AND blocking_locks.database IS NOT DISTINCT FROM blocked_locks.database
    AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
    AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
    AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
    AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
    AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
    AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
    AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
    AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
    AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity
    ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.granted;

Monitor Serialization Failures

-- Check for serialization failures in logs
-- postgresql.conf: log_min_error_statement = error

-- Or monitor in application metrics
SELECT
    datname,
    xact_rollback,
    conflicts
FROM pg_stat_database;

Configuration Parameters

Key parameters affecting concurrency:

ParameterDescriptionDefault
default_transaction_isolationDefault isolation levelread committed
max_connectionsMaximum concurrent connections100
deadlock_timeoutTime before deadlock detection1s
lock_timeoutMax time to wait for a lock0 (infinite)
idle_in_transaction_session_timeoutKill idle transactions0 (disabled)
max_pred_locks_per_transactionPredicate locks per transaction64
max_pred_locks_per_relationPredicate locks per relation-2
max_pred_locks_per_pagePredicate locks per page2
-- Kill transactions idle too long (prevent connection/lock holding)
SET idle_in_transaction_session_timeout = '5min';

-- Don't wait forever for locks
SET lock_timeout = '10s';

-- Log slow queries for analysis
SET log_min_duration_statement = 1000;  -- 1 second

Summary: Decision Guide

Choosing an Isolation Level

RequirementRecommended Level
Simple CRUD, high concurrencyRead Committed
Consistent reads across multiple queriesRepeatable Read
Correctness is critical, willing to retrySerializable
Read-only analytical queriesSerializable Read Only Deferrable

Locking Strategy

NeedSolution
Prevent concurrent modificationSELECT ... FOR UPDATE
Read-only but prevent changesSELECT ... FOR SHARE
Skip locked rows (queue pattern)SELECT ... FOR UPDATE SKIP LOCKED
Application-level coordinationAdvisory locks
Optimistic concurrencyVersion columns

Locking Strategy Decision Tree

                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚ Do you need to prevent      โ”‚
                    โ”‚ concurrent modifications?   โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                  โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ–ผ                             โ–ผ
                  Yes                            No
                    โ”‚                             โ”‚
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                 โ–ผ
        โ”‚ Is the transaction    โ”‚         No locking needed
        โ”‚ short (< 1 second)?   โ”‚         (MVCC handles it)
        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                    โ”‚
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ–ผ                       โ–ผ
       Yes                     No
        โ”‚                       โ”‚
        โ–ผ                       โ–ผ
  Pessimistic Lock        Optimistic Lock
  (SELECT FOR UPDATE)     (Version column)
        โ”‚                       โ”‚
        โ”‚                       โ”‚
        โ–ผ                       โ–ผ
  High contention?        Need retry logic
  Use NOWAIT/SKIP LOCKED  in application

Key Takeaways

  1. PostgreSQL never allows dirty reads โ€” even Read Uncommitted behaves as Read Committed
  2. MVCC enables readers and writers to coexist without blocking each other
  3. Always handle serialization failures in Repeatable Read and Serializable
  4. Short transactions are better โ€” they hold fewer locks and cause fewer conflicts
  5. Test concurrent scenarios โ€” bugs often only appear under load
  6. Use FOR UPDATE SKIP LOCKED for queue-like patterns
  7. Serializable is safer than you think โ€” SSI doesn't block, it just detects anomalies
  8. Choose pessimistic locking for high-contention, short transactions (financial operations)
  9. Choose optimistic locking for low-contention, long transactions (document editing)
  10. Version columns are the most reliable optimistic locking strategy

References

  1. PostgreSQL 18 Documentation - Chapter 13. Concurrency Control. (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/18/mvcc.html
  2. PostgreSQL 18 Documentation - 13.2. Transaction Isolation. (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/18/transaction-iso.html
  3. PostgreSQL 18 Documentation - 13.3. Explicit Locking. (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/18/explicit-locking.html
  4. PostgreSQL 18 Documentation - 13.1. Introduction (MVCC). (n.d.). Retrieved December 24, 2025, from https://www.postgresql.org/docs/18/mvcc-intro.html
  5. Berenson, H., Bernstein, P., Gray, J., Melton, J., O'Neil, E., & O'Neil, P. (1995). A Critique of ANSI SQL Isolation Levels. SIGMOD Record, 24(2), 1-10.
  6. Ports, D. R. K., & Grittner, K. (2012). Serializable Snapshot Isolation in PostgreSQL. Proceedings of the VLDB Endowment, 5(12), 1850-1861.

ยฉ 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-12-24). PostgreSQL Transaction Isolation, MVCC, and Writing Secure Concurrent Programs. https://caiborui.com/blog/2025-12-24-en-postgresql-transaction-isolation-mvcc-concurrent-programming

@misc{borui2025-a33bacfc,
  author = {borui},
  title = {{PostgreSQL Transaction Isolation, MVCC, and Writing Secure Concurrent Programs}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-12-24-en-postgresql-transaction-isolation-mvcc-concurrent-programming}
}