<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[fsync’d]]></title><description><![CDATA[fsync’d]]></description><link>https://saumyakr.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:52:54 GMT</lastBuildDate><atom:link href="https://saumyakr.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Postgres Lives in the Past]]></title><description><![CDATA[How snapshots decide which committed transactions you're allowed to see: isolation, the I in ACID]]></description><link>https://saumyakr.hashnode.dev/postgres-lives-in-the-past</link><guid isPermaLink="true">https://saumyakr.hashnode.dev/postgres-lives-in-the-past</guid><dc:creator><![CDATA[Somya kumar]]></dc:creator><pubDate>Fri, 27 Nov 2026 12:00:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6af682d28e0395cb3d77e3d4/e564e4ca-a6b6-48c7-befe-c54d37209676.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>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.</p>
<p>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. (<code>SELECT ... FOR UPDATE</code> and table-level locks are another story.)</p>
<p>Each transaction reads the database as it existed at a single moment in time. Every reader in Postgres lives in the past.</p>
<p>Which past, exactly? Postgres doesn't copy your data to freeze it. Instead, it takes a <strong>snapshot</strong>: 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.</p>
<p>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.</p>
<h2>The promise: act as if you're alone</h2>
<p>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.</p>
<p>We'll reuse the accounts from Part 1. Saumya and Mohit each start with 1000.</p>
<table>
<thead>
<tr>
<th>Anomaly</th>
<th>What goes wrong</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td>Dirty read</td>
<td>You read another transaction's uncommitted change</td>
<td>T1 sets Saumya to 500 but hasn't committed. T2 reads 500. T1 rolls back. T2 saw a value that never existed.</td>
</tr>
<tr>
<td>Non-repeatable read</td>
<td>You read the same row twice and get different values</td>
<td>T2 reads Saumya = 1000. T1 sets 900 and commits. T2 reads again: 900.</td>
</tr>
<tr>
<td>Phantom read</td>
<td>You run the same query twice and get new rows</td>
<td>T2 counts accounts with balance &gt; 500: 2. T1 inserts Ravi with 800 and commits. T2 counts again: 3.</td>
</tr>
</tbody></table>
<p>There are two more anomalies, lost updates and write skew, but they need two <em>writers</em>. They get their own post.</p>
<h2>Two obvious fixes, and what they cost</h2>
<p><strong>Naive idea 1: run transactions one at a time.</strong> 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.</p>
<p><strong>Naive idea 2: lock what you touch.</strong> 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.</p>
<p>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.</p>
<blockquote>
<p><strong>Pause.</strong> 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 <em>yours</em>?</p>
</blockquote>
<h2>Piece 1: The snapshot — who was still running</h2>
<p>Postgres's answer: the one that matches your snapshot.</p>
<p>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:</p>
<table>
<thead>
<tr>
<th>Field</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>xmin</code></td>
<td>The oldest transaction ID still running</td>
</tr>
<tr>
<td><code>xmax</code></td>
<td>One past the highest transaction ID that had completed. Everything from here up counts as not finished, including IDs not even handed out yet</td>
</tr>
<tr>
<td><code>xip</code></td>
<td>The IDs between <code>xmin</code> and <code>xmax</code> that are still running</td>
</tr>
</tbody></table>
<p>Here's the actual struct (trimmed; the comments are Postgres's own):</p>
<pre><code class="language-c">typedef struct SnapshotData
{
    SnapshotType snapshot_type; /* type of snapshot */
    ...
    TransactionId xmin;         /* all XID &lt; xmin are visible to me */
    TransactionId xmax;         /* all XID &gt;= 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 &lt; curcid are visible */
    ...
} SnapshotData;
</code></pre>
<p>Source: <a href="https://github.com/postgres/postgres/blob/REL_17_12/src/include/utils/snapshot.h#L142"><code>snapshot.h:142</code></a></p>
<p>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.</p>
<p>You can look at your own. The text format is <code>xmin:xmax:xip_list</code>, the same three fields as the struct.</p>
<p>I open four sessions, B to E. Each one runs <code>BEGIN; SELECT pg_current_xact_id();</code> to force an xid. The first and third stay open; the second and fourth commit:</p>
<table>
<thead>
<tr>
<th>Session</th>
<th>xid</th>
<th>State</th>
</tr>
</thead>
<tbody><tr>
<td>B</td>
<td>762</td>
<td>open</td>
</tr>
<tr>
<td>C</td>
<td>763</td>
<td>committed</td>
</tr>
<tr>
<td>D</td>
<td>764</td>
<td>open</td>
</tr>
<tr>
<td>E</td>
<td>765</td>
<td>committed</td>
</tr>
</tbody></table>
<pre><code class="language-plaintext">lab=# SELECT pg_current_snapshot();
 pg_current_snapshot
---------------------
 762:766:762,764
