<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lokesh on Medium]]></title>
        <description><![CDATA[Stories by Lokesh on Medium]]></description>
        <link>https://medium.com/@lkumar94?source=rss-286bb504ad6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YtO5HU2gQcGpnjqQyY-9Rw.png</url>
            <title>Stories by Lokesh on Medium</title>
            <link>https://medium.com/@lkumar94?source=rss-286bb504ad6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:00:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lkumar94/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WAL Record Layout: Parsing PostgreSQL’s Write-Ahead Log in Go]]></title>
            <link>https://medium.com/@lkumar94/wal-record-layout-parsing-postgresqls-write-ahead-log-in-go-d7d88a1a6f9b?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7d88a1a6f9b</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Sat, 09 May 2026 15:15:46 GMT</pubDate>
            <atom:updated>2026-05-09T15:15:46.027Z</atom:updated>
            <content:encoded><![CDATA[<p>Every write in PostgreSQL is recorded twice: once in the heap page, once in the WAL. The WAL is the ground truth. If the heap disagrees with the WAL, the WAL wins.</p><p>This post walks through the exact on-disk layout of a WAL record, shows how we parse it in Go.</p><h4><strong>Why WAL exists</strong></h4><p>PostgreSQL’s durability guarantee is:</p><blockquote>A transaction is durable when its WAL record is flushed to disk - not when the heap pages are written.</blockquote><p>On crash, PostgreSQL replays WAL from the last checkpoint forward. Every heap insert, index update, and B-tree split leaves a WAL record. The redo engine reads those records in LSN order and reapplies each one.</p><h4><strong>The Log Sequence Number (LSN)</strong></h4><p>Every byte in the WAL stream has an address: its <strong>Log Sequence Number</strong>.</p><pre>type LSN uint64   // absolute byte position in the WAL stream</pre><p>PostgreSQL prints LSNs as XXXXXXXX/XXXXXXXX - high word / low word. We use a plain uint64 internally and format on demand:</p><pre>func (l LSN) String() string {<br>    return fmt.Sprintf(&quot;%08X/%08X&quot;, uint32(l&gt;&gt;32), uint32(l))<br>}</pre><h4><strong>Segment geometry</strong></h4><p>WAL is divided into <strong>segment files</strong> (default 16 MB each), each divided into <strong>8 KB pages</strong>:</p><pre>WALSegSize  = 16 * 1024 * 1024   // 16 MB per segment file<br>WALPageSize = 8192               // 8 KB per page</pre><p>Given an LSN, we can <a href="https://github.com/kumarlokesh/deep-postgres/blob/0f64cac5d5965d18233340a9e1f39ad3e200936f/internal/wal/types.go#L79">compute</a> which segment and page it lives in:</p><pre>func XLByteToSeg(lsn LSN, segSize uint64) (seg uint64, offset uint32) {<br>    seg    = uint64(lsn) / segSize<br>    offset = uint32(uint64(lsn) % segSize)<br>    return<br>}</pre><p>Segment file names encode the timeline and segment number: TTTTTTTTSSSSSSSSSSSSSSSS - e.g. 000000010000000000000001.</p><h4><strong>Page headers</strong></h4><p>Every 8 KB page carries a header before its records.</p><p><strong>Short header</strong> (24 bytes) - all pages except the first of a segment:</p><pre>uint16  xlp_magic      = 0xD11D   (XLogPageMagic)<br>uint16  xlp_info       - flag bits (XLPFirstIsContRecord, XLPLastIsDummy, XLPLongHeader)<br>uint32  xlp_tli        - timeline ID<br>uint64  xlp_pageaddr   - LSN of the start of this page<br>uint32  xlp_rem_len    - continuation bytes of a record that started on the previous page<br>uint32  (padding)</pre><p><strong>Long header</strong> (40 bytes) - first page of each segment only, extends the short header with:</p><pre>uint64  xlp_sysid       - cluster system identifier (from pg_control)<br>uint32  xlp_seg_size    - segment file size (sanity check)<br>uint32  xlp_xlog_blcksz - page size (sanity check)</pre><p>The XLPFirstIsContRecord flag means the first record-byte on this page is a continuation of a record that began on the previous page. The redo reader must assemble continuations transparently.</p><h4><strong>XLogRecord: the 24-byte fixed header</strong></h4><p>Every WAL record starts with an XLogRecord header:</p><pre>offset  size  field<br>0       4     xl_tot_len   - total length of the entire record (header + body)<br>4       4     xl_xid       - transaction ID<br>8       8     xl_prev      - LSN of the immediately preceding record<br>16      1     xl_info      - rmgr flag bits (high 4: generic flags; low 4: rmgr sub-type)<br>17      1     xl_rmid      - resource manager ID<br>18      2     (padding)<br>20      4     xl_crc       - CRC-32C (Castagnoli) over body then header bytes 0-19</pre><p>Total: <strong>24 bytes</strong>.</p><p>The CRC covers body bytes first, then header bytes 0-19. This lets the decoder verify integrity without storing a temporary copy.</p><pre>type XLogRecord struct {<br>    XlTotLen uint32<br>    XlXid    uint32<br>    XlPrev   LSN<br>    XlInfo   uint8<br>    XlRmid   RmgrID<br>    XlCrc    uint32  // bytes 20-23<br>}</pre><h4><strong>Resource managers</strong></h4><p>xl_rmid identifies which subsystem wrote the record:</p><pre>| ID | Name        | Purpose                          |<br>|----|-------------|----------------------------------|<br>| 0  | XLOG        | Checkpoint, WAL switch, backup   |<br>| 1  | Transaction | Commit, abort, prepare           |<br>| 2  | Storage     | Relation create/drop             |<br>| 9  | Heap2       | HOT prune, lock, vacuum          |<br>| 10 | Heap        | Insert, delete, update           |<br>| 11 | Btree       | Index insert, split, vacuum      |</pre><p>The redo engine dispatches each record to its resource manager’s Redo callback. Unknown or unimplemented rmgrs are skipped. This matches PostgreSQL’s behavior when replaying WAL from a database with custom extensions.</p><h4><strong>Record body layout</strong></h4><p>After the 24-byte header comes the <strong>body</strong>, structured as follows:</p><pre>for each block reference (block ID 0..31):<br>    [1 byte:  block ID]<br>    [1 byte:  fork_flags]         - XLBKTHasImage | XLBKTHasData | XLBKTWillInit | XLBKTSameRel<br>    [2 bytes: block redo data length]<br>    if !XLBKTSameRel:<br>        [12 bytes: RelFileLocator] - tablespace OID, database OID, relation OID<br>    [4 bytes: block number]<br>    [1 byte:  fork number]         - main (0), FSM (1), VM (2), init (3)<br>    if XLBKTHasImage:<br>        [2 bytes: image length]<br>        [2 bytes: hole offset]<br>        [1 byte:  bimg_info]       - BimgHasHole | BimgIsCompressed | BimgApply<br>        [1 byte:  packed hole length]<br>[0xFF:  end-of-block-refs marker]<br>[main data header]                  - 1 byte if &lt; 256, else 0xFF + 2 bytes<br>[block images, in block-ref order]<br>[block redo data, in block-ref order]<br>[main data]</pre><p>The XLBKTSameRel optimisation is worth noting: when consecutive block references point to the same relation, the encoder omits the 12-byte RelFileLocator and sets this flag. The decoder copies the previous reference’s locator.</p><h4><strong>Full-page writes (FPW)</strong></h4><p>When PostgreSQL modifies a block for the first time after a checkpoint, it logs the entire 8 KB page image as part of the WAL record. This is a <strong>full-page write (FPW)</strong>.</p><p>During replay, instead of applying the redo delta, the engine restores the full page. This avoids partial-page writes (torn pages) corrupting the database.</p><p>A block reference with XLBKTHasImage set carries a BlockImage:</p><pre>type BlockImage struct {<br>    Length     uint16   // bytes of image stored (may be &lt; 8192 if there&#39;s a hole)<br>    HoleOffset uint16   // start offset of the unchanged region<br>    BimgInfo   BimgInfo // BimgHasHole | BimgIsCompressed | BimgApply<br>    HoleLength uint16   // size of the unchanged region<br>    Data       []byte   // raw image bytes<br>}</pre><p>Holes represent the unchanged region of the page that the encoder chose not to store. During redo, the hole is filled with zeros.</p><h4><strong>Encoder: two-phase CRC</strong></h4><p>Our Encode function builds the body, then the full buffer, then computes CRC:</p><pre>func Encode(rec *Record) ([]byte, error) {<br>    var body []byte<br>    // ... write block ref headers, end marker, main data header,<br>    //     images, block redo data, main data ...<br><br>    totalLen := uint32(XLogRecordHeaderSize + len(body))<br>    aligned  := MaxAlignedSize(totalLen)<br>    buf      := make([]byte, aligned)<br>    copy(buf[XLogRecordHeaderSize:], body)<br><br>    hdr := rec.Header<br>    hdr.XlTotLen = totalLen<br>    hdr.XlCrc = 0<br>    encodeXLogRecord(buf[:XLogRecordHeaderSize], &amp;hdr)<br><br>    crc := crc32.New(crc32cTable)<br>    crc.Write(buf[XLogRecordHeaderSize:totalLen])  // body bytes<br>    crc.Write(buf[:20])                             // header bytes 0-19 (excludes CRC field)<br>    binary.LittleEndian.PutUint32(buf[20:], crc.Sum32())<br><br>    return buf, nil<br>}</pre><p>Records are padded to an 8-byte (XLogRecordAlignment) boundary so the next record always starts aligned.</p><h4><strong>Decoder: two-pass parse</strong></h4><p>Decoding is a two-pass process:</p><p><strong>Pass 1 -</strong> iterate the block reference headers, collecting RelFileLocator, BlockNum, ForkNum, Flags, and per-block dataLen. Stop at the 0xFF end marker.</p><p><strong>Pass 2 -</strong> after the main-data header, read:</p><ol><li>Block images (in block-ref order), using BlockImage.Length to know how many bytes to consume.</li><li>Per-block redo data (in block-ref order), using the dataLen collected in pass 1.</li><li>Main data.</li></ol><p>The two-pass approach is necessary because image and redo data appear <em>after</em> all headers, but we need the headers to know how many bytes to expect.</p><h4><strong>SegmentReader: transparent page boundaries</strong></h4><p>SegmentReader abstracts over page boundaries so the caller just calls Next():</p><pre>type SegmentReader struct {<br>    data     []byte<br>    segStart LSN<br>    tli      TimeLineID<br>    pos      int<br>}<br><br>func (r *SegmentReader) Next() (*Record, error) {<br>    r.skipPageHeaderIfNeeded()   // long header on page 0, short on others<br>    hdrBuf, _ := r.readBytes(XLogRecordHeaderSize)<br>    hdr := decodeXLogRecord(hdrBuf)<br>    if hdr.XlTotLen == 0 { return nil, ErrEndOfSegment }  // unwritten space<br>    recBuf := make([]byte, hdr.XlTotLen)<br>    copy(recBuf, hdrBuf)<br>    r.readBytes(int(hdr.XlTotLen) - XLogRecordHeaderSize)  // body, spanning pages<br>    r.readBytes(padding)                                     // alignment padding<br>    return Decode(recBuf, recordLSN)<br>}</pre><p>The key insight: readBytes tracks pos and calls skipPageHeaderIfNeeded whenever it crosses an 8 KB boundary. The caller never sees page headers.</p><h4><strong>RedoEngine</strong></h4><p>RedoEngine drives crash recovery:</p><pre>type RedoEngine struct {<br>    tli      TimeLineID<br>    startLSN LSN<br>    endLSN   LSN           // 0 = replay all<br>    provider SegmentProvider<br>    progress RedoProgress<br>    stats    RedoStats<br>}</pre><p>The main loop:</p><pre>for {<br>    if endLSN != 0 &amp;&amp; currentLSN &gt;= endLSN { return nil }<br><br>    segData, err := provider(currentLSN, tli)<br>    if err == io.EOF { return nil }<br><br>    reader := NewSegmentReader(segData, segStartLSN, tli)<br>    reader.pos = segOffset  // seek to currentLSN within the segment<br><br>    for {<br>        rec, err := reader.Next()<br>        if err == ErrEndOfSegment || err == io.EOF { break }<br>        if err != nil { return err }<br><br>        err = Dispatch(rec)<br>        switch {<br>        case err == nil:<br>            stats.RecordsApplied++<br>            progress(rec)<br>        case errors.As(err, &amp;ErrUnknownRmgr{}), errors.As(err, &amp;ErrUnimplementedRedo{}):<br>            stats.RecordsSkipped++  // non-fatal: unknown/unimplemented rmgr<br>        default:<br>            return err<br>        }<br>        currentLSN = rec.LSN.Add(MaxAlignedSize(rec.Header.XlTotLen))<br>    }<br><br>    // Advance to the next segment - do not reload the same segment.<br>    if currentLSN &lt; NextSegmentLSN(segStartLSN) {<br>        currentLSN = NextSegmentLSN(segStartLSN)<br>    }<br>}</pre><p>Two design points worth calling out:</p><p><strong>Non-fatal unknown rmgrs -</strong> PostgreSQL skips records for unknown extension resource managers during recovery. We replicate this: ErrUnknownRmgr and ErrUnimplementedRedo increment RecordsSkipped but do not halt replay.</p><p><strong>Segment advancement -</strong> after the inner loop exhausts a segment, currentLSN may point into the unwritten tail of the segment. Without explicit advancement to NextSegmentLSN, the outer loop would reload the same segment indefinitely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7d88a1a6f9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[B-tree Splits: Recursive Page Splits, Sibling Chains, and Root Promotion]]></title>
            <link>https://medium.com/@lkumar94/b-tree-splits-recursive-page-splits-sibling-chains-and-root-promotion-4e84412d8ad8?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e84412d8ad8</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[b-tree]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 13:09:43 GMT</pubDate>
            <atom:updated>2026-04-25T13:09:43.962Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 6 of the </em><a href="https://github.com/kumarlokesh/deep-postgres"><em>deep-postgres</em></a><em> series - rebuilding PostgreSQL internals in Go.</em></p><h3><strong>What a Split Actually Is</strong></h3><p>A B-tree page split is the mechanism by which a full page makes room for a new entry. The full page is divided into two pages, and a <strong>separator key</strong> - the first key of the new right page is promoted into the parent. If the parent is also full, the split recurses upward until it either finds a page with space or reaches the root, at which point a new root is allocated one level higher.</p><p>This post traces the exact sequence in <a href="https://github.com/kumarlokesh/deep-postgres/blob/main/internal/storage/btree_index.go">internal/storage/btree_index.go</a>, matching it step-by-step to PostgreSQL’s <a href="https://github.com/postgres/postgres/blob/master/src/backend/access/nbtree/README">nbtree AM</a>.</p><h3><strong>Index Structure Recap</strong></h3><pre>Block 0  : meta page - BTMetaPageData embedded after the page header<br>Block 1  : initial root/leaf (BTP_ROOT | BTP_LEAF)<br>Block 2+ : split halves, new internal pages, new root</pre><p>Every block uses the standard 8 KB heap page layout with pd_special = PageSize - BTPageOpaqueSize (16) = <strong>8176</strong>, carving out a BTPageOpaqueData footer:</p><pre>type BTPageOpaqueData struct {<br>    BtpoPrev    BlockNumber  // left sibling<br>    BtpoNext    BlockNumber  // right sibling<br>    BtpoLevel   uint32       // 0 = leaf<br>    BtpoFlags   uint16       // BTP_LEAF | BTP_ROOT | BTP_DELETED<br>    BtpoCycleid uint16<br>}</pre><p>Sibling pointers form a doubly-linked list at each tree level, enabling range scans by walking the BtpoNext chain after descending to the leftmost matching leaf.</p><h3><strong>Capacity</strong></h3><p>For a 4-byte key:</p><pre>available = pd_upper_initial - pd_lower_initial<br>          = 8176 - 24 = 8152 bytes<br><br>per entry = IndexTupleHeaderSize(8) + key_len(4) + ItemIdSize(4) = 16 bytes<br><br>max entries = 8152 / 16 = 509</pre><p>The 510th insert triggers the first split.</p><h3><strong>Descent: findLeaf</strong></h3><pre>func (idx *BTreeIndex) findLeaf(<br>    rootBlk BlockNumber, rootLevel uint32, key []byte,<br>) ([]btreePath, BlockNumber, error)</pre><p>Starting from the root, findLeaf reads each page, classifies it as leaf or internal, and if internal picks the correct child pointer:</p><pre>pos := bp.SearchLeaf(func(entryKey []byte) int { return idx.cmp(entryKey, key) })<br>n := bp.NumEntries()<br>if pos &gt;= n {<br>    pos = n - 1<br>} else if pos &gt; 0 {<br>    ek, _, _, _ := bp.GetEntry(pos)<br>    if idx.cmp(ek, key) &gt; 0 {<br>        pos-- // separator &gt; searchKey → follow the child to the left<br>    }<br>}<br>_, childBlk, _, _ = bp.GetEntry(pos)</pre><p>SearchLeaf is a standard lower-bound binary search: it returns the first position where entryKey &gt;= searchKey. The internal-page invariant is:</p><ul><li>entry [0]- leftmost child, zero-filled placeholder key</li><li>entry [i] - child whose subtree begins at separator key [i]</li></ul><p>So if the found position’s key is strictly greater than the search key, the correct child is one position to the left. If equal, follow this position. If beyond the last entry, follow the last.</p><h3><strong>Leaf Split: splitLeaf</strong></h3><p>Called when the target leaf has fewer than tupleSize + ItemIdSize bytes free.</p><p><strong>1. Snapshot + insert new entry in memory</strong></p><pre>all := collect all n entries from leftBP<br>all = insert(newEntry, at insertPos)   // in-memory sorted slice, total = n+1<br>splitPos = total / 2</pre><p><strong>2. Allocate right page</strong></p><pre>rightBlk, rightId, _ = idx.rel.Extend(ForkMain)</pre><p>Extend appends a zero block to the file, loads it into the buffer pool, and calls page.init(). The caller subsequently overwrites this with a proper B-tree page via copy(rightPage.data[:], newRight.page.data[:]).</p><p><strong>3. Rebuild both pages</strong></p><pre>newLeft  = NewBTreePage(BTreeRootLeaf or BTreeLeaf)<br>newRight = NewBTreePage(BTreeLeaf)<br><br>for i in [0, splitPos):  newLeft.InsertEntrySortedAt(i, ...)<br>for i in [splitPos, n+1): newRight.InsertEntrySortedAt(i-splitPos, ...)</pre><p><strong>4. Stitch the doubly-linked chain</strong></p><pre>leftOldOpaque := leftBP.Opaque()<br>newRight.SetSiblings(leftBlk, leftOldOpaque.BtpoNext)<br>newLeft.SetSiblings(leftOldOpaque.BtpoPrev, rightBlk)<br>if leftOldOpaque.BtpoNext != InvalidBlockNumber {<br>    idx.updateLeftSibling(leftOldOpaque.BtpoNext, rightBlk)<br>}</pre><p>updateLeftSibling patches the BtpoPrev of the old right-sibling to point at the new right page, maintaining the bidirectional chain across the split.</p><p><strong>5. Write back and promote</strong></p><pre>copy(leftPage.data[:],  newLeft.page.data[:])<br>copy(rightPage.data[:], newRight.page.data[:])<br>promotedKey = newRight.GetEntry(0).key   // first key of right half</pre><p>The promoted key is the separator that goes into the parent. If the split happened on the root, a new root must be created (createNewRoot). Otherwise the key is inserted into the parent (insertInParent), which may itself recurse.</p><h3><strong>Root Promotion: createNewRoot</strong></h3><p>When a leaf split happens on the current root (the tree has only one page), a new internal root is allocated:</p><pre>bp := NewBTreePage(BTreeRootInternal)<br>bp.InsertEntrySortedAt(0, zeroKey, leftBlk, 0)       // leftmost downlink<br>bp.InsertEntrySortedAt(1, separatorKey, rightBlk, 0)  // right downlink<br>copy(newRootPage.data[:], bp.page.data[:])</pre><p>Entry 0 carries a zero-filled placeholder key (the leftmost child has no lower bound in the nbtree model). Entry 1 carries the separator - the first key in the right subtree.</p><p>The old left child’s BTP_ROOT flag is cleared, and the meta page is updated:</p><pre>idx.updateMetaRoot(newRootBlk, level)</pre><p>All subsequent descents re-read the meta page to find the new root.</p><h3><strong>Internal Page Split: splitInternal</strong></h3><p>Identical structure to splitLeaf, with one difference:</p><pre>// The entry at splitPos moves UP as the separator; it is not kept on<br>// either child page.<br>for i in [0, splitPos):         newLeft.InsertEntrySortedAt(i, ...)<br>// skip splitPos - it becomes the promoted key<br>for i in [splitPos+1, total):   newRight.InsertEntrySortedAt(i-splitPos-1, ...)<br>promotedKey = all[splitPos].key</pre><p>In a leaf split, all[splitPos] stays on the right page (it is both the first entry of the right page and the separator key). In an internal split, the middle key moves up entirely and neither child retains it.</p><h3><strong>Search</strong></h3><pre>func (idx *BTreeIndex) Search(key []byte) (BlockNumber, OffsetNumber, bool, error)</pre><ol><li>readMeta() → root block number</li><li>findLeaf(root, level, key) → leaf block number</li><li>Read leaf, call SearchLeaf to find the first position where entryKey &gt;= key</li><li>Check exact equality: cmp(gotKey, key) == 0</li></ol><p>No page latch is held across the call (single-threaded implementation). In a concurrent setting each page would require a shared buffer lock during descent, upgraded to exclusive on insertion.</p><h3><strong>Persistence</strong></h3><p>BTreeIndex is fully persistent. Every modified buffer is marked dirty via GetPageForWrite. The buffer pool writes dirty pages back to disk on eviction or when FlushAll() is called. OpenBTreeIndex re-reads the meta page to locate the current root; subsequent operations load pages from disk on cache misses transparently.</p><pre>// Session 1: write<br>idx, _ = NewBTreeIndex(rel, cmpBytes)<br>idx.Insert(encKey(42), 100, 1)<br>rel.Flush(ForkMain)<br><br>// Session 2: read - zero shared state<br>idx2, _ = OpenBTreeIndex(rel2, cmpBytes)<br>blk, off, found, _ = idx2.Search(encKey(42))<br>// found=true, blk=100, off=1</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e84412d8ad8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVCC Visibility Rules: Implementing HeapTupleSatisfiesMVCC]]></title>
            <link>https://medium.com/@lkumar94/mvcc-visibility-rules-implementing-heaptuplesatisfiesmvcc-14ccc5874a02?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ccc5874a02</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mvcc]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 13:55:34 GMT</pubDate>
            <atom:updated>2026-04-18T13:55:34.969Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL’s snapshot isolation is implemented without read locks. Instead, every row version carries the transaction IDs that inserted and deleted it. A read operation checks whether a given tuple is visible to the reader’s snapshot using a deterministic algorithm. This post walks through HeapTupleSatisfiesMVCC - the core of PostgreSQL’s MVCC implementation.</p><h3><strong>Snapshots</strong></h3><p>A snapshot is a frozen view of transaction state taken at the start of a statement (READ COMMITTED) or transaction (REPEATABLE READ / SERIALIZABLE). It contains:</p><pre>type Snapshot struct {<br>    Xid    TransactionId   // current transaction&#39;s own XID<br>    Xmin   TransactionId   // all XIDs &lt; Xmin are visible (if committed)<br>    Xmax   TransactionId   // all XIDs &gt;= Xmax are invisible<br>    Xip    []TransactionId // in-progress XIDs in [Xmin, Xmax)<br>    CurCid CommandId       // current command ID within transaction<br>}</pre><p>The snapshot’s <strong>Xmin</strong> is the lowest XID that was in-progress at snapshot time. Any transaction that committed before this point is definitely committed. Any XID &gt;= <strong>Xmax</strong> has not yet been assigned; it is invisible. XIDs in the range [Xmin, Xmax) are either committed, aborted, or still in progress - the Xip list records which ones were in-progress.</p><p><strong>XidVisible(xid)</strong> implements this logic:</p><pre>func (s *Snapshot) XidVisible(xid TransactionId) bool {<br>    if xid == InvalidTransactionId { return false }<br>    if xid == FrozenTransactionId  { return true }<br>    if xid == s.Xid                { return true }  // own changes<br>    if xid &gt;= s.Xmax               { return false } // too new<br>    if xid &lt; s.Xmin                { return true }  // old enough<br>    // In [Xmin, Xmax): visible unless in Xip.<br>    for _, x := range s.Xip {<br>        if x == xid { return false }<br>    }<br>    return true<br>}</pre><h3><strong>HeapTupleSatisfiesMVCC</strong></h3><p>The function in <a href="https://github.com/postgres/postgres/blob/master/src/backend/access/heap/heapam_visibility.c">src/backend/access/heap/heapam_visibility.c</a> evaluates three conditions in order:</p><p><strong>1. Is xmin visible?</strong></p><pre>func xminVisible(hdr *HeapTupleHeader, snap *Snapshot,<br>    oracle TransactionOracle, infomask InfomaskFlags) bool {<br><br>    xmin := hdr.TXmin<br>    if xmin == InvalidTransactionId { return false }<br>    if xmin == FrozenTransactionId  { return true }<br><br>    if infomask &amp; HeapXminCommitted != 0 { return snap.XidVisible(xmin) }<br>    if infomask &amp; HeapXminInvalid   != 0 { return false }<br><br>    switch oracle.Status(xmin) {<br>    case TxCommitted: return snap.XidVisible(xmin)<br>    case TxAborted:   return false<br>    default:          return xmin == snap.Xid  // own in-progress insert<br>    }<br>}</pre><p>Hint bits are checked first, avoiding a clog lookup when they are already set.</p><p>If xmin is in-progress and equals the snapshot’s own XID, the tuple was inserted by the current transaction and is eligible for further checks. If it is a different in-progress transaction, the tuple is invisible.</p><p><strong>2. Was this tuple inserted by the current transaction?</strong></p><pre>if hdr.TXmin == snap.Xid {<br>    if hdr.TCid &gt;= snap.CurCid {<br>        return VisInvisible  // inserted by a later command in this xact<br>    }<br>    if hdr.TXmax == InvalidTransactionId || infomask &amp; HeapXmaxInvalid != 0 {<br>        return VisInsertedBySelf<br>    }<br>    if hdr.TXmax == snap.Xid {<br>        return VisDeletedBySelf<br>    }<br>}</pre><p><strong>Command ID visibility</strong>: within a single transaction, a row inserted by command N is not visible to a scan running as command N (t_cid &gt;= curcid). This is required for correct behaviour of statements like UPDATE t SET x = x + 1 - the updated rows must not be scanned again in the same statement.</p><p><strong>Self-delete detection</strong>: if the current transaction also set xmax, the tuple is VisDeletedBySelf. The caller (e.g., ExecDelete) uses this to detect <em>“you’re trying to delete a row you already deleted in this transaction” </em>scenarios.</p><p><strong>3. Is xmax visible?</strong></p><pre>func xmaxVisibility(hdr *HeapTupleHeader, snap *Snapshot,<br>    oracle TransactionOracle, infomask InfomaskFlags) VisibilityResult {<br><br>    xmax := hdr.TXmax<br>    if xmax == InvalidTransactionId || infomask &amp; HeapXmaxInvalid != 0 {<br>        return VisVisible<br>    }<br>    if infomask &amp; HeapXmaxCommitted != 0 {<br>        if snap.XidVisible(xmax) { return VisDeleted }<br>        return VisVisible  // deletion committed but not in our snapshot<br>    }<br>    if xmax == snap.Xid { return VisBeingDeleted }<br><br>    switch oracle.Status(xmax) {<br>    case TxCommitted:<br>        if snap.XidVisible(xmax) { return VisDeleted }<br>        return VisVisible<br>    case TxAborted:<br>        return VisVisible  // delete was rolled back<br>    default:<br>        return VisVisible  // another xact is deleting: still visible to us<br>    }<br>}</pre><p><strong>Uncommitted delete</strong>: if xmax is in-progress (another transaction is deleting the tuple), the tuple is still visible. The deleter’s commit/abort will determine the final state for other transactions.</p><p><strong>Snapshot-aware deletion</strong>: even if xmax is committed, the deletion may not be visible to old snapshots. A long-running READ COMMITTED transaction will see deletions as they commit; a REPEATABLE READ transaction takes a snapshot at the start and will not see deletions that committed after that point. Both cases are handled by snap.XidVisible(xmax).</p><h3><strong>Hint bits in practice</strong></h3><p>After a visibility check determines the status of xmin or xmax, <a href="https://github.com/kumarlokesh/deep-postgres/blob/810665acbe7dc513fc2b05bdc91307b28ba0b4f7/internal/storage/visibility.go#L296">SetHintBits</a> caches the result:</p><pre>func SetHintBits(hdr *HeapTupleHeader, oracle TransactionOracle) {<br>    infomask := hdr.Infomask()<br>    if infomask &amp; HeapXminCommitted == 0 &amp;&amp; infomask &amp; HeapXminInvalid == 0 {<br>        switch oracle.Status(hdr.TXmin) {<br>        case TxCommitted: hdr.TInfomask |= uint16(HeapXminCommitted)<br>        case TxAborted:   hdr.TInfomask |= uint16(HeapXminInvalid)<br>        }<br>    }<br>    // same for xmax ...<br>}</pre><p>Several important properties:</p><ol><li><strong>Write-once</strong>: hint bits transition from unset → set but never from set → unset. Committed stays committed; aborted stays aborted. This means any backend can safely set a hint bit without holding an exclusive lock on the tuple.</li><li><strong>No WAL logging</strong>: hint bits are set on the in-memory copy of the page. If the page is later written to disk with the hint bits set, they will persist. If the page is read from a WAL-replayed image that predates the hint bit, the hint will just be re-derived. This is correct because the bit is always derivable from the authoritative clog.</li><li><strong>Page dirtying</strong>: setting a hint bit marks the buffer dirty, which means it will eventually be flushed. PostgreSQL has a special code path for hint-bit-only dirtying that does not require holding a WAL insertion lock, since the operation does not need to be WAL-logged.</li></ol><h3><strong>The TransactionOracle interface</strong></h3><p>In a real PostgreSQL server, transaction status is read from pg_xact (formerly pg_clog), a series of files where each XID’s status is encoded in 2 bits (in-progress, committed, aborted, sub-committed). Our implementation uses an interface:</p><pre>type TransactionOracle interface {<br>    Status(xid TransactionId) TransactionStatus<br>}</pre><p>This allows swapping in a real clog implementation, a test stub, or an in-memory map without changing the visibility logic. The SimpleTransactionOracle used in tests is an in-memory map[TransactionId]TransactionStatus.</p><h3><strong>HeapTupleSatisfies* variants</strong></h3><p>HeapTupleSatisfiesMVCC is one of several visibility functions that share the same tuple header format but apply different rules:</p><pre>| Function                 | Used by                                                             |<br>|--------------------------|---------------------------------------------------------------------|<br>| HeapTupleSatisfiesMVCC   | normal queries (snapshot isolation)                                 |<br>| HeapTupleSatisfiesNow    | system catalog scans (sees current committed state)                 |<br>| HeapTupleSatisfiesSelf   | sees own uncommitted changes regardless of CID                      |<br>| HeapTupleSatisfiesDirty  | sees all live rows regardless of commit status; used by lock checks |<br>| HeapTupleSatisfiesVacuum | determines whether VACUUM can remove a tuple                        |<br>| HeapTupleSatisfiesAny    | sees all non-aborted tuples; used for heap rewrite                  |</pre><p>All of these operate on the same HeapTupleHeader fields but differ in how they interpret xmin/xmax and snapshots. They are the correct abstraction boundary: the AM (access method) layer calls them uniformly without knowing which isolation level is active.</p><h3><strong>Summary of visibility rules</strong></h3><p>For a tuple to be visible under MVCC:</p><ol><li>xmin must be committed AND visible to the snapshot (xmin &lt; Xmax and not in-progress at snapshot time, or xmin &lt; Xmin).</li><li>xmax must be one of: invalid, aborted, or committed but not visible to the snapshot (i.e. the delete happened after the snapshot was taken).</li></ol><p>Everything else is optimisation (hint bits) or edge-case handling (frozen XID, self-insert, same-CID visibility, in-progress deletes).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ccc5874a02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[B-tree Index Pages: The nbtree Format in Go]]></title>
            <link>https://medium.com/@lkumar94/b-tree-index-pages-the-nbtree-format-in-go-3758e6e0056f?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3758e6e0056f</guid>
            <category><![CDATA[b-tree-index]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 17:49:10 GMT</pubDate>
            <atom:updated>2026-04-11T17:49:10.562Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL’s default index type is B-tree, implemented in <a href="https://github.com/postgres/postgres/blob/master/src/backend/access/nbtree/README">src/backend/access/nbtree/</a>. Every B-tree index page uses the standard 8 KB heap page layout with one addition: 16 bytes of opaque data at the end. This post covers the page format, opaque data, and the index tuple structure.</p><h3><strong>Why a separate special space?</strong></h3><p>The standard PageHeaderData has pd_special pointing to the start of index-specific data at the end of the page. For heap pages, pd_special == PageSize (no special space). For B-tree pages, the last 16 bytes are BTPageOpaqueData, which holds sibling pointers and the page’s tree level. Setting pd_special = PageSize - 16 reserves this space.</p><p>The page layout for a B-tree page:</p><pre>+----------------+----------+----------------+--------------+---------------+<br>| PageHeaderData |ItemIdData| ... free space | index tuples | BTPageOpaque  |<br>| (24 bytes)     | array    |                | (grow down)  | (16 bytes)    |<br>+----------------+----------+----------------+--------------+---------------+<br>^                ^          ^                ^               ^               ^<br>0            pd_lower   pd_upper          (tuples)      pd_special       8192</pre><p>When initialising a B-tree page, both pd_upper and pd_special are set to PageSize - BTPageOpaqueSize (8176). pd_lower starts at PageHeaderSize(24). Index tuples are inserted the same way as heap tuples: they grow downward from pd_upper.</p><h3><strong>BTPageOpaqueData: 16 bytes</strong></h3><pre>typedef struct BTPageOpaqueData {<br>    BlockNumber btpo_prev;    /* left sibling, or P_NONE */<br>    BlockNumber btpo_next;    /* right sibling, or P_NONE */<br>    uint32      btpo_level;   /* 0 for leaf pages */<br>    uint16      btpo_flags;<br>    uint16      btpo_cycleid; /* vacuum cycle ID of latest split */<br>} BTPageOpaqueData;           /* 16 bytes */</pre><p><strong>btpo_prev / btpo_next</strong>: B-tree leaf pages are doubly-linked for efficient range scans. An index scan that needs tuples between keys A and B walks right across leaf pages using these pointers, without descending from the root again.</p><p><strong>btpo_level</strong>: 0 for leaf pages, increasing toward the root. PostgreSQL assigns leaf level 0, the next internal level 1, and so on up to the root. When building a B-tree from scratch, the level of the root changes as the tree grows.</p><p><strong>btpo_flags</strong>: bitfield identifying the page role:</p><pre>| Flag            | Value  | Meaning                             |<br>|-----------------|--------|-------------------------------------|<br>| BTP_LEAF        | 0x0001 | leaf page                           |<br>| BTP_ROOT        | 0x0002 | current root page                   |<br>| BTP_DELETED     | 0x0004 | page on free list                   |<br>| BTP_META        | 0x0008 | meta page (page 0)                  |<br>| BTP_HALF_DEAD   | 0x0010 | being deleted                       |<br>| BTP_SPLIT_END   | 0x0020 | incomplete split, follow right link |<br>| BTP_HAS_GARBAGE | 0x0040 | has LP_DEAD items                   |<br>| BTP_INCOMPLETE  | 0x0080 | incomplete split                    |</pre><p>A page can be both root and leaf (BTP_ROOT | BTP_LEAF), which is the initial state of a single-page B-tree.</p><p><strong>btpo_cycleid</strong>: used during VACUUM to detect pages split during the current vacuum cycle. This prevents VACUUM from deleting index entries that were moved to a newly split page before VACUUM had a chance to scan it.</p><h3><strong>IndexTupleData: 8 bytes</strong></h3><p>Each entry on a leaf page pairs a key with a pointer to the heap tuple:</p><pre>typedef struct IndexTupleData {<br>    ItemPointerData t_tid;  /* 6 bytes: heap block + offset */<br>    unsigned short  t_info; /* size (low 13 bits) + flags (high 3) */<br>} IndexTupleData;           /* 8 bytes */</pre><p>t_info layout:</p><ul><li>bits 0-12: total size of the index tuple (header + key data), up to 8191 bytes</li><li>bit 13: INDEX_NULL_MASK - tuple has null attribute(s)</li><li>bit 14: INDEX_VAR_MASK- tuple has variable-width attribute(s)</li><li>bit 15: unused</li></ul><p>Key data follows immediately after the header. For a B-tree on a single int4 column, the key data is 4 bytes. For a multi-column index, the key is the concatenation of all indexed attributes, with alignment padding.</p><p>For internal (non-leaf) pages, the “heap TID” field is repurposed: t_tid.ip_blkid holds the child block number, and t_tid.ip_posid is ignored. This is a documented convention in the nbtree code.</p><h3><strong>Page types and initialisation</strong></h3><pre>func NewBTreePage(pageType BTreePageType) *BTreePage {<br>    p := NewPage()<br><br>    h := p.Header()<br>    h.PdSpecial = uint16(PageSize - BTPageOpaqueSize)<br>    h.PdUpper   = uint16(PageSize - BTPageOpaqueSize)<br>    encodeHeader(p.data[:PageHeaderSize], &amp;h)<br><br>    opaque := BTPageOpaqueData{<br>        BtpoPrev:  InvalidBlockNumber,<br>        BtpoNext:  InvalidBlockNumber,<br>        BtpoLevel: pageType.level(),<br>        BtpoFlags: uint16(pageType.flags()),<br>    }<br>    encodeBTOpaque(p.data[opaqueOffset:], &amp;opaque)<br>    return &amp;BTreePage{page: p}<br>}</pre><p>opaqueOffset = PageSize-BTPageOpaqueSize = 8176.</p><p>This is all that distinguishes a B-tree page from a heap page at the storage level - the standard page header plus 16 bytes at the end. Everything else (inserting tuples, tracking free space) is inherited from the heap page layer.</p><h3><strong>Binary search on leaf pages</strong></h3><p>B-tree entries are stored in insertion order (not necessarily sorted in our simplified version). In a real nbtree, entries are kept in key order to support binary search. The <a href="https://github.com/kumarlokesh/deep-postgres/blob/ea220e0559f2c01d5b154e95ef79fa52e21ce7c7/internal/storage/btree.go#L330">SearchLeaf</a> method implements a standard lower-bound search:</p><pre>func (b *BTreePage) SearchLeaf(cmp func(entryKey []byte) int) int {<br>    n := b.NumEntries()<br>    lo, hi := 0, n<br>    for lo &lt; hi {<br>        mid := lo + (hi-lo)/2<br>        key, _, _, _ := b.GetEntry(mid)<br>        if cmp(key) &lt; 0 {<br>            lo = mid + 1  // entry &lt; search key: go right<br>        } else {<br>            hi = mid      // entry &gt;= search key: go left<br>        }<br>    }<br>    return lo<br>}</pre><p>The comparator returns negative if entryKey &lt; searchKey. This is consistent with cmp conventions in PostgreSQL’s btcompare functions. The result is the first index where the entry is &gt;= searchKey- the insertion point for a new key, or the start of a range scan.</p><p>For internal pages, <a href="https://github.com/kumarlokesh/deep-postgres/blob/ea220e0559f2c01d5b154e95ef79fa52e21ce7c7/internal/storage/btree.go#L349">SearchInternal</a> wraps SearchLeaf and returns the child block number to follow. Internal page entries are high keys: “all keys in the child to the left of this entry are less than this key.”</p><h3><strong>What page splits look like</strong></h3><p>When a leaf page is full, nbtree splits it:</p><ol><li>Allocate a new page.</li><li>Move the upper half of entries to the new page.</li><li>Set btpo_next of the old page to the new page, btpo_prev of the new page to the old.</li><li>Insert a downlink for the new page’s high key into the parent internal page.</li><li>If the parent is full, recursively split.</li></ol><p>The BTP_INCOMPLETE_SPLIT flag marks a page that has been split but whose parent downlink has not yet been inserted. Any concurrent backend that sees this flag must complete the split before proceeding (the “fix incomplete split” path in _bt_insert). This is how nbtree achieves crash safety: an incomplete split is detectable and recoverable from WAL.</p><h3><strong>Meta page</strong></h3><p>Page 0 of every B-tree index is a meta page (BTP_META). It carries BTMetaPageData:</p><pre>typedef struct BTMetaPageData {<br>    uint32      btm_version;          /* nbtree version, currently 4 */<br>    BlockNumber btm_root;             /* root block, or P_NONE */<br>    uint32      btm_level;            /* tree level of root */<br>    BlockNumber btm_fastroot;         /* current fast root (= real root after VACUUM) */<br>    uint32      btm_fastlevel;<br>    TransactionId btm_oldest_btpo_xact; /* oldest deleted page XID */<br>    float4      btm_last_cleanup_num_heap_tuples;<br>    bool        btm_allequalimage;    /* can dedup? */<br>} BTMetaPageData;</pre><p>btm_root / btm_fastroot: the meta page lets the system find the root without scanning from page 0. btm_fastroot is updated to skip deleted root pages from old splits; it converges to btm_root after a complete VACUUM.</p><p>The meta page is not in the standard page format (it does not have a valid pd_special); its data is stored in the “special space” area, directly after the fixed page header.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3758e6e0056f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Buffer Manager: Clock-Sweep Eviction and Pin Semantics]]></title>
            <link>https://medium.com/@lkumar94/building-a-buffer-manager-clock-sweep-eviction-and-pin-semantics-5834445f3696?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5834445f3696</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[buffer-management]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 15:26:14 GMT</pubDate>
            <atom:updated>2026-04-04T15:26:14.655Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL’s buffer manager (<a href="https://github.com/postgres/postgres/blob/master/src/backend/storage/buffer/README">src/backend/storage/buffer/</a>) is the layer between the rest of the system and disk. It maintains a fixed-size pool of 8 KB page slots in memory. Every read and write of a heap or index page goes through it. This post covers the data structures and the clock-sweep replacement algorithm.</p><h4><strong>Why a buffer pool?</strong></h4><p>Accessing a page means:</p><ol><li>Is it already in memory? If yes, use it (no I/O).</li><li>If not, find a slot (possibly evicting an existing page), read from disk, and serve it.</li></ol><p>PostgreSQL’s shared buffer pool defaults to 128 MB (shared_buffers). Every backend process shares the same pool via shared memory, which is why the system can serve many concurrent queries without each one reading independently from disk.</p><h4><strong>BufferTag: identifying a disk block</strong></h4><p>A page is uniquely identified by its storage location:</p><pre>typedef struct buftag {<br>    Oid         spcOid;      /* tablespace OID */<br>    Oid         dbOid;       /* database OID */<br>    RelFileNumber relNumber;  /* relation file number */<br>    ForkNumber  forkNum;      /* main / FSM / VM / init */<br>    BlockNumber blockNum;<br>} BufferTag;</pre><p>In our <a href="https://github.com/kumarlokesh/deep-postgres/blob/4405a4a891632ff062d9d1cdeaabfaab0d878f5d/internal/storage/buffer.go#L40">implementation</a> we simplify to (relation_id, fork, block_num), which is sufficient for single-database experiments:</p><pre>type BufferTag struct {<br>    RelationId Oid<br>    Fork       ForkNumber<br>    BlockNum   BlockNumber<br>}</pre><p>A hash map from BufferTag → BufferId gives O(1) lookup for cached pages.</p><h4><strong>ForkNumber</strong></h4><p>PostgreSQL stores a relation across up to four “forks” - separate physical files with the same base OID but different suffixes:</p><pre>| Fork     | Suffix  | Purpose                                        |<br>|----------|---------|------------------------------------------------|<br>| Main (0) | none    | table / index data                             |<br>| FSM (1)  | `_fsm`  | free space map                                 |<br>| VM (2)   | `_vm`   | visibility map (all-visible / all-frozen bits) |<br>| Init (3) | `_init` | unlogged table init fork                       |</pre><p>The FSM lets INSERT quickly find pages with enough free space. The VM accelerates sequential scans by skipping pages where all tuples are known-visible, and is required by VACUUM to set PD_ALL_VISIBLE.</p><h4><strong>BufferDesc</strong></h4><p>Each slot in the pool has a descriptor:</p><pre>type BufferDesc struct {<br>    Tag        BufferTag<br>    State      BufferStateFlags  // BM_VALID, BM_DIRTY, BM_IO_IN_PROGRESS<br>    refcount   atomic.Uint32     // pin count<br>    UsageCount uint8             // 0–5, used by clock sweep<br>}</pre><p><strong>Pin count</strong> (refcount): incremented when a backend starts using a buffer, decremented when done. A buffer with refcount &gt; 0 cannot be evicted. Every ReadBuffer returns a pinned buffer; the caller must call UnpinBuffer when finished. This is the primary safety mechanism: the buffer manager guarantees that a pinned page will not be evicted from under a caller.</p><p><strong>Usage count</strong>: a coarse approximation of recency. Set to maxUsageCount (5) on each access. The clock-sweep eviction algorithm decrements it before evicting, giving recently accessed pages multiple chances to survive.</p><p><strong>BM_DIRTY</strong>: set when a page is written via GetPageForWrite. Dirty pages must be written to disk before they can be reused. In our implementation, the write is simulated; a real smgr layer would call smgrwrite.</p><h4><strong>Clock-sweep eviction</strong></h4><p>PostgreSQL uses a simple clock (circular buffer hand) with usage counts. The full algorithm in StrategyGetBuffer (freelist.c):</p><pre>advance clock hand<br>if buffer is pinned → skip<br>if usage_count &gt; 0 → decrement and skip<br>if usage_count == 0 → evict this buffer</pre><p>The key property: a buffer with usage_count = 5 must be passed by the clock hand 5 times before it becomes a candidate. Hot pages that are accessed on every sweep will have their usage count refreshed before it reaches zero.</p><p>PostgreSQL caps usage_count at BM_MAX_USAGE_COUNT (5). There is no LRU list or per-page timestamp. The algorithm is O(1) per eviction attempt and requires no sorting or list operations.</p><p>Our Go implementation:</p><pre>func (p *BufferPool) allocateBuffer() (BufferId, error) {<br>    // Reject immediately if every slot is pinned.<br>    for i := range p.descriptors {<br>        if !p.descriptors[i].IsPinned() {<br>            goto sweep<br>        }<br>    }<br>    return InvalidBufferId, errBufferExhausted()<br><br>sweep:<br>    for {<br>        id := p.clockHand<br>        p.clockHand = (p.clockHand + 1) % p.numBuffers<br><br>        desc := &amp;p.descriptors[id]<br>        if desc.IsPinned() {<br>            continue<br>        }<br>        if desc.UsageCount &gt; 0 {<br>            desc.UsageCount--<br>            continue<br>        }<br>        return BufferId(id), nil<br>    }<br>}</pre><p>The pre-check (allPinned) prevents an infinite loop when every buffer is pinned. Without it, the sweep would spin forever. In PostgreSQL, this condition triggers the ERROR: no unpinned buffers available message (which is extremely rare in practice).</p><h4><strong>ReadBuffer semantics</strong></h4><pre>func (p *BufferPool) ReadBuffer(tag BufferTag) (BufferId, error) {<br>    if id, ok := p.tagMap[tag]; ok {<br>        // Already cached: increment pin and usage count.<br>        desc := &amp;p.descriptors[id]<br>        desc.Pin()<br>        desc.UsageCount = maxUsageCount<br>        return id, nil<br>    }<br>    // Allocate a new slot via clock sweep.<br>    id, err := p.allocateBuffer()<br>    // ... initialise tag, pin, page, add to tagMap<br>}</pre><p>When the page is already in the pool, no I/O occurs. The usage count is bumped to maxUsageCount - a fresh access makes the page “hot” again.</p><p>On a miss, the evicted slot’s old tag is removed from the hash map, the slot is initialised with the new tag, the page is read from disk (or initialised to empty in our implementation), and the slot is returned pinned.</p><h4><strong>The pin protocol</strong></h4><pre>// Acquire<br>id, err := pool.ReadBuffer(tag)<br>// Use<br>page, err := pool.GetPage(id)         // read-only<br>page, err := pool.GetPageForWrite(id) // marks dirty<br>// Release<br>pool.UnpinBuffer(id)</pre><p>GetPage enforces refcount &gt; 0. Attempting to access an unpinned buffer returns ErrBufferNotPinned. This mirrors PostgreSQL’s assertion BufferIsPinned(buf) that guards all BufferGetPage calls in production code.</p><p>GetPageForWrite sets BM_DIRTY in addition to returning the page. In PostgreSQL this corresponds to MarkBufferDirty(buf), which must be called before releasing the buffer lock after any modification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5834445f3696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heap Tuples and MVCC Headers: How PostgreSQL Tracks Transaction Visibility]]></title>
            <link>https://medium.com/@lkumar94/heap-tuples-and-mvcc-headers-how-postgresql-tracks-transaction-visibility-2442ca05f8b8?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2442ca05f8b8</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mvcc]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 16:00:37 GMT</pubDate>
            <atom:updated>2026-04-04T15:28:53.480Z</atom:updated>
            <content:encoded><![CDATA[<p>Every row stored in a PostgreSQL heap has a 23-byte (padded to 24) header prepended to its attribute data. This header carries the MVCC bookkeeping that makes snapshot isolation possible without read locks. This post breaks down the structure field by field.</p><h4><strong>The HeapTupleHeader layout</strong></h4><p>From <a href="https://github.com/postgres/postgres/blob/master/src/include/access/htup_details.h">src/include/access/htup_details.h</a>:</p><pre>typedef struct HeapTupleHeaderData {<br>    union {<br>        HeapTupleFields  t_heap;   /* normal tuple: xmin, xmax, cid */<br>        DatumTupleFields t_datum;  /* composite type: varlena header */<br>    } t_choice;<br><br>    ItemPointerData t_ctid;        /* 6 bytes: self or newer TID */<br><br>    uint16  t_infomask2;           /* natts (low 11 bits) + flags */<br>    uint16  t_infomask;            /* MVCC flags */<br>    uint8   t_hoff;                /* offset to user data */<br>    /* ^ 23 bytes ^ */<br>    bits8   t_bits[FLEXIBLE_ARRAY_MEMBER]; /* null bitmap */<br>} HeapTupleHeaderData;</pre><p>For the common case (heap tuple, not a composite datum), t_choice expands to:</p><pre>typedef struct HeapTupleFields {<br>    TransactionId t_xmin;  /* inserting XID */<br>    TransactionId t_xmax;  /* deleting XID, or 0 */<br>    union {<br>        CommandId   t_cid; /* command ID, or combo CID */<br>        TransactionId t_xvac; /* VACUUM XID (old pre-9.0 path) */<br>    } t_field3;<br>} HeapTupleFields;</pre><p>Adding up: t_xmin (4) + t_xmax (4) + t_cid (4) + t_ctid (4+2) + t_infomask2 (2) + t_infomask (2) + t_hoff (1) + 1 byte padding = 24 bytes.</p><h4><strong>MVCC fields</strong></h4><p><strong>xmin</strong></p><p>The transaction ID that inserted this tuple version. A tuple is visible only if xmin has committed and the committing transaction is visible to the reader’s snapshot.</p><p>Special cases:</p><ul><li>FrozenTransactionId (2): always committed, always visible. VACUUM ages tuples by rewriting xmin to 2 to prevent XID wrap-around failures.</li><li>InvalidTransactionId (0): tuple was never properly inserted; ignore it.</li></ul><p><strong>xmax</strong></p><p>The XID that deleted or updated this tuple, or 0 if the tuple is live. When a row is updated, PostgreSQL creates a new tuple version and sets xmax on the old one to the updating transaction’s XID. The new version’s xmin is the same XID.</p><p>A tuple is deleted (invisible) when xmax is committed and visible to the reader’s snapshot.</p><p><strong>t_cid</strong></p><p>The command ID within the inserting transaction. PostgreSQL assigns a monotonically increasing CID to each statement within a transaction. This is used for intra-transaction visibility: a tuple inserted by command 3 is not visible to a scan running as command 3 (same CID → invisible), but is visible to command 4.</p><p><strong>t_ctid</strong></p><p>The current TID (tuple identifier = block number + offset) for this tuple or its successor. On insert, t_ctid points to itself. On update, the old tuple’s t_ctid is updated to point to the new version, forming a version chain (HOT or otherwise). This enables an index scan to follow the chain without consulting the heap multiple times.</p><h4><strong>Infomask flags (t_infomask)</strong></h4><p>t_infomask is a 16-bit field encoding the tuple’s known state. The MVCC-critical bits:</p><pre>|     Constant        | Value  |          Meaning                      |<br>|---------------------|--------|---------------------------------------|<br>| HEAP_XMIN_COMMITTED | 0x0100 | xmin is known committed (hint bit)    |<br>| HEAP_XMIN_INVALID   | 0x0200 | xmin is known aborted (hint bit)      |<br>| HEAP_XMAX_COMMITTED | 0x0400 | xmax is known committed (hint bit)    |<br>| HEAP_XMAX_INVALID   | 0x0800 | xmax is invalid / xact aborted        |<br>| HEAP_XMAX_LOCK_ONLY | 0x0080 | xmax is a row locker, not a deleter   |<br>| HEAP_COMBOCID       | 0x0020 | t_cid is a combo CID (from subxact)   |<br>| HEAP_UPDATED        | 0x2000 | tuple was updated (not just inserted) |</pre><p>The four “hint bits” (XMIN_COMMITTED, XMIN_INVALID, XMAX_COMMITTED, XMAX_INVALID) are a performance optimisation. Without them, every visibility check requires a clog (pg_xact) lookup for each XID. With them, once the status of a transaction is known, it is cached directly in the tuple header. Any backend that performs a visibility check can set hint bits; they are write-once (committed stays committed) and do not require WAL logging.</p><h4><strong>t_infomask2</strong></h4><p>The low 11 bits hold the number of attributes (natts), allowing up to 1600. The high 5 bits are flags:</p><pre>|   Constant       |  Value |      Meaning                            |<br>|------------------|--------|-----------------------------------------|<br>| HEAP_HOT_UPDATED | 0x4000 | this tuple was updated via HOT          |<br>| HEAP_ONLY_TUPLE  | 0x8000 | this is a heap-only (HOT) tuple version |</pre><p>HOT (Heap-Only Tuples) is a critical optimisation: when an updated column is not part of any index, PostgreSQL can create the new version on the same page without updating any index. The old tuple’s t_ctid points to the new version; the HEAP_HOT_UPDATED flag marks the old tuple, and HEAP_ONLY_TUPLE marks the new one. Index scans that reach the old version follow the chain within the page.</p><h4><strong>t_hoff: variable-length header</strong></h4><p>t_hoff stores the byte offset from the start of the HeapTupleHeader to the first attribute. It equals sizeof(HeapTupleHeaderData) (24 bytes) when there are no null attributes. If any attribute is NULL, a null bitmap follows the fixed header at byte 24; t_hoff is then rounded up to MAXALIGN (8 bytes) past the bitmap.</p><h4><strong>Serialisation in Go</strong></h4><p>PostgreSQL’s C code accesses the header via direct pointer casts ((HeapTupleHeader)ptr), which works because the struct is #[repr(C)]-equivalent. In Go, we serialise explicitly:</p><pre>func encodeHeapTupleHeader(dst []byte, h *HeapTupleHeader) {<br>    binary.LittleEndian.PutUint32(dst[0:],  h.TXmin)<br>    binary.LittleEndian.PutUint32(dst[4:],  h.TXmax)<br>    binary.LittleEndian.PutUint32(dst[8:],  h.TCid)<br>    binary.LittleEndian.PutUint32(dst[12:], h.TCtidBlock)<br>    binary.LittleEndian.PutUint16(dst[16:], h.TCtidOffset)<br>    binary.LittleEndian.PutUint16(dst[18:], h.TInfomask2)<br>    binary.LittleEndian.PutUint16(dst[20:], h.TInfomask)<br>    dst[22] = h.THoff<br>    dst[23] = 0 // padding<br>}</pre><h4><strong>The HeapTuple wrapper</strong></h4><p>A HeapTuple pairs the header with the variable-length data payload (null bitmap + attribute values):</p><pre>type HeapTuple struct {<br>    Header HeapTupleHeader<br>    Data   []byte<br>}<br><br>func (t *HeapTuple) ToBytes() []byte {<br>    buf := make([]byte, HeapTupleHeaderSize+len(t.Data))<br>    encodeHeapTupleHeader(buf[:HeapTupleHeaderSize], &amp;t.Header)<br>    copy(buf[HeapTupleHeaderSize:], t.Data)<br>    return buf<br>}</pre><p>The serialised form is what Page.InsertTuple receives - the page layer is agnostic to tuple content and treats everything as opaque bytes. This clean separation mirrors PostgreSQL’s heapam.c / bufpage.h layering.</p><h4><strong>Key invariants</strong></h4><ul><li>A newly inserted tuple has xmax = 0 and HEAP_XMAX_INVALID set.</li><li>HEAP_XMIN_COMMITTED and HEAP_XMIN_INVALID are mutually exclusive.</li><li>Same for HEAP_XMAX_COMMITTED and HEAP_XMAX_INVALID.</li><li>Hint bits can only be set, never cleared (monotone transitions). This means a heap scan that sets a hint bit is safe without a WAL record - the page will be re-read and re-set if it is recovered from an older version.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2442ca05f8b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Page Layout: Rebuilding the 8 KB Heap Page in Go]]></title>
            <link>https://medium.com/@lkumar94/postgresql-page-layout-rebuilding-the-8-kb-heap-page-in-go-4bd982b3e029?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bd982b3e029</guid>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 22:48:54 GMT</pubDate>
            <atom:updated>2026-04-04T15:30:09.136Z</atom:updated>
            <content:encoded><![CDATA[<p>Every table and index in PostgreSQL is stored as a sequence of 8 KB pages on disk. The format is defined in <a href="https://github.com/postgres/postgres/blob/master/src/include/storage/bufpage.h"><em>src/include/storage/bufpage.h</em></a> and has been stable since PostgreSQL 8. This post walks through that layout in detail and shows how to reproduce it faithfully in Go.</p><h4><strong>The physical layout</strong></h4><pre><br>+----------------+-----------+----------------+-----------+<br>| PageHeaderData | ItemIdData| ... free space | tuples... |<br>| (24 bytes)     | array     |                | grow down |<br>+----------------+-----------+----------------+-----------+<br>^                ^           ^                ^           ^<br>0            pd_lower    pd_upper         pd_special   8192</pre><p><strong>PageHeaderData</strong> occupies the first 24 bytes. After it, a growing array of 4-byte <strong>line pointers</strong> (ItemIdData) extends upward. Tuple data is packed downward from pd_special (or the end of the page for heap pages). The <strong>free space</strong> is whatever sits between pd_upper and pd_lower: line pointers grow up from pd_lower, tuple data grows down from pd_upper, and the gap between them is available for new data.</p><h4><strong>PageHeaderData: 24 bytes</strong></h4><p>The C definition (bufpage.h):</p><pre>typedef struct PageHeaderData {<br>    PageXLogRecPtr pd_lsn;       /* 8 bytes: high + low uint32 */<br>    uint16         pd_checksum;<br>    uint16         pd_flags;<br>    LocationIndex  pd_lower;     /* offset to start of free space */<br>    LocationIndex  pd_upper;     /* offset to end of free space   */<br>    LocationIndex  pd_special;   /* offset to start of special space */<br>    uint16         pd_pagesize_version;<br>    TransactionId  pd_prune_xid;<br>} PageHeaderData;               /* total: 24 bytes */</pre><p>Sizes: 4+4+2+2+2+2+2+2+4 = 24. The LSN is stored as two uint32 fields because C bitfield semantics vary across compilers; two explicit integers are portable.</p><p>pd_pagesize_version encodes two fields: the high byte is page_size / 256 and the low byte is the layout version number (currently 4 for PostgreSQL 16.x). An 8 KB page encodes as 0x2004.</p><p>In Go, there is no bytemuck or #[repr(C)]. We use encoding/binary and explicit serialisation:</p><pre>type PageHeaderData struct {<br>    PdLsnHi           uint32<br>    PdLsnLo           uint32<br>    PdChecksum        uint16<br>    PdFlags           uint16<br>    PdLower           uint16<br>    PdUpper           uint16<br>    PdSpecial         uint16<br>    PdPagesizeVersion uint16<br>    PdPruneXid        uint32<br>}<br><br>func encodeHeader(dst []byte, h *PageHeaderData) {<br>    binary.LittleEndian.PutUint32(dst[0:], h.PdLsnHi)<br>    binary.LittleEndian.PutUint32(dst[4:], h.PdLsnLo)<br>    binary.LittleEndian.PutUint16(dst[8:], h.PdChecksum)<br>    // ... 24 bytes total<br>}</pre><p>The choice of LittleEndian matches x86/ARM64 host byte order where Postgres typically runs. A real implementation would detect and match host byte order; for research purposes, little-endian is a reasonable constant.</p><h4><strong>ItemIdData: 4-byte bit field</strong></h4><p>Every tuple on the page is referenced by a <strong>line pointer</strong> (ItemIdData) in the header region. The C definition packs three fields into 32 bits:</p><pre>typedef struct ItemIdData {<br>    unsigned lp_off:15,   /* offset to tuple from page start */<br>             lp_flags:2,  /* LP_UNUSED / LP_NORMAL / LP_REDIRECT / LP_DEAD */<br>             lp_len:15;   /* byte length of tuple */<br>} ItemIdData;             /* 4 bytes */</pre><p>Bit layout (LSB to MSB):</p><ul><li>bits 0–14: lp_off (offset, up to 32767)</li><li>bits 15–16: lp_flags (2-bit state)</li><li>bits 17–31: lp_len (length, up to 32767)</li></ul><p>Go has no bit fields. We store ItemIdData as a uint32 and manually pack/unpack:</p><pre>type ItemIdData uint32<br><br>const (<br>    lpOffMask    = uint32(0x7FFF)<br>    lpFlagsShift = uint32(15)<br>    lpLenShift   = uint32(17)<br>    lpLenMask    = uint32(0x7FFF)<br>)<br><br>func NewItemId(offset, length uint16) ItemIdData {<br>    off   := uint32(offset) &amp; lpOffMask<br>    flags := uint32(LpNormal) &lt;&lt; lpFlagsShift<br>    ln    := (uint32(length) &amp; lpLenMask) &lt;&lt; lpLenShift<br>    return ItemIdData(off | flags | ln)<br>}<br><br>func (i ItemIdData) Off() uint16  { return uint16(uint32(i) &amp; lpOffMask) }<br>func (i ItemIdData) Len() uint16  { return uint16((uint32(i) &gt;&gt; lpLenShift) &amp; lpLenMask) }</pre><h4><strong>Inserting a tuple</strong></h4><p>INSERT in PostgreSQL’s heap AM (heap_insert, <a href="https://github.com/postgres/postgres/blob/master/src/backend/access/heap/heapam.c"><em>src/backend/access/heap/heapam.c</em></a>) does the following to lay a tuple on a page:</p><ol><li>Compute required space: tuple_size + sizeof(ItemIdData).</li><li>Check pd_upper - pd_lower &gt;= required.</li><li>Decrement pd_upper by tuple_size, write data there.</li><li>Write a new ItemIdData at pd_lower, increment pd_lower by 4.</li></ol><p>In Go:</p><pre>func (p *Page) InsertTuple(tupleData []byte) (int, error) {<br>    tupleLen := len(tupleData)<br>    required := tupleLen + ItemIdSize<br>    if p.FreeSpace() &lt; required {<br>        return 0, errPageFull(required, p.FreeSpace())<br>    }<br><br>    h := p.Header()<br>    newUpper  := int(h.PdUpper) - tupleLen<br>    itemIndex := h.ItemCount()<br><br>    copy(p.data[newUpper:], tupleData)<br><br>    lp := NewItemId(uint16(newUpper), uint16(tupleLen))<br>    encodeItemId(p.data[itemIdOffset(itemIndex):], lp)<br><br>    h.PdUpper  = uint16(newUpper)<br>    h.PdLower += uint16(ItemIdSize)<br>    p.setHeader(h)<br><br>    return itemIndex, nil<br>}</pre><p>The invariant pd_lower &lt;= pd_upper always holds; free space is zero when they are equal.</p><h4><strong>Page flags and special space</strong></h4><p>pd_flags carries three bits currently:</p><pre>| Flag                | Value  | Meaning                                                     |<br>|---------------------|--------|-------------------------------------------------------------|<br>| `PD_HAS_FREE_LINES` | 0x0001 | Page has LP_DEAD or LP_UNUSED slots reusable without vacuum |<br>| `PD_PAGE_FULL`      | 0x0002 | No free space for new tuples                                |<br>| `PD_ALL_VISIBLE`    | 0x0004 | All tuples visible to all active transactions               |</pre><p>pd_special points to the start of any index-specific opaque data at the end of the page. For heap pages it equals PageSize (no special space). For B-tree pages, 16 bytes are reserved there for BTPageOpaqueData. This is why pd_upper is initialised to pd_special, not PageSize, when a B-tree page is created.</p><h4><strong>Validation</strong></h4><p>On reading a page from disk, PostgreSQL’s PageIsValid and related checks verify:</p><ul><li>pd_lower &gt;= sizeof(PageHeaderData) (line pointer area not below header)</li><li>pd_upper &lt;= pd_special (tuple region doesn’t overlap special space)</li><li>pd_special &lt;= PAGE_SIZE</li><li>pd_lower &lt;= pd_upper (free space is non-negative)</li><li>Encoded page size in pd_pagesize_version matches PAGE_SIZE</li></ul><p>These are cheap assertions that catch storage corruption early.</p><h4><strong>What we built</strong></h4><p>The Page type in <a href="https://github.com/kumarlokesh/deep-postgres/blob/main/internal/storage/page.go"><em>internal/storage/page.go</em></a> implements all of the above: byte-accurate header encoding, bit-packed line pointers, insert-with-free-space-tracking, and validation. Tests verify the layout down to individual byte offsets and confirm that inserting until ErrPageFull leaves pd_lower == pd_upper.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bd982b3e029" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Computational Complexity of Topic Exchanges in RabbitMQ: Benchmarks, Pathologies, and Design…]]></title>
            <link>https://medium.com/@lkumar94/the-computational-complexity-of-topic-exchanges-in-rabbitmq-benchmarks-pathologies-and-design-467dd1e3387a?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/467dd1e3387a</guid>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 22:14:03 GMT</pubDate>
            <atom:updated>2026-03-03T22:14:03.346Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Computational Complexity of Topic Exchanges in RabbitMQ: Benchmarks, Pathologies, and Design Strategies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZiDtTkBiIevAuZ6NrKLWg.png" /></figure><p>Most performance discussions around RabbitMQ focus on disk throughput, consumer lag, or clustering. Far fewer examine the computational cost of routing itself.</p><p>In systems that rely heavily on topic exchanges, routing frequently becomes the dominant CPU cost long before disk or network saturation. This article examines topic exchanges as a pattern-matching engine, derives their computational properties, identifies pathological cases, and proposes architectural strategies to control complexity.</p><p>The goal is not to restate documentation. It is to provide a mental model that predicts scaling behavior.</p><h4>Topic Exchange Routing Is Pattern Matching Over a Binding Set</h4><p>A topic exchange routes messages by matching a routing key against binding patterns that may contain:</p><ul><li>* - matches exactly one word</li><li># - matches zero or more words</li></ul><p>Routing keys are dot-separated tokens. A binding such as:</p><pre>logs.error.*</pre><p>is effectively a predicate over token sequences.</p><p>At publish time, RabbitMQ must evaluate the routing key against every binding attached to the exchange. Conceptually:</p><pre>for binding in exchange.bindings:<br>    if match(binding.pattern, routing_key):<br>        route(message, binding.destination)</pre><p>This implies that routing complexity is at least:</p><pre>O(B × M)</pre><p>Where:</p><ul><li>B = number of bindings</li><li>M = cost of pattern evaluation</li></ul><p>The cost of M depends on token length and wildcard structure.</p><p>This is not an indexed lookup. It is a predicate evaluation loop.</p><h4>Direct vs Topic: Why Topic Is Strictly More Expensive</h4><p>Direct exchanges perform equality comparison:</p><pre>binding_key == routing_key</pre><p>This is constant time per binding.</p><p>Topic exchanges require tokenization and wildcard evaluation. Even when implemented efficiently, wildcard matching introduces branching and backtracking for #.</p><p>Therefore:</p><ul><li>Direct: O(B)</li><li>Topic: O(B × T)</li></ul><p>Where T is proportional to token count and wildcard branching complexity.</p><p>At small scale, the difference is negligible.</p><p>At 10,000+ bindings, it becomes measurable.</p><h4>Empirical Observations Under High Binding Cardinality</h4><p>In synthetic benchmarks where:</p><ul><li>5,000-20,000 bindings exist</li><li>Routing keys average 5-8 tokens</li><li>Binding patterns include mixed * and #</li></ul><p>We observe:</p><ol><li>Publish latency increases linearly with binding count.</li><li>CPU utilization scales with publish rate × binding count.</li><li>Wildcard-heavy patterns degrade performance disproportionately.</li></ol><p>The worst case occurs when:</p><ul><li>Many bindings contain #</li><li>Routing keys match large portions of the binding space</li><li>Overlapping patterns produce large routing sets</li></ul><p>In such cases, routing cost grows not only due to predicate evaluation but also due to increased downstream queue enqueues.</p><p>Topic exchanges are therefore susceptible to both evaluation amplification and fanout amplification.</p><h4>Pathological Pattern: Overlapping Wildcards</h4><p>Consider the following bindings:</p><pre>metrics.#<br>metrics.*.cpu<br>metrics.us.*.#<br>metrics.us.east.*</pre><p>A routing key:</p><pre>metrics.us.east.cpu</pre><p>matches all four bindings.</p><p>If 5,000 bindings follow similar overlapping schemes, a single publish may match hundreds or thousands of queues.</p><p>This is not a misconfiguration. It is a predictable consequence of independent predicate evaluation.</p><p>The pathological pattern emerges when:</p><ul><li>Bindings are not mutually exclusive</li><li>Wildcards are used liberally</li><li>Tenants or services encode hierarchy inconsistently</li></ul><p>The system becomes a combinatorial matcher rather than a router.</p><h4>Memory and CPU Implications</h4><p>Routing state is held in memory. Every binding consumes memory for:</p><ul><li>Pattern representation</li><li>Destination reference</li><li>Exchange metadata linkage</li></ul><p>High binding cardinality increases memory footprint linearly.</p><p>CPU cost scales with:</p><pre>publish_rate × binding_count × match_cost</pre><p>When publish rate increases, CPU increases proportionally. When binding count increases, CPU increases proportionally.</p><p>This is why scaling publishers and scaling tenants simultaneously often produces nonlinear performance degradation.</p><p>The multiplicative interaction is frequently underestimated.</p><h4>Exchange-to-Exchange Topologies Multiply Complexity</h4><p>When topic exchanges are chained:</p><pre>Exchange A → Exchange B → Queue</pre><p>Routing becomes multi-stage.</p><p>Each stage evaluates its own binding set.</p><p>Total cost approximates:</p><pre>Σ over stages (B_i × M_i)</pre><p>Deep routing graphs can therefore multiply routing latency even when individual exchanges appear manageable.</p><p>This is especially problematic in systems that use exchange chaining for logical separation without considering computational cost.</p><h4>Why Indexing Is Not a Silver Bullet</h4><p>A natural question is whether RabbitMQ could index bindings to reduce complexity.</p><p>In theory, a trie-based structure could reduce matching cost for prefix patterns. However:</p><ol><li># introduces unbounded wildcard depth.</li><li>Bindings are mutable at runtime.</li><li>Exchange-to-exchange routing introduces dynamic graph traversal.</li><li>Backward compatibility constraints limit radical internal redesign.</li></ol><p>Pattern matching with arbitrary wildcard placement resists constant-time indexing without significant memory tradeoffs.</p><p>Topic routing is fundamentally more complex than direct routing.</p><h4>Strategies to Control Complexity</h4><p>The solution is architectural discipline, not tuning flags.</p><h4>1. Partition Binding Space Across Exchanges</h4><p>Instead of 20,000 bindings on one exchange, use:</p><ul><li>20 exchanges with 1,000 bindings each</li></ul><p>Publishers select exchange based on coarse partition key (tenant, domain, region).</p><p>This reduces B per publish.</p><h4>2. Avoid Unbounded # Usage</h4><p>Prefer explicit hierarchy depth.</p><p>Instead of:</p><pre>metrics.#</pre><p>Use:</p><pre>metrics.system.*<br>metrics.app.*</pre><p>Reducing wildcard breadth limits match amplification.</p><h4>3. Enforce Binding Mutual Exclusivity</h4><p>Design binding patterns such that:</p><ul><li>Each routing key matches a bounded number of bindings</li><li>Overlap is intentional and minimal</li></ul><p>This transforms routing from combinatorial to predictable.</p><h4>4. Measure Routing Cost Explicitly</h4><p>Using tools like <a href="https://github.com/kumarlokesh/amqp-routing-inspector"><strong>amqp-routing-inspector</strong></a>, instrument publish paths to measure:</p><ul><li>Routing latency</li><li>Match count per publish</li><li>Binding cardinality</li></ul><p>If match count grows unexpectedly, topology has drifted.</p><h4>5. Prefer Direct Exchanges When Possible</h4><p>If routing semantics do not require wildcard flexibility, direct exchanges provide:</p><ul><li>Simpler mental model</li><li>Lower CPU cost</li><li>More predictable scaling</li></ul><p>Topic exchanges should be justified, not defaulted.</p><h4>Topic Exchanges Are a Computational Contract</h4><p>Using topic exchanges implicitly commits the system to:</p><ul><li>Linear binding evaluation</li><li>Wildcard predicate cost</li><li>Potential match amplification</li></ul><p>These costs scale with system growth.</p><p>At small scale, they are invisible.</p><p>At large scale, they dominate.</p><p>Understanding this contract allows you to predict failure modes before they manifest.</p><h4>Conclusion</h4><p>Topic exchanges are powerful because they encode routing logic declaratively. That power has computational consequences.</p><p>Routing is not free. It is a pattern-matching workload whose complexity grows with binding cardinality and wildcard structure.</p><p>Engineers who treat topic exchanges as an abstraction will eventually encounter scaling surprises. Engineers who treat them as a computational engine can design systems that scale predictably.</p><p>The difference is mental model fidelity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467dd1e3387a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RabbitMQ Routing Is a Binding Evaluation Engine: A Protocol-Level Examination]]></title>
            <link>https://medium.com/@lkumar94/rabbitmq-routing-is-a-binding-evaluation-engine-a-protocol-level-examination-7a25e505ed88?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a25e505ed88</guid>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 21:15:27 GMT</pubDate>
            <atom:updated>2026-02-24T21:15:27.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqQYeZ9MNaFDhJcDEWviwA.png" /></figure><p>RabbitMQ is typically introduced as a message broker consisting of producers, exchanges, queues, and consumers. In most architectural discussions, exchanges are described as simple routing components that forward messages to queues based on routing keys and bindings. This description is directionally correct but omits the operational and computational characteristics that emerge under realistic workloads.</p><p>After instrumenting routing behavior at the protocol level using <a href="https://github.com/kumarlokesh/amqp-routing-inspector"><strong>amqp-routing-inspector</strong></a>, it becomes clear that RabbitMQ routing is fundamentally a binding evaluation engine whose performance and correctness properties depend directly on binding cardinality, exchange topology, and metadata propagation semantics. These characteristics have material implications for scalability, latency, and failure behavior, and are often the underlying cause of production issues attributed more generically to “RabbitMQ performance.”</p><p>This article examines RabbitMQ routing from the perspective of its internal evaluation model rather than its conceptual abstraction.</p><h4>Routing Is a Linear Predicate Evaluation Problem</h4><p>At publish time, RabbitMQ performs routing by evaluating the message’s routing key against the set of bindings attached to the target exchange. Each binding defines a predicate: a condition under which the message should be routed to a destination queue or downstream exchange.</p><p>Conceptually, routing can be approximated as:</p><pre>for binding in exchange.bindings:<br>    if binding.matches(message.routing_key):<br>        route(message, binding.destination)</pre><p>This evaluation is performed synchronously as part of message ingress. There is no indexing structure that reduces routing to constant-time lookup in the general case, particularly for topic exchanges where wildcard matching is required. As a result, routing latency increases with the number of bindings associated with the exchange.</p><p>This behavior is not apparent in small systems, where exchanges may have tens of bindings. However, in systems with thousands or tens of thousands of bindings - common in multi-tenant or dynamically provisioned environments - routing latency becomes measurable and can dominate publish-side CPU usage.</p><p>Empirically, routing traces show that routing time increases approximately linearly with binding count, with additional overhead introduced by wildcard pattern matching in topic exchanges. This establishes routing as a CPU-bound operation under high binding cardinality, rather than an I/O-bound one.</p><p>This has direct architectural implications: exchange design determines routing scalability.</p><h4>Routing Produces the Union of All Matching Bindings</h4><p>RabbitMQ does not attempt to resolve a single “best match” among bindings. Instead, routing produces the set-theoretic union of all bindings whose predicates evaluate to true.</p><p>For example, given the following bindings on a topic exchange:</p><pre>logs.*<br>logs.error<br>logs.#</pre><p>and a message published with routing key:</p><pre>logs.error</pre><p>all three bindings match, and the message is routed to all corresponding destinations.</p><p>This behavior is correct according to AMQP semantics but often contradicts implicit assumptions that more specific bindings override or supersede more general ones. RabbitMQ does not implement routing precedence or specificity ranking; bindings are independent predicates. As a result, overlapping binding patterns can easily produce unintended duplicate deliveries.</p><p>From a systems perspective, this means RabbitMQ routing is equivalent to evaluating a set of independent routing predicates and emitting the union of their outputs, rather than performing hierarchical dispatch.</p><h4>Routing Cost and Complexity Depend on Exchange Type</h4><p>Exchange type determines predicate complexity.</p><p>Direct exchanges perform equality comparison between routing key and binding key. Topic exchanges perform wildcard pattern matching, which requires tokenizing routing keys and evaluating wildcard operators such as * and #. Fanout exchanges bypass predicate evaluation entirely and route to all bindings unconditionally.</p><p>Topic exchanges therefore impose strictly greater computational overhead per binding than direct exchanges. At large binding counts, this difference becomes significant.</p><p>This explains why systems with heavy use of topic exchanges often encounter broker CPU saturation even when message rates are modest relative to hardware capacity. The limiting factor is predicate evaluation throughput, not message persistence or network transfer.</p><p>Exchange selection should therefore be considered a performance-critical architectural decision rather than a purely semantic one.</p><h4>Routing Is Atomic With Respect to Local Metadata, Not Global Cluster State</h4><p>RabbitMQ clusters replicate metadata such as exchanges, queues, and bindings across nodes. However, this replication is asynchronous. Each node maintains its own in-memory representation of routing metadata, which is updated as cluster changes propagate.</p><p>Routing decisions are made against the metadata available locally on the node that receives the publish.</p><p>This creates a window during which routing behavior can differ between nodes.</p><p>For example, if a new binding is created on node A, and a publisher sends a message to node B before the binding has propagated, node B will route the message according to its current metadata, which does not include the new binding.</p><p>This is not a violation of RabbitMQ’s guarantees. RabbitMQ does not provide linearizable routing semantics across cluster nodes. Routing consistency is bounded by metadata propagation latency.</p><p>This behavior is an inherent consequence of distributing routing state.</p><p>Architecturally, this means RabbitMQ routing must be treated as eventually consistent at cluster scale.</p><h4>Routing and Persistence Are Separate Phases</h4><p>Routing determines which queues should receive the message. Persistence determines whether the message survives broker failure.</p><p>Routing occurs before persistence completes. After routing decisions are made, messages are enqueued to target queues and persistence operations are initiated according to queue durability and message persistence settings.</p><p>Publisher confirms are issued when the broker determines that the message has reached a state consistent with the confirm mode being used.</p><p>This sequencing means routing success does not imply durable persistence. A message may be routed successfully but lost if the broker fails before persistence completes.</p><p>Routing and durability are orthogonal concerns.</p><h4>Exchange-to-Exchange Bindings Introduce Multi-Hop Routing</h4><p>RabbitMQ supports bindings between exchanges, allowing messages to traverse multiple exchanges before reaching queues.</p><p>This transforms routing from a single-stage predicate evaluation into a graph traversal problem, where exchanges and queues form nodes and bindings form directed edges.</p><p>Routing latency in such topologies accumulates across traversal steps. Each exchange evaluates its own bindings and forwards matching messages downstream.</p><p>Complex routing graphs can therefore introduce significant routing overhead, particularly when combined with high binding cardinality.</p><p>This graph structure also complicates reasoning about routing behavior, since the set of reachable queues is determined by transitive closure over exchange bindings.</p><h4>Routing Guarantees Ordering Only Within Individual Queues</h4><p>RabbitMQ preserves message order within a queue, but makes no ordering guarantees across queues.</p><p>When a message is routed to multiple queues, each queue receives the message in publish order relative to other messages routed to that queue. However, differences in consumer speed, prefetch settings, and scheduling can cause messages to be observed in different orders across queues.</p><p>This distinction is often misunderstood when RabbitMQ is used as a broadcast mechanism.</p><p>Routing does not provide global ordering.</p><p>Ordering is a queue-local property.</p><h4>Routing Is the Dominant CPU Cost in Many RabbitMQ Deployments</h4><p>At moderate scale, disk and network I/O are often assumed to be the primary performance constraints in message brokers. However, routing predicate evaluation frequently becomes the dominant CPU cost before these limits are reached.</p><p>This is especially true in systems with:</p><ul><li>high binding cardinality</li><li>heavy use of topic exchanges</li><li>complex exchange-to-exchange routing graphs</li></ul><p>In such systems, reducing binding count or simplifying routing topology can produce greater performance improvements than hardware upgrades.</p><p>Routing complexity is therefore a first-order scalability parameter.</p><h4>Implications for System Design</h4><p>Several practical conclusions follow from this analysis.</p><p>Exchange topology should be designed to limit binding cardinality per exchange. Distributing bindings across multiple exchanges can reduce routing cost.</p><p>Topic exchanges should be used selectively, and wildcard patterns should be designed carefully to avoid excessive overlap.</p><p>Systems should tolerate routing inconsistency during cluster topology changes, since routing metadata propagation is not instantaneous.</p><p>Routing should be considered part of the system’s computational workload and monitored accordingly.</p><p>These considerations are rarely emphasized in RabbitMQ introductions but are essential for operating RabbitMQ reliably at scale.</p><h4>Conclusion</h4><p>RabbitMQ routing is not simply a logical abstraction for directing messages. It is a concrete computational process whose performance and correctness depend on binding structure, exchange topology, and metadata distribution.</p><p>Understanding RabbitMQ as a binding evaluation engine rather than a conceptual routing box provides a more accurate mental model of its behavior under load and failure.</p><p>This mental model makes routing behavior predictable, and predictability is the foundation of reliable distributed systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a25e505ed88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built amqp-routing-inspector: A RabbitMQ Routing Debugging Tool]]></title>
            <link>https://medium.com/@lkumar94/how-i-built-amqp-routing-inspector-a-rabbitmq-routing-debugging-tool-23cb991d61fe?source=rss-286bb504ad6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/23cb991d61fe</guid>
            <category><![CDATA[amqp]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Lokesh]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 21:50:51 GMT</pubDate>
            <atom:updated>2026-02-20T21:50:51.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6-pvCFDytKaNWoOzkjHsg.png" /></figure><h3>Introduction</h3><p>RabbitMQ’s core abstraction - exchanges, bindings and queues - is simple in concept but surprisingly opaque in practice. Developers and operators often struggle to answer basic questions like:</p><ul><li><em>“Why did this message land in queue X instead of Y?”</em></li><li><em>“Is my topic binding behaving as expected?”</em></li><li><em>“Why am I seeing duplicates even though queue depths look normal?”</em></li></ul><p>Typical metrics (queue depths, consumer rates) only tell part of the story. To <em>really</em> understand routing behavior you need visibility at the <strong>protocol level</strong> - right when messages traverse the broker’s routing logic.</p><p>That’s why I built <a href="https://github.com/kumarlokesh/amqp-routing-inspector"><strong>amqp-routing-inspector</strong></a>: a CLI tool that consumes RabbitMQ <strong>firehose/tracing events</strong> and surfaces routing decisions in <strong>human-readable, JSON, and graph formats</strong>. You can trace routing paths, build visual routing graphs, and reason about bindings with confidence.</p><h3>What amqp-routing-inspector Does</h3><p>At a high level, this tool:</p><ul><li>Connects resiliently to RabbitMQ using AMQP</li><li>Subscribes to the <strong>firehose/tracing exchange</strong> to capture real routing events</li><li>Parses event metadata like exchanges, routing keys, and matched destinations</li><li>Outputs results in three modes:</li><li><strong>CLI</strong> - line-by-line human output</li><li><strong>JSON -</strong> structured, machine-friendly records</li><li><strong>DOT</strong> - Graphviz graph format for visualization</li></ul><p>This provides a level of introspection that traditional metrics and dashboards don’t offer.</p><h3>Why This Matters</h3><p>RabbitMQ is widely used but most production observability focuses on high-level metrics. Routing - especially with complex topic patterns - is a frequent source of confusion and bugs. Typical scenarios include:</p><ul><li>Misconfigured binding keys</li><li>Unexpected queue selections with topic exchanges</li><li>Multiple bindings causing duplication</li><li>Silent routing failures</li></ul><p>Because amqp-routing-inspector taps into the <strong>firehose</strong> (RabbitMQ’s internal routing trace mechanism), it <em>reveals what the broker actually does</em> - not just what you think it does.</p><h3>How It Works</h3><p>The core logic is composed of:</p><p><strong>1. Resilient Connection Manager</strong><br>Handles automatic reconnects and backoff to maintain continuous tracing even if the broker restarts.</p><p><strong>2. Firehose Consumer</strong><br>Subscribes to the broker’s amq.rabbitmq.trace exchange (or configured alternative) and captures routing events at wire-level precision.</p><p><strong>3. Routing Event Parser</strong><br> Extracts:</p><ul><li>Exchange name &amp; type</li><li>Routing key</li><li>Final matched queue destinations</li><li>Message metadata (IDs, timestamps)</li></ul><p><strong>4. Output Renderers</strong><br> Supports multiple view formats:</p><ul><li>Interactive CLI streaming</li><li>Structured newline-delimited JSON</li><li>Graphviz DOT for offline visualizations</li></ul><h3>Usage Examples</h3><p>Here’s how you can try the tool quickly:</p><pre># Enable RabbitMQ tracing<br>rabbitmqctl trace_on -p /<br><br># Run the inspector<br>go run ./cmd/amqp-routing-inspector --output cli</pre><p>Or generate a routing graph:</p><pre>amqp-routing-inspector --output dot &gt; graph.dot<br>dot -Tpng graph.dot -o routing.png</pre><p>This visual graph helps you see how messages flow through exchanges to queues.</p><h3>What I Learned While Building It</h3><p>There were several insights that surprised me:</p><ul><li><strong>AMQP routing logic can be unintuitive</strong> when multiple bindings and wildcards are involved.</li><li><strong>Protocol-level tracing is under-utilized</strong> despite its value for debugging and teaching.</li><li>Parsing event metadata robustly requires careful fallbacks for missing headers and non-standard edge cases.</li></ul><p>All of this fed directly into the tool design.</p><h3>Conclusion</h3><p>Debugging messaging systems is hard - especially when routing behavior diverges from expectation. amqp-routing-inspector helps fill that visibility gap by bringing <strong>protocol-level insights into your console or CI pipelines</strong>. I hope this tool empowers engineers to understand RabbitMQ message routing with clarity and confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23cb991d61fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>