Skip to main content

Postgres Lives in the Past

How snapshots decide which committed transactions you're allowed to see: isolation, the I in ACID

Updated 21 min readMarkdown
Part of seriesACID, Connected
Postgres Lives in the Past

In Part 1, we saw that Postgres doesn't look back: it never undoes a write, it just marks a transaction aborted and leaves the old row version untouched.

That same choice has a second consequence. A writer never overwrites a row in place. It adds a new version beside the old one. So a reader takes no row lock to hold the row steady: it reads the old version while the writer works on the new one. For ordinary reads and writes, readers don't block writers, and writers don't block readers. (SELECT ... FOR UPDATE and table-level locks are another story.)

Each transaction reads the database as it existed at a single moment in time. Every reader in Postgres lives in the past.

Which past, exactly? Postgres doesn't copy your data to freeze it. Instead, it takes a snapshot: a lightweight record of which transactions were in flight at the moment you looked. Anything that hadn't committed before that instant hasn't happened yet, as far as your query is concerned.

This post is about that snapshot: what's inside it, how Postgres captures it, and why choosing an isolation level is really choosing when the shutter clicks. Then we'll see what it costs when one transaction refuses to leave the past.

The promise: act as if you're alone

Isolation is the I in ACID. Ideally, each transaction behaves as if it were running alone, even when thousands run at once. Each isolation level relaxes that ideal by a different amount, and says exactly how much of the others' work you may see. When concurrent transactions interfere, they produce specific, named failures called anomalies.

We'll reuse the accounts from Part 1. Saumya and Mohit each start with 1000.

Anomaly What goes wrong Example
Dirty read You read another transaction's uncommitted change T1 sets Saumya to 500 but hasn't committed. T2 reads 500. T1 rolls back. T2 saw a value that never existed.
Non-repeatable read You read the same row twice and get different values T2 reads Saumya = 1000. T1 sets 900 and commits. T2 reads again: 900.
Phantom read You run the same query twice and get new rows T2 counts accounts with balance > 500: 2. T1 inserts Ravi with 800 and commits. T2 counts again: 3.

There are two more anomalies, lost updates and write skew, but they need two writers. They get their own post.

Two obvious fixes, and what they cost

Naive idea 1: run transactions one at a time. Serial execution never produces an anomaly. It also means 999 users wait in line behind the first, and one slow report freezes the whole system.

Naive idea 2: lock what you touch. Take a shared lock on every row you read and an exclusive lock on every row you write, and hold them all until commit. This is two-phase locking (2PL). With range locks as well, so new rows can't slip in, it prevents these anomalies.

But now readers block writers and writers block readers. A long analytics query holds shared locks on millions of rows, and every UPDATE on those rows waits behind it. Two transactions that each read a row the other wants to write wait on each other forever: a deadlock, and one of them has to be killed.

Pause. Postgres avoids all of this by keeping the old version beside the new one, so the reader takes no lock. But now a page may hold two, three, ten versions of the same row. Which one is yours?

Piece 1: The snapshot — who was still running

Postgres's answer: the one that matches your snapshot.

When a transaction needs to read, Postgres takes a snapshot. The surprising part is what's in it. A snapshot is not a copy of any data. It is a tiny record of which transactions were in progress at that moment:

Field Meaning
xmin The oldest transaction ID still running
xmax One past the highest transaction ID that had completed. Everything from here up counts as not finished, including IDs not even handed out yet
xip The IDs between xmin and xmax that are still running

Here's the actual struct (trimmed; the comments are Postgres's own):

typedef struct SnapshotData
{
    SnapshotType snapshot_type; /* type of snapshot */
    ...
    TransactionId xmin;         /* all XID < xmin are visible to me */
    TransactionId xmax;         /* all XID >= xmax are invisible to me */
    ...
    TransactionId *xip;
    uint32        xcnt;         /* # of xact ids in xip[] */
    ...
    TransactionId *subxip;
    ...
    bool          takenDuringRecovery;  /* recovery-shaped snapshot? */
    bool          copied;       /* false if it's a static snapshot */

    CommandId     curcid;       /* in my xact, CID < curcid are visible */
    ...
} SnapshotData;