</code></pre>
<p>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.</p>
<p>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.</p>
<blockquote>
<p><strong>Pause.</strong> A snapshot holds a few transaction IDs and no data. Given a row version with <code>xmin = 763</code>, what else do you need to decide whether you can see it?</p>
</blockquote>
<h2>Piece 2: The visibility rule — snapshot first, pg_xact second</h2>
<p>In Part 1, every row version carried <code>xmin</code> (who created it) and <code>xmax</code> (who deleted or replaced it), and a reader asked pg_xact one question: did that transaction commit?</p>
<p>Isolation asks a sharper one: did it commit <em>as far as my snapshot is concerned</em>?</p>
<blockquote>
<p><strong>Note:</strong> Postgres reuses two names here. On a row version, <code>xmin</code> and <code>xmax</code> are the transactions that created and deleted it. On a snapshot, <code>xmin</code> is the oldest transaction still running and <code>xmax</code> is one past the last one that finished. Same names, different jobs. Below, <code>snapshot.xmax</code> means the snapshot's boundary.</p>
</blockquote>
<p>For a row version with <code>xmin = X</code>, Postgres checks:</p>
<ol>
<li><strong>X is my own transaction?</strong> Changes from earlier commands in my transaction are visible to me (that's <code>curcid</code> in the struct).</li>
<li><strong>X ≥</strong> <code>snapshot.xmax</code><strong>?</strong> X hadn't finished when the photo was taken. Invisible.</li>
<li><strong>X is in</strong> <code>xip</code><strong>?</strong> X was still running at the photo. Invisible, even if it has committed since.</li>
<li><strong>Otherwise</strong>, 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.</li>
</ol>
<p>Notice what the snapshot doesn't store: it never knows <em>whether</em> 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 <code>xmin</code> as visible, dirty reads are impossible in Postgres at any isolation level.</p>
<p>Step 3 is the everyday case in Repeatable Read. The photo is kept for the whole transaction, so anything in <code>xip</code> stays invisible however long ago it committed. Read Committed hits it too, but only within one statement.</p>
<p>The same rule runs on <code>xmax</code>, 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.</p>
<h2>Piece 3: How the Postgres shutter works</h2>
<p>So far the snapshot has been a given. Now let's watch Postgres build one, and then watch it hide a commit.</p>
<p><em>Everything below is from PostgreSQL 17.12, with a debugger (lldb) attached to session A's backend. Code excerpts are trimmed from the</em> <a href="https://github.com/postgres/postgres/blob/REL_17_12/"><em>REL_17_12 source</em></a><em>:</em> <code>...</code> <em>marks removed lines,</em> <code>/* */</code> <em>comments are Postgres's own, and</em> <code>//</code> <em>comments are mine.</em></p>
<p>The setup: Saumya's balance is 1000. Session B updates it to 900 and commits. Session A, in Read Committed, runs:</p>
<pre><code class="language-sql">SELECT balance FROM accounts WHERE id = 1;
</code></pre>
<p>I ran this twice, each time with one breakpoint in a different place. In the first run, the breakpoint catches A <em>while it builds</em> the photo. In the second, it catches A <em>after</em> the photo is taken but before it reads a single row. That's why the transaction IDs differ between the two runs.</p>
<hr />
<h3>Run 1: the photo being taken</h3>
<p><strong>A asks for a photo.</strong> Here's A, stopped inside <code>GetSnapshotData()</code>:</p>
<pre><code class="language-plaintext">* 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
</code></pre>
<p>Before planning anything, <code>exec_simple_query()</code> asks <code>GetTransactionSnapshot()</code> for a photo. The first thing that function does is decide whether A even needs a new one:</p>
<pre><code class="language-c">Snapshot
GetTransactionSnapshot(void)
{
    ...
    /* First call in transaction? */
    if (!FirstSnapshotSet)
    {
        ...
        if (IsolationUsesXactSnapshot())       // Repeatable Read or Serializable
        {
            ...
            CurrentSnapshot = GetSnapshotData(&amp;CurrentSnapshotData);
            /* Make a saved copy */
            CurrentSnapshot = CopySnapshot(CurrentSnapshot);
            FirstXactSnapshot = CurrentSnapshot;   // kept for the whole transaction
            ...
        }
        else
            CurrentSnapshot = GetSnapshotData(&amp;CurrentSnapshotData);

        FirstSnapshotSet = true;
        return CurrentSnapshot;
    }

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

    return CurrentSnapshot;
}
</code></pre>
<p>Source: <a href="https://github.com/postgres/postgres/blob/REL_17_12/src/backend/utils/time/snapmgr.c#L216"><code>snapmgr.c:216</code></a></p>
<p>Keep this <code>if</code> in mind: the whole of Piece 4 lives inside it. The isolation level doesn't change <em>how</em> Postgres decides what you see. It only changes whether this function hands you the old photo or takes a new one.</p>
<p><strong>A wants everyone to hold still.</strong> 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.</p>
<blockquote>
<p><strong>Pause.</strong> A only wants to <em>read</em> that list. Why would it need a lock?</p>
</blockquote>
<pre><code class="language-c">LWLockAcquire(ProcArrayLock, LW_SHARED);
</code></pre>
<p>A is frozen on the line right after this one. In session B, transaction <strong>791</strong> has already updated Saumya's row. Now B (pid 5631) types <code>COMMIT</code>, and it hangs. From a third session, C:</p>
<pre><code class="language-plaintext">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
</code></pre>
<p>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:</p>
<pre><code class="language-c">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
    }
    ...
}
</code></pre>
<p>And the part that actually takes B out of the list:</p>
<pre><code class="language-c">ProcArrayEndTransactionInternal(PGPROC *proc, TransactionId latestXid)
{
    ...
    ProcGlobal-&gt;xids[pgxactoff] = InvalidTransactionId;   // "I'm no longer running"
    ...
    /* Also advance global latestCompletedXid while holding the lock */
    MaintainLatestCompletedXid(latestXid);

    /* Same with xactCompletionCount  */
    TransamVariables-&gt;xactCompletionCount++;   // tells GetSnapshotDataReuse() old snapshots are stale
}
</code></pre>
<p>Source: <a href="https://github.com/postgres/postgres/blob/REL_17_12/src/backend/storage/ipc/procarray.c#L667"><code>procarray.c:667</code></a>, <a href="https://github.com/postgres/postgres/blob/REL_17_12/src/backend/storage/ipc/procarray.c#L731"><code>procarray.c:731</code></a></p>
<p>B needs the lock <strong>exclusively</strong>. A holds it <strong>shared</strong>. So the conditional acquire fails, B joins the group-clearing path, and waits.¹</p>
<p>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.</p>
<p>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.</p>
<p>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 <code>xmax</code> and missing from <code>xip</code> has already written its final answer to pg_xact. That's why step 4 in Piece 2 can safely ask pg_xact.</p>
<p><strong>A counts the living.</strong> First, it draws the line above which everything counts as still running. Another transaction, <strong>792</strong>, finished just before A took the lock:</p>
<pre><code class="language-c">latest_completed = TransamVariables-&gt;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) &amp;&amp; NormalTransactionIdPrecedes(myxid, xmin))
    xmin = myxid;
</code></pre>
<blockquote>
<p><strong>Pause.</strong> Why not just list every running transaction? Why have an <code>xmax</code> at all?</p>
</blockquote>
<p>Because everything at or above <code>xmax</code> 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.</p>
<p>Then A walks the array of running xids. But first, one fork in the road:</p>
<pre><code class="language-c">snapshot-&gt;takenDuringRecovery = RecoveryInProgress();

if (!snapshot-&gt;takenDuringRecovery)
{
    ...
    for (int pgxactoff = 0; pgxactoff &lt; 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;                              // &gt;= xmax: already invisible, don't bother listing

        statusFlags = allStatusFlags[pgxactoff];
        if (statusFlags &amp; (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-&gt;subxip, &amp;xmin,
                                              xmax);
    ...
}
</code></pre>
<p>Source: <a href="https://github.com/postgres/postgres/blob/REL_17_12/src/backend/storage/ipc/procarray.c#L2177"><code>procarray.c:2177</code></a></p>
<blockquote>
<p>On a hot standby, the running transactions live on the primary. While in recovery, the standby rebuilds them from WAL into <code>KnownAssignedXids</code>, and the <code>else</code> branch builds the snapshot from that, putting every xid in <code>subxip</code> and leaving <code>xip</code> empty. This post follows the primary.</p>
</blockquote>
<p>A finds <strong>791</strong> in the array. B hasn't removed itself yet, because it's waiting for the very lock A holds. 791 is below <code>xmax</code>, so it goes into <code>xip</code>.</p>
<p><strong>The photo develops.</strong></p>
<pre><code class="language-c">if (!TransactionIdIsValid(MyProc-&gt;xmin))
    MyProc-&gt;xmin = TransactionXmin = xmin;     // remember this line: it comes back in the last section

LWLockRelease(ProcArrayLock);
</code></pre>
<p>A's photo, as lldb sees it (trimmed):</p>
<pre><code class="language-plaintext">(lldb) p CurrentSnapshotData
(SnapshotData) {
  snapshot_type = SNAPSHOT_MVCC
  xmin = 791
  xmax = 793
  xcnt = 1
  takenDuringRecovery = false
  ...
}
</code></pre>
<p><code>791:793:791</code>. Everything below 791 finished, nothing from 793 up had finished, and 791 itself was still running. The moment the lock is released, B's <code>COMMIT</code> returns.</p>
<hr />
<h3>Run 2: a commit the photo can't see</h3>
<p>Run 1 shows the photo being built. But my first attempts at the next step failed: A kept printing 900.</p>
<p>The reason is in Run 1's backtrace. That snapshot came from <code>exec_simple_query()</code> at postgres.c:1168, for <em>planning</em>. In Read Committed, the same <code>SELECT</code> asks for a second photo just before execution, in <a href="https://github.com/postgres/postgres/blob/REL_17_12/src/backend/tcop/pquery.c#L484"><code>PortalStart()</code></a>, and that second one decides what you see. By the time I let A go, B had committed, and the second photo included it.</p>
<p>So for Run 2, I put the breakpoint on <code>standard_ExecutorRun()</code>, after the execution photo is taken and before a single row is read:</p>
<pre><code class="language-plaintext">* 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
</code></pre>
<p>B is transaction <strong>805</strong>, with its update done but not yet committed. The photo the executor is about to use:</p>
<pre><code class="language-plaintext">(lldb) p *queryDesc-&gt;snapshot
(SnapshotData) {
  snapshot_type = SNAPSHOT_MVCC
  xmin = 805
  xmax = 805
  xcnt = 0
  ...
}
</code></pre>
<p><code>805:805:</code>. B sits exactly at <code>xmax</code>, 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:</p>
<pre><code class="language-plaintext">lab=# SELECT pg_xact_status('805');
 pg_xact_status
----------------
 committed
</code></pre>
<p><strong>A reads the row.</strong> The page holds two versions of Saumya's row, as Part 1 left them: the old one with <code>xmax = 805</code>, the new one with <code>xmin = 805</code>. A checks the new version:</p>
<pre><code class="language-c">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) &amp;&amp;
        XidInMVCCSnapshot(HeapTupleHeaderGetRawXmin(tuple), snapshot))
        return false;
}
</code></pre>
<p>Source: <a href="https://github.com/postgres/postgres/blob/REL_17_12/src/backend/access/heap/heapam_visibility.c#L960"><code>heapam_visibility.c:960</code></a></p>
<p>This is Piece 2's rule, in the order the code really runs it. <code>XidInMVCCSnapshot(805)</code> says 805 ≥ <code>xmax</code>, 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:</p>
<pre><code class="language-plaintext">lab=# SELECT balance FROM accounts WHERE id = 1;
 balance
