paulserban.eu

Writing Edition

Paul Serban

Writing, snippets & book notes

Cheat sheet · Post

PostgreSQL Internals: MVCC, Indexing, and Transaction Behavior

← Back to PostgreSQL Fundamentals: A Practical Guide to How It Actually Works

PostgreSQL's SQL surface hides a small set of internal mechanisms - concurrency control, indexing, and transaction isolation - that determine correctness and performance under real production load.

Overview

Key Concepts

Process Architecture & Connection Overhead

MVCC (Multi-Version Concurrency Control)

Write-Ahead Log (WAL)

Index Types

-- Without this index, a JSONB containment query forces a full table scan:
CREATE INDEX idx_products_attributes_gin ON products USING GIN (attributes);

Transaction Isolation Levels

Locking

Trade-offs / Caveats

Example in Practice

A funds-transfer operation needs stronger guarantees than the Read Committed default provides across multiple statements, so it explicitly sets isolation level and takes a row lock:

def transfer_funds(from_account_id, to_account_id, amount_cents):
    with pool.connection() as conn:
        conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
        with conn.transaction():
            cur = conn.execute(
                "SELECT balance_cents FROM accounts WHERE id = %s FOR UPDATE",
                (from_account_id,),
            )
            balance = cur.fetchone()[0]
            if balance < amount_cents:
                raise ValueError("Insufficient funds")
            conn.execute(
                "UPDATE accounts SET balance_cents = balance_cents - %s WHERE id = %s",
                (amount_cents, from_account_id),
            )
            conn.execute(
                "UPDATE accounts SET balance_cents = balance_cents + %s WHERE id = %s",
                (amount_cents, to_account_id),
            )

FOR UPDATE takes a row lock on the source account, closing the gap that Read Committed alone leaves open - a second concurrent transfer can't read a stale balance mid-transaction.

Related topics