Source: snapshot.h:142

Two xids, a list, and a counter for your own commands. No rows, no pages, no copy of anything. Its size depends on how many transactions are running, not on how much data you have.

You can look at your own. The text format is xmin:xmax:xip_list, the same three fields as the struct.

I open four sessions, B to E. Each one runs BEGIN; SELECT pg_current_xact_id(); to force an xid. The first and third stay open; the second and fourth commit:

Session xid State
B 762 open
C 763 committed
D 764 open
E 765 committed
lab=# SELECT pg_current_snapshot();
 pg_current_snapshot
---------------------
 762:766:762,764

This reads as: transactions below 762 have all finished, nothing at 766 or above had finished, and of the ones in between, 762 and 764 were still running when the photo was taken. 763 and 765 aren't in the list, so they count as done.

The data stays on the heap pages exactly where it was. The snapshot only decides which of the row versions sitting there count as real for you.

Pause. A snapshot holds a few transaction IDs and no data. Given a row version with xmin = 763, what else do you need to decide whether you can see it?

Piece 2: The visibility rule — snapshot first, pg_xact second

In Part 1, every row version carried xmin (who created it) and xmax (who deleted or replaced it), and a reader asked pg_xact one question: did that transaction commit?

Isolation asks a sharper one: did it commit as far as my snapshot is concerned?

Note: Postgres reuses two names here. On a row version, xmin and xmax are the transactions that created and deleted it. On a snapshot, xmin is the oldest transaction still running and xmax is one past the last one that finished. Same names, different jobs. Below, snapshot.xmax means the snapshot's boundary.