---------
    1000
</code></pre>
<p>I run the same query again, with a fresh photo:</p>
<pre><code class="language-plaintext"> balance
---------
     900
</code></pre>
<blockquote>
<p><strong>Pause.</strong> pg_xact said committed before A read a single row. Even a "committed" hint bit wouldn't have changed anything. Was A wrong?</p>
</blockquote>
<p>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.</p>
<p>That's why the code checks the snapshot <em>before</em> pg_xact, and why even the "committed" hint bit isn't the final word. pg_xact answers <em>"did 805 commit?"</em> The snapshot answers <em>"had 805 committed when I looked?"</em> Isolation is the second question.</p>
<blockquote>
<p><strong>Pause.</strong> You run <code>BEGIN ISOLATION LEVEL REPEATABLE READ;</code>, go for a coffee, and meanwhile someone commits an update. Your first <code>SELECT</code> runs after you return. Does it see the update?</p>
</blockquote>
<h2>Piece 4: Isolation level = when the shutter clicks</h2>
<p>Yes, it sees the update. <code>BEGIN</code> takes no photo. Look at the <code>if</code> again: the first photo is taken by the first statement that asks for one, and Repeatable Read keeps <em>that</em> one.</p>
<p>The visibility rule never changes between levels; only the <code>if</code> at the top of <code>GetTransactionSnapshot()</code> does.</p>
<p><strong>Read Committed</strong> (the default) takes a new photo per statement, so between two statements other commits become visible: non-repeatable reads and phantoms. <strong>Repeatable Read</strong> takes one photo at the transaction's first query (not at <code>BEGIN</code>) and keeps it, so neither can happen.</p>
<p>You can watch it. Two statements in one Read Committed transaction, with transaction 807 committing in another session between them:</p>
<pre><code class="language-plaintext">lab=# BEGIN ISOLATION LEVEL READ COMMITTED;
lab=*# SELECT pg_current_snapshot();
 807:807:
lab=*# SELECT pg_current_snapshot();
 808:808:
</code></pre>
<p>A new photo per statement: the second one already counts 807 as finished.</p>
<p>The same thing in Repeatable Read, while another transaction finishes in between:</p>
<pre><code class="language-plaintext">lab=# BEGIN ISOLATION LEVEL REPEATABLE READ;
lab=*# SELECT pg_current_snapshot();
 808:808:
lab=*# SELECT pg_current_snapshot();
 808:808:
</code></pre>
<p>Session B, outside the transaction, already sees <code>809:809:</code>. A is still living at 808.</p>
<p>For these three anomalies, Postgres is stricter than the SQL standard:</p>
<table>
<thead>
<tr>
<th>Level</th>
<th>Dirty read</th>
<th>Non-repeatable read</th>
<th>Phantom read</th>
</tr>
</thead>
<tbody><tr>
<td>Read Uncommitted</td>
<td>never (behaves as Read Committed)</td>
<td>possible</td>
<td>possible</td>
</tr>
<tr>
<td>Read Committed</td>
<td>never</td>
<td>possible</td>
<td>possible</td>
</tr>
<tr>
<td>Repeatable Read</td>
<td>never</td>
<td>never</td>
<td>never (the standard would allow it)</td>
</tr>
<tr>
<td>Serializable</td>
<td>never</td>
<td>never</td>
<td>never</td>
</tr>
</tbody></table>
<p>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.</p>
<blockquote>
<p><strong>Pause.</strong> 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?</p>
</blockquote>
<h2>The cost: a transaction that won't leave the past</h2>
<p>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.</p>
<p>Each backend publishes the oldest xid its photo needs: the <code>MyProc-&gt;xmin</code> line from Piece 3. The oldest across the database is the <strong>xmin horizon</strong>, and nothing newer can be cleaned up.</p>
<p>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.</p>
<p>In one session, I open a Repeatable Read transaction, take its photo with <code>SELECT 1;</code>, and walk away. In another, I update Saumya's row 1,000 times and vacuum:</p>
<pre><code class="language-plaintext">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
</code></pre>
<p>1,000 dead versions, and VACUUM removed none. The cutoff is 809. Who's holding it there?</p>
<pre><code class="language-plaintext">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
</code></pre>
<p>The idle Repeatable Read session, <code>backend_xmin = 809</code>: exactly the cutoff. (5631 is the session running this query.) I commit it and vacuum again:</p>
<pre><code class="language-plaintext">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
</code></pre>
<p>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.</p>
<p>It isn't only Repeatable Read. A transaction that has <em>written</em> holds the horizon too, through its own xid. So do open cursors, prepared transactions, replication slots and <code>hot_standby_feedback</code>. The culprit shows up as an old <code>backend_xmin</code> (or <code>backend_xid</code>) in <code>pg_stat_activity</code>.</p>
<h2>Recap</h2>
<table>
<thead>
<tr>
<th>Mechanism</th>
<th>Its job in isolation</th>
</tr>
</thead>
<tbody><tr>
<td>Snapshot (<code>xmin</code>, <code>xmax</code>, <code>xip</code>)</td>
<td>A record of which transactions were running, not a copy of data</td>
</tr>
<tr>
<td><code>GetSnapshotData()</code></td>
<td>Under <code>ProcArrayLock</code>: <code>xmax = latestCompletedXid + 1</code>, list running xids below it, publish <code>MyProc-&gt;xmin</code></td>
</tr>
<tr>
<td>Visibility rule</td>
<td>Snapshot first, then Part 1's hint bits and pg_xact; uncommitted is never visible</td>
</tr>
<tr>
<td>Read Committed</td>
<td>A new snapshot per statement</td>
</tr>
<tr>
<td>Repeatable Read</td>
<td>One snapshot per transaction, taken at the first query</td>
</tr>
</tbody></table>
<p>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.</p>
<p>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.</p>
<p><em>Next in ACID, Connected: When Writers Collide, covering lost updates, first updater wins, and the one anomaly a snapshot can never catch.</em></p>
<hr />
<p>¹ <em>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.</em></p>
]]></content:encoded></item><item><title><![CDATA[Postgres Doesn’t Look Back]]></title><description><![CDATA[Postgres writes uncommitted data to disk and never undoes it on ROLLBACK, yet stays atomic. See how MVCC, WAL, pg_xact and hint bits make it work.]]></description><link>https://saumyakr.hashnode.dev/postgres-doesn-t-look-back</link><guid isPermaLink="true">https://saumyakr.hashnode.dev/postgres-doesn-t-look-back</guid><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Databases]]></category><category><![CDATA[System Design]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Somya kumar]]></dc:creator><pubDate>Thu, 19 Nov 2026 06:11:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6af682d28e0395cb3d77e3d4/8fc7bd07-29f5-41bb-a234-9cfee3190ec8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every textbook explains atomicity the same way: if a transaction fails, the database goes back and undoes what it did. Rollback means looking back.</p>
<p>So when I started reading the Postgres docs, it came as a shock: Postgres refuses to look back. It writes your uncommitted rows to disk without hesitation, and when you hit ROLLBACK it doesn't undo a single byte. Yet a Postgres transaction is still all-or-nothing, even across a crash.</p>
<p>The short answer is that atomicity in Postgres is not a feature living in one module. It falls out of four mechanisms working together: MVCC tuple headers, the buffer manager, the write-ahead log (WAL), and a tiny file called pg_xact. HOT updates then test the whole design. Let's build it up one piece at a time.</p>
<h2>What atomicity actually promises</h2>
<p>Atomicity is the A in ACID: a transaction's changes either all happen or none of them do. Nobody, not a concurrent reader and not the database after a crash, should ever see half a transaction.</p>
<p>Take the classic example:</p>
<pre><code class="language-sql">BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;  -- Saumya
UPDATE accounts SET balance = balance + 500 WHERE id = 2;  -- Mohit
COMMIT;
</code></pre>
<p>These two rows may live on two different 8 KB pages. Disks write pages one at a time. So the database must make two physically separate writes look like one indivisible event.</p>
<blockquote>
<p><strong>Pause.</strong> The machine can lose power between any two disk writes. What single thing could the database write that, by itself, decides whether the whole transaction happened?</p>
</blockquote>
<h2>Why the naive approaches fail</h2>
<p>There are two obvious ways to get atomicity, and both are too slow or too restrictive for a real database.</p>
<p><strong>Naive idea 1: never let uncommitted data reach disk ("no-steal").</strong> Keep every page a transaction touched pinned in memory until COMMIT. Then the disk only ever holds committed data.</p>
<p>This breaks the moment a transaction is bigger than memory. An <code>UPDATE</code> over a 200 GB table cannot keep 200 GB of dirty pages pinned in a 4 GB buffer pool. The buffer manager must be allowed to evict, or "steal", a dirty page even when its owner hasn't committed.</p>
<p><strong>Naive idea 2: write every touched page to disk at COMMIT ("force").</strong> Then a committed transaction is always fully on disk.</p>
<p>This is painfully slow. A transaction that touches 1,000 rows scattered over 1,000 pages now needs 1,000 random writes before COMMIT can return. And it still isn't atomic: a crash halfway through those 1,000 writes leaves half a transaction on disk.</p>
<p>So a fast database wants the opposite of both: <strong>steal</strong> (evict dirty uncommitted pages whenever needed) and <strong>no-force</strong> (don't flush data pages at commit). Postgres does exactly that.</p>
<blockquote>
<p><strong>Pause.</strong> With steal + no-force, the disk can hold uncommitted changes, and can be missing committed ones. Most databases fix the first problem with an UNDO log that rolls changes back. Postgres has no UNDO log. How could it possibly get away with that?</p>
</blockquote>
<h2>Piece 1: MVCC — Never destroy the old truth</h2>
<p>In Postgres, an <code>UPDATE</code> does not change a row in place. It writes a brand-new version of the row (a new <em>tuple</em>) and leaves the old one where it was. A <code>DELETE</code> writes nothing new; it just marks the old version as deleted.</p>
<p>Every tuple carries a header with, among other things:</p>
<table>
<thead>
<tr>
<th>Field</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>xmin</code></td>
<td>ID of the transaction that created this version</td>
</tr>
<tr>
<td><code>xmax</code></td>
<td>ID of the transaction that deleted or replaced it (0 if none)</td>
</tr>
<tr>
<td><code>t_ctid</code></td>
<td>Pointer to the newer version, if this one was updated</td>
</tr>
<tr>
<td><code>t_infomask</code></td>
<td>Flag bits, including the <em>hint bits</em> we'll meet soon</td>
</tr>
</tbody></table>
<p>So after <code>UPDATE accounts SET balance = 500 WHERE id = 1</code> run by transaction 101, the heap page holds two versions:</p>
<pre><code class="language-text">v1: xmin=90   xmax=101  balance=1000  t_ctid -&gt; v2
v2: xmin=101  xmax=0    balance=500
</code></pre>
<p>Which version a reader sees is decided at read time, by asking two questions about each tuple: <em>did the creator (xmin) commit?</em> and <em>did the deleter (xmax) commit?</em> A version is visible if its xmin committed and its xmax did not (or there is none).</p>
<p>Notice what this means. The tuple itself never records whether it is "real". It only records <em>who</em> made it. Whether that transaction committed is stored somewhere else entirely.</p>
<blockquote>
<p><strong>Pause.</strong> If correctness depends only on whether transaction 101 committed, does it matter whether v2 is sitting on disk when 101 aborts?</p>
</blockquote>
<h2>Piece 2: The Buffer Manager — Where uncommitted data leaks to disk</h2>
<p>The shared buffer pool is a cache of 8 KB pages. When a backend needs a page that isn't cached and the pool is full, the <strong>clock-sweep algorithm</strong> picks a victim. If the victim is dirty, it is written to disk first. The background writer and the checkpointer also write dirty pages on their own schedule.</p>
<p>None of these ask "has the transaction that dirtied this page committed?" They can't even answer it: one page may hold tuples from dozens of transactions, some committed, some running, some aborted. A page is just bytes.</p>
<p>So it is completely normal for v2 (<code>xmin=101</code>) to reach the data file while transaction 101 is still running, or after it aborts. This is the <strong>steal</strong> policy from earlier, and after Piece 1 it's no longer scary. A tuple on disk is not a claim that the change happened. It is a claim that <em>transaction 101 tried to make</em> this change. Whether 101 succeeded is a separate fact.</p>
<p>The buffer manager obeys exactly one rule when it writes a page, and that rule belongs to the WAL.</p>
<h2>Piece 3: The WAL — One sequential write decides everything</h2>
<p>Every change to a page is first described in the write-ahead log, an append-only sequential file. Each WAL record gets a position called an <strong>LSN</strong>, and the page remembers the <strong>LSN</strong> of the last record that touched it (<code>pd_lsn</code> in the page header).</p>
<p><strong>The WAL rule:</strong> before a dirty page is written to the data file, the WAL must be flushed at least up to that page's <code>pd_lsn</code>. The buffer manager enforces this on every page write. So the log always knows about any change that the data file has.</p>
<p>Now look at what COMMIT actually does, in this order:</p>
<ol>
<li>Write a <strong>commit record</strong> for the transaction ID into the WAL.</li>
<li><code>fsync</code> the WAL up to and including that record (with <code>synchronous_commit = on</code>).</li>
<li>Set the transaction's status to <em>committed</em> in pg_xact.</li>
<li>Remove the transaction from the shared list of running transactions, so new snapshots see it as finished.</li>
</ol>
<p>Step 2 is the atomic moment. Before the commit record is durable, the transaction did not happen. After, it did. One sequential write of a few dozen bytes decides the fate of every row the transaction touched, whether it touched 2 rows or 2 million.</p>
<p>That answers the first Pause: the single thing is the commit record.</p>
<p>And ROLLBACK? Postgres writes an abort record and marks the transaction <em>aborted</em> in <strong>pg_xact</strong>. That's all. No page is touched. The dead tuples stay where they are until VACUUM removes them later.</p>
<blockquote>
<p><strong>Pause.</strong> We now have the truth ("101 committed") in one place and the data (v2 with xmin=101) in another. A reader holding only the page sees <code>xmin=101</code>. How does it find out what happened to 101?</p>
</blockquote>
<h2>Piece 4: pg_xact and Hint Bits — Shifting burden to the reader</h2>
<p><strong>pg_xact</strong> (called <code>pg_clog</code> before Postgres 10) is the commit log: 2 bits per transaction ID, with four states: in progress, committed, aborted, sub-committed. At 2 bits each, one 8 KB page covers 32,768 transactions, so the recent part of it sits comfortably in a small dedicated cache.</p>
<p>When a reader meets v2 with <code>xmin=101</code> and no other information, it does roughly this:</p>
<ol>
<li>Is 101 still running (in my snapshot)? Then v2 is invisible to me. Stop.</li>
<li>Otherwise, look up 101 in pg_xact.</li>
<li>Committed: v2's xmin is good. Aborted, or never finished: v2 never existed.</li>
</ol>
<p>That lookup costs something on every tuple. And the answer can never change: once 101 commits or aborts, it stays that way forever. So Postgres caches the answer <strong>on the tuple itself</strong>, in <code>t_infomask</code>:</p>
<table>
<thead>
<tr>
<th>Hint bit</th>
<th>Means</th>
</tr>
</thead>
<tbody><tr>
<td><code>HEAP_XMIN_COMMITTED</code></td>
<td>xmin is known committed</td>
</tr>
<tr>
<td><code>HEAP_XMIN_INVALID</code></td>
<td>xmin is known aborted</td>
</tr>
<tr>
<td><code>HEAP_XMAX_COMMITTED</code></td>
<td>xmax is known committed</td>
</tr>
<tr>
<td><code>HEAP_XMAX_INVALID</code></td>
<td>xmax is known aborted or unset</td>
</tr>
</tbody></table>
<p>The first reader that resolves 101 sets the hint bit and marks the page dirty. Every later reader skips pg_xact entirely. This is why the first <code>SELECT</code> after a big load can produce a burst of disk writes: <strong>the first read of a tuple is also a write.</strong></p>
<p>Two subtle details are worth knowing:</p>
<ul>
<li>Setting a hint bit is not WAL-logged. Losing it in a crash is harmless; the next reader just checks pg_xact again. (If data checksums or <code>wal_log_hints</code> are on, the first hint change after a checkpoint logs a full-page image, so a torn page can't fail its checksum.)</li>
<li>With asynchronous commit, Postgres won't set <code>HEAP_XMIN_COMMITTED</code> until the WAL is flushed past that commit record. Otherwise a hint bit could reach disk claiming a commit that a crash then erases.</li>
</ul>
<p>So the steal policy and the hint bits fit together. The buffer manager writes v2 to disk whenever it likes. Whoever reads v2 first asks pg_xact, and writes the answer back onto the tuple.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6af682d28e0395cb3d77e3d4/e32c61d6-8e2a-48ba-8491-866022b19ab8.png" alt="xmin-visibility-check" style="display:block;margin:0 auto" />

<p>Only the first reader takes the long path down to pg_xact; everyone after it stops at the first diamond. The xmax check works the same way, with the result flipped.</p>
<h2>Piece 5: HOT Chains — Readers only walk forward</h2>
<p>MVCC has a cost: every <code>UPDATE</code> creates a new tuple at a new location (a new TID). Normally every index on the table then needs a new entry pointing at it, even if you only changed a column no index cares about.</p>
<p><strong>HOT (heap-only tuple)</strong> removes that cost when two conditions hold: no indexed column changed, and the new version fits on the same page. Then:</p>
<ul>
<li>The old version is flagged <code>HEAP_HOT_UPDATED</code>, and its <code>t_ctid</code> points to the new one.</li>
<li>The new version is flagged <code>HEAP_ONLY_TUPLE</code>. No index entry is created for it.</li>
<li>Indexes keep pointing at the <em>root</em> of the chain, the original line pointer.</li>
</ul>
<p>An index scan lands on the root and walks the chain <strong>forward</strong>, old to new, testing each version for visibility. It returns the one version its snapshot can see.</p>
<p>That direction matters. Chains in Postgres only point from older to newer. No reader ever starts at the newest version and walks back to find an older one.</p>
<blockquote>
<p><strong>Pause.</strong> Transaction 101 HOT-updates row 1 (v1 → v2), the page is evicted to disk, then 101 aborts. A new reader arrives through the index. Which version does it return, and why doesn't it need to "go back"?</p>
</blockquote>
<p>Walk the chain:</p>
<pre><code class="language-text">v1: xmin=90 (committed)   xmax=101 (aborted)   -&gt; visible: xmax doesn't count
v2: xmin=101 (aborted)    xmax=0               -&gt; invisible: never existed
</code></pre>
<p>The reader reaches v1 first. Its deleter, 101, aborted, so the deletion never happened and v1 is still the live row. The reader sets <code>HEAP_XMAX_INVALID</code> on v1, then <code>HEAP_XMIN_INVALID</code> on v2 if it looks at it. Nobody went backward. The "older" value was never removed: an aborted xmax is simply ignored.</p>
<p>Later, page pruning (run opportunistically by readers when a page has room to reclaim) cuts dead members like v2 out of the chain. VACUUM handles the rest. Cleanup happens long after the abort, in the background, and correctness never depended on it.</p>
<h2>Putting it together: pull the plug</h2>
<p>Back to the transfer. Transaction 101 debits Saumya's row on page A and credits Mohit's row on page B. Each update leaves an old version with <code>xmax=101</code> and a new version with <code>xmin=101</code>. Pull the power cord at three different moments.</p>
<p><strong>Crash before the commit record is durable.</strong> Page A was evicted mid-transaction, so A's new version is on disk; B's isn't. Recovery replays the WAL from the last checkpoint and may rebuild B's new version too. But there is no commit record for 101. After restart 101 isn't running, and pg_xact doesn't say committed, so it is treated as aborted. Both new versions are invisible, both old versions are live. The half-written state is on disk, and it doesn't matter.</p>
<p><strong>Crash after the commit record, before any data page was written.</strong> This is the no-force case: the committed data is missing from the data files. But the WAL is flushed through the commit record, and by the WAL rule it holds every change 101 made. Redo replays them onto pages A and B, then replays the commit record into pg_xact. Both new versions are visible.</p>
<p><strong>Crash after the commit record, before the pg_xact page was written.</strong> pg_xact is cached in memory too, so its update can be lost. Redo replays the commit record and sets the bit again. Same result as above.</p>
<p>In every case both rows move together, because both are judged by the same 2 bits about 101, and those bits are fixed by one WAL record. That's the whole trick. The WAL only ever needs to <em>redo</em>. Postgres has no UNDO log because MVCC never destroyed the old version in the first place. "Undoing" a transaction is just declaring its xid aborted.</p>
<p>One more failure mode for completeness: a power cut in the middle of writing an 8 KB page can leave a <em>torn</em> page, half old and half new. Postgres guards against this with <code>full_page_writes</code>: the first change to a page after each checkpoint logs the whole page image to WAL, so redo can start from a clean copy.</p>
<h2>No Free Lunch: The price of never undoing anything</h2>
<p>Every system design is a trade-off, and this one is no exception. The costs show up in places every Postgres operator knows:</p>
<ul>
<li><strong>Bloat.</strong> Aborted and outdated versions sit in the heap until VACUUM reclaims them. A rolled-back bulk load leaves gigabytes of dead tuples behind.</li>
<li><strong>Write amplification on reads.</strong> The first read after a big write sets hint bits and dirties pages, and with checksums on it can also log full-page images.</li>
<li><strong>Transaction ID wraparound.</strong> Visibility leans on 32-bit xids compared against pg_xact, so old tuples must eventually be <em>frozen</em> by VACUUM before the counter wraps.</li>
</ul>
<p>In exchange, Postgres gets an instant ROLLBACK of any size, a crash recovery that only replays forward, and readers that never block writers.</p>
<h2>Recap</h2>
<table>
<thead>
<tr>
<th>Mechanism</th>
<th>Its job in atomicity</th>
</tr>
</thead>
<tbody><tr>
<td>MVCC tuple headers</td>
<td>Store <em>who</em> made each version, never whether it's valid</td>
</tr>
<tr>
<td>Buffer manager (steal, no-force)</td>
<td>Write any page anytime, without regard to commit status</td>
</tr>
<tr>
<td>WAL + commit record</td>
<td>Make the commit one durable, sequential write: the atomic moment</td>
</tr>
<tr>
<td>pg_xact</td>
<td>Hold the 2-bit truth about every transaction</td>
</tr>
<tr>
<td>Hint bits</td>
<td>Cache that truth on the tuple, so the first read pays once</td>
</tr>
<tr>
<td>HOT chains</td>
<td>Keep versions on one page; readers walk old → new and pick the visible one</td>
</tr>
</tbody></table>
<p>Atomicity in Postgres isn't enforced by cleaning up after failures. It comes from never letting data decide its own validity. Every row points at a transaction, every transaction points at one bit, and that bit is set by one write.</p>
<p><em>Next in ACID, Connected: how snapshots decide which committed transactions you're allowed to see, which is isolation, the I in ACID.</em></p>
]]></content:encoded></item><item><title><![CDATA[Every Program Promises to Call close(). Here's How That Promise Breaks.]]></title><description><![CDATA[RAII from the Kernel Up, Part B: The Traditional close()]]></description><link>https://saumyakr.hashnode.dev/every-program-promises-to-call-close-here-s-how-that-promise-breaks</link><guid isPermaLink="true">https://saumyakr.hashnode.dev/every-program-promises-to-call-close-here-s-how-that-promise-breaks</guid><category><![CDATA[C]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Somya kumar]]></dc:creator><pubDate>Tue, 17 Nov 2026 03:23:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6af682d28e0395cb3d77e3d4/4a3b03e2-3a39-4a1c-b141-c3587f755616.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In <a href="#">Part A</a>, I opened one file and followed it into the kernel. The fd slot, the open file description and the inode all stay alive until someone calls <code>close()</code>. While the process is running, the kernel won't do it for you, because it has no idea when you're done.</p>
<p>So every program that opens a file makes a promise: call <code>close()</code> exactly once, on every path out of the code that opened it.</p>
<p>This post is about how that promise breaks, including the time I broke it myself.</p>
<h2>The traditional discipline</h2>
<p>Here's a function that writes a sorted run to a temp file, the kind of thing an external sort does thousands of times:</p>
<pre><code class="language-cpp">bool write_run(const char* path, const std::vector&lt;uint64_t&gt;&amp; page) {
    int fd = ::open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd &lt; 0) return false;

    if (page.empty()) return false;
    if (!validate(page)) return false;
    write_page(fd, page);   // may throw
    ::close(fd);
    return true;
}
</code></pre>
<blockquote>
<p>🤔 <strong>Pause and ponder</strong><br />Once <code>open()</code> succeeds, how many ways out of this function are there, and how many of them close the fd?</p>
</blockquote>
<hr />
<p>There are four: two early returns, an exception from <code>write_page</code>, and the normal return. Only the last one closes the fd. The other three leak it.</p>
<p>The textbook fix is discipline: put <code>close(fd)</code> before every return. In C, the common pattern is <code>goto cleanup</code>, where every error path jumps to one label at the bottom that releases everything:</p>
<pre><code class="language-c">    int ok = 0;
    if (page_empty) goto cleanup;
    if (!valid)     goto cleanup;
    ok = write_page(fd, page);
cleanup:
    close(fd);
    return ok;
</code></pre>
<p>This works. It also depends entirely on someone getting it right every time.</p>
<h2>Where it breaks</h2>
<ol>
<li><strong>Exceptions.</strong> In C++, <code>write_page</code> can throw. Control jumps straight out of the function, past every <code>close</code> you wrote. <code>goto cleanup</code> can't help either, because an exception never goes to your label.</li>
<li><strong>New exit paths.</strong> The function is correct today. Six months later someone adds <code>if (page.size() &gt; MAX) return false;</code> without a close. The compiler doesn't complain, the tests pass, and the leak ships.</li>
<li><strong>Several resources.</strong> Add a buffer and a lock. Now every exit has to release all three, in the right order: unlock before the close, or after? Get it wrong on one path and you've traded a leak for a deadlock.</li>
<li><strong>Closing twice.</strong> Over-correct and close the same fd twice, and it's worse than a leak. The kernel always hands out the lowest free fd number, so if another <code>open()</code>, often in another thread, reused that number in between, your second <code>close()</code> shuts someone else's file. Nothing crashes. Something unrelated fails later.</li>
</ol>
<p>All four have the same root: correctness depends on a human remembering, on every path, forever.</p>
<h2>I wrote this bug while studying it</h2>
<p>For this series I wrote <code>gen.cpp</code>, a small program that writes 10 million numbers to a file with <code>fwrite</code>. My first version didn't check what <code>fwrite</code> returned. When I fixed that, I added an early <code>return false</code> for a failed write, and that return skipped <code>fclose</code>.</p>
<p>I was studying fd leaks, and I introduced one by making my code <em>more</em> careful. That's the point: this isn't a beginner's mistake. It's what happens whenever cleanup is a rule you have to remember.</p>
<h2>Watch it die</h2>
<p>To see the failure for real, I wrote <a href="#"><code>leak.cpp</code></a>: a <code>write_run</code> that returns early without closing, called in a loop. Every 10 calls, it counts the entries in <code>/proc/self/fd</code>. The core of it:</p>
<pre><code class="language-cpp">bool write_run(const char* path, bool fail_early) {
    int fd = ::open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) { std::perror("open"); return false; }
    if (fail_early) return false;          // forgot ::close(fd)
    ::close(fd);
    return true;
}

