<?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 Aditya Prasad on Medium]]></title>
        <description><![CDATA[Stories by Aditya Prasad on Medium]]></description>
        <link>https://medium.com/@adityanprasad275?source=rss-4b696ef09b28------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*H0s7Rwu1h4Anctax</url>
            <title>Stories by Aditya Prasad on Medium</title>
            <link>https://medium.com/@adityanprasad275?source=rss-4b696ef09b28------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:08:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adityanprasad275/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[Benchmarking AtlasDB: Heap Scan vs B+ Tree Index]]></title>
            <link>https://medium.com/@adityanprasad275/benchmarking-atlasdb-heap-scan-vs-b-tree-index-6db61ed47c59?source=rss-4b696ef09b28------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db61ed47c59</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[b-plus-tree]]></category>
            <dc:creator><![CDATA[Aditya Prasad]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 10:45:07 GMT</pubDate>
            <atom:updated>2026-04-14T10:45:07.675Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: All code can be found in the github repo <a href="https://github.com/AdityaPrasad275/AtlasDB">github.com/AdityaPrasad275/AtlasDB</a></p><h3>The Rules</h3><p>For point queries:</p><p>- heap path: full table scan for key = x<br>- index path: B+ tree point lookup, then heap fetch by RID</p><p>For range queries:</p><p>- heap path: full table scan, filter low &lt;= key &lt;= high, then sort matches by key<br>- index path: B+ tree lowerBound(low), then walk leaf pages until key &gt; high</p><p>For writes:</p><p>- heap-only insert: just store the row<br>- indexed insert: store the row and maintain key -&gt; RID</p><h3>Profiles</h3><p>We split benchmark intent into two categories.</p><h4>Storage-scale profiles</h4><p>These are the heavyweight profiles. No involvment of index, just measuring in some sense, the disk speed.</p><p>- quick<br>- dev<br>- large<br>- stress</p><p>They are useful for storage-layer scaling and general pressure testing.</p><h4>Query-comparison profiles</h4><p>These are the profiles that matter for heap-scan-vs-index comparisons:</p><p>- compare_quick<br>- compare_dev<br>- compare_large</p><h3>The setup</h3><p>Current sizes:</p><p>- compare_quick: up to 10,000 query dataset records<br>- compare_dev: up to 50,000 query dataset records<br>- compare_large: up to 100,000 query dataset records</p><p>The benchmark suite measures:</p><p>- throughput<br>- average latency</p><p>This post focuses on the big-picture story.</p><h4>Result 1: indexed inserts are slower, as expected</h4><p>This is the least surprising result in the whole set.</p><p>Insert throughput:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*bpxpPsMOHYDd7pj6sY-gww.png" /><figcaption>slow inserts with index</figcaption></figure><p>So indexed inserts are about 4x to 5x slower than heap-only inserts in these runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9byV191squnQ8zAdn7bCg.jpeg" /><figcaption>histogram for insert throughput</figcaption></figure><p>That is not a failure.</p><p>That is the cost of maintaining a sorted access path on every write:</p><p>- find position in the tree<br>- insert into leaf<br>- maybe split<br>- maybe propagate split upward<br>- maintain key -&gt; RID</p><p>Heap-only insert just has less work to do.</p><p>This is the classic database tradeoff:</p><p>- pay more on writes<br>- save a huge amount on reads</p><h4>Result 2: point lookup speedup is absurdly large</h4><p>Warm point-query comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*42R4glQ6pjesxq88tumBlQ.png" /><figcaption>its over 7000!!!!</figcaption></figure><p>Cold point-query comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*rqybR7G4D-cvZASwIIarTQ.png" /><figcaption>its over 7000!!!</figcaption></figure><p>The obvious reaction is:</p><blockquote>that speedup looks ridiculous</blockquote><p>It is ridiculous.</p><p>And it is also correct for this comparison.</p><p>Why so large?</p><p>Because heap point lookup here means:</p><blockquote>scan the table until the key is found</blockquote><p>while indexed lookup means:</p><blockquote>descend the B+ tree, get RID, fetch row</blockquote><p>As dataset size grows:</p><p>- the scan path gets linearly worse<br>- the indexed path stays close to shallow-tree lookup plus one heap fetch</p><p>That is exactly the point of the index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8y2oKkb0YvlFe8-r-bHRg.jpeg" /><figcaption>Point query throughput warm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6XVyAd6CRATvXXAH7dy_kw.jpeg" /><figcaption>Point query throughput cold</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMVki-C-j91680SQ8073VA.jpeg" /><figcaption>point query speed warm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRPvAIptHfMRFHDtFlmEkg.jpeg" /><figcaption>point query speedup cold</figcaption></figure><h4>Result 3: range queries also strongly favor the B+ tree</h4><p>Warm range-query comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*IfyVYj9uDTYV5Y_dMTJd7g.png" /></figure><p>Cold range-query comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*RtQBV4D77y-GCPevjebqdA.png" /></figure><p>This is where the leaf links really matter.</p><p>The indexed path can:</p><p>1. seek to the first matching key<br>2. walk forward in sorted order<br>3. stop as soon as the range ends</p><p>The heap scan path cannot do that.</p><p>It has to inspect every row.</p><p>And because the heap’s physical order is not key order, the scan path in AtlasDB also sorts the matching rows by key before returning them so the result contract matches the index path.</p><p>So range queries do not just show that the B+ tree is faster.</p><p>They show why the leaf-layer design exists at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqM-B7_Hw8J_g5-iLKSCIw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQUX2DbhjkV4n4oe2i79bw.jpeg" /><figcaption>range query throughput</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o36cnb8REr3sLInAQt5-GQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeEEVIs1up-Ljloe59Yupg.jpeg" /><figcaption>range query speedup</figcaption></figure><h4>Result 4: the benchmark now reflects the real tradeoff</h4><p>This is the part I like most.</p><p>The current benchmark tells a story that actually makes sense:</p><p>- heap-only insert is cheaper<br>- indexed insert is more expensive<br>- scan-based point lookup becomes terrible as data grows<br>- index-based point lookup stays fast<br>- scan-based range lookup also degrades badly<br>- index-based range lookup remains practical because the B+ tree can seek and iterate</p><p>That is a real storage-engine story.</p><h4>Warm vs cold</h4><p>One thing I expected to matter more than it ended up mattering was the warm/cold split for the comparison profiles.</p><p>It does matter, but the bigger force here is the algorithmic difference between:</p><p>- full scan<br>- indexed lookup</p><p>When one path is O(n) and the other is closer to O(log n) for point seek plus ordered leaf walk for ranges, the asymmetry dominates.</p><p>So the warm/cold numbers are interesting, but they are not the headline.</p><p>The headline is that once the workload is query-shaped, the index wins by a lot.</p><h4>What these numbers do not mean</h4><p>This does <strong>not </strong>mean:</p><p>- “B+ trees are always 7000x faster”<br>- “heap tables are bad”<br>- “the benchmark is universal”</p><p>It means:</p><p>- for AtlasDB’s current implementation<br>- under this row format<br>- under these dataset sizes<br>- for key-based point and range lookups<br>- compared against honest heap-scan baselines</p><p>the B+ tree access path is overwhelmingly better for reads, while writes pay a clear maintenance cost.</p><p>That is a much narrower and much more useful claim.</p><h3>Final thought</h3><p>The B+ tree post is the one about the data structure.</p><p>The TableWithIndex post is the one about making that data structure useful.</p><p>This post is the payoff:</p><p>once the pieces were connected properly, the numbers started telling the exact story you would expect from a real index.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db61ed47c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Database From Scratch: TableWithIndex]]></title>
            <link>https://medium.com/@adityanprasad275/building-a-database-from-scratch-tablewithindex-8d846bb4f74f?source=rss-4b696ef09b28------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d846bb4f74f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[b-tree-index]]></category>
            <category><![CDATA[build-from-scratch]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Aditya Prasad]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 17:51:09 GMT</pubDate>
            <atom:updated>2026-04-10T17:51:09.467Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The layer that finally makes “heap vs B+ tree” a real comparison.</em></p><p>Note: All code can be found in the github repo <a href="https://github.com/AdityaPrasad275/AtlasDB">github.com/AdityaPrasad275/AtlasDB</a> . This is “next episode” of <a href="https://medium.com/@adityanprasad275/building-a-database-from-scratch-b-tree-3554c4c4ed23">B+tree</a></p><h3>The problem after building the B+ tree</h3><p>Getting a B+ tree working feels like the hard part.</p><p>It is hard, but it is not the whole story.</p><p>After AtlasDB had:</p><p>- a heap Table<br>- a standalone BPlusTree</p><p>I still could not honestly say:</p><blockquote>the database can answer indexed queries</blockquote><p>because the two pieces were not actually connected in a query-shaped way.</p><p>The heap knew how to do:</p><p>- insert row bytes<br>- fetch by RID<br>- update by RID<br>- delete by RID<br>- now, full-table scan (small section in last blog)</p><p>The B+ tree knew how to do:</p><p>- insert key -&gt; RID<br>- exact key lookup<br>- ordered traversal<br>- delete a key</p><p>But a user-level query is not:</p><blockquote>give me the RID for key 42</blockquote><p>and it is also not:</p><blockquote>given this RID, fetch the row</blockquote><p>The actual question is:</p><blockquote>give me the row where key = 42</blockquote><p><strong>What </strong><strong>TableWithIndex actually is</strong></p><p>TableWithIndex is not a new storage engine.</p><p>It is a composition layer:</p><p>- Table remains the heap row store<br>- BPlusTree remains the index from key -&gt; RID<br>- TableWithIndex turns those two into query operations</p><p>This is the point where the implementation finally starts to look like a tiny database access path instead of two unrelated data structures.</p><p>Conceptually:</p><pre><br>heap table: RID -&gt; row bytes<br>index: key -&gt; RID<br>query layer: key -&gt; row bytes</pre><p><strong>The shape of the class</strong></p><p>At a high level, the class is simple:</p><p>- one heap table<br>- one B+ tree<br>- helper methods to translate between stored row bytes and structured rows</p><p>The row format is intentionally boring:</p><pre><br>[ int key ][ payload bytes… ]<br></pre><p>That means:</p><p>- the heap stores the full row<br>- scans can read the key directly from stored row bytes<br>- index lookups can fetch the heap row by `RID`</p><p>This was an important design choice.</p><p>The B+ tree does <strong>not</strong> store the row.<br>It stores the location of the row.</p><p>That keeps the architecture clean:</p><p>- heap owns row storage<br>- index owns access acceleration</p><p><strong>The internal helper methods</strong></p><p>Most of the private logic in TableWithIndex is just glue.</p><p><strong>_serializeRow</strong></p><p>This takes:</p><p>- key<br>- payload pointer<br>- payload size</p><p>and produces the row bytes that get written into the heap.</p><p>The key is embedded into the stored row so that a heap scan can evaluate predicates without any index help.</p><p><strong>_deserializeRow</strong></p><p>This does the reverse:</p><p>- reads the integer key from the first bytes<br>- copies the payload bytes out<br>- attaches the RID</p><p>That turns raw heap bytes into an IndexedRow:</p><p>- key<br>- payload<br>- rid</p><p><strong>_fetchRowByRid</strong></p><p>This is the bridge from index to table:</p><p>1. fetch the row bytes from the heap using RID<br>2. deserialize them into an IndexedRow</p><p>This helper is why the index path becomes end-to-end:</p><blockquote>key -&gt; B+ tree -&gt; RID -&gt; heap row -&gt; IndexedRow</blockquote><h3>Insert: maintaining both worlds</h3><p>Insert is the first place where the combined layer really matters.</p><p>An insert now has to maintain two structures:</p><p>1. the heap row store<br>2. the index</p><p>So the flow is:</p><p>1. check whether the key already exists in the B+ tree<br>2. serialize the row<br>3. insert the row into the heap and get a RID<br>4. insert key -&gt; RID into the B+ tree</p><p>If both succeed, the row is now:</p><p>- physically stored in the heap<br>- logically reachable by key</p><p>This is the basic shape of index maintenance in databases.</p><p>Even in this small project, you can already feel the tradeoff:</p><p>- heap-only insert is cheaper<br>- indexed insert does more work, but unlocks much faster reads later</p><h3><strong>Point lookup, scan path</strong></h3><p>getByKeyScan is the honest no-index baseline.</p><p>Its job is:</p><p>1. start at the first live heap record<br>2. deserialize each row<br>3. check whether `row.key == target`<br>4. stop when found</p><p>So this path is effectively:</p><blockquote>key -&gt; full table scan -&gt; row</blockquote><h3>Point lookup, index path</h3><p>getByKeyIndex is the indexed access path.</p><p>Its job is:</p><p>1. ask the B+ tree for the RID matching the key<br>2. fetch the row from the heap using that RID<br>3. deserialize into an IndexedRow</p><p>This path is:</p><blockquote>key -&gt; B+ tree -&gt; RID -&gt; heap row</blockquote><p>That is the exact thing we wanted all along.</p><p>Delete: not just “remove from the tree”</p><p>Delete is where the integration becomes more obviously database-like.</p><p>Deleting by key now means:</p><p>1. look up the key in the index<br>2. get the RID<br>3. delete the row from the heap<br>4. remove the key from the B+ tree</p><p>Again, two structures need to stay in sync.</p><p>That is why TableWithIndex exists at all.</p><p>If delete logic lived partly in callers and partly in the index, the system would be much easier to break.</p><h3><strong>Update: the subtle one</strong></h3><p>updateByKey is more interesting than it first looks.</p><p>Why?</p><p>Because updating a row can change:</p><p>- its payload<br>- its key<br>- its RID</p><p>That last one matters because AtlasDB’s heap update may relocate the row if the updated record no longer fits in place.</p><p>So the update flow is:</p><p>1. find the current RID through the index<br>2. serialize the updated row<br>3. update the heap record<br>4. check whether the RID changed<br>5. check whether the key changed<br>6. if either changed, repair the B+ tree entry</p><p>That is a subtle but very important piece of correctness.</p><p>Without this layer, it would be easy for the heap and index to silently disagree.</p><h3><strong>Range scan, scan path</strong></h3><p>rangeScanScan(low, high) does the boring but honest thing:</p><p>1. walk the heap<br>2. deserialize each row<br>3. keep rows where low &lt;= key &lt;= high<br>4. sort the result by key</p><p>That last sort is important.</p><p>Heap order is physical storage order, not key order.</p><p>If we want to compare scan results with index results, both paths should produce rows in the same logical order.</p><p>So the heap scan path explicitly sorts its matches by key before returning them.</p><h3>Range scan, index path</h3><p>rangeScanIndex(low, high) is where the B+ tree finally gets to show off.</p><p>The flow is:</p><p>1. seek to low using lowerBound<br>2. walk forward through the leaf layer with the cursor<br>3. stop once key &gt; high<br>4. fetch each matching row from the heap by RID</p><p>That means the ordered-leaf design of the B+ tree is not just a nice implementation detail.</p><p>It directly powers efficient range queries.</p><p>This is one of the main reasons databases love B+ trees.</p><p><strong>What this layer finally gave AtlasDB</strong></p><p>After adding TableWithIndex, AtlasDB could finally answer the same logical query in two different ways:</p><p>- scan path<br>- index path</p><p>That gave us proper query parity for:</p><p>- point lookup<br>- range lookup<br>- insert/delete/update maintenance</p><p>Now we could say:</p><p>- heap scan point lookup vs indexed point lookup<br>- heap scan range lookup vs indexed range lookup<br>- heap-only insert vs indexed insert maintenance cost</p><p>That is a real comparison.</p><h3>Final thought</h3><p>Building the B+ tree was the flashy part.</p><p>Building TableWithIndex was the part that made the whole thing honest.</p><p>It is the layer where AtlasDB started being a</p><blockquote>a storage engine that can answer the same query through either a scan path or an index path</blockquote><p>And that is exactly what we needed before saying anything serious about benchmarking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d846bb4f74f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Database from Scratch — B+Tree]]></title>
            <link>https://medium.com/@adityanprasad275/building-a-database-from-scratch-b-tree-3554c4c4ed23?source=rss-4b696ef09b28------2</link>
            <guid isPermaLink="false">https://medium.com/p/3554c4c4ed23</guid>
            <category><![CDATA[b-tree]]></category>
            <category><![CDATA[build-from-scratch]]></category>
            <category><![CDATA[b-tree-index]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Aditya Prasad]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 17:35:58 GMT</pubDate>
            <atom:updated>2026-04-10T17:35:58.054Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Making queries actually fast.</em></p><p>Note: All code can be found in the github repo <a href="https://github.com/AdityaPrasad275/AtlasDB">github.com/AdityaPrasad275/AtlasDB</a></p><h3>We were supposed to benchmark this though?</h3><p>The way table was left in the last post, it has perfect CRUD api’s with RIDs as input. Which meant it was just a fancy disk reader. I did benchmark at this stage (as can be seen in repo with heap_writes , reads, warm, cold, in this <a href="https://github.com/AdityaPrasad275/AtlasDB/blob/main/logs/benchmark_results.csv">csv</a>). But its not exactly “valuable” information. We need table to have the ability to find and move in the heap. Thats just two methods</p><pre>// walking the heap in table order<br>bool getFirstRecord(RID&amp; rid, std::vector&lt;char&gt;&amp; data); <br>bool getNextRecord(const RID&amp; current, RID&amp; next, std::vector&lt;char&gt;&amp; data);</pre><p>This enables use to answer queries. But its super slow. And standalone benchmarking of this wouldnt be too great. So we skip ahead to B+tree, implement a TableWithIndex and compare B+tree with normal heap access. Spoiler alert, 7000x difference! But that comes later, lets solve B+ Tree first!</p><h3><strong>What problem is a B+ tree solving?</strong></h3><p>Suppose you have a heap table.</p><p>You can:</p><p>- insert rows<br>- fetch rows by RID<br>- update rows<br>- delete rows</p><p>But if someone asks:</p><p>give me the row with key = 42</p><p>and all you have is the heap, you do not know where that row is. You have to scan. That is O(n) work. Fine for small tables but awful for large tables</p><p>So the real problem is not “how do I store rows?”</p><p>It is:</p><p>how do I find the row location from a key quickly?</p><p>That means we want an index.</p><p>In AtlasDB, the index stores:</p><p>key -&gt; RID</p><p>and then the heap stores:</p><p>RID -&gt; row bytes</p><p>So yes, the row itself still lives in the heap. The B+ tree helps you locate it fast. Super fast!</p><p>But we got to be careful here. While index can be applied in general to any column or any type of keys, for rather simpler implementation, I restricted keys to int. To first implementation manageable.</p><p>Why integers help:</p><p>- total order is obvious<br>- comparisons are cheap<br>- page capacity math is easy<br>- internal and leaf layouts stay simple</p><p>Later, sure, you can generalize keys. But integer keys are the right choice for getting the structure working first.</p><p><strong>So what even is a B+ tree?</strong></p><p>A B+ tree is a tree-shaped index where:</p><p>- internal nodes route you toward the right place<br>- leaf nodes store the actual (key, RID) entries<br>- leaves are linked left-to-right for ordered scans</p><p>That last point matters a lot.</p><p>If you only cared about exact-match lookup, many structures could help.</p><p>But databases also care about:</p><ul><li>key = x</li><li>key &gt;= x</li><li>x &lt;= key &lt;= y</li><li>ordered iteration</li></ul><p>That is where B+ trees shine.</p><p><strong>The basic shape</strong></p><p>Leaf pages store actual entries:</p><pre><br>[(10, ridA), (15, ridB), (22, ridC)]<br></pre><p>Internal pages do not store rows. They store signposts.</p><p>Conceptually:</p><pre><br>P0, K1, P1, K2, P2<br></pre><p>Where:</p><p>- P0 points to keys &lt; K1<br>- P1 points to keys &gt;= K1 and &lt; K2<br>- P2 points to keys &gt;= K2</p><p>So internal nodes answer:</p><blockquote>which child subtree should I follow for this key?</blockquote><p>and leaf nodes answer:</p><blockquote>here is the actual RID for this key</blockquote><p><strong>Why this is fast</strong></p><p>Inside a page, entries are stored in sorted order. Which enables us to</p><p>- binary search inside a page<br>- only a handful of page traversals from root to leaf</p><p>And because each page can hold many keys, the tree stays shallow, enabling us to sift through a billion keys in 3, 4 hops</p><h3><strong>AtlasDB implementation split</strong></h3><p>The implementation becomes a lot easier to reason about once you accept this separation:</p><p>- page classes manage page-local layout<br>- BPlusTree manages the actual algorithm</p><p>In AtlasDB that means:</p><p>- BPlusTreePageBase<br>- BPlusTreeLeafPage<br>- BPlusTreeInternalPage<br>- BPlusTree</p><p><strong>BPlusTreeLeafPage</strong></p><p>This is where actual (key, RID) entries live.</p><p>Its job is local:</p><p>- find a key in one leaf<br>- insert into one leaf<br>- remove from one leaf<br>- split one leaf into two leaves<br>- move entries during borrow/merge</p><p><strong>BPlusTreeInternalPage</strong></p><p>This is routing logic, not data storage.</p><p>Its job is:</p><p>- choose the correct child for a key<br>- insert/remove separator entries locally<br>- split one internal node<br>- help with redistribution/merge</p><p><strong>BPlusTree</strong></p><p>This is the big one.</p><p>This class owns the global algorithm:</p><p>- start at root<br>- descend to the right leaf<br>- decide when to split<br>- propagate splits upward<br>- create a new root<br>- decide whether delete should borrow or merge<br>- shrink the root when needed</p><p>The BPlusTree class owns the actual tree behavior.</p><p><strong>Insert: where the fun begins</strong></p><p>Reading sounds simple. Insert is where the maintenance pain starts.</p><p>High-level insert story:</p><p>1. Start at the root.<br>2. Route down internal pages until you reach the correct leaf.<br>3. Insert (key, RID) into that leaf in sorted order.<br>4. If the leaf still fits, done.<br>5. If the leaf overflows, split it.<br>6. Push a separator key up into the parent.<br>7. If the parent overflows, split the parent too.<br>8. Keep going upward until the tree is valid again.<br>9. If the old root splits, create a brand new root.</p><p>That recursive “push the split upward” behavior is the heart of B+ tree insert.</p><p><strong>Leaf split</strong></p><p>Suppose a leaf is full and a new key must go in, We:</p><p>- create a new leaf<br>- move half the entries into it<br>- keep both leaves sorted<br>- stitch leaf links correctly</p><p>Now the parent must learn that there is a new child.</p><p>That means a new separator key has to be inserted into the parent.</p><p><strong>Parent split</strong></p><p>If the parent has room, easy.</p><p>If the parent is also full, same story again:</p><p>- split parent<br>- push separator upward</p><p>This keeps going until:</p><p>- some parent has room, or<br>- a brand new root is created</p><p>Easy right? Wait for delete!</p><p><strong>Read is almost disappointingly simple</strong></p><p>Compared to insert and delete, lookup is nice.</p><p>High-level story:</p><p>1. Start at root.<br>2. At each internal node, choose the correct child for the key.<br>3. Keep descending until you hit a leaf.<br>4. Binary search within the leaf.<br>5. Return the RID if found.</p><p>That is basically it.</p><p>If the key is not in the leaf, it is not in the tree.</p><p>Ordered iteration is also nice once leaf links exist:</p><p>- find the starting leaf<br>- walk leaf entries in order<br>- hop across sibling leaves as needed</p><p>That is how range scans become possible.</p><p><strong>Delete is where I lost my patience</strong></p><p>Insert is annoying.<br>Delete is worse.</p><p>The reason is simple:</p><p>When you remove a key, you might not just remove a key.<br>You might break the occupancy rules of the tree.</p><p>That means after a delete, the node may be underfull (something we have defined as containing less than half the max keys)</p><p>Then the tree has to repair itself.</p><p>High-level delete story:</p><p>1. Find the leaf containing the key.<br>2. Remove the key from the leaf.<br>3. If the leaf still has enough entries, done.<br>4. If it underflows, try borrowing from a sibling.<br>5. If borrowing is not possible, merge with a sibling.<br>6. Parent loses a separator entry because of the merge.<br>7. Parent may now underflow too.<br>8. Repeat the same logic upward.<br>9. If the root becomes degenerate, adjust the root.</p><p>That is the idea.</p><p><strong>Borrow before merge</strong></p><p>If a sibling has more than the minimum number of entries, we can redistribute.</p><p>For a leaf:</p><p>- borrow one entry from left or right sibling<br>- update the relevant parent separator key</p><p>This is cheaper than merging because the tree height does not change.</p><p><strong>Merge when borrowing fails</strong></p><p>If neither sibling can spare an entry, then two siblings have to collapse into one.</p><p>That means:</p><p>- move all entries from donor into survivor<br>- repair leaf linkage if this is a leaf merge<br>- delete the separator from parent<br>- delete the pointer to the removed child from parent</p><p>And now the parent might underflow too.</p><p>So yes, delete can cascade upward.</p><p><strong>Root adjustment</strong></p><p>Root is special.</p><p>Two important cases:</p><p>- If the root is a leaf and becomes empty, the tree becomes empty.<br>- If the root is an internal node and ends up with only one child, that child gets promoted to become the new root.</p><p>Without root adjustment, delete logic is incomplete.</p><h3>What AtlasDB has now</h3><p>At this point AtlasDB’s B+ tree supports:</p><p>- insert<br>- exact key lookup<br>- delete<br>- ordered traversal with cursor-style iteration<br>- lower-bound seeking for range scans</p><h3>Final thought</h3><p>B+ tree is one of those things that looks elegant from far away and absolutely chaotic once you start implementing it.</p><p>But the chaos is not random.<br>It comes from the invariants.</p><p>Once you accept that:</p><ul><li>internal nodes route</li><li>leaves store data entries</li><li>insert may split upward</li><li>delete may borrow/merge upward</li><li>root is special</li></ul><p>the whole thing becomes much less mystical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3554c4c4ed23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Database from Scratch — Tables!]]></title>
            <link>https://medium.com/@adityanprasad275/building-database-from-scratch-tables-dd5c93f1e851?source=rss-4b696ef09b28------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd5c93f1e851</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[build-from-scratch]]></category>
            <category><![CDATA[table]]></category>
            <dc:creator><![CDATA[Aditya Prasad]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 12:01:02 GMT</pubDate>
            <atom:updated>2026-03-26T12:01:02.593Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Organising the inside of a page.</em></p><p>Note: All code can be found in the github repo <a href="https://github.com/AdityaPrasad275/AtlasDB">github.com/AdityaPrasad275/AtlasDB</a></p><p>This blog is a follow up of <a href="https://medium.com/@adityanprasad275/building-a-database-from-scratch-pages-503130d77f56">Building a Database from scratch — Pages</a></p><h3>We can move pages now. Great. What goes inside them?</h3><p>In the previous step, we built the machinery for handling database pages:</p><ul><li>Page</li><li>DiskManager</li><li>BufferPoolManager</li><li>LRUReplacer</li></ul><p>That solved one big problem:</p><p><strong>how do we move fixed-size blocks between disk and RAM safely?</strong></p><p>But that still leaves the next question:</p><p><strong>once a page is in memory, how do we actually store records inside it?</strong></p><p>Because a 4 KB page is just raw space.</p><p>If someone asks us to insert three records into that page, where exactly do they go?</p><p>How do we find record number 2 later?</p><p>How do we delete one record without shuffling the whole page every time?</p><p>How do we support variable-length records instead of pretending everything is a fixed-size struct?</p><p>That is the problem this step solves.</p><p>We are no longer talking about moving pages around.</p><p>Now we are talking about <strong>organising the bytes inside one page.</strong></p><p>That brings us to TablePage, RID, and finally Table.</p><p>— -</p><h3>The non-technical story</h3><p>Imagine a single page is a suitcase.</p><p>You have 4 KB of space inside it.</p><p>Now suppose you want to pack variable-sized items into that suitcase:</p><ul><li>one item is 20 bytes</li><li>one is 100 bytes</li><li>one is 500 bytes</li></ul><p>You could just start stuffing items from the front.</p><p>That works for inserts.</p><p>But then imagine someone says:</p><blockquote>&gt; Give me the third item you packed.</blockquote><p>Now you have a problem.</p><p>If you never stored any metadata, the only way to find it is to walk through item 1, then item 2, then finally reach item 3.</p><p>That is not great.</p><p>So instead, you keep a small index card near the front of the suitcase.</p><p>For each item, the card says:</p><ul><li>where the item starts</li><li>how large the item is</li></ul><p>Now you can jump directly to the item you want.</p><p>That is the basic idea of a <strong>slotted page.</strong></p><p><strong>One page, three regions</strong></p><p>A TablePage is divided into three conceptual regions:</p><p>1. a <strong>header</strong> at the beginning<br>2. a s<strong>lot array</strong> right after the header<br>3. the actual <strong>record bytes</strong> packed from the end of the page backwards</p><p>So the page grows inward from both sides:</p><ul><li>metadata grows from the front</li><li>record data grows from the back</li></ul><p>And the free space is the gap in the middle.</p><p>That layout gives us two really useful properties:</p><ul><li>we can append new metadata entries as more records arrive</li><li>we can store variable-length record data without needing it to be tightly tied to slot position</li></ul><p>This is a very common database trick because it is simple and effective.</p><p>— -</p><h3>The technical part</h3><p>Like the database_pages write-up, the goal here is not to dump every line of implementation.</p><p>The goal is to explain the moving parts cleanly enough that the header and .cpp files feel obvious.</p><p>We will go bottom-up:</p><p>1. RID<br>2. Slot<br>3. TablePage<br>4. Table</p><p>— -</p><p><strong>1. </strong><strong>RID</strong></p><p>Once records live inside pages, we need a way to identify them.</p><p>A record is not identified just by page id.</p><p>One page can hold many records.</p><p>So we use a <strong>Record ID,</strong> or RID:</p><pre>struct RID {<br>    page_id_t page_id;<br>    slot_id_t slot_id;<br><br>    bool operator==(const RID&amp; other) const {<br>        return page_id == other.page_id and slot_id == other.slot_id;<br>    }<br>};<br></pre><p>This is the full address of a record:</p><ul><li>page_id tells us <strong>which page</strong></li><li>slot_id tells us <strong>which slot within that page</strong></li></ul><p>That is enough to uniquely locate a record inside a heap-file style table.</p><p>— -</p><p><strong>2. </strong><strong>Slot</strong></p><p>A slot is the tiny metadata entry that makes the whole page layout work.</p><p>Here is the struct:</p><pre>struct Slot {<br>    int offset;<br>    int size;<br>    // we represent a deleted record by putting offset = -1<br>};</pre><p>Each slot tells us:</p><ul><li>where the record starts inside the page</li><li>how many bytes belong to that record</li></ul><p>That means the slot array acts like a mini index for records within one page.</p><p><strong>Why store slots separately from record bytes?</strong></p><p>Because records are variable length.</p><p>If record 0 is 30 bytes and record 1 is 300 bytes, their positions are not predictable from arithmetic alone.</p><p>But once the slot stores `(offset, size)`, lookup becomes trivial.</p><p><strong>Deletion as a tombstone</strong></p><p>When a record is deleted, this implementation does not compact the page immediately.</p><p>Instead, it marks the slot as deleted by setting:</p><pre>offset = -1</pre><p>That is a tombstone.</p><p>This is much simpler than shifting record bytes around every time we delete something.</p><p>The downside is that deletions do not immediately reclaim fragmented space.</p><p>That is a tradeoff we accept for now.</p><p>— -</p><p><strong>3. </strong><strong>TablePage</strong></p><p>TablePage is where the slotted-page idea becomes concrete.</p><p>It defines how one 4 KB page is organised in memory.</p><p>Here is the class:</p><pre>class TablePage {<br>public:<br>    void init(page_id_t prev_page_id, page_id_t page_id);<br><br>    bool insertRecord(const char* data, int size);<br><br>    char* getRecord(slot_id_t slot_id, int&amp; record_size);<br><br>    bool updateRecord(slot_id_t slot_id, const char* data, int size);<br><br>    bool deleteRecord(slot_id_t slot_id);<br><br>    page_id_t getNextPageId() { return _next_page_id; }<br>    void setNextPageId(page_id_t next_page_id) { _next_page_id = next_page_id; }<br><br>    page_id_t getPrevPageId() { return _prev_page_id; }<br>    void setPrevPageId(page_id_t prev_page_id ) { _prev_page_id = prev_page_id; }<br><br>    int getSlotCount() { return _slot_count; }<br><br>private:<br>    page_id_t _prev_page_id;<br>    page_id_t _next_page_id;<br>    page_id_t _page_id;<br><br>    int _free_space_pointer;<br>    int _slot_count;<br><br>    Slot* _getSlot(slot_id_t slot_id);<br>};</pre><p><strong>What lives in the header?</strong></p><p>The in-page header stores:</p><ul><li>_prev_page_id</li><li>_next_page_id</li><li>_page_id</li><li>_free_space_pointer</li><li>_slot_count</li></ul><p>So the header is carrying both:</p><ul><li><strong>navigation metadata</strong> for linking pages together</li><li><strong>layout metadata</strong> for understanding the inside of this page</li></ul><p><strong>The physical layout</strong></p><p>Conceptually, the page looks like this:</p><pre>+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -+<br>| Header | Slot 0 | Slot 1 | Slot 2 | … | Free Space |<br>+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -+<br>| … record bytes … |<br>+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -+</pre><p>More precisely:</p><ul><li>the header starts at byte 0</li><li>slots begin immediately after sizeof(TablePage)</li><li>record bytes are copied from the <strong>end of the page backward</strong></li><li>_free_space_pointer marks the current start of free space from the back side</li></ul><p>At initialization:</p><ul><li>_slot_count = 0</li><li>_free_space_pointer = Page::PAGE_SIZE</li><li>_next_page_id = Page::INVALID_PAGE_ID</li></ul><p>So an empty page begins with metadata at the front and all remaining space free.</p><p><strong>Why store record bytes from the end?</strong></p><p>Because slots need room to grow too.</p><p>If both slots and records grew in the same direction, they would constantly collide in awkward ways.</p><p>Instead:</p><ul><li>slots grow forward from the front</li><li>records grow backward from the end</li></ul><p>The free space is whatever remains between them.</p><p>This is a very clean mental model:</p><pre>front -&gt; [header][slots] …..free space….. [records] &lt;- back</pre><p>When the gap becomes too small, the page is full.</p><p>— -</p><p><strong>_getSlot(slot_id)</strong></p><p>This helper is the pointer-arithmetic core of the implementation.</p><pre>Slot* TablePage::_getSlot(slot_id_t slot_id) {<br>    auto header = reinterpret_cast&lt;char*&gt;(this);<br>    auto slot_start = reinterpret_cast&lt;Slot*&gt;(header + sizeof(TablePage));<br>    return slot_start + slot_id;<br>}</pre><p>The important part is the cast to char*.</p><p>Why?</p><p>Because char* arithmetic moves in <strong>bytes.</strong></p><p>If we added 1 to a TablePage*, we would jump by sizeof(TablePage).</p><p>But here we want byte-level movement:</p><ul><li>first reach the start of the page</li><li>then skip the header bytes</li><li>then treat that location as the start of the slot array</li></ul><p>From there, slot_start + slot_id works because pointer arithmetic on Slot* advances slot-by-slot.</p><p>— -</p><p><strong>insertRecord</strong></p><p>Insertion does four things:</p><p>1. compute how much space is currently available<br>2. check whether we have room for both:<br>- the new record bytes<br>- one new Slot<br>3. copy the record into free space near the end of the page<br>4. create a slot that points to it</p><p>The key check is:</p><pre>available_space = free_space_pointer - current_slots_end</pre><p>If that available space is smaller than:</p><pre><br>record_size + sizeof(Slot)<br></pre><p>then insertion fails.</p><p>Otherwise:</p><ul><li>_free_space_pointer moves backward by size</li><li>the record bytes are copied there with memcpy</li><li>the next slot is filled with (offset, size)</li><li>_slot_count is incremented</li></ul><p>That is the whole insert path.</p><p>No searching.</p><p>No compaction.</p><p>Just place the bytes and add a slot.</p><p>— -</p><p><strong>getRecord</strong></p><p>Lookup is straightforward:</p><p>1. validate the slot id<br>2. fetch the slot<br>3. reject tombstoned slots<br>4. return a pointer to page_start + slot-&gt;offset</p><p>This is exactly why the slot array exists.</p><p>Without slots, we would have to scan earlier records to find later ones.</p><p>With slots, record access becomes direct.</p><p>— -</p><p><strong>updateRecord</strong></p><p>Updates have two cases.</p><p><strong>Case 1: new record is smaller or equal</strong></p><p>If the new payload size is &lt;= the old one, we can overwrite in place:</p><ul><li>memcpy the new bytes over the old location</li><li>update slot-&gt;size</li></ul><p>Simple.</p><p><strong>Case 2: new record is larger</strong></p><p>If the new payload is bigger, the current location may no longer fit.</p><p>In this implementation, TablePage tries a page-local relocation:</p><ul><li>check whether the page still has enough remaining free space</li><li>if yes, allocate fresh space from the back</li><li>copy the new bytes there</li><li>update the slot to point at the new location</li></ul><p>If even that fails, TablePage::updateRecord returns false.</p><p>And that is an important design decision:</p><p><strong>a page should not decide to allocate another page for itself.</strong></p><p>That responsibility belongs to Table, which knows about the whole page chain.</p><p>— -</p><p><strong>deleteRecord</strong></p><p>Deletion is intentionally cheap:</p><pre><br>slot-&gt;offset = -1;<br></pre><p>That is all.</p><p>We are not compacting bytes.</p><p>We are not shifting later records forward.</p><p>We are not shrinking the slot array.</p><p>This keeps deletion simple, but it also means free space can become fragmented over time.</p><p>That is acceptable for now.</p><p>A future version could add page compaction or slot reuse.</p><p>— -</p><p><strong>4. </strong><strong>Table</strong></p><p>TablePage explains how records live inside one page.</p><p>But users do not want to think in terms of individual pages.</p><p>They want a table-like abstraction:</p><ul><li>insert a record</li><li>read a record</li><li>update a record</li><li>delete a record</li></ul><p>That is what Table provides.</p><p>It acts as the layer above TablePage and coordinates with the BufferPoolManager.</p><p>Here is the interface:</p><pre><br>class Table {<br>private:<br>    BufferPoolManager* _bpm;<br>    page_id_t _first_page_id;<br>    page_id_t _last_page_id;<br><br>    void _updateRIDandUnpinPage(RID&amp; rid, TablePage* tp, page_id_t page_id);<br>    TablePage* _fetchAndCast(page_id_t page_id);<br><br>public:<br>    Table(BufferPoolManager* bpm, page_id_t first_page_id = Page::INVALID_PAGE_ID);<br><br>    bool insertRecord(const char* data, int size, RID&amp; rid);<br>    bool getRecord(const RID&amp; rid, std::vector&lt;char&gt;&amp; data);<br>    bool updateRecord(const char* data, int size, RID&amp; rid);<br>    bool deleteRecord(const RID&amp; rid);<br><br>    page_id_t getFirstPageId() { return _first_page_id; };<br>};<br></pre><p><strong>What kind of structure is a </strong><strong>Table?</strong></p><p>Internally, this table is a <strong>heap file</strong> implemented as a doubly linked list of TablePages.</p><p>Each page stores:</p><ul><li>prev_page_id</li><li>next_page_id</li></ul><p>So Table itself does not need a vector&lt;TablePage*&gt;.</p><p>It only needs:</p><ul><li>_first_page_id</li><li>_last_page_id</li><li>_bpm</li></ul><p>That is enough to:</p><ul><li>find the start of the chain</li><li>append to the end of the chain</li><li>fetch pages through the buffer pool</li></ul><p>— -</p><p><strong>Constructor</strong></p><p>The constructor supports two cases.</p><p><strong>Case 1: creating a brand-new table</strong></p><p>If first_page_id == Page::INVALID_PAGE_ID, then the table does not exist yet.</p><p>So we:</p><p>1. ask the buffer pool for a new page<br>2. cast that page data to TablePage*<br>3. initialize it<br>4. set _first_page_id and _last_page_id<br>5. unpin it as dirty</p><p>This creates a one-page table.</p><p><strong>Case 2: reopening an existing table</strong></p><p>If we already know first_page_id, then the table exists on disk.</p><p>In that case:</p><ul><li>_first_page_id is known immediately</li><li>_last_page_id is not</li></ul><p>So the constructor traverses the linked list using next_page_id until it finds the page whose next_page_id == Page::INVALID_PAGE_ID.</p><p>That final page becomes _last_page_id.</p><p>This is a nice example of why page-to-page links belong in the header.</p><p>They let the table reconstruct its own structure from storage alone.</p><p>— -</p><p><strong>_fetchAndCast</strong></p><p>This helper is small but conceptually important:</p><pre>TablePage* Table::_fetchAndCast(page_id_t page_id) {<br>    Page* page = _bpm-&gt;fetchPage(page_id);<br>    if (page == nullptr) {<br>        return nullptr;<br>    }<br>    return reinterpret_cast&lt;TablePage*&gt;(page-&gt;getData());<br>}</pre><p>BufferPoolManager speaks in terms of generic Pages.</p><p>But record operations need to speak in terms of TablePage.</p><p>So this helper does two jobs:</p><ul><li>fetch the page through the buffer pool</li><li>interpret its raw bytes as a `TablePage`</li></ul><p>That reinterpretation is basically saying:</p><blockquote>&gt; These 4096 bytes are not just anonymous data.<br>&gt; <br>&gt; For this page type, we know how to read them.</blockquote><p>— -</p><p><strong>insertRecord</strong></p><p>Insertion is append-oriented.</p><p>The table always tries the current last page first.</p><p>The logic is:</p><p>1. fetch _last_page_id<br>2. try TablePage::insertRecord<br>3. if it succeeds:<br> — populate the `RID`<br> — unpin the page dirty<br>4. if it fails because the page is full:<br> — allocate a new page through the buffer pool<br> — link the old last page to the new page<br> — initialize the new page<br> — insert there instead<br> — update _last_page_id</p><p>That means inserts are effectively:</p><ul><li>append to the last page until full</li><li>then append a new page to the table</li></ul><p>Simple and very heap-file-like.</p><p>— -</p><p><strong>getRecord</strong></p><p>Reading a record is a two-hop lookup:</p><p>1. use rid.page_id to fetch the right page<br>2. use rid.slot_id to fetch the right slot inside that page</p><p>Then the bytes are copied into a std::vector&lt;char&gt;.</p><p>This separation is useful:</p><ul><li>RID identifies the record globally within the table</li><li>Slot identifies its physical location within one page</li></ul><p>Together they bridge table-level logic and page-level layout.</p><p>— -</p><p><strong>updateRecord</strong></p><p>Update is where TablePage and Table collaborate.</p><p>First, Table asks the current page to handle the update locally:</p><pre>if (tp-&gt;updateRecord(rid.slot_id, data, size)) {<br>    _bpm-&gt;unpinPage(rid.page_id, true);<br>    return true;<br>}</pre><p>If that succeeds, we are done.</p><p>If it fails, that usually means the larger version cannot fit in that page.</p><p>So Table takes over:</p><p>1. tombstone the old slot<br>2. unpin the old page dirty<br>3. insert the new record somewhere else in the table<br>4. update the caller’s RID</p><p>That last part matters.</p><p>If the record moved to a different page or slot, its address changed.</p><p>So the caller’s RID must change too.</p><p>This is one of the cleanest reasons to keep RID explicit in the API.</p><p>— -</p><p><strong>deleteRecord</strong></p><p>Deletion at the table level is just:</p><p>1. fetch page from rid.page_id<br>2. call TablePage::deleteRecord(rid.slot_id)<br>3. unpin dirty</p><p>So the table-level delete is simple because the page-level delete is simple.</p><p>That is a recurring theme in storage engines:</p><p>good local abstractions make upper layers much easier to write.</p><p>— -</p><h3>Where we are now</h3><p>At this point, AtlasDB has something much more database-like than a raw page manager.</p><p>We now have:</p><ul><li>a fixed-size page abstraction</li><li>a buffer pool that moves pages between disk and RAM</li><li>a slotted page layout for variable-length records</li><li>a heap-file style Table built as a linked list of pages</li><li>CRUD operations expressed in terms of RID</li></ul><p>That is a big step.</p><p>Because now pages are not just anonymous 4 KB blocks anymore.</p><p>They have internal structure.</p><p>And once pages have internal structure, higher layers can start pretending they are working with records instead of raw memory.</p><p>That is where databases start to feel real.</p><p>In the next blog we’ll benchmark our database!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd5c93f1e851" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Database from scratch — Pages]]></title>
            <link>https://medium.com/@adityanprasad275/building-a-database-from-scratch-pages-503130d77f56?source=rss-4b696ef09b28------2</link>
            <guid isPermaLink="false">https://medium.com/p/503130d77f56</guid>
            <category><![CDATA[pages]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[building-from-scratch]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Aditya Prasad]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 08:37:59 GMT</pubDate>
            <atom:updated>2026-03-25T08:37:59.242Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Handling memory ourselves!</em></p><p>Note: All code can be found in the github repo <a href="https://github.com/AdityaPrasad275/AtlasDB">github.com/ AdityaPrasad275/AtlasDB</a> ,specifically in the branch feature-pages</p><p>Also Note: This is ‘Step-1’ after step 0 of building databases, and heres the previous blog — <a href="https://medium.com/@adityanprasad275/building-a-database-from-scratch-step-0-kv-store-d3282b554505">Building a Database from Scratch Step 0 — KV store</a></p><h3>Hashmap, you gotta go</h3><p>In <strong>Step 0,</strong> we built a tiny persistent database.</p><p>It had:</p><ul><li>a <strong>write-ahead log</strong> on disk</li><li>a<strong> hashmap</strong> in memory</li></ul><p>That gave us a surprisingly decent first version:</p><ul><li>writes were durable</li><li>crashes were recoverable</li><li>reads were fast</li></ul><p>Nice.</p><p>But there was one very obvious problem.</p><p>The actual database state still lived inside a hashmap in RAM.</p><p>That is fine if your dataset is small.</p><p>It is not fine if your database is 100 GB and your machine has 8 GB of RAM.</p><p>Or 4 GB.</p><p>Or 1 GB.</p><p>At that point the hashmap has to go.</p><p>Not because hashmaps are bad.</p><p>They are great.</p><p>But because we need a database whose <strong>working memory is bounded</strong>, even when the data on disk is much larger.</p><p>So this step is about a different problem:</p><p>not “how do we store key-value data?”</p><p>but:</p><p><strong>how do we move data between disk and RAM in a controlled way?</strong></p><p>That brings us to pages, frames, and the buffer pool.</p><p>— -</p><h3>The non-technical story</h3><p>Forget tables for a second.</p><p>Forget rows.</p><p>Forget even key-value pairs.</p><p>For now, pretend the database is just a giant pile of paper.</p><p><strong>1. Disk is a huge stack of sheets</strong></p><p>Imagine your disk contains a million sheets.</p><p>Each sheet is one <strong>page</strong>.</p><p>Together they represent your whole database.</p><p>Maybe 100 GB worth of it.</p><p>You cannot spread all of those sheets out on your desk at once.</p><p>You only have space for, say, 10 transparent folders on your desk.</p><p>Those folders are your <strong>frames in RAM.</strong></p><p>At any point in time, you can only actively work with the sheets currently sitting in those folders.</p><p>So the real problem becomes:</p><blockquote><em>I need page </em><em>#132<br><br>Is it already on my desk?<br>If not, which folder do I empty out?<br>And if that sheet was modified, do I need to put it back carefully before replacing it?</em></blockquote><p>That is basically the whole game.</p><p><strong>2. Who does what?</strong></p><p>In this story:</p><ul><li>the giant stack of sheets is the <strong>disk</strong></li><li>the desk with a few folders is the <strong>buffer pool in RAM</strong></li><li>the person deciding what stays and what leaves is the <strong>BufferPoolManager</strong></li><li>the person physically moving sheets to and from storage is the <strong>DiskManager</strong></li><li>each individual sheet is a <strong>Page</strong></li></ul><p>And the important part is this:</p><p>we are building the infrastructure first.</p><p>At this stage, a page is mostly just a 4 KB blob of bytes.</p><p>We are not yet talking about how rows are laid out inside it.</p><p>That comes later.</p><p>Right now we are only solving:</p><blockquote><strong><em>how do pages enter memory, leave memory, and get written back safely?</em></strong></blockquote><p>— -</p><p><strong>3. Why pages?</strong></p><p>We could imagine loading arbitrary byte ranges from disk.</p><p>But databases usually do not think in terms of “give me bytes 21873 through 26101”.</p><p>They think in terms of <strong>fixed-size blocks.</strong></p><p>That fixed-size block is the page.</p><p>And 4 KB is a very common size.</p><p>Why 4 KB?</p><p>Because at the OS and storage level, I/O tends to happen in chunks anyway.</p><p>Disk is <strong>dramatically slower</strong> than RAM, so the system tries to batch and amortize work.</p><p>If our database also treats storage as fixed-size 4 KB pages, the whole design becomes simpler:</p><ul><li>page 0 lives at offset 0</li><li>page 1lives at offset 4096</li><li>page 2 lives at offset 8192</li></ul><p>and in general:</p><pre><br>offset = page_id * PAGE_SIZE<br></pre><p>Simple is good.</p><p>— -</p><h3>The technical part</h3><p>Unlike Step 0, the goal here is not to dump every implementation detail.</p><p>The goal is to explain the moving parts cleanly enough that the header files make sense.</p><p>We will go bottom-up:</p><p>1. Page<br>2. DiskManager<br>3. BufferPoolManager<br>4. LRUReplacer</p><p>— -</p><p><strong>1. </strong><strong>Page</strong></p><p>A Pageis the smallest unit the buffer pool works with.</p><p>At the most basic level, it contains:</p><ul><li>the actual <strong>data bytes</strong></li><li>a small amount of <strong>metadata</strong></li></ul><p>The data is just a 4 KB byte array.</p><p>The metadata is there so the buffer pool can reason about the page while it is in memory.</p><p><strong>1a. What metadata do we need?</strong></p><p>We keep things like:</p><ul><li>page_id</li><li>pin_count</li><li>is_dirty</li><li>lsn</li></ul><p>The first three matter immediately.</p><p>lsn becomes important later when recovery gets more serious.</p><p><strong>1b. </strong><strong>pin_count</strong></p><p>This tracks how many active users currently hold the page.</p><p>If pin_count &gt; 0, the page is considered <strong>in use.</strong></p><p>That means the buffer pool is not allowed to evict it.</p><p>Otherwise we could throw out a page while some thread is still reading or writing it.</p><p>That would be bad.</p><p><strong>1c. </strong><strong>is_dirty</strong></p><p>This tells us whether the page was modified in RAM after being read from disk.</p><p>If a page is dirty, then before reusing its frame we must first write its data back to disk.</p><p>If it is not dirty, we can just drop it from memory and reload it later if needed.</p><p><strong>1d. Important clarification: what is actually stored on disk?</strong></p><p>The Page object in memory contains both:</p><ul><li>the raw bytes</li><li>the metadata the buffer manager cares about</li></ul><p>But on disk, what we really persist here is the <strong>page data block</strong> itself.</p><p>Things like pin_count are runtime bookkeeping.</p><p>They help the buffer pool manage RAM.</p><p>They are not part of the database file format in the same way the 4 KB data region is.</p><p>Here is the class:</p><pre>class Page {<br>public:<br>    static constexpr int PAGE_SIZE = 4096;<br>    static constexpr int INVALID_PAGE_ID = -1;<br><br>    Page() { resetMemory(); }<br>    ~Page() = default;<br><br>    char *getData() { return _data; }<br>    page_id_t getPageId() { return _page_id; }<br>    int getPinCount() { return _pin_count; }<br>    bool isDirty() { return _is_dirty; }<br>    void setDirty(bool is_dirty = true) { _is_dirty = is_dirty; }<br><br>    void pin() { _pin_count++; }<br>    void unpin() { if (_pin_count &gt; 0) _pin_count--; }<br><br>    void resetMemory() {<br>        std::memset(_data, 0, PAGE_SIZE);<br>        _page_id = INVALID_PAGE_ID;<br>        _pin_count = 0;<br>        _is_dirty = false;<br>        _lsn = 0;<br>    }<br><br>    friend class BufferPoolManager;<br><br>private:<br>    char _data[PAGE_SIZE];<br><br>    page_id_t _page_id;<br>    int _pin_count;<br>    bool _is_dirty;<br>    lsn_t _lsn;<br>};</pre><p>There is no fancy .cpp file here because there does not need to be one.</p><p>Pageis mostly just a container.</p><p>Which is exactly what we want.</p><p>— -</p><p><strong>2. </strong><strong>DiskManager</strong></p><p>Once we have a page abstraction, we need something that can move page-sized chunks between RAM and the database file.</p><p>That is the DiskManager.</p><p>Its job is intentionally boring:</p><ul><li>read page X from disk</li><li>write page X to disk</li></ul><p>That is it.</p><p><strong>2a. How does it locate a page?</strong></p><p>The database file, atlas.db, is treated as a contiguous sequence of fixed-size pages.</p><p>So page lookup is just offset arithmetic:</p><pre><br>page_id -&gt; page_id * PAGE_SIZE</pre><p>If we want page 5, we seek to:</p><pre><br>5 * 4096 = 20480</pre><p>Then we read or write exactly 4096 bytes.</p><p>That means DiskManager does not care what is <strong>inside</strong> a page.</p><p>It only cares about moving a page-sized block correctly.</p><p>That separation is important.</p><p>The lower layers should stay dumb.</p><p>Dumb layers are easier to trust.</p><p>Here is the interface:</p><pre>class DiskManager {<br>public:<br>    DiskManager(const std::string &amp;fileName);<br>    ~DiskManager();<br><br>    void writePage(page_id_t page_id, const char *data);<br>    void readPage(page_id_t page_id, char *data);<br><br>    void shutDown();<br><br>private:<br>    int _fd;<br>};</pre><p>The actual implementation is mostly systems-programming detail:</p><ul><li>file descriptors</li><li>open/close</li><li>seek</li><li>read/write</li><li>error handling</li></ul><p>Not conceptually hard.</p><p>Just a bit annoying.</p><p>— -</p><p><strong>3. </strong><strong>BufferPoolManager</strong></p><p>Now we get to the main character.</p><p>The BufferPoolManage is the piece that makes limited RAM feel larger than it really is.</p><p>It manages:</p><ul><li>which pages are currently resident in memory</li><li>which frame each page occupies</li><li>which pages are safe to evict</li><li>when dirty pages need to be flushed back to disk</li></ul><p>This is the actual “brain” of the storage layer.</p><p><strong>3a. Frames vs pages</strong></p><p>This distinction matters.</p><p>A <strong>page</strong> is a unit of data identified by page_id.</p><p>A <strong>frame</strong> is a slot in RAM that can currently hold one page.</p><p>So:</p><ul><li>page_id answers: which logical page on disk?</li><li>frame_id answers: which slot in memory?</li></ul><p>The buffer pool owns a fixed number of frames.</p><p>Each frame contains one Page object.</p><p>If the pool size is 10, then at most 10 pages can be in RAM at once.</p><p><strong>3b. What state does it need?</strong></p><p>To manage all of this, we keep a few core structures.</p><p><strong>3b.1. The frame array</strong></p><p>This is the actual buffer pool.</p><p>An array of Page objects.</p><p>Each index is a frame.</p><p><strong>3b.2. The page table</strong></p><p>We often know the page_id we want.</p><p>But the buffer pool stores pages in frames.</p><p>So we need a fast mapping:</p><pre><br>page_id -&gt; frame_id<br></pre><p>Yes, ironically, a hashmap comes back here.</p><p>Not as the database itself.</p><p>Just as a tiny metadata structure to help manage memory.</p><p>That is a much more reasonable use of a hashmap.</p><p><strong>3b.3. The free frame list</strong></p><p>At startup, all frames are empty.</p><p>So the easiest possible victim is simply an unused frame.</p><p>We keep a list of those.</p><p><strong>3b.4. The replacement policy</strong></p><p>Eventually all frames are occupied.</p><p>Now when a new page must be loaded, the buffer pool needs to decide:</p><p><strong>which current frame should be reused?</strong></p><p>That decision is delegated to an LRUReplacer.</p><p>We will get to that in a minute.</p><p><strong>3b.5. </strong><strong>next_page_id</strong></p><p>When creating a brand new page, we need a fresh logical page id.</p><p>That is what next_page_id is for.</p><p>It points at the next unused location in the file.</p><p><strong>3c. Why </strong><strong>pin_count and </strong><strong>is_dirty suddenly matter</strong></p><p>This is where the page metadata becomes operational.</p><p>If a page is pinned, it is currently in use.</p><p>So even if it is the coldest page in the entire system, we are not allowed to evict it.</p><p>If a page is dirty, it has newer contents in RAM than on disk.</p><p>So before reusing its frame, we must flush it.</p><p>That gives us the two key safety checks:</p><ul><li>pinned pages cannot be evicted</li><li>dirty pages must be written back before eviction</li></ul><p>Without those two rules, the whole thing falls apart.</p><p><strong>3d. Core methods</strong></p><p>The buffer pool API ends up being surprisingly intuitive.</p><p><strong>3d.1 </strong><strong>fetchPage(page_id)</strong></p><p>This means:</p><blockquote>I want page X.</blockquote><p>The manager does roughly this:</p><p>1. Check if page X is already in RAM.<br>2. If yes, return it and increment pin_count.<br>3. If not, find a usable frame.<br>4. If the chosen frame holds a dirty page, flush it first.<br>5. Read page Xfrom disk into that frame.<br>6. Update the page table.<br>7. Pin and return the page.</p><p>That is the heart of the whole system.</p><p><strong>3d.2 </strong><strong>newPage(page_id)</strong></p><p>This means:</p><blockquote>Give me a brand-new empty page.</blockquote><p>We still need a frame for it, just like fetchPage.</p><p>But instead of reading existing bytes from disk, we allocate a fresh logical page id and hand back a zeroed-out page in memory.</p><p>Eventually that page will be flushed to disk.</p><p><strong>3d.3 </strong><strong>unpinPage(page_id, is_dirty)</strong></p><p>This means:</p><blockquote>I am done using this page for now.</blockquote><p>So we decrement pin_count.</p><p>And if the caller modified the page, we mark it dirty.</p><p>This step is extremely important because if pages never get unpinned, the buffer pool eventually has nothing left it is allowed to evict.</p><p>Then everything jams.</p><p><strong>3d.4 </strong><strong>flushPage(page_id) and </strong><strong>flushAllPages()</strong></p><p>These force modified in-memory data back to disk.</p><p>Sometimes we flush one page.</p><p>Sometimes we flush everything.</p><p>Either way, the point is to synchronize RAM state with persistent storage.</p><p><strong>3d.5 </strong><strong>deletePage(page_id)</strong></p><p>This removes a page from the in-memory structures.</p><p>In this stage of the project, page deletion is still fairly primitive.</p><p>The important idea is just that the buffer pool can stop tracking that page and free the corresponding frame if appropriate.</p><p><strong>3d.6 </strong><strong>_findVictim(frame_id)</strong></p><p>This is an internal helper.</p><p>Its job is to answer:</p><blockquote>which frame can I use right now?</blockquote><p>It first tries the free list.</p><p>If there are no unused frames left, it asks the replacement policy for an evictable one.</p><p>That gives us this interface:</p><pre>class BufferPoolManager {<br>public:<br>    BufferPoolManager(size_t pool_size, DiskManager *disk_manager);<br>    ~BufferPoolManager();<br><br>    Page *fetchPage(page_id_t page_id);<br><br>    bool unpinPage(page_id_t page_id, bool is_dirty);<br><br>    Page *newPage(page_id_t &amp;page_id);<br><br>    bool deletePage(page_id_t page_id);<br><br>    bool flushPage(page_id_t page_id);<br><br>    void flushAllPages();<br><br>private:<br>    size_t _pool_size;<br>    Page *_frames;<br><br>    DiskManager *_disk_manager;<br><br>    std::unordered_map&lt;page_id_t, frame_id_t&gt; _page_table;<br><br>    LRUReplacer *_replacer;<br>    std::list&lt;frame_id_t&gt; _free_frames_list;<br><br>    std::mutex _latch;<br><br>    page_id_t _next_page_id;<br><br>    bool _findVictim(frame_id_t *frame_id);<br>};</pre><p>There is a lot going on here, but it is all in service of one idea:</p><p>we have many more pages on disk than frames in memory,</p><p>so the buffer manager decides which few pages get to be “hot” right now.</p><p>— -</p><p><strong>4.</strong><strong> LRUReplacer</strong></p><p>Eventually the free list runs out.</p><p>Now the buffer pool has to evict something.</p><p>But what?</p><p>One common answer is <strong>LRU: Least Recently Used</strong>.</p><p>The idea is simple:</p><p>if a page has not been touched for the longest time, it is a decent candidate for eviction.</p><p>Not always optimal.</p><p>But simple, intuitive, and good enough for this stage.</p><p><strong>4a. How it works</strong></p><p>We keep:</p><ul><li>a doubly linked list</li><li>a hashmap from `frame_id` to the corresponding list node</li></ul><p>This gives us:</p><ul><li>O(1) insert into the list</li><li>O(1) removal from the list</li><li>O(1) lookup of a frame’s position</li></ul><p>The convention is:</p><ul><li>front = hottest / most recently available for replacement bookkeeping</li><li>back = coldest / best victim candidate</li></ul><p><strong>4b. Pinning and unpinning</strong></p><p>This part is easy to miss.</p><p>The replacer only tracks frames that are <strong>evictable.</strong></p><p>If a page is pinned, that frame must not appear in the replacer.</p><p>So:</p><ul><li>when a page becomes pinned, remove its frame from LRU</li><li>when a page becomes unpinned and its pin count drops to zero, add its frame back</li></ul><p>Then when the buffer pool needs space, it asks for a victim and gets the coldest frame from the back.</p><p>Here is the interface:</p><pre>class LRUReplacer {<br>private:<br>    std::list&lt;frame_id_t&gt; _lru_list;<br>    std::unordered_map&lt;frame_id_t, list_iterator&gt; _lru_map;<br><br>    std::mutex _latch;<br><br>public:<br>    LRUReplacer();<br>    ~LRUReplacer();<br><br>    void unpin(frame_id_t frame_id);<br><br>    void pin(frame_id_t frame_id);<br><br>    bool victim(frame_id_t *frame_id);<br><br>    int size();<br>};</pre><p>So yes.</p><p>Something from interview prep finally showed up in a real system.</p><p>Annoying, but fair.</p><p>— -</p><h3>What we actually achieved in this step</h3><p>In Step 0, the interesting idea was:</p><p><strong>make writes durable</strong></p><p>In this step, the interesting idea is:</p><p><strong>make memory usage bounded</strong></p><p>We no longer need the whole database in RAM.</p><p>Instead:</p><ul><li>disk holds the full dataset</li><li>RAM holds only a small working set of pages</li><li>BufferPoolManager moves pages in and out</li><li>DiskManager does the raw I/O</li><li>LRUReplacer decides what can leave</li></ul><p>That is a real architectural shift.</p><p>We are no longer just building a durable hashmap.</p><p>We are starting to build an actual storage engine.</p><p>— -</p><h3>What is still missing?</h3><p>Quite a lot, actually.</p><p>Right now a page is still basically just:</p><pre><br>4096 bytes of mystery<br></pre><p>We know how to move pages around.</p><p>We do <strong>not</strong> yet have a clean structure for storing records inside those pages.</p><p>That is the next step.</p><p>We will turn these blank 4 KB containers into <strong>table pages</strong> with an actual record layout.</p><p>That is where heap files and slotted pages enter the picture.</p><p>But not yet.</p><p>For now, this step was about replacing the “entire database in a hashmap” model with something that can scale beyond RAM.</p><p>And that is the point where the project starts feeling much more like a database.</p><p>PS. You can also find all blogs in my portfolio <a href="https://adityaprasad275.github.io/">https://adityaprasad275.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=503130d77f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Database from Scratch Step 0 — KV store]]></title>
            <link>https://medium.com/@adityanprasad275/building-a-database-from-scratch-step-0-kv-store-d3282b554505?source=rss-4b696ef09b28------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3282b554505</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[build-your-own]]></category>
            <category><![CDATA[key-value-storage]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Aditya Prasad]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 14:15:53 GMT</pubDate>
            <atom:updated>2026-03-10T14:15:53.312Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A tiny persistent key–value store</em></p><p>Note: All code can be found in the github repo <a href="https://github.com/AdityaPrasad275/AtlasDB">github.com/AdityaPrasad275/AtlasDB</a></p><h3>The fairly non-technical story</h3><p><strong>1. Overview</strong></p><p>First we build a simple <strong>key–value store.</strong> It should support three basic operations:</p><ul><li>Set a value for a key INSERT key value</li><li>Retrieve a value GET key</li><li>Delete a key DELETE key</li></ul><p>Nothing fancy yet.</p><p><strong>2. Hashmap!</strong></p><p>Technically, all of these objectives are solved by a simple <strong>hashmap</strong>.</p><p>Initialize a hashmap and you’re done.</p><ul><li>insert → O(1)</li><li>get → O(1)</li><li>delete → O(1)</li></ul><p>Perfect.</p><p>Except… if you close the program, <strong>all the data disappears.</strong> Which completely defeats the point of a database.</p><p>So we actually need two components:</p><ul><li><strong>Data in memory (RAM)</strong> — fast reads and writes</li><li><strong>Persistence on disk</strong> — so data survives program restarts</li></ul><p><strong>3. Persistence</strong></p><p>When dealing with persistence, we care about two main goals:</p><ul><li>Atomicity</li><li>Durability</li></ul><p>Atomicity means an operation either <strong>fully happens or doesn’t happen at all.</strong></p><p>In memory this is rarely a problem. If you insert into a hashmap, it either succeeds or throws an error.</p><p>But writing to disk is different. There are many things that can go wrong:</p><ul><li>power failure</li><li>OS crash</li><li>disk failure</li><li>partial writes</li></ul><p>We don’t want a situation where we try to write:</p><pre><br>INSERT alice hi<br></pre><p>but the program crashes halfway and later we see something like:</p><pre><br>alice → “h”<br></pre><p>That would be… bad.</p><p><strong>4. What actually happens when we write to a file?</strong></p><p>Writing to disk isn’t just one step. The data travels through several layers:</p><pre><br>Program<br> ↓<br>libc / system call<br> ↓<br>Kernel Page Cache (RAM)<br> ↓<br>Filesystemte<br> ↓<br>Block layer<br> ↓<br>Disk controller cache<br> ↓<br>Actual disk / SSD<br></pre><p>You don’t need to memorize these layers. The important idea is:</p><blockquote><strong><em>a lot of caching happens before data actually reaches the disk.</em></strong></blockquote><p>The OS decides:</p><ul><li>what stays in memory</li><li>when writes actually hit the disk</li></ul><p>And even the <strong>disk itself has its own cache</strong>.</p><p>This means a storage device might say “write successful” while the data is still sitting in some cache somewhere.</p><p>Power goes out.</p><p>Data disappears.</p><p>Oops.</p><p><strong>5. Enter </strong><strong>fsync</strong></p><p>Thankfully, there is a system call called fsync</p><p>When we call fsync(fd) we tell the OS</p><blockquote><strong><em>flush everything related to this file to the disk.</em></strong></blockquote><p>This forces the OS to push cached data down to the storage device.</p><p>Now, we can only be <strong>as durable as the hardware allows.</strong> If the disk itself lies about flushing data (which unfortunately happens), there isn’t much we can do.</p><p>But fsyncstill gives us a strong durability guarantee at the OS level.</p><p>To protect even further against partial writes, we could later add things like:</p><ul><li>record lengths</li><li>checksums</li></ul><p>We won’t do that yet.</p><p><strong>6. Ok cool, but is this fast?</strong></p><p>Suppose we store key-value pairs directly in a file like this:</p><pre><br>key,value<br>1,hi<br>2,bye<br></pre><p>Now we want to run:</p><pre><br>INSERT 3 why<br></pre><p>To do this correctly we must:</p><p>1. scan the entire file<br>2. check if the key already exists<br>3. append the new record</p><p>That means <strong>insert becomes O(n).</strong></p><p>And <strong>get becomes O(n)</strong> too.</p><p>Not great.</p><p><strong>7. WAL — Write Ahead Log</strong></p><p>There’s a smarter approach.</p><p>Instead of storing the <strong>state</strong> of the database, we store the <strong>operations</strong> that happened.</p><p>Example log file:</p><pre><br>INSERT name Alice<br>INSERT age 25<br>INSERT city New York<br>INSERT age 26<br>DELETE city<br>DELETE job</pre><p>Each operation is simply <strong>appended to the end of the file</strong>.</p><p>This is very efficient because <strong>appending is cheap</strong>.</p><p>When the program starts, we:</p><p>1. read the entire log<br>2. replay every command<br>3. rebuild the in-memory hashmap</p><p>This is called a <strong>Write Ahead Log (WAL).</strong></p><p>The rule becomes:</p><p>1. Write operation to log<br>2. fsync<br>3. update in-memory state</p><p>If the system crashes, we just <strong>replay the log</strong> when the program restarts.</p><p>And boom.</p><p>We now have a <strong>persistent key–value store</strong>.</p><p>Not amazing yet, but a solid starting point.</p><h3>The technical part</h3><p>We’re implementing this in <strong>C++</strong>.</p><p>We’ll create a class called DataBase<br>Boring name, but it gets the job done.</p><p><strong>1. db.h</strong></p><pre>#pragma once<br><br>#include &lt;string&gt;<br>#include &lt;unordered_map&gt;<br><br>class Database {<br>public:<br>    Database(const std::string logFile);<br>    ~Database();<br><br>    void insert(const std::string &amp;key, const std::string &amp;value);<br>    std::string get(const std::string &amp;key);<br>    void deleteKey(const std::string &amp;key);<br><br>private:<br>    std::string _logFile;<br>    int _fd; // file descriptor<br><br>    std::unordered_map&lt;std::string, std::string&gt; _in_memory_store;<br><br>    void _replayLog();<br>    void _appendLog(const std::string&amp; record);<br>};</pre><p>The public API is simple:</p><ul><li>insert</li><li>get</li><li>delete</li></ul><p>Internally we keep:</p><ul><li>a <strong>file descriptor</strong> for the log file</li><li>an i<strong>n-memory hashmap</strong> for fast lookups</li><li>_replayLog() rebuilds the hashmap when the program starts.</li><li>_appendLog() writes operations to disk safely.</li></ul><p><strong>2. Constructor</strong></p><pre>Database::Database(const std::string logFile)<br>: _logFile(logFile), _fd(-1)<br>{<br>    _fd = open(_logFile.c_str(),<br>               O_RDWR | O_APPEND | O_CREAT | O_CLOEXEC,<br>               0644);<br><br>    // O_RDWR   -&gt; read and write<br>    // O_APPEND -&gt; writes always go to end of file<br>    // O_CREAT  -&gt; create file if it doesn&#39;t exist<br>    // O_CLOEXEC -&gt; don&#39;t leak fd into child processes<br><br>    if (_fd == -1) {<br>        throw std::runtime_error(<br>            &quot;Failed to open logfile: &quot; +<br>            std::string(strerror(errno))<br>        );<br>    }<br><br>    _replayLog();<br>}</pre><p>This:</p><p>1. opens the log file<br>2. verifies it worked<br>3. rebuilds the in-memory state</p><p><strong>3. Ensuring writes are actually written</strong></p><pre>void Database::_appendLog(const std::string&amp; record)<br>{<br>    const char* data = record.c_str();<br>    size_t remaining = record.size();<br><br>    while (remaining &gt; 0) {<br>        ssize_t written = write(_fd, data, remaining);<br><br>        if (written == -1)<br>            throw std::runtime_error(<br>                &quot;write failed: &quot; +<br>                std::string(strerror(errno))<br>            );<br><br>        data += written;<br>        remaining -= written;<br>    }<br><br>    if (fsync(_fd) == -1)<br>        throw std::runtime_error(<br>            &quot;fsync failed: &quot; +<br>            std::string(strerror(errno))<br>        );<br>}</pre><p>Why the loop?</p><p>Because <strong>writedoes not guarantee the full buffer is written in one call.</strong></p><p>Things that can interrupt writes:</p><ul><li>signals</li><li>kernel buffer limits</li><li>partial writes</li></ul><p>So we keep writing until everything is written.</p><p>Then we call fsyncto force the data onto disk.</p><p>This gives us a strong durability guarantee.</p><p>(Again, assuming the storage device behaves.)</p><p><strong>4. Insert / Get / Delete</strong></p><p>Now we just wrap everything nicely.</p><p><strong>4a. Insert</strong></p><pre>void Database::insert(const std::string&amp; key,<br>                      const std::string&amp; value)<br>{<br>    std::string record =<br>        &quot;INSERT &quot; + key + &quot; &quot; + value + &quot;\n&quot;;<br><br>    // problem: value could contain spaces<br>    // even worse: value could contain &quot;\n&quot;<br>    // man this tuff<br><br>    _appendLog(record);<br><br>    _in_memory_store[key] = value;<br><br>    std::cout &lt;&lt; &quot;If no error appeared, it worked!\n&quot;;<br>}</pre><p><strong>4b. Get</strong></p><pre>std::string Database::get(const std::string&amp; key)<br>{<br>    if (_in_memory_store.count(key))<br>        return _in_memory_store[key];<br><br>    return &quot;&quot;;<br>}</pre><p><strong>4c. Delete</strong></p><pre>void Database::deleteKey(const std::string &amp;key)<br>{<br>    std::string record = &quot;DELETE &quot; + key + &quot;\n&quot;;<br><br>    _appendLog(record);<br><br>    _in_memory_store.erase(key);<br><br>    std::cout &lt;&lt; &quot;If no error appeared, it worked!\n&quot;;<br>}</pre><p>Not the most elegant success signal, but it works.</p><p>If something goes wrong, an exception will be thrown.</p><p>If nothing explodes, we’re good.</p><h3>And that’s Step 0</h3><p>We now have a <strong>persistent key–value store</strong> with:</p><ul><li>O(1) reads using a hashmap</li><li>durable writes using fsync</li><li>crash recovery using a write-ahead log</li></ul><p>Of course, this is still extremely primitive.</p><p>Problems we still have:</p><ul><li>the log grows forever</li><li>replay gets slower over time</li><li>we don’t verify log integrity</li><li>no indexing beyond the hashmap</li></ul><p>In the next step we’ll start fixing these issues by adding:</p><ul><li>record lengths</li><li>checksums</li><li>and eventually <strong>B+-tree indexing</strong></li></ul><p>This is where things start getting interesting. I’ll implement it in the same github, and create a new blog for it! For more information you can always check my personal website (which arguably has better formating, no shade to medium whatsoever) <a href="https://adityaprasad275.github.io/">https://adityaprasad275.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3282b554505" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>