For a row version with xmin = X, Postgres checks:

  1. X is my own transaction? Changes from earlier commands in my transaction are visible to me (that's curcid in the struct).
  2. X ≥ snapshot.xmax? X hadn't finished when the photo was taken. Invisible.
  3. X is in xip? X was still running at the photo. Invisible, even if it has committed since.
  4. Otherwise, X finished before the photo. Only now does Postgres ask Part 1's question: hint bits, else pg_xact. Committed means visible; aborted means it never existed.

Notice what the snapshot doesn't store: it never knows whether 763 committed. It only knows 763 wasn't running when the photo was taken. pg_xact answers the rest. And because no step ever treats an uncommitted xmin as visible, dirty reads are impossible in Postgres at any isolation level.

Step 3 is the everyday case in Repeatable Read. The photo is kept for the whole transaction, so anything in xip stays invisible however long ago it committed. Read Committed hits it too, but only within one statement.

The same rule runs on xmax, flipped around. If the deleting transaction doesn't count as committed for my snapshot, the deletion hasn't happened for me, and the old version is still my live row.

Piece 3: How the Postgres shutter works

So far the snapshot has been a given. Now let's watch Postgres build one, and then watch it hide a commit.

Everything below is from PostgreSQL 17.12, with a debugger (lldb) attached to session A's backend. Code excerpts are trimmed from the REL_17_12 source: ... marks removed lines, /* */ comments are Postgres's own, and // comments are mine.

The setup: Saumya's balance is 1000. Session B updates it to 900 and commits. Session A, in Read Committed, runs:

SELECT balance FROM accounts WHERE id = 1;

I ran this twice, each time with one breakpoint in a different place. In the first run, the breakpoint catches A while it builds the photo. In the second, it catches A after the photo is taken but before it reads a single row. That's why the transaction IDs differ between the two runs.


Run 1: the photo being taken

A asks for a photo. Here's A, stopped inside GetSnapshotData():

* frame #0: postgres`GetSnapshotData(snapshot=0x0000000105347130) at procarray.c:2243:27
  frame #1: postgres`GetTransactionSnapshot at snapmgr.c:268:22
  frame #2: postgres`exec_simple_query(query_string="SELECT balance FROM accounts WHERE id = 1;") at postgres.c:1168:23
  frame #3: postgres`PostgresMain(dbname="lab", username="somyakumar") at postgres.c:4791:7

Before planning anything, exec_simple_query() asks GetTransactionSnapshot() for a photo. The first thing that function does is decide whether A even needs a new one:

Snapshot
GetTransactionSnapshot(void)
{
    ...
    /* First call in transaction? */
    if (!FirstSnapshotSet)
    {
        ...
        if (IsolationUsesXactSnapshot())       // Repeatable Read or Serializable
        {
            ...
            CurrentSnapshot = GetSnapshotData(&CurrentSnapshotData);
            /* Make a saved copy */
            CurrentSnapshot = CopySnapshot(CurrentSnapshot);
            FirstXactSnapshot = CurrentSnapshot;   // kept for the whole transaction
            ...
        }
        else
            CurrentSnapshot = GetSnapshotData(&CurrentSnapshotData);

        FirstSnapshotSet = true;
        return CurrentSnapshot;
    }

    if (IsolationUsesXactSnapshot())
        return CurrentSnapshot;                // Repeatable Read: same photo, every statement
    ...
    CurrentSnapshot = GetSnapshotData(&CurrentSnapshotData);   // Read Committed: new photo

    return CurrentSnapshot;
}

Source: snapmgr.c:216

Keep this if in mind: the whole of Piece 4 lives inside it. The isolation level doesn't change how Postgres decides what you see. It only changes whether this function hands you the old photo or takes a new one.

A wants everyone to hold still. A needs a list of every running transaction. But there are many backends, and by the time A finished asking each one, the first answers would already be stale.

Pause. A only wants to read that list. Why would it need a lock?

LWLockAcquire(ProcArrayLock, LW_SHARED);

A is frozen on the line right after this one. In session B, transaction 791 has already updated Saumya's row. Now B (pid 5631) types COMMIT, and it hangs. From a third session, C:

lab=# SELECT pid, state, wait_event_type, wait_event FROM pg_stat_activity WHERE pid = 5631;
 pid  | state  | wait_event_type | wait_event
------+--------+-----------------+------------
 5631 | active | LWLock          | ProcArray

B is stuck on the last step of its commit. Part 1 covered the first two: the commit record is in the WAL, and pg_xact says committed. What's left is removing itself from the list of running transactions:

void
ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid)
{
    if (TransactionIdIsValid(latestXid))
    {
        ...
        if (LWLockConditionalAcquire(ProcArrayLock, LW_EXCLUSIVE))
        {
            ProcArrayEndTransactionInternal(proc, latestXid);
            LWLockRelease(ProcArrayLock);
        }
        else
            ProcArrayGroupClearXid(proc, latestXid);   // B ends up here: A holds the lock
    }
    ...
}

And the part that actually takes B out of the list:

ProcArrayEndTransactionInternal(PGPROC *proc, TransactionId latestXid)
{
    ...
    ProcGlobal->xids[pgxactoff] = InvalidTransactionId;   // "I'm no longer running"
    ...
    /* Also advance global latestCompletedXid while holding the lock */
    MaintainLatestCompletedXid(latestXid);

    /* Same with xactCompletionCount  */
    TransamVariables->xactCompletionCount++;   // tells GetSnapshotDataReuse() old snapshots are stale
}

Source: procarray.c:667, procarray.c:731

B needs the lock exclusively. A holds it shared. So the conditional acquire fails, B joins the group-clearing path, and waits.¹

That's the answer to the Pause. The shared lock doesn't protect A from other readers: any number of snapshots can be built at once.

It protects A from a commit landing halfway through its scan, where A might count B as running in one place and finished in another. With the lock held, every transaction is either fully in A's photo or fully out of it.

Normally A holds that lock for microseconds; lldb stretched it so we could watch. And notice the order of B's commit: pg_xact first, proc array second. So any transaction that's below xmax and missing from xip has already written its final answer to pg_xact. That's why step 4 in Piece 2 can safely ask pg_xact.

A counts the living. First, it draws the line above which everything counts as still running. Another transaction, 792, finished just before A took the lock:

latest_completed = TransamVariables->latestCompletedXid;   // 792
...
/* xmax is always latestCompletedXid + 1 */
xmax = XidFromFullTransactionId(latest_completed);
TransactionIdAdvance(xmax);                                  // 793
...
/* initialize xmin calculation with xmax */
xmin = xmax;

/* take own xid into account, saves a check inside the loop */
if (TransactionIdIsNormal(myxid) && NormalTransactionIdPrecedes(myxid, xmin))
    xmin = myxid;

Pause. Why not just list every running transaction? Why have an xmax at all?

Because everything at or above xmax is invisible by definition: none of it had finished when the photo was taken. The snapshot never needs to store those IDs, only the line. That's what keeps a snapshot tiny.

Then A walks the array of running xids. But first, one fork in the road:

snapshot->takenDuringRecovery = RecoveryInProgress();

if (!snapshot->takenDuringRecovery)
{
    ...
    for (int pgxactoff = 0; pgxactoff < numProcs; pgxactoff++)
    {
        /* Fetch xid just once - see GetNewTransactionId */
        TransactionId xid = UINT32_ACCESS_ONCE(other_xids[pgxactoff]);
        uint8       statusFlags;
        ...
        if (likely(xid == InvalidTransactionId))   // no xid yet: hasn't written anything
            continue;

        if (pgxactoff == mypgxactoff)              // that's me (already folded into xmin above)
            continue;
        ...
        if (!NormalTransactionIdPrecedes(xid, xmax))
            continue;                              // >= xmax: already invisible, don't bother listing

        statusFlags = allStatusFlags[pgxactoff];
        if (statusFlags & (PROC_IN_LOGICAL_DECODING | PROC_IN_VACUUM))
            continue;                              // lazy VACUUM writes no user rows; logical decoding tracks its xmin separately

        if (NormalTransactionIdPrecedes(xid, xmin))
            xmin = xid;

        /* Add XID to snapshot. */
        xip[count++] = xid;                        // still running: into the photo
        ...                                        // (then its subtransaction xids, into subxip)
    }
}
else
{
    /*
     * We're in hot standby, so get XIDs from KnownAssignedXids.
     ...
     */
    subcount = KnownAssignedXidsGetAndSetXmin(snapshot->subxip, &xmin,
                                              xmax);
    ...
}

Source: procarray.c:2177

On a hot standby, the running transactions live on the primary. While in recovery, the standby rebuilds them from WAL into KnownAssignedXids, and the else branch builds the snapshot from that, putting every xid in subxip and leaving xip empty. This post follows the primary.

A finds 791 in the array. B hasn't removed itself yet, because it's waiting for the very lock A holds. 791 is below xmax, so it goes into xip.

The photo develops.

if (!TransactionIdIsValid(MyProc->xmin))
    MyProc->xmin = TransactionXmin = xmin;     // remember this line: it comes back in the last section

LWLockRelease(ProcArrayLock);

A's photo, as lldb sees it (trimmed):

(lldb) p CurrentSnapshotData
(SnapshotData) {
  snapshot_type = SNAPSHOT_MVCC
  xmin = 791
  xmax = 793
  xcnt = 1
  takenDuringRecovery = false
  ...
}

791:793:791. Everything below 791 finished, nothing from 793 up had finished, and 791 itself was still running. The moment the lock is released, B's COMMIT returns.


Run 2: a commit the photo can't see

Run 1 shows the photo being built. But my first attempts at the next step failed: A kept printing 900.

The reason is in Run 1's backtrace. That snapshot came from exec_simple_query() at postgres.c:1168, for planning. In Read Committed, the same SELECT asks for a second photo just before execution, in PortalStart(), and that second one decides what you see. By the time I let A go, B had committed, and the second photo included it.

So for Run 2, I put the breakpoint on standard_ExecutorRun(), after the execution photo is taken and before a single row is read:

* frame #0: postgres`standard_ExecutorRun(queryDesc=0x0000007cd2400d00, ...) at execMain.c:320:2
  frame #1: postgres`ExecutorRun(...) at execMain.c:306:3
  frame #2: postgres`PortalRunSelect(...) at pquery.c:926:4
  frame #3: postgres`PortalRun(...) at pquery.c:770:18
  frame #4: postgres`exec_simple_query(query_string="SELECT balance FROM accounts WHERE id = 1;") at postgres.c:1279:10