for (int i = 0; i &lt; 10000; i++) {
    write_run("leak_test.dat", true);
    if (i % 10 == 0)
        std::cout &lt;&lt; "iteration: " &lt;&lt; i &lt;&lt; "  open fds: " &lt;&lt; open_fd_count() &lt;&lt; '\n';
}
</code></pre>
<p>I ran it with a limit of 64 descriptors so it would die quickly.</p>
<blockquote>
<p>🤔 <strong>Pause and ponder</strong></p>
<p>Which call do you expect to fail first?</p>
</blockquote>
<hr />
<pre><code class="language-plaintext">$ (ulimit -n 64; ./leak)
iteration: 0  open fds: 4
iteration: 10  open fds: 14
iteration: 20  open fds: 24
iteration: 30  open fds: 34
iteration: 40  open fds: 44
iteration: 50  open fds: 54
terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error'
  what():  filesystem error: directory iterator cannot open directory: Too many open files [/proc/self/fd]
Aborted
</code></pre>
<p>The count climbs by exactly one per call. Each step is one forgotten <code>close()</code>.</p>
<p>But look at what died. I expected <code>open()</code> inside <code>write_run</code> to fail. It never got the chance. The program died inside the code I wrote to <em>measure</em> the leak: reading <code>/proc/self/fd</code> needs a descriptor too, and at iteration 60 the leak had taken the last one.</p>
<p>That's what fd leaks look like in production. The code that leaks keeps running. Something unrelated, like a log write, a new socket or a health check, is what crashes, and <strong>the stack trace points at the victim, not the culprit.</strong></p>
<p>Then I counted every open and close with <code>strace</code>:</p>
<pre><code class="language-plaintext">$ (ulimit -n 64; strace -c -e trace=openat,close ./leak)
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 99.10    0.000996          13        73         1 openat
  0.90    0.000009           0        11           close
</code></pre>
<p>73 opens and 11 closes. The 11 closes all belong to someone else: 5 from the dynamic loader opening shared libraries at startup, and 6 from my <code>/proc</code> monitor. Take those away, plus the monitor's one failed open, and you're left with <code>write_run</code>: 61 files opened, zero closed.</p>
<h2>The one-line fix</h2>
<p>Put the missing line back:</p>
<pre><code class="language-cpp">if (fail_early) {
    ::close(fd);      // the line that was missing
    return false;
}
</code></pre>
<pre><code class="language-plaintext">$ (ulimit -n 64; ./leak_fixed) | head -n 3
iteration: 0  open fds: 3
iteration: 10  open fds: 3
iteration: 20  open fds: 3

$ (ulimit -n 64; ./leak_fixed) | tail -n 2
iteration: 9980  open fds: 3
iteration: 9990  open fds: 3
</code></pre>
<p>The count stays flat for all 10,000 iterations. One line fixed it. Now add one more early return and see whether you remember that line too.</p>
<h2>Finding the missing close() in a real codebase</h2>
<p>Counting and inspecting a process's fds, as in Part A, tells you <em>that</em> you're leaking and <em>which files</em> are piling up. To find <em>where</em>:</p>
<ol>
<li><strong>Pair opens with closes.</strong> <code>strace -f -e trace=openat,close -p &lt;pid&gt;</code> on the live process. Match each <code>openat</code> that returned fd N with a later <code>close(N)</code>. The ones without a partner are the leak.</li>
<li><strong>Let a tool report leaks at exit.</strong> <code>valgrind --track-fds=yes ./prog</code> lists every descriptor still open when the program exits, with the stack trace of the call that opened it.</li>
<li><strong>Catch it before it ships.</strong> Static analyzers such as <code>cppcheck</code> flag an <code>fopen</code> that isn't matched by an <code>fclose</code> on some path. They miss leaks that cross function boundaries, but they're cheap to run in CI.</li>
</ol>
<p>Every one of these finds the leak <em>after</em> someone wrote it. None of them stops the next developer from adding the next return.</p>
<h2>Now scale it up</h2>
<p>My <code>leak.cpp</code> is 40 lines, and the leak is obvious because I put it there.</p>
<blockquote>
<p>🤔 <strong>Pause and ponder</strong><br />Picture a real service: 50,000 lines. A file is opened in one module, passed through three layers, and supposed to be closed in a fourth. Every function on the way has early returns, error branches, and calls that can throw. After six hours, a health check crashes with <em>Too many open files</em>. Which of those hundreds of exit paths forgot to close?</p>
</blockquote>
<hr />
<p>You can't answer that by reading the code. The crash points at the victim. The tools point at the file. Finding the path means checking every way out of every function that ever touched that fd, and the next commit can add one more.</p>
<p>That's the real cost of the traditional rule. It isn't that <code>close()</code> is hard to write. It's that the program's correctness lives in every exit path at once, and nobody can hold all of them in their head.</p>
<p>Humans forget. Compilers don't.</p>
<p>What if closing the file weren't a line you had to remember at all, but something the language did for you, on every path out, exceptions included? That's <strong>Part C: RAII</strong>.</p>
<blockquote>
<p>🤔 <strong>Pause and ponder before you read it</strong><br />your local variables already clean themselves up on every path out of a function, exceptions included. What would it take to make a file descriptor behave like a local variable?</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[I Opened One File and Followed It Into the Kernel]]></title><description><![CDATA[RAII from the Kernel Up, Part A: What the Kernel Holds Until You Close It.]]></description><link>https://saumyakr.hashnode.dev/i-opened-one-file-and-followed-it-into-the-kernel</link><guid isPermaLink="true">https://saumyakr.hashnode.dev/i-opened-one-file-and-followed-it-into-the-kernel</guid><dc:creator><![CDATA[Somya kumar]]></dc:creator><pubDate>Sun, 15 Nov 2026 17:38:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6af682d28e0395cb3d77e3d4/d0d33072-0190-40ae-92fc-1dd081b12316.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>The bug that started this</h2>
<p>Picture a service that runs fine for six hours. Then every new connection, every log rotation and every temp file fails with the same error:</p>
<pre><code class="language-plaintext">open: Too many open files
</code></pre>
<p>You restart it, and it's fine again, for another six hours.</p>
<p>Before chasing the bug, I wanted to understand what was actually running out. What <em>is</em> an open file? Where does it live? And what exactly fills up?</p>
<p>So I opened a file on Linux and looked at everything the kernel created for it. Every command below runs in bash, so you can follow along in your own terminal.</p>
<h2>What open() actually creates</h2>
<p>First, make a small file: 100 lines of 11 bytes each.</p>
<pre><code class="language-bash">cd /tmp
printf 'hello raii\n%.0s' {1..100} &gt; run_0.dat   # %.0s eats each number and prints nothing
wc -c run_0.dat                                   # 1100 run_0.dat
</code></pre>
<p>Look at it before anyone opens it:</p>
<pre><code class="language-plaintext">$ stat run_0.dat
  Size: 1100        Blocks: 8          IO Block: 4096   regular file
Device: 0,60        Inode: 275         Links: 1
</code></pre>
<p>That <code>Inode: 275</code> is the file's identity: its size, its permissions and where its blocks are stored. It existed before we touched the file, and it will exist after. Opening a file doesn't create the file. It creates something else.</p>
<p>Now open it. <code>exec 3&lt; run_0.dat</code> makes the shell open the file and keep it as descriptor 3. Then we list the shell's open descriptors through <code>/proc</code> (<code>$$</code> is the shell's own PID):</p>
<pre><code class="language-plaintext">$ ls -l /proc/$$/fd           # before
0 -&gt; /dev/pts/1
1 -&gt; /dev/pts/1
2 -&gt; /dev/pts/1
255 -&gt; /dev/pts/1

$ exec 3&lt; run_0.dat
$ ls -l /proc/$$/fd           # after
0 -&gt; ...                      # same as before
1 -&gt; ...                      # same as before
2 -&gt; ...                      # same as before
255 -&gt; ...                    # same as before
3 -&gt; /tmp/run_0.dat           &lt;- new
</code></pre>
<p>(255 is bash keeping a copy of the terminal for itself. Ignore it.)</p>
<blockquote>
<p>🤔 <strong>Pause and ponder</strong></p>
<p>Why 3, and not some random number?</p>
</blockquote>
<hr />
<p>Every process has a table of open descriptors, and slots 0, 1 and 2 are taken by stdin, stdout and stderr. The kernel always hands out the lowest free slot. That's all an fd is: an index into this table. It's an integer, nothing more.</p>
<p>So what does slot 3 point to? <code>/proc</code> gives us a view of it:</p>
<pre><code class="language-plaintext">$ cat /proc/$$/fdinfo/3
pos:    0
flags:  0400000
...
ino:    275
</code></pre>
<p>This is a window into the kernel's <strong>open file description</strong> (<code>struct file</code> in the kernel source). It records how <em>this particular open</em> is going: the current offset (<code>pos</code>), the mode it was opened with (<code>flags</code>), and which inode it belongs to (<code>ino</code>). (<code>mnt_id</code> just says which mount the file lives on; we won't need it.)</p>
<p><code>flags</code> is printed in octal. <code>O_RDONLY</code> is 0, so the only bit set is <code>O_LARGEFILE</code>, which the kernel adds on 64-bit systems. It's <code>0400000</code> on ARM64 (my machine) and <code>0100000</code> on x86-64.</p>
<p>Now watch the offset move. I read two lines (11 bytes each) and looked again:</p>
<pre><code class="language-plaintext">$ read -u 3 line; read -u 3 line
$ cat /proc/$$/fdinfo/3
pos:    22
...
</code></pre>
<blockquote>
<p>🤔 <strong>Pause and ponder</strong></p>
<p>My program never stored "22" anywhere. So who remembers where I am in the file?</p>
</blockquote>
<hr />
<p>The kernel does. The read position isn't in your program, and it isn't in the inode either. It lives in the open file description.¹</p>
<p>Put together, the chain looks like this:</p>
<pre><code class="language-plaintext">your program    kernel memory                                 disk
------------    ------------------------------------------    ----