B is transaction 805, with its update done but not yet committed. The photo the executor is about to use:

(lldb) p *queryDesc->snapshot
(SnapshotData) {
  snapshot_type = SNAPSHOT_MVCC
  xmin = 805
  xmax = 805
  xcnt = 0
  ...
}

805:805:. B sits exactly at xmax, so it counts as not finished. Now, with A still frozen, B commits. It returns at once: A holds no lock this time. And pg_xact agrees B is done:

lab=# SELECT pg_xact_status('805');
 pg_xact_status
----------------
 committed

A reads the row. The page holds two versions of Saumya's row, as Part 1 left them: the old one with xmax = 805, the new one with xmin = 805. A checks the new version:

if (!HeapTupleHeaderXminCommitted(tuple))
{
    ...
    else if (XidInMVCCSnapshot(HeapTupleHeaderGetRawXmin(tuple), snapshot))
        return false;                // the snapshot is asked first
    else if (TransactionIdDidCommit(HeapTupleHeaderGetRawXmin(tuple)))
        SetHintBits(...);            // only then pg_xact
    ...
}
else
{
    /* xmin is committed, but maybe not according to our snapshot */
    if (!HeapTupleHeaderXminFrozen(tuple) &&
        XidInMVCCSnapshot(HeapTupleHeaderGetRawXmin(tuple), snapshot))
        return false;
}

Source: heapam_visibility.c:960

This is Piece 2's rule, in the order the code really runs it. XidInMVCCSnapshot(805) says 805 ≥ xmax, so the 900 version is invisible, and pg_xact is never asked. The old version's deletion is by the same 805, so for A it hasn't happened. I detach lldb, and A prints:

lab=# SELECT balance FROM accounts WHERE id = 1;
 balance
---------
    1000

I run the same query again, with a fresh photo:

 balance
---------
     900

Pause. pg_xact said committed before A read a single row. Even a "committed" hint bit wouldn't have changed anything. Was A wrong?

No. A's photo was taken before B committed. Nobody outside the database could have known B was finished when A started, so 1000 is an honest answer.

That's why the code checks the snapshot before pg_xact, and why even the "committed" hint bit isn't the final word. pg_xact answers "did 805 commit?" The snapshot answers "had 805 committed when I looked?" Isolation is the second question.

Pause. You run BEGIN ISOLATION LEVEL REPEATABLE READ;, go for a coffee, and meanwhile someone commits an update. Your first SELECT runs after you return. Does it see the update?

Piece 4: Isolation level = when the shutter clicks

Yes, it sees the update. BEGIN takes no photo. Look at the if again: the first photo is taken by the first statement that asks for one, and Repeatable Read keeps that one.

The visibility rule never changes between levels; only the if at the top of GetTransactionSnapshot() does.

Read Committed (the default) takes a new photo per statement, so between two statements other commits become visible: non-repeatable reads and phantoms. Repeatable Read takes one photo at the transaction's first query (not at BEGIN) and keeps it, so neither can happen.

You can watch it. Two statements in one Read Committed transaction, with transaction 807 committing in another session between them:

lab=# BEGIN ISOLATION LEVEL READ COMMITTED;
lab=*# SELECT pg_current_snapshot();
 807:807:
lab=*# SELECT pg_current_snapshot();
 808:808:

A new photo per statement: the second one already counts 807 as finished.

The same thing in Repeatable Read, while another transaction finishes in between:

lab=# BEGIN ISOLATION LEVEL REPEATABLE READ;
lab=*# SELECT pg_current_snapshot();
 808:808:
lab=*# SELECT pg_current_snapshot();
 808:808:

Session B, outside the transaction, already sees 809:809:. A is still living at 808.

For these three anomalies, Postgres is stricter than the SQL standard:

Level Dirty read Non-repeatable read Phantom read
Read Uncommitted never (behaves as Read Committed) possible possible
Read Committed never possible possible
Repeatable Read never never never (the standard would allow it)
Serializable never never never