int fd = 3 --&gt; fd table[3] ---&gt; open file desc --&gt; inode --&gt;  data blocks
               (per process)    (pos, flags)              (cached in RAM)
</code></pre>
<p>Notice where everything lives. The fd table, the open file description and the cached inode are all in kernel memory. None of it is on your stack, and none of it is on your heap. Your program holds exactly one thing: the integer 3.</p>
<blockquote>
<p>🤔 <strong>Pause and ponder</strong></p>
<p>Why two layers? Why not keep <code>pos</code> right inside the fd table slot?</p>
</blockquote>
<hr />
<p>First, open the same file a second time:</p>
<pre><code class="language-plaintext">$ exec 4&lt; run_0.dat
$ cat /proc/$$/fdinfo/4
pos:    0
...
ino:    275
</code></pre>
<p>Same inode (275), but <code>pos</code> is back to 0. Each <code>open()</code> creates its own description with its own offset.</p>
<p>So far, one slot means one description. But two slots can also share one description. <code>exec 5&lt;&amp;3</code> duplicates fd 3 (this is <code>dup()</code> under the hood). Read one line through fd 5, then check fd 3:</p>
<pre><code class="language-plaintext">$ exec 5&lt;&amp;3
$ read -u 5 line
$ cat /proc/$$/fdinfo/3
pos:    33
...
</code></pre>
<p>I never touched fd 3, but its offset moved, because both slots point to the same description. The same thing happens across <code>fork()</code>: a child inherits its parent's descriptors and shares their offsets. That's how a shell script and the commands it runs can append to one log without overwriting each other. So the fd table answers "which opens does this process hold?", and the description answers "how far along is this open?"</p>
<pre><code class="language-bash">exec 5&lt;&amp;-    # done with the duplicate
</code></pre>
<h2>So what runs out?</h2>
<p>If every open takes a slot in that table and a description in kernel memory, both must have a ceiling:</p>
<pre><code class="language-plaintext">$ ulimit -n
1048576                      # max descriptors this process may hold

$ cat /proc/sys/fs/file-nr
738     0       9223372036854775807
# open file descriptions: allocated, free (always 0 on modern kernels), max (system-wide)
</code></pre>
<p>Two ceilings, two different errors:</p>
<ul>
<li>Hit the <strong>per-process</strong> limit and <code>open()</code> fails with <code>EMFILE</code>: <em>Too many open files</em>.</li>
<li>Hit the <strong>system-wide</strong> limit and it fails with <code>ENFILE</code>: <em>Too many open files in system</em>.</li>
</ul>
<p>On my machine the system-wide max is effectively unlimited (that number is 2⁶³−1), so the per-process limit is the one you'll actually hit. Our server's message was <code>EMFILE</code> too, so the problem was in that one process.</p>
<p>Every open that is never closed keeps its slot. Once the table is full, the next <code>open()</code> has nowhere to go. The process isn't out of memory or disk. It's out of slots.</p>
<h2>Spotting a leak</h2>
<p>If you suspect a leak, this one line tells you:</p>
<pre><code class="language-bash">ls /proc/&lt;pid&gt;/fd | wc -l
</code></pre>
<p>Run it every few minutes. A healthy service goes up and down. A leaking one only goes up. When you've found the leak, <code>lsof -p &lt;pid&gt;</code> shows <em>which</em> files are piling up, and that usually points straight at the code path. <code>grep 'open files' /proc/&lt;pid&gt;/limits</code> shows the ceiling it's heading toward.</p>
<h2>The twist: a deleted file that still eats disk</h2>
<p>Here's the experiment that changed how I think about <code>rm</code>. I kept fd 3 open and deleted the file:</p>
<pre><code class="language-plaintext">$ rm run_0.dat
$ ls -l /proc/$$/fd/3
3 -&gt; /tmp/run_0.dat (deleted)

$ stat -L -c 'links=%h size=%s' /proc/$$/fd/3
links=0 size=1100
</code></pre>
<p>The name is gone from the directory (<code>links=0</code>), but the inode and its 1100 bytes are still there, because fd 3 still points to them.</p>
<blockquote>
<p>🤔 <strong>Pause and ponder</strong></p>
<p>If the file is "deleted" but still holds its blocks, does the disk get its space back?</p>
</blockquote>
<hr />
<p>To make it visible, I repeated this with a 500 MB file:</p>
<pre><code class="language-plaintext">$ fallocate -l 500M big.bin &amp;&amp; exec 3&lt; big.bin
$ df -m .
Filesystem     1M-blocks  Used Available Use% Mounted on
tmpfs              12830   500     12330   4% /tmp

$ rm big.bin
$ df -m .
Filesystem     1M-blocks  Used Available Use% Mounted on
tmpfs              12830   500     12330   4% /tmp      &lt;- still 500

$ lsof +L1 | grep big
bash    1319 user       3r   REG   0,50 524288000     0  411 /tmp/big.bin (deleted)
grep    1470 user       3r   REG   0,50 524288000     0  411 /tmp/big.bin (deleted)

$ exec 3&lt;&amp;-
$ df -m .
Filesystem     1M-blocks  Used Available Use% Mounted on
tmpfs              12830     0     12830   0% /tmp      &lt;- freed only now
</code></pre>
<p>Notice <code>grep</code> in the <code>lsof</code> output. It never opened <code>big.bin</code>, but bash forked it, and a child inherits its parent's descriptors. That's the <code>fork()</code> sharing from earlier, caught in the wild.</p>
<p><code>rm</code> doesn't free the space. It only removes the name. The blocks stay allocated until the last descriptor pointing to the inode is closed.</p>
<p>This is a real production mystery: <code>df</code> says the disk is full, <code>du</code> can't find the files responsible, and the culprit is a long-running process still holding descriptors to log files that were rotated and deleted days ago. <code>lsof +L1</code> finds them.</p>
<h2>Back to the six-hour bug</h2>
<p>Both experiments tell the same story. The leaked slot and the deleted file that kept filling the disk are the same thing: kernel state that stays alive until someone closes the descriptor.</p>
<p>That's also why restarting the server "fixes" it. When a process exits, the kernel closes every descriptor it held: the table empties, the descriptions are freed, and deleted files finally give back their blocks. Six hours later, the same leak fills the same table again.</p>
<p>So the contract is simple. The kernel holds the state for every open file until you give it back, and every program that opens a file takes on one duty: call <code>close()</code> exactly once, on every path out.</p>
<p>That sounds easy. So why do real programs keep breaking it? That's Part B: <em>The traditional close()</em>.</p>
<hr />
<p>¹ <em>If you</em> <code>strace</code> <em>the shell, you'll see bash read a bigger chunk and then</em> <code>lseek</code> <em>back to just after the newline. That's how it lands at exactly 22. On a pipe, which can't seek, it reads one byte at a time instead.</em></p>
]]></content:encoded></item></channel></rss>