The standard lets Repeatable Read show phantoms. Postgres doesn't, because a photo of the whole database can't grow new rows. But the table doesn't show everything. Postgres's Repeatable Read is snapshot isolation, and it still allows one anomaly a lock-based Repeatable Read would block: write skew. Only Serializable stops it. That's Part 3.

Pause. A photo only works if the old row versions it points to are still on the page. So when can Postgres throw an old version away, and what happens if one photo never goes away?

The cost: a transaction that won't leave the past

VACUUM can remove an old version only once no snapshot could still need it. If an old photo might still count that version as the live row, removing it would make the photo lie.

Each backend publishes the oldest xid its photo needs: the MyProc->xmin line from Piece 3. The oldest across the database is the xmin horizon, and nothing newer can be cleaned up.

In Read Committed, that value is cleared when each statement ends, so an idle session that has only read holds nothing back. A Repeatable Read transaction keeps its photo until it ends. Watch what one does.

In one session, I open a Repeatable Read transaction, take its photo with SELECT 1;, and walk away. In another, I update Saumya's row 1,000 times and vacuum:

lab=# VACUUM VERBOSE accounts;
INFO:  finished vacuuming "lab.public.accounts": index scans: 0
tuples: 0 removed, 1004 remain, 1000 are dead but not yet removable
removable cutoff: 809, which was 1 XIDs old when operation ended

1,000 dead versions, and VACUUM removed none. The cutoff is 809. Who's holding it there?

lab=# SELECT pid, state, backend_xmin, now() - xact_start AS open_for
      FROM pg_stat_activity WHERE backend_xmin IS NOT NULL;
 pid  |        state        | backend_xmin |    open_for
------+---------------------+--------------+-----------------
 5572 | idle in transaction |          809 | 00:01:07.332442
 5631 | active              |          810 | 00:00:00

The idle Repeatable Read session, backend_xmin = 809: exactly the cutoff. (5631 is the session running this query.) I commit it and vacuum again:

lab=# VACUUM VERBOSE accounts;
tuples: 1000 removed, 4 remain, 0 are dead but not yet removable
removable cutoff: 810, which was 0 XIDs old when operation ended

All 1,000 gone. One idle session held back a minute of cleanup here. Leave it open for hours on a busy database and every table in it bloats.

It isn't only Repeatable Read. A transaction that has written holds the horizon too, through its own xid. So do open cursors, prepared transactions, replication slots and hot_standby_feedback. The culprit shows up as an old backend_xmin (or backend_xid) in pg_stat_activity.

Recap

Mechanism Its job in isolation
Snapshot (xmin, xmax, xip) A record of which transactions were running, not a copy of data
GetSnapshotData() Under ProcArrayLock: xmax = latestCompletedXid + 1, list running xids below it, publish MyProc->xmin
Visibility rule Snapshot first, then Part 1's hint bits and pg_xact; uncommitted is never visible
Read Committed A new snapshot per statement
Repeatable Read One snapshot per transaction, taken at the first query

Part 1 showed that Postgres never destroys an old version. Part 2 is what that buys: every reader gets its own moment in the past, for free, without stopping anyone.

But readers can live in the past. Writers can't: you can only update the newest version of a row, and a photo can't tell you what the transaction next to you is about to write.

Next in ACID, Connected: When Writers Collide, covering lost updates, first updater wins, and the one anomaly a snapshot can never catch.


¹ Group clearing arrived in PostgreSQL 9.6: committing backends that can't get the lock join a group, and one leader clears all their xids in a single exclusive acquisition. Either way, B's xid can't leave the array while A holds the lock.

139 views

About the author

  • Storage & database engineer. Database internals, modern C++, concurrency.

No comments yet. Be the first to comment.

ACID, Connected

Part 2 of 2

Atomicity, consistency, isolation, durability: how Postgres keeps each promise, and how its parts connect to do it. One letter at a time, from the problem to the design.

Start from the beginningPostgres Doesn’t Look BackHow MVCC, WAL and one bit in pg_xact keep transactions atomic without undoing a single byte.