<?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 Preran on Medium]]></title>
        <description><![CDATA[Stories by Preran on Medium]]></description>
        <link>https://medium.com/@preran248?source=rss-6111607ccc1d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*47lhSYr0UpZgkwJ7</url>
            <title>Stories by Preran on Medium</title>
            <link>https://medium.com/@preran248?source=rss-6111607ccc1d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:12:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@preran248/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[B-Trees and B+ Trees in DBMS]]></title>
            <link>https://medium.com/@preran248/b-trees-and-b-trees-in-dbms-0556026c8167?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0556026c8167</guid>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[b-tree]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 16:12:04 GMT</pubDate>
            <atom:updated>2026-10-18T16:12:04.137Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding how databases search, organize, and retrieve millions of records efficiently.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*uF2wvvRBPs515avR.png" /></figure><h3>1. Introduction: Why Do Databases Need Trees?</h3><p>Imagine a database containing 10 million student records. Each record stores information such as student ID, name, department, and marks.</p><p>Suppose we execute this query:</p><pre>SELECT *<br>FROM Student<br>WHERE student_id = 10542;</pre><p>Without an index, the database might need to examine many records to find the matching student. This is called a <strong>table scan</strong>.</p><p>An index helps the database locate records without examining the entire table.</p><p>Two important tree structures used for database indexing are:</p><ul><li><strong>B-Tree</strong></li><li><strong>B+ Tree</strong></li></ul><p>Both are balanced search trees designed to organize keys efficiently. They are particularly useful in database systems because they reduce the number of disk accesses required to search for data.</p><h3>2. What Is a B-Tree?</h3><p>A <strong>B-Tree is a self-balancing multiway search tree</strong> in which each node can store multiple keys and have multiple children.</p><p>Unlike a binary search tree, where each node has at most two children, a B-Tree can have many children.</p><p>This makes the tree shorter and helps reduce disk I/O during database operations.</p><h3>Structure of a B-Tree</h3><p>Consider this example:</p><pre>                  [20 | 40]<br>                 /    |     \<br>                /     |      \<br>       [5 | 10 | 15] [25 | 30 | 35] [45 | 50 | 55]</pre><p>The root contains two keys: 20 and 40.</p><p>These keys divide the possible values into three ranges:</p><ul><li>Left child: values less than 20</li><li>Middle child: values from 20 to less than 40</li><li>Right child: values greater than or equal to 40</li></ul><p>The exact boundary convention depends on the implementation. The important idea is that keys guide the search toward the appropriate child.</p><p>In a B-Tree, nodes can contain both keys and associated record references. Depending on the implementation, a search may find the desired record in an internal node or in a leaf node.</p><h3>Important Terminology</h3><p><strong>Root node:</strong> The topmost node of the tree.</p><p><strong>Internal node:</strong> A node that has children and directs the search.</p><p><strong>Leaf node:</strong> A node at the bottom level of the tree.</p><p><strong>Key:</strong> A value used to organize records and guide searches.</p><p><strong>Child pointer:</strong> A reference to another node in the tree.</p><p><strong>Order:</strong> Commonly denoted by (P), representing the maximum number of children an internal node can have under a particular textbook convention.</p><h3>3. Properties of a B-Tree</h3><p>For a B-Tree of order (P), using the common definition that order means maximum children:</p><ol><li>An internal node can have at most (P) children.</li><li>A node with (k) children has (k-1) separator keys.</li><li>A non-root internal node generally has at least (\lceil P/2\rceil) children.</li><li>The root has at least two children when it is an internal node.</li><li>All leaves occur at the same depth.</li><li>Keys within each node are stored in sorted order.</li></ol><p>These rules help maintain the tree’s balance.</p><p><strong>Why does balance matter?</strong></p><p>If a tree becomes excessively tall, searching requires traversing more nodes. A balanced tree keeps the number of levels small, making searches more efficient.</p><h3>4. Searching in a B-Tree</h3><p>Suppose we want to find the key 30.</p><p>Using our earlier tree:</p><pre>                 [20 | 40]<br>                 /    |     \<br>       [5 | 10 | 15] [25 | 30 | 35] [45 | 50 | 55]</pre><p>The search works as follows:</p><ol><li>Start at the root: [20 | 40].</li><li>Compare 30 with the root keys.</li><li>Since 20 &lt; 30 &lt; 40, follow the middle child.</li><li>Search [25 | 30 | 35].</li><li>Find 30 and retrieve its associated record reference.</li></ol><p>The database does not need to scan every record. It follows the appropriate pointers through the tree.</p><h3>5. Insertion in a B-Tree</h3><p>When a new key is inserted, the tree must preserve its ordering and balance.</p><p>Consider inserting a key into a node that already contains the maximum permitted number of keys.</p><p>The general insertion process is:</p><ol><li>Search for the appropriate leaf position.</li><li>Insert the key in sorted order.</li><li>If the node exceeds its capacity, split it into two nodes.</li><li>Promote a separator key into the parent.</li><li>If the parent also overflows, split it as well.</li><li>If the root splits, create a new root.</li></ol><p>This process ensures that the tree remains balanced.</p><p><strong>Remember:</strong> A split can propagate upward, potentially increasing the tree’s height by one.</p><h3>6. Deletion in a B-Tree</h3><p>Deletion is more complicated because removing a key can leave a node with too few keys.</p><p>The general process is:</p><ol><li>Locate the key to delete.</li><li>Remove it, or replace it with a predecessor or successor if necessary.</li><li>Check whether the affected node still satisfies its minimum occupancy requirement.</li><li>If it does not, borrow a key through the parent from a sibling, when possible.</li><li>Otherwise, merge nodes and update the parent.</li><li>Continue repairing the tree if the parent becomes underfull.</li></ol><p>The root may shrink if its last separator key is removed and it is left with a single child.</p><p>These operations preserve the B-Tree’s ordering and balance.</p><h3>7. Insertion in a B-Tree: A Step-by-Step Example</h3><p>Let’s understand insertion using an order-4 B-Tree.</p><p>For this example:</p><ul><li>Maximum children per node = 4</li><li>Maximum keys per node = 3</li><li>Minimum keys in a non-root node = 1</li></ul><h3>Example: Insert 10, 20, 30, 40, and 50</h3><p><strong>Step 1: Insert 10, 20, and 30</strong></p><p>Initially, the tree is empty. We insert the keys in sorted order.</p><pre>[10 | 20 | 30]</pre><p>The root can hold up to three keys, so no split is needed.</p><p><strong>Step 2: Insert 40</strong></p><p>Inserting 40 would produce four keys in the root:</p><pre>[10 | 20 | 30 | 40]</pre><p>This exceeds the maximum capacity. The node must split, and a separator key is promoted to become the new root.</p><p>One valid result is:</p><pre>            [20]<br>           /    \<br>        [10]  [30 | 40]</pre><p>The tree now has a root and two children.</p><p><strong>Step 3: Insert 50</strong></p><p>Since 50 is greater than 20, we follow the right child and insert it there.</p><pre>            [20]<br>           /    \<br>        [10]  [30 | 40 | 50]</pre><p>The right child has three keys, which is allowed. The insertion is complete.</p><h3>What happens if we insert another key?</h3><p>Suppose we insert 60. The right child would overflow, so it must split. The promoted separator is inserted into the root:</p><pre>               [20 | 40]<br>              /    |    \<br>           [10]  [30]  [50 | 60]</pre><p>The tree remains balanced, and every node satisfies its capacity constraints.</p><p><strong>Key takeaway:</strong> When a node overflows, split it and promote a separator key to the parent. If the parent overflows, the process can continue upward.</p><h3>8. Deletion in a B-Tree: A Step-by-Step Example</h3><p>Deletion is more complex because removing a key may leave a node with fewer keys than permitted.</p><p>There are three common situations:</p><ol><li>Deletion without underflow.</li><li>Borrowing a key from a sibling.</li><li>Merging nodes when borrowing is impossible.</li></ol><h3>Case 1: Deletion without underflow</h3><p>Consider this tree:</p><pre>             [20 | 40]<br>            /    |    \<br>        [5 | 10] [25 | 30] [45 | 50]</pre><p>Let’s delete 10.</p><p>The left leaf becomes [5].</p><pre>             [20 | 40]<br>            /    |    \<br>           [5] [25 | 30] [45 | 50]</pre><p>The node still contains one key, satisfying the minimum requirement. No further adjustment is needed.</p><h3>Case 2: Deletion requiring borrowing</h3><p>Consider this tree:</p><pre>             [20]<br>            /    \<br>          [10]  [25 | 30]</pre><p>Delete 10. The left child becomes empty, violating the minimum occupancy rule.</p><p>The right sibling has two keys, so it can lend one.</p><p>The keys are redistributed, and the parent separator is updated:</p><pre>             [25]<br>            /    \<br>          [20]   [30]</pre><p>The left child receives 20, while 25 moves up from the right sibling to become the parent separator.</p><p>Both children now contain one key, so the tree is valid again.</p><h3>Case 3: Deletion requiring merging</h3><p>Consider this tree:</p><pre>             [20]<br>            /    \<br>          [10]   [30]</pre><p>Delete 10. The left child becomes empty.</p><p>The right sibling contains only one key, so it cannot lend a key without becoming underfull.</p><p>Instead, merge the empty child, the parent separator 20, and the sibling containing 30.</p><pre>[20 | 30]</pre><p>The former root becomes empty and is removed. The merged node becomes the new root, reducing the height of the tree.</p><h3>Summary of B-Tree deletion</h3><ul><li>If the node still satisfies the minimum occupancy rule, stop.</li><li>If it becomes underfull, try borrowing from a sibling.</li><li>If borrowing is impossible, merge with a sibling using the parent separator.</li><li>If the parent becomes underfull, repeat the repair process upward.</li></ul><p><strong>Key takeaway:</strong> Deletion must preserve both the search-tree ordering and the B-Tree’s balance. Borrowing redistributes keys; merging combines nodes and may reduce the tree’s height.</p><h3>7. What Is a B+ Tree?</h3><p>A <strong>B+ Tree is a variation of a B-Tree designed to make database indexing and ordered data access efficient</strong>.</p><p>The most important difference is where the data entries are stored.</p><p>In a B+ Tree:</p><ul><li>Internal nodes contain separator keys and child pointers.</li><li>All actual data entries, or pointers to the corresponding records, are stored at the leaf level.</li><li>Leaf nodes are linked together in sorted order.</li></ul><p>The internal nodes act like a navigation system. The leaves contain the entries we ultimately want to access.</p><h3>Structure of a B+ Tree</h3><p>Consider this simplified example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*I0Kh-Pd9vMSBWCJq.jpg" /></figure><pre>                    [20 | 40]<br>                   /    |     \<br>                  /     |      \<br>          [5 | 10 | 15] [20 | 25 | 35] [40 | 45 | 50]<br>                  ───────→────────→<br>                   Linked leaf nodes</pre><p>Here, 20 and 40 appear in the root as separator keys and may also appear in leaf nodes as data entries.</p><p>The repeated keys are intentional: an internal key guides the search, while the corresponding leaf entry represents the indexed value.</p><p>A search for 25 proceeds as follows:</p><ol><li>Start at the root.</li><li>Use the separator keys to choose the middle child.</li><li>Reach the appropriate leaf.</li><li>Find 25 and retrieve the associated record reference.</li></ol><p>In a B+ Tree, a search typically continues to a leaf even if the searched key matches an internal separator.</p><h3>8. Why Are All Leaf Nodes Connected in a B+ Tree?</h3><p>This is one of the most important features of a B+ Tree.</p><p>Suppose a university wants to retrieve all students whose marks are between 20 and 40.</p><pre>SELECT *<br>FROM Student<br>WHERE marks BETWEEN 20 AND 40;</pre><p>The database needs more than one individual value. It needs a continuous range of values.</p><p>Linked leaves make this operation efficient.</p><h3>Without linked leaves</h3><p>The database could find the first value, then need additional tree navigation to locate subsequent values.</p><h3>With linked leaves</h3><p>The database can:</p><ol><li>Search the tree once to find the first relevant leaf.</li><li>Read entries in sorted order.</li><li>Follow the leaf links to subsequent leaves.</li><li>Stop when the values exceed the upper limit.</li></ol><p>For example:</p><pre>[10 | 15] → [20 | 25 | 30] → [35 | 40 | 45]</pre><p>For a range from 20 through 40, the database starts at 20, follows the links, and stops after 40.</p><p>This is why B+ Trees are particularly effective for:</p><ul><li>Range queries</li><li>Sequential scans over indexed keys</li><li>Finding the next or previous key</li><li>Queries involving ORDER BY</li><li>Reading records in sorted order</li></ul><p>The exact implementation may link leaves in one direction or both directions.</p><h3>9. Searching in a B+ Tree</h3><p>Searching follows a similar path to searching in a B-Tree, but there is one important distinction: the search typically ends at a leaf.</p><p>For example, to search for 35:</p><pre>                 [20 | 40]<br>                /    |     \<br>               /     |      \<br>        [5 | 10] [20|25|35] [40 | 45]</pre><ol><li>Compare 35 with the root separators.</li><li>Since 20 ≤ 35 &lt; 40, follow the middle pointer.</li><li>Search the leaf [20 | 25 | 35].</li><li>Find 35 and follow its record pointer.</li></ol><p>This consistent search path is useful because data entries are kept at the leaf level.</p><h3>10. Insertion in a B+ Tree</h3><p>Insertion must maintain both the tree’s balance and the linked sequence of leaves.</p><p>The general process is:</p><ol><li>Search for the appropriate leaf.</li><li>Insert the new key in sorted order.</li><li>If the leaf overflows, split it into two leaves.</li><li>Update the leaf links so that the new leaves remain connected in sorted order.</li><li>Copy an appropriate separator key into the parent.</li><li>If an internal node overflows, split it and propagate the necessary separator upward.</li><li>If the root splits, create a new root.</li></ol><p>Unlike a B-Tree, splitting a B+ Tree leaf normally retains all data entries at the leaf level. A separator is copied into the parent rather than moving the only copy of that data entry out of the leaf.</p><h3>11. Deletion in a B+ Tree</h3><p>Deleting a key also requires preserving the structure.</p><ol><li>Find the appropriate leaf.</li><li>Delete the entry.</li><li>Check whether the leaf has enough entries.</li><li>If it is underfull, try borrowing from a sibling.</li><li>If borrowing is not possible, merge it with a sibling.</li><li>Update separator keys and parent pointers as necessary.</li><li>Repair any underfull internal nodes.</li></ol><p>Leaf links must also be updated if two leaves merge.</p><p>This keeps the tree balanced and ensures that sequential traversal still works correctly.</p><h3>12. B-Tree vs. B+ Tree: Key Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0DMbExmWR-pEHPyyClqRA.png" /></figure><h3>13. What Determines the Order of a Tree?</h3><p>The order is a design parameter, not something determined directly by the application’s business logic.</p><p>In database indexes, node capacity depends on factors such as:</p><ul><li>Database page size</li><li>Size of each key</li><li>Size of child pointers</li><li>Record-reference size</li><li>Node overhead and implementation rules</li></ul><p>For example, if the order is (P=4), using the common maximum-children definition:</p><ul><li>Maximum children per internal node = 4.</li><li>Maximum separator keys per internal node = 3.</li><li>A non-root internal node generally has at least 2 children.</li></ul><p>Actual B+ Tree implementations may specify leaf capacity separately from internal-node capacity.</p><p>A larger fan-out allows a node to point to more children, often reducing the number of levels required to index a large dataset.</p><h3>14. Where Are B+ Trees Used?</h3><p>B+ Trees are widely used for database indexes because they support efficient lookups and ordered traversal.</p><p>For example, an index on student_id can help with:</p><pre>-- Find one student<br>SELECT *<br>FROM Student<br>WHERE student_id = 10542;</pre><pre>-- Find a range of students<br>SELECT *<br>FROM Student<br>WHERE student_id BETWEEN 10000 AND 10100;</pre><pre>-- Read students in index order<br>SELECT *<br>FROM Student<br>ORDER BY student_id;</pre><p>The database optimizer decides whether using the index is beneficial for a particular query. An index does not guarantee that every query will use it.</p><h3>15. Final Takeaway</h3><p>B-Trees and B+ Trees solve the same broad problem: keeping indexed data organized so that databases can locate entries efficiently.</p><p>The easiest way to remember their difference is:</p><p><strong>B-Tree:</strong> Data entries may be found in internal nodes or leaf nodes.</p><p><strong>B+ Tree:</strong> Internal nodes guide the search, all data entries are at the leaf level, and linked leaves make sequential and range access efficient.</p><p>When studying DBMS, focus on three things: <strong>node structure, how insertion and deletion preserve balance, and why linked leaves make B+ Trees especially useful for database indexing.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0556026c8167" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Instagram-Style Feed from Scratch: V7 → V13]]></title>
            <link>https://medium.com/@preran248/building-an-instagram-style-feed-from-scratch-v7-v13-631feed4f8db?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/631feed4f8db</guid>
            <category><![CDATA[instagram-reels]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[instagram-feed]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 15:32:18 GMT</pubDate>
            <atom:updated>2026-09-04T15:32:18.925Z</atom:updated>
            <content:encoded><![CDATA[<h3>From a Basic Feed to Real-Time Personalization</h3><p>In my previous article, I started with a simple question:</p><blockquote><strong><em>How do you actually build an Instagram-style feed from scratch?</em></strong></blockquote><p>The first version was intentionally simple. I started with MongoDB, fetched posts, sorted them chronologically, and returned them to the client.</p><p>Then, version by version, the system evolved.</p><p>We added cursor pagination, database indexes, load testing, Redis, fanout-on-write, hybrid fanout, candidate generation, heuristic ranking, and diversity-aware re-ranking.</p><p>By V6, the architecture looked roughly like this:</p><pre>Posts<br>                          |<br>                          ↓<br>                Candidate Generation<br>                          |<br>          ┌───────────────┼───────────────┐<br>          ↓               ↓               ↓<br>      Following        Trending       Exploration<br>          └───────────────┼───────────────┘<br>                          ↓<br>                    Feature Extraction<br>                          ↓<br>                    Heuristic Ranking<br>                          ↓<br>                  Diversity Re-ranking<br>                          ↓<br>                       Top 20</pre><p>This was already much closer to how a real recommendation system is structured.</p><p>But there was still one major limitation:</p><p><strong>The system wasn’t learning from the user.</strong></p><p>It could rank content.</p><p>It could retrieve candidates.</p><p>It could make the feed diverse.</p><p>But it didn’t really understand how users behaved.</p><p>That became the starting point for V7.</p><p>The evolution from here was:</p><pre>V7  → Event &amp; Feedback Pipeline<br>V8  → Training Dataset<br>V9  → Machine Learning Ranking<br>V10 → Intelligent Candidate Retrieval<br>V11 → Multi-Objective Ranking<br>V12 → Real-Time Personalization<br>V13 → Exploration vs Exploitation</pre><p>V13 is the next stage of the project, so it is intentionally treated as <strong>future work</strong> rather than an implemented feature.</p><h3>V7 — Event &amp; Feedback Pipeline</h3><p>Until V6, our system was essentially a one-way pipeline:</p><pre>User<br> ↓<br>Feed</pre><p>The recommendation system produced content, but we weren’t systematically capturing what happened afterward.</p><p>That’s a huge problem.</p><p>Imagine the feed shows:</p><pre>Post A<br>Post B<br>Post C<br>Post D</pre><p>The user then:</p><pre>likes A<br>ignores B<br>saves C<br>shares D</pre><p>Those actions contain valuable information.</p><p>They tell us something about the user’s preferences.</p><p>So the next step was to build an <strong>event and feedback pipeline</strong>.</p><h3>What Is an Event?</h3><p>An event represents an action taken by a user.</p><p>For example:</p><pre>impression<br>view<br>like<br>comment<br>save<br>share</pre><p>For future video content such as Reels, this can become much richer:</p><pre>impression<br>view<br>watch_25<br>watch_50<br>watch_75<br>watch_100<br>rewatch<br>skip<br>like<br>comment<br>save<br>share</pre><p>A generic event structure might look like:</p><pre>{<br>  user: userId,<br>  content: contentId,<br>  contentType: &quot;post&quot;,<br>  eventType: &quot;like&quot;,<br>  timestamp: new Date()<br>}</pre><p>The important decision here is that the event system is <strong>content-type agnostic</strong>.</p><p>The same pipeline can eventually handle:</p><pre>Posts<br>Reels<br>Stories</pre><p>without creating an entirely separate feedback architecture for each one.</p><h3>The Importance of Impressions</h3><p>One event deserves special attention:</p><pre>impression</pre><p>An impression means that the recommendation system actually showed a piece of content to the user.</p><p>Why is that important?</p><p>Consider these two situations:</p><pre>Post A<br>→ never shown to user</pre><pre>Post B<br>→ shown to user<br>→ user didn&#39;t interact</pre><p>We cannot treat both as:</p><pre>negative feedback</pre><p>For Post A, we have no information.</p><p>For Post B, we have at least some information.</p><p>Maybe the user saw it and wasn’t interested.</p><p>Maybe they didn’t notice it.</p><p>Maybe they simply didn’t have enough time.</p><p>So:</p><blockquote><strong><em>No interaction is not automatically a negative interaction.</em></strong></blockquote><p>This distinction becomes extremely important when creating our machine-learning dataset.</p><h3>Capturing the State at Impression Time</h3><p>There is another subtle problem: <strong>data leakage</strong>.</p><p>Suppose a post had:</p><pre>10 likes<br>2 comments</pre><p>when it was shown to the user.</p><p>Later, the post becomes popular:</p><pre>10,000 likes<br>500 comments</pre><p>If we train the model using the second set of numbers for the original recommendation, we’re giving the model information that didn’t exist when the recommendation was made.</p><p>So ideally, the impression event stores the feature snapshot:</p><pre>{<br>  eventType: &quot;impression&quot;,</pre><pre>  features: {<br>    likes: 10,<br>    comments: 2,<br>    postAgeHours: 1.5,<br>    isFollowingAuthor: true,<br>    source: &quot;following&quot;<br>  },</pre><pre>  timestamp: new Date()<br>}</pre><p>Now we know exactly what information the ranking system had at that moment.</p><p>This becomes our bridge from a running application to a machine-learning system.</p><h3>The Feedback Loop</h3><p>V7 fundamentally changes the architecture.</p><p>Before:</p><pre>Candidate Generation<br>        ↓<br>Ranking<br>        ↓<br>Feed</pre><p>After V7:</p><pre>Candidate Generation<br>        ↓<br>Ranking<br>        ↓<br>Feed<br>        ↓<br>User Interaction<br>        ↓<br>Event Pipeline<br>        ↓<br>Training Data</pre><p>Now the system can observe its own recommendations.</p><p>And that opens the door to machine learning.</p><h3>V8 — Turning Events into Training Data</h3><p>Collecting events is useful, but raw events aren’t directly usable by our neural network.</p><p>Suppose we have:</p><pre>10:00 → impression → Post A<br>10:02 → like       → Post A</pre><pre>10:05 → impression → Post B</pre><pre>10:08 → impression → Post C<br>10:10 → save       → Post C</pre><p>We need to transform these events into training examples.</p><p>Conceptually, one training example represents:</p><pre>User<br>+<br>Post<br>+<br>Features at impression time<br>+<br>Actions after the impression</pre><p>For example:</p><p>likescommentsagefollowingsourcelikecommentsaveshare1021.51following1010503.20trending00002040.81following1110</p><p>Now the data has a clear input and target.</p><h3>Multi-Label Prediction</h3><p>A user can perform multiple actions on the same post.</p><p>For example:</p><pre>like    = 1<br>comment = 0<br>save    = 1<br>share   = 0</pre><p>So our target is:</p><p>y=[1,0,1,0]y = [1,0,1,0]</p><p>This is a <strong>multi-label prediction</strong> problem.</p><p>The model can independently predict:</p><p>P(like)P(like) P(comment)P(comment) P(save)P(save) P(share)P(share)</p><p>We don’t use Softmax because these actions aren’t mutually exclusive.</p><p>A user can like and save the same post.</p><h3>Time-Aware Training</h3><p>Another problem appears when splitting our dataset.</p><p>We don’t want to randomly mix old and future interactions.</p><p>Instead:</p><pre>Past events<br>    ↓<br>Training<br></pre><pre>More recent events<br>    ↓<br>Validation / Test</pre><p>For example:</p><pre>January ───────── June<br>       Training</pre><pre>July ─── August<br>       Validation/Test</pre><p>This is much closer to the real-world problem:</p><blockquote><strong><em>Use the past to predict the future.</em></strong></blockquote><h3>V9 — Machine Learning Ranking</h3><p>Now we have enough data to replace our manually designed ranking formula with a learned model.</p><p>Previously, our ranking system used manually selected signals:</p><pre>likes<br>comments<br>recency<br>relationship<br>source</pre><p>and combined them using manually chosen weights.</p><p>For example:</p><p>Score=likes+3×comments+recency+relationshipScore = likes + 3 \times comments + recency + relationship</p><p>This was useful for building the system.</p><p>But the weights were chosen by us.</p><p>Now we want the model to learn those relationships from user behavior.</p><h3>Our First Neural Ranker</h3><p>A simple neural network can look like:</p><pre>Input Features<br>      ↓<br>Dense 256<br>      ↓<br>ReLU<br>      ↓<br>Dense 128<br>      ↓<br>ReLU<br>      ↓<br>Dense 64<br>      ↓<br>ReLU<br>      ↓<br>Output</pre><p>The input could initially contain:</p><pre>likes<br>comments<br>postAgeHours<br>isFollowingAuthor<br>source</pre><p>The network learns weights and biases that map these features to predicted user behavior.</p><h3>What Happens During Training?</h3><p>The training loop is:</p><pre>Features<br>   ↓<br>Neural Network<br>   ↓<br>Predictions<br>   ↓<br>Loss<br>   ↓<br>loss.backward()<br>   ↓<br>optimizer.step()</pre><p>One important distinction I learned here is that:</p><pre>loss.backward()</pre><p>does <strong>not</strong> update the weights.</p><p>It calculates the gradients of the loss with respect to the trainable parameters using reverse-mode automatic differentiation.</p><p>Then:</p><pre>optimizer.step()</pre><p>actually updates the parameters.</p><p>So conceptually:</p><p>W←W−η∂L∂WW \leftarrow W-\eta\frac{\partial L}{\partial W}</p><p>where:</p><ul><li>WW = model weights</li><li>LL = loss</li><li>η\eta = learning rate</li></ul><p>This process repeats over many examples until the model learns useful parameters.</p><h3>V10 — Intelligent Candidate Retrieval</h3><p>At this point, we have a machine-learning ranker.</p><p>But now we run into a scalability problem.</p><p>Imagine the system has:</p><pre>10 million posts</pre><p>We obviously can’t send all 10 million through the ranking model every time a user opens the app.</p><p>So recommendation systems are generally divided into stages.</p><p>Instead of:</p><pre>10,000,000<br>     ↓<br>Ranking<br>     ↓<br>20</pre><p>we want:</p><pre>10,000,000<br>      ↓<br>Candidate Retrieval<br>      ↓<br>~1,000<br>      ↓<br>Ranking<br>      ↓<br>~100<br>      ↓<br>Re-ranking<br>      ↓<br>20</pre><p>This gives us an important separation:</p><blockquote><strong><em>Candidate generation finds what is worth considering.</em></strong></blockquote><blockquote><strong><em>Ranking decides what is best.</em></strong></blockquote><h3>Candidate Sources</h3><p>Our existing candidate sources remain useful:</p><pre>Following<br>Trending<br>Exploration</pre><p>They provide different types of candidates.</p><h3>Following</h3><p>Posts from accounts the user follows.</p><h3>Trending</h3><p>Posts currently receiving strong engagement.</p><h3>Exploration</h3><p>Posts outside the user’s normal social graph.</p><p>We merge these sources:</p><pre>Following<br>    \<br>Trending ----→ Merge → Deduplicate<br>    /<br>Exploration</pre><p>and produce our candidate pool.</p><h3>Embeddings Enter the System</h3><p>V10 is also where content embeddings become particularly useful.</p><p>A post can be converted into a numerical representation:</p><pre>&quot;How transformers work&quot;<br>        ↓<br>Embedding model<br>        ↓<br>[0.12, -0.42, 0.81, ...]</pre><p>The vector represents the semantic characteristics of the content.</p><p>Now two posts such as:</p><pre>&quot;How Transformers work&quot;</pre><pre>&quot;Understanding self-attention&quot;</pre><p>can potentially be recognized as semantically similar even if they don’t contain exactly the same words.</p><p>This opens the door to vector-based candidate retrieval.</p><p>Instead of only asking:</p><blockquote><em>Who does this user follow?</em></blockquote><p>we can eventually ask:</p><blockquote><strong><em>What content is similar to the content this user has shown interest in?</em></strong></blockquote><p>That’s a major step toward intelligent retrieval.</p><h3>V11 — Multi-Objective ML Ranking</h3><p>V10 improves candidate retrieval.</p><p>Now we want the ranking model itself to become more sophisticated.</p><p>Instead of predicting one generic notion of engagement, we can predict multiple user actions independently.</p><p>The model can output:</p><pre>P(like)<br>P(comment)<br>P(save)<br>P(share)</pre><p>For example:</p><pre>like    = 0.82<br>comment = 0.21<br>save    = 0.73<br>share   = 0.08</pre><p>Now the ranking system has a much richer understanding of the candidate.</p><h3>Why Predict Multiple Actions?</h3><p>Not all interactions have the same meaning.</p><p>A like tells us something.</p><p>A save may tell us something stronger.</p><p>A share can be an even stronger indication that the content was valuable enough to pass on.</p><p>So we can initially construct a ranking score such as:</p><p>Score=1.0P(like)+3.0P(comment)+4.0P(save)+5.0P(share)Score = 1.0P(like) + 3.0P(comment) + 4.0P(save) + 5.0P(share)</p><p>Again, these aren’t magical constants.</p><p>They’re an initial design.</p><p>The eventual system can learn better objectives from actual user behavior.</p><h3>V11 Input Becomes Richer</h3><p>The ranking model can now combine:</p><pre>User information<br>+<br>Post information<br>+<br>Relationship information<br>+<br>Engagement<br>+<br>Recency<br>+<br>Candidate source<br>+<br>Content representation</pre><p>The goal is no longer simply:</p><blockquote><em>“Is this post popular?”</em></blockquote><p>It’s:</p><blockquote><strong><em>“How likely is this particular user to find this particular post valuable?”</em></strong></blockquote><p>That distinction is the heart of personalization.</p><h3>V12 — Real-Time Personalization</h3><p>This is where the system becomes significantly more interesting.</p><p>A user’s interests are not static.</p><p>Suppose historically a user mostly interacts with:</p><pre>AI<br>Programming<br>Machine Learning</pre><p>But today they spend an hour interacting with:</p><pre>Football<br>Football<br>Football</pre><p>Should we retrain our entire neural network?</p><p>No.</p><p>The model weights don’t need to change.</p><p>Instead, we maintain <strong>real-time user state</strong>.</p><p>This gives us two different representations:</p><pre>U_long<br>U_short</pre><h3>Long-Term Memory</h3><p>Long-term memory represents:</p><blockquote><strong><em>What does this user generally like?</em></strong></blockquote><p>We build it from historical interactions with content embeddings.</p><p>Conceptually:</p><pre>Historical Interactions<br>        ↓<br>Post Embeddings<br>        ↓<br>Interaction Strength<br>        ↓<br>Time Decay<br>        ↓<br>U_long</pre><p>The important characteristic is that it changes <strong>slowly</strong>.</p><p>A single interaction shouldn’t completely change someone’s long-term interests.</p><p>For example:</p><pre>U_long</pre><pre>AI             ████████<br>Programming    ██████<br>Machine ML     █████<br>Photography    ███<br>Football       ██</pre><h3>Short-Term Memory</h3><p>Short-term memory answers a different question:</p><blockquote><strong><em>What is this user interested in right now?</em></strong></blockquote><p>We use recent interactions:</p><pre>Recent Interactions<br>        ↓<br>Post Embeddings<br>        ↓<br>Interaction Weights<br>        ↓<br>Recency Decay<br>        ↓<br>U_short</pre><p>For example:</p><pre>User recently:</pre><pre>liked AI post<br>saved Transformer post<br>saved Diffusion post</pre><p>Those embeddings have a strong influence on the current short-term representation.</p><h3>Recency Decay</h3><p>A recent interaction should generally matter more than an old interaction for short-term memory.</p><p>We can model this using exponential decay:</p><p>R(t)=e−λtR(t)=e^{-\lambda t}</p><p>where:</p><ul><li>tt = age of the interaction</li><li>λ\lambda = decay rate</li></ul><p>Then an interaction’s influence can be represented as:</p><p>w=interactionWeight×recencyWeightw = interactionWeight \times recencyWeight</p><p>So:</p><pre>Recent + strong interaction<br>        ↓<br>Large influence</pre><pre>Old + weak interaction<br>        ↓<br>Small influence</pre><p>This allows the short-term representation to change rapidly without destroying the user’s historical profile.</p><h3>Long-Term vs Short-Term</h3><p>This distinction is critical.</p><p>Imagine a user whose historical interests are:</p><pre>AI<br>Programming<br>Machine Learning</pre><p>but their recent activity is:</p><pre>Football<br>Football<br>Football</pre><p>We want:</p><pre>U_long<br>→ AI / Programming / ML</pre><p>and:</p><pre>U_short<br>→ Football</pre><p>Now the system knows two things simultaneously:</p><blockquote><strong><em>What this user generally likes</em></strong></blockquote><p>and</p><blockquote><strong><em>What this user currently seems interested in</em></strong></blockquote><p>That is far more useful than trying to represent the user with a single static profile.</p><h3>Creating the Current User Representation</h3><p>We can combine the two:</p><p>Ucurrent=αUlong+(1−α)UshortU_{current} = \alpha U_{long} + (1-\alpha)U_{short}</p><p>For example:</p><pre>70% long-term<br>30% short-term</pre><p>This creates a representation that is:</p><pre>stable<br>+<br>responsive</pre><p>A user can temporarily explore a new interest without completely rewriting their historical profile.</p><h3>Comparing User and Post Embeddings</h3><p>Now every candidate post has an embedding:</p><p>PP</p><p>and the user has:</p><p>UlongU_{long} UshortU_{short} UcurrentU_{current}</p><p>We can calculate cosine similarity:</p><p>sim(U,P)=U⋅P∣∣U∣∣∣∣P∣∣sim(U,P) = \frac{U\cdot P} {||U||||P||}</p><p>For example:</p><pre>Post A</pre><pre>long-term similarity  = 0.91<br>short-term similarity = 0.32</pre><p>This means the post strongly matches the user’s historical interests but isn’t particularly aligned with their recent interests.</p><p>Another candidate might have:</p><pre>Post B</pre><pre>long-term similarity  = 0.30<br>short-term similarity = 0.94</pre><p>Now we know that the post matches what the user is interested in <strong>right now</strong>.</p><p>These similarity signals can then be provided to the ranking model.</p><h3>Real-Time Personalization</h3><p>The important part is what happens after the user interacts.</p><p>Suppose the user saves a post:</p><pre>User saves post<br>      ↓<br>Event Pipeline<br>      ↓<br>Post Embedding<br>      ↓<br>Update U_short<br>      ↓<br>Slowly update U_long</pre><p>The next feed request uses the updated user state.</p><pre>New U_short<br>+<br>New U_long<br>+<br>Candidate Posts<br>        ↓<br>Ranking<br>        ↓<br>Personalized Feed</pre><p>The model itself did not need to be retrained.</p><p>This gives us two different types of learning:</p><pre>Model learning<br>→ happens periodically through training</pre><pre>User-state learning<br>→ happens continuously through interactions</pre><p>That separation is extremely important.</p><h3>Diversity Re-ranking</h3><p>There is another problem that appears once ranking becomes good.</p><p>Suppose the model gives us:</p><pre>AI post #1 → 0.98<br>AI post #2 → 0.97<br>AI post #3 → 0.96<br>AI post #4 → 0.95<br>Football   → 0.91<br>Travel     → 0.89</pre><p>If we simply take the top 20, the feed could become:</p><pre>AI<br>AI<br>AI<br>AI<br>AI<br>AI<br>...</pre><p>The posts may individually have excellent scores, but the <strong>overall feed experience is repetitive</strong>.</p><p>That’s why we use diversity re-ranking.</p><p>The ranking model asks:</p><blockquote><strong><em>How good is each post individually?</em></strong></blockquote><p>The re-ranker asks:</p><blockquote><strong><em>How good is this collection of posts together?</em></strong></blockquote><h3>Author Diversity</h3><p>We might prevent one creator from dominating the feed.</p><p>For example:</p><pre>Alice<br>Alice<br>Alice<br>Alice<br>Bob<br>Charlie</pre><p>could become:</p><pre>Alice<br>Alice<br>Bob<br>Charlie<br>Alice</pre><p>while preserving as much relevance as possible.</p><h3>Semantic Diversity</h3><p>Once we have embeddings, we can take this further.</p><p>Suppose:</p><pre>Post A → &quot;How Transformers work&quot;<br>Post B → &quot;Understanding self-attention&quot;<br>Post C → &quot;Attention mechanisms explained&quot;</pre><p>Their embeddings might be extremely similar.</p><p>Even if they come from different creators, showing all three consecutively isn’t necessarily useful.</p><p>So eventually the re-ranker can penalize candidates that are too similar to posts already selected.</p><p>This creates a feed that is not only relevant, but also <strong>varied</strong>.</p><h3>The Complete V12 Architecture</h3><p>At this point, the system looks like:</p><pre>ALL POSTS<br>                             |<br>                             ↓<br>                  Candidate Generation<br>                             |<br>            ┌────────────────┼────────────────┐<br>            ↓                ↓                ↓<br>        Following         Trending        Exploration<br>            └────────────────┼────────────────┘<br>                             ↓<br>                         Candidates<br>                             ↓<br>                     Feature Extraction<br>                             ↓<br>              ┌──────────────┴──────────────┐<br>              ↓                             ↓<br>          User State                   Post State<br>              ↓                             ↓<br>      U_long + U_short              Post Embedding<br>              ↓                             ↓<br>           U_current                  Similarity<br>              └──────────────┬──────────────┘<br>                             ↓<br>                         ML Ranker<br>                             ↓<br>                 P(like/comment/save/share)<br>                             ↓<br>                       Ranking Score<br>                             ↓<br>                    Diversity Re-ranking<br>                             ↓<br>                           Top 20<br>                             ↓<br>                           USER<br>                             ↓<br>                       Interaction<br>                             ↓<br>                           EVENT<br>                             ↓<br>                  ┌──────────┴──────────┐<br>                  ↓                     ↓<br>             User Memory           Training Data<br>                  ↓                     ↓<br>          U_short / U_long        Model Training<br>                  ↓                     ↓<br>             Next Feed            New Model</pre><p>This is the point where the feed has become a genuine feedback-driven recommendation system.</p><h3>V13 — Exploration vs Exploitation</h3><p>And now we reach the <strong>next problem</strong>.</p><p>This is not implemented yet.</p><p>It’s where I want to take the system next.</p><p>Suppose the model has learned that a user loves AI content.</p><p>The safest thing to do is:</p><pre>AI<br>AI<br>AI<br>AI<br>AI<br>AI</pre><p>The model will probably get good engagement.</p><p>But there’s a problem.</p><p>Maybe the user would also love:</p><pre>Robotics<br>3D Graphics<br>Astronomy<br>Photography</pre><p>We don’t know.</p><p>Because we’ve never shown them.</p><p>This creates the classic recommendation-system tradeoff:</p><blockquote><strong><em>Exploitation vs Exploration</em></strong></blockquote><h3>Exploitation</h3><p>Exploitation means:</p><blockquote><strong><em>Show what we already believe the user will like.</em></strong></blockquote><p>For example:</p><pre>AI post → 0.95<br>AI post → 0.93<br>AI post → 0.91</pre><p>These are safe recommendations.</p><p>We have strong evidence that the user likes them.</p><h3>Exploration</h3><p>Exploration means:</p><blockquote><strong><em>Show something we’re less certain about so that we can learn more about the user.</em></strong></blockquote><p>For example:</p><pre>AI          → 0.95<br>AI          → 0.93<br>Robotics    → 0.61<br>AI          → 0.91<br>Photography → 0.55</pre><p>The robotics post has a lower predicted score.</p><p>But suppose the user saves it.</p><p>Now we’ve learned something new:</p><pre>Robotics<br>   ↓<br>User saved it<br>   ↓<br>Strong signal<br>   ↓<br>Update user representation<br>   ↓<br>Future robotics recommendations</pre><p>Exploration therefore isn’t about randomly throwing content into the feed.</p><p>It’s about <strong>gathering information about the user’s interests</strong>.</p><h3>Why Exploration Matters</h3><p>Without exploration, the system can get stuck:</p><pre>Known interests<br>      ↓<br>Recommend same content<br>      ↓<br>User interacts with same content<br>      ↓<br>System learns same interests<br>      ↓<br>Recommend same content<br>      ↓<br>...</pre><p>Exploration breaks this cycle:</p><pre>Known interests<br>      ↓<br>Exploitation<br>      +<br>Unknown possibilities<br>      ↓<br>Exploration<br>      ↓<br>Observe response<br>      ↓<br>Learn<br>      ↓<br>Improve user representation</pre><p>A simple first implementation could eventually use something like:</p><pre>80% exploitation<br>20% exploration</pre><p>But that’s only a starting point.</p><p>The eventual goal is to make exploration intelligent rather than random.</p><h3>The Road From V1 to V13</h3><p>Looking back, the architecture has changed dramatically.</p><pre>V1<br>MongoDB<br>    ↓<br>Chronological Feed</pre><pre>V2<br>Cursor Pagination<br>    ↓<br>Efficient Pagination</pre><pre>V3<br>Database Indexing<br>    ↓<br>Efficient Queries</pre><pre>V4<br>Load Testing<br>    ↓<br>Measure the System</pre><pre>V5<br>Redis + Fanout<br>    ↓<br>Fast Feed Reads</pre><pre>V5.6<br>Hybrid Fanout<br>    ↓<br>Handle Large Accounts</pre><pre>V6<br>Candidate Generation<br>    ↓<br>Following + Trending + Exploration</pre><pre>V6.5<br>Feature Extraction<br>    +<br>Heuristic Ranking</pre><pre>V6.6<br>Diversity Re-ranking</pre><pre>V7<br>Event &amp; Feedback Pipeline</pre><pre>V8<br>Training Dataset</pre><pre>V9<br>Machine Learning Ranking</pre><pre>V10<br>Intelligent Candidate Retrieval<br>    +<br>Embeddings</pre><pre>V11<br>Multi-Objective Ranking</pre><pre>V12<br>Real-Time Personalization<br>    +<br>Long-Term Memory<br>    +<br>Short-Term Memory</pre><pre>V13<br>Exploration vs Exploitation<br>    ↓<br>Future Work</pre><h3>Final Architecture</h3><p>The simple chronological feed we started with:</p><pre>MongoDB<br>   ↓<br>Sort by date<br>   ↓<br>Feed</pre><p>has evolved into:</p><pre>USER<br>                               |<br>                         Feed Request<br>                               |<br>                               ↓<br>                    Candidate Generation<br>                               |<br>              ┌────────────────┼────────────────┐<br>              ↓                ↓                ↓<br>          Following         Trending        Exploration<br>              └────────────────┼────────────────┘<br>                               ↓<br>                          Candidates<br>                               ↓<br>                       Feature Extraction<br>                               ↓<br>                    User + Post Representation<br>                               ↓<br>                         ML Ranking<br>                               ↓<br>               P(like/comment/save/share)<br>                               ↓<br>                         Relevance<br>                               ↓<br>                    Diversity Re-ranking<br>                               ↓<br>                             Top 20<br>                               ↓<br>                             USER<br>                               ↓<br>                         Interactions<br>                               ↓<br>                            Events<br>                               ↓<br>                 ┌─────────────┴─────────────┐<br>                 ↓                           ↓<br>            User Memory                 Training Data<br>                 ↓                           ↓<br>          U_long / U_short              ML Training<br>                 ↓                           ↓<br>          Next Feed                    New Model</pre><p>And eventually:</p><pre>EXPLOIT<br>                +<br>             EXPLORE<br>                ↓<br>       Better understanding<br>          of the user<br>                ↓<br>       Better recommendations<br>                ↓<br>          Better feedback<br>                ↓<br>             ...</pre><h3>What This Project Taught Me</h3><p>The biggest lesson from V7 to V12 wasn’t simply how to train a neural network.</p><p>It was realizing that a recommendation system is <strong>not just a model</strong>.</p><p>It’s a continuously running system:</p><pre>Retrieve<br>   ↓<br>Rank<br>   ↓<br>Show<br>   ↓<br>Observe<br>   ↓<br>Learn<br>   ↓<br>Update User State<br>   ↓<br>Retrieve Again<br>   ↓<br>Rank Again<br>   ↓<br>...</pre><p>Each version solves a different problem:</p><p>VersionProblem<strong>V7</strong>How do we collect meaningful user feedback?<strong>V8</strong>How do we turn that feedback into training data?<strong>V9</strong>How do we learn ranking instead of manually defining it?<strong>V10</strong>How do we retrieve relevant candidates at scale?<strong>V11</strong>How do we predict different types of user behavior?<strong>V12</strong>How do we personalize recommendations in real time?<strong>V13</strong>How do we discover interests we don’t know about yet?</p><p>What started as an Instagram-style feed has gradually turned into something much more interesting:</p><blockquote><strong><em>A scalable, feedback-driven recommendation system with candidate generation, machine-learning ranking, content embeddings, real-time user representations, and eventually intelligent exploration.</em></strong></blockquote><p>And that is the part of this project I find most interesting.</p><p>Because the goal was never just to make a feed that works.</p><p>The goal was to keep asking:</p><blockquote><strong><em>“Okay, this works. But how would I make it better?”</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631feed4f8db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Instagram-Style Feed from Scratch: V1 → V7]]></title>
            <link>https://medium.com/@preran248/building-an-instagram-style-feed-from-scratch-v1-v7-79c58ce0c519?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/79c58ce0c519</guid>
            <category><![CDATA[instagram-feed]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[instagram-reels]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 21:10:10 GMT</pubDate>
            <atom:updated>2026-09-03T21:10:10.686Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re building an Instagram-like application, creating a feed is deceptively simple.</p><p>At first, it looks like:</p><pre>Get posts → Sort by date → Return posts</pre><p>Done.</p><p>But that’s not really how a scalable recommendation feed works.</p><p>As the system grows, you run into questions like:</p><ul><li>How do we paginate millions of posts?</li><li>What MongoDB indexes do we need?</li><li>What happens when thousands of users request feeds simultaneously?</li><li>Should we use Redis?</li><li>Should we push posts to followers when they’re created?</li><li>What happens when a celebrity with 10 million followers posts?</li><li>How do we generate personalized candidates?</li><li>How do we eventually rank posts using ML?</li><li>How do we collect user behavior for training?</li></ul><p>I decided to build my Instagram-style feed progressively instead of jumping straight into a complicated architecture.</p><p>The goal was to go from a simple MongoDB feed to a system that eventually becomes a personalized ML-powered recommendation system.</p><p>This is the journey from <strong>V1 to V7</strong>.</p><h3>The Architecture We Are Building</h3><p>The overall evolution looks like this:</p><pre>V1  → Basic chronological feed<br>V2  → Cursor pagination<br>V3  → Database indexing<br>V4  → Load testing &amp; benchmarking<br>V5  → Redis + fanout<br>V5.6 → Hybrid fanout<br>V6  → Candidate generation<br>V6.5 → Ranking<br>V6.6 → Re-ranking &amp; diversity<br>V7  → Event / feedback pipeline</pre><p>And eventually:</p><pre>V8  → Training dataset<br>V9  → ML ranking<br>V10 → Intelligent candidate retrieval<br>V11 → Multi-objective ranking<br>V12 → Real-time personalization<br>V13 → Exploration vs exploitation</pre><p>This article focuses on <strong>V1 → V7</strong>.</p><h3>V1 — The Simplest Possible Feed</h3><p>Let’s start with the obvious implementation.</p><p>We have a Post collection:</p><pre>{<br>    _id,<br>    user,<br>    image,<br>    caption,<br>    likes,<br>    comments,<br>    createdAt<br>}</pre><p>A user follows several people.</p><p>For example:</p><pre>User A<br> ├── follows B<br> ├── follows C<br> └── follows D</pre><p>When A opens their feed, we find posts belonging to:</p><pre>B<br>C<br>D<br>A</pre><p>and sort them by creation time.</p><p>The query is conceptually:</p><pre>const posts = await Post.find({<br>    user: {<br>        $in: [<br>            ...user.following,<br>            user._id<br>        ]<br>    }<br>})<br>.sort({ createdAt: -1 })<br>.limit(20);</pre><p>That’s V1.</p><h3>What does this give us?</h3><p>If the database contains:</p><pre>B → Post 1<br>C → Post 2<br>D → Post 3<br>B → Post 4</pre><p>and the creation times are:</p><pre>Post 1 → 10:00<br>Post 2 → 10:05<br>Post 3 → 10:10<br>Post 4 → 10:20</pre><p>the feed becomes:</p><pre>Post 4<br>Post 3<br>Post 2<br>Post 1</pre><p>Simple.</p><p>But there is a problem.</p><h3>The First Scaling Problem</h3><p>Imagine a user follows:</p><pre>10 people</pre><p>No big deal.</p><p>But eventually:</p><pre>100<br>1,000<br>10,000<br>100,000</pre><p>Now the database query has to search a huge amount of data.</p><p>And we’re also using:</p><pre>skip</pre><p>if we implement traditional pagination.</p><p>For example:</p><pre>Post.find(...)<br>    .sort({ createdAt: -1 })<br>    .skip(1000)<br>    .limit(20);</pre><p>At scale, that’s not something we want to rely on.</p><p>So we move to V2.</p><h3>V2 — Cursor Pagination</h3><p>Instead of saying:</p><blockquote><em>“Give me page 5.”</em></blockquote><p>we say:</p><blockquote><em>“Give me posts older than this post.”</em></blockquote><p>This is called <strong>cursor pagination</strong>.</p><p>Suppose the first request returns:</p><pre>Post A → 12:00<br>Post B → 11:55<br>Post C → 11:50<br>Post D → 11:45</pre><p>The client remembers the last item:</p><pre>cursor = 11:45</pre><p>The next request becomes:</p><pre>Give me posts where:</pre><pre>createdAt &lt; 11:45</pre><p>So:</p><pre>const query = {<br>    user: { $in: followingIds }<br>};</pre><pre>if (cursor) {<br>    query.createdAt = {<br>        $lt: new Date(Number(cursor))<br>    };<br>}</pre><pre>const posts = await Post.find(query)<br>    .sort({ createdAt: -1 })<br>    .limit(20);</pre><h3>Why Cursor Pagination?</h3><p>Imagine:</p><pre>Page 1<br>Post A<br>Post B<br>Post C<br>Post D</pre><p>Then someone creates:</p><pre>Post X</pre><p>If you’re using page numbers and offsets, the positions of posts can shift.</p><p>Cursor pagination avoids that problem because we’re saying:</p><pre>Continue from HERE.</pre><p>rather than:</p><pre>Give me items 21–40.</pre><h3>A subtle issue</h3><p>A timestamp-only cursor isn’t perfect.</p><p>Two posts can theoretically have the same:</p><pre>createdAt</pre><p>A production cursor should therefore usually be based on:</p><pre>(createdAt, _id)</pre><p>rather than just:</p><pre>createdAt</pre><p>For a learning project, a timestamp cursor is a perfectly reasonable first implementation.</p><h3>V3 — MongoDB Indexing</h3><p>Now we’ve got pagination.</p><p>But our database still needs to efficiently find posts.</p><p>Our query looks like:</p><pre>user IN following users<br>AND<br>createdAt &lt; cursor</pre><pre>SORT BY createdAt DESC</pre><p>So we need an index that helps MongoDB with this access pattern.</p><p>A useful index is:</p><pre>postSchema.index({<br>    user: 1,<br>    createdAt: -1<br>});</pre><p>Now MongoDB can much more efficiently locate posts belonging to particular users and ordered by creation time.</p><h3>Why Indexes Matter</h3><p>Without an appropriate index, MongoDB may need to inspect a huge portion of the collection.</p><p>Conceptually:</p><pre>WITHOUT INDEX</pre><pre>MongoDB<br>  ↓<br>Post 1<br>Post 2<br>Post 3<br>Post 4<br>...<br>Post 1,000,000<br>  ↓<br>find matching posts</pre><p>With an index:</p><pre>WITH INDEX</pre><pre>Index<br>  ↓<br>relevant user<br>  ↓<br>relevant time range<br>  ↓<br>matching posts</pre><p>The database doesn’t magically become O(1), but we dramatically improve the access path.</p><h3>V4 — Load Testing</h3><p>At this point, the feed works.</p><p>But here’s a mistake many projects make:</p><blockquote><em>“It works on my laptop, therefore it’s scalable.”</em></blockquote><p>Nope. 😂</p><p>Now we need to <strong>measure it</strong>.</p><p>Instead of guessing whether our feed is fast, we load test it.</p><p>For example:</p><pre>100 users<br>1,000 requests<br>10 concurrent users</pre><p>Then increase:</p><pre>1,000 users<br>10,000 requests<br>100 concurrent users</pre><p>We measure:</p><ul><li>average latency</li><li>p50 latency</li><li>p95 latency</li><li>p99 latency</li><li>requests/second</li><li>error rate</li><li>MongoDB CPU</li><li>MongoDB memory</li><li>Redis latency later</li></ul><h3>Why p95 and p99?</h3><p>Suppose:</p><pre>Average = 100ms</pre><p>Sounds great.</p><p>But maybe:</p><pre>95% → 100ms<br>5%  → 5 seconds</pre><p>The average hides that problem.</p><p>So we care about:</p><pre>p50 → typical request<br>p95 → slow tail<br>p99 → very slow tail</pre><p>This stage is important because we’re establishing a <strong>baseline</strong>.</p><p>For example:</p><pre>V1/V2/V3</pre><pre>p95 = 350ms</pre><p>After introducing Redis:</p><pre>V5</pre><pre>p95 = 90ms</pre><p>Now we have an actual measurement instead of saying:</p><blockquote><em>“Redis makes it faster.”</em></blockquote><h3>V5 — Redis Enters the Picture</h3><p>Now we hit one of the biggest architectural changes.</p><p>Instead of calculating the entire feed from MongoDB every time, we can maintain a <strong>feed cache</strong> in Redis.</p><p>We create:</p><pre>feed:&lt;userId&gt;</pre><p>For example:</p><pre>feed:123</pre><p>And store post IDs in a Redis Sorted Set.</p><p>Conceptually:</p><pre>feed:123</pre><pre>postA → score 1725430000<br>postB → score 1725431000<br>postC → score 1725432000</pre><p>The score is the post’s creation timestamp.</p><p>Redis Sorted Sets are useful because they keep elements ordered by score.</p><h3>Why Store IDs Instead of Entire Posts?</h3><p>This is an important design decision.</p><p>We don’t put:</p><pre>entire post object<br>comments<br>likes<br>author<br>etc.</pre><p>inside Redis.</p><p>Instead:</p><pre>Redis<br>↓<br>post IDs + ordering</pre><p>and:</p><pre>MongoDB<br>↓<br>actual post data</pre><p>MongoDB remains our <strong>source of truth</strong>.</p><p>So:</p><pre>Redis<br>feed:123<br> ├── P10<br> ├── P24<br> ├── P71<br> └── P92</pre><pre>        ↓</pre><pre>MongoDB<br> ├── P10 → actual post<br> ├── P24 → actual post<br> ├── P71 → actual post<br> └── P92 → actual post</pre><p>This keeps the cache relatively lightweight.</p><h3>Fanout-on-Write</h3><p>Now comes an important idea.</p><p>Suppose:</p><pre>User A</pre><p>has:</p><pre>100 followers</pre><p>A creates:</p><pre>Post X</pre><p>Instead of waiting for each follower to request their feed, we can immediately add:</p><pre>Post X</pre><p>to their Redis feeds.</p><p>So:</p><pre>A creates Post X<br>       ↓<br>find followers<br>       ↓<br>F1<br>F2<br>F3<br>...<br>F100<br>       ↓<br>ZADD feed:F1<br>ZADD feed:F2<br>ZADD feed:F3<br>...</pre><p>This is called:</p><blockquote><strong><em>Fanout-on-write</em></strong></blockquote><h3>Why Is Fanout Powerful?</h3><p>Without fanout:</p><pre>User opens feed<br>       ↓<br>calculate posts from followed users<br>       ↓<br>MongoDB work<br>       ↓<br>return</pre><p>With fanout:</p><pre>Post created<br>       ↓<br>already inserted into follower feeds<br>       ↓<br>User opens feed<br>       ↓<br>Redis lookup<br>       ↓<br>very fast</pre><p>We move work from <strong>read time</strong> to <strong>write time</strong>.</p><h3>But Fanout Has a Massive Problem</h3><p>Imagine a celebrity:</p><pre>10,000,000 followers</pre><p>They post once.</p><p>Fanout-on-write says:</p><pre>insert post into</pre><pre>10,000,000 Redis feeds</pre><p>That’s obviously terrible.</p><p>One write creates millions of operations.</p><p>This is the classic:</p><blockquote><strong><em>Hot user / celebrity problem.</em></strong></blockquote><p>So V5 can’t blindly fan out everything.</p><h3>V5.6 — Hybrid Fanout</h3><p>This is where we make the architecture smarter.</p><p>We define a threshold.</p><p>For example:</p><pre>const FANOUT_THRESHOLD = 500;</pre><p>If a user has fewer than 500 followers:</p><pre>fanout normally</pre><p>If they have more:</p><pre>don&#39;t fanout</pre><p>So:</p><pre>Normal user<br>   ↓<br>500 followers<br>   ↓<br>fanout</pre><pre>Celebrity<br>   ↓<br>500,000 followers<br>   ↓<br>skip fanout</pre><p>For a large account, we fetch their posts separately during feed generation.</p><p>This creates a hybrid system:</p><pre>Post Created<br>                      │<br>            ┌─────────┴─────────┐<br>            ↓                   ↓<br>      Small account        Large account<br>            ↓                   ↓<br>       Fanout write        No fanout<br>            ↓                   ↓<br>       Redis feeds       Fetch on read</pre><h3>Following Feed Candidate Generation</h3><p>Now our feed isn’t just:</p><pre>MongoDB → posts</pre><p>We introduce the concept of <strong>candidate generation</strong>.</p><p>The following candidate service can use:</p><pre>Redis feed<br>+<br>direct MongoDB query<br>+<br>large-account posts</pre><p>This is important because Redis isn’t necessarily perfect.</p><p>For example:</p><pre>Redis write fails</pre><p>We don’t want the user’s post to simply disappear.</p><p>MongoDB remains the fallback/source of truth.</p><p>Conceptually:</p><pre>Following Candidates</pre><pre>Redis<br>  ↓<br>post IDs<br>  +<br>MongoDB<br>  ↓<br>direct following posts<br>  +<br>large-account posts<br>  ↓<br>merge<br>  ↓<br>deduplicate<br>  ↓<br>following candidates</pre><h3>Backfilling When Someone Follows</h3><p>There’s another problem.</p><p>Suppose:</p><pre>User A follows User B</pre><p>B already has:</p><pre>20 recent posts</pre><p>Those posts weren’t previously in A’s Redis feed because A wasn’t following B.</p><p>So when the follow happens, we can backfill recent posts:</p><pre>User A follows B<br>       ↓<br>fetch recent B posts<br>       ↓<br>ZADD feed:A</pre><p>Now A immediately gets relevant recent content.</p><h3>Unfollow</h3><p>When:</p><pre>A unfollows B</pre><p>we should remove B’s posts from A’s feed cache.</p><p>Conceptually:</p><pre>ZREM feed:A post1<br>ZREM feed:A post2<br>...</pre><p>At small scale that’s fine.</p><p>At enormous scale, we would want more sophisticated strategies.</p><p>Again, the goal here is to progressively learn the architecture rather than pretend we’re already operating Instagram at planetary scale.</p><h3>V6 — Candidate Generation</h3><p>This is where the feed fundamentally changes.</p><p>Until now, our thinking was:</p><pre>Following posts<br>       ↓<br>sort<br>       ↓<br>feed</pre><p>But recommendation systems don’t work like that.</p><p>There are potentially millions of posts.</p><p>We don’t want to rank all of them.</p><p>Instead:</p><pre>ALL POSTS<br>   ↓<br>Candidate Generation<br>   ↓<br>~1000 candidates<br>   ↓<br>Filtering<br>   ↓<br>Ranking<br>   ↓<br>Top 20</pre><p>The candidate generation stage answers:</p><blockquote><strong><em>“Which posts are even worth considering?”</em></strong></blockquote><h3>Multiple Candidate Sources</h3><p>Our V6 system uses three main sources.</p><h3>1. Following</h3><p>Posts from:</p><pre>people you follow<br>+<br>your own posts</pre><p>This comes from the architecture we built in V5/V5.6.</p><h3>2. Trending</h3><p>We maintain another Redis Sorted Set:</p><pre>trending:posts</pre><p>Posts receive scores based on engagement.</p><p>For example:</p><pre>like    → +1<br>comment → +3<br>share   → +5<br>save    → +4</pre><p>Then:</p><pre>ZINCRBY trending:posts</pre><p>updates the score.</p><p>A simplified ranking might look like:</p><pre>P1 → 500<br>P2 → 430<br>P3 → 300<br>P4 → 200</pre><p>We can retrieve the highest-scoring posts.</p><h3>3. Exploration</h3><p>We also need posts outside the user’s normal network.</p><p>Otherwise the system becomes:</p><pre>You follow 20 people<br>      ↓<br>you only ever see those 20 people&#39;s posts</pre><p>Exploration gives the system a way to discover new content.</p><p>The simplest version is:</p><pre>posts from users<br>you don&#39;t follow</pre><p>Later this becomes much smarter using:</p><pre>interests<br>embeddings<br>vector search<br>topics<br>similar users</pre><p>But for V6, simple exploration is enough.</p><h3>Candidate Sources Are Not Final Feed Sections</h3><p>This is an important distinction.</p><p>We aren’t doing:</p><pre>Following<br>↓<br>10 posts</pre><pre>Trending<br>↓<br>10 posts</pre><pre>Exploration<br>↓<br>10 posts</pre><p>and then displaying them like that.</p><p>Instead:</p><pre>Following ─────┐<br>Trending ──────┼──→ merge → deduplicate → rank<br>Exploration ───┘</pre><p>For example:</p><pre>Following      → 40<br>Trending       → 40<br>Exploration    → 40</pre><pre>Total          → 120</pre><p>After deduplication:</p><pre>~100 candidates</pre><p>Then ranking decides what actually appears.</p><h3>V6.5 — Feature Extraction + Ranking</h3><p>Now we have candidates.</p><p>But how do we decide which candidate should appear first?</p><p>We extract features.</p><p>For each candidate post:</p><pre>likes<br>comments<br>post age<br>following relationship<br>media type<br>source</pre><p>For example:</p><pre>{<br>    likes: 120,<br>    comments: 14,<br>    postAgeHours: 2.4,<br>    isFollowingAuthor: true,<br>    mediaType: &quot;image&quot;,<br>    source: &quot;following&quot;<br>}</pre><p>Now we can calculate a score.</p><h3>Heuristic Ranking</h3><p>Before ML, we can build a heuristic ranker.</p><p>For example:</p><pre>Engagement score<br>=<br>likes × 1<br>+<br>comments × 3</pre><p>Then add recency:</p><pre>recencyScore =<br>20 / sqrt(postAgeHours + 2)</pre><p>Then relationship:</p><pre>following author<br>→ +15</pre><p>Then source:</p><pre>following   → +10<br>trending    → +5<br>exploration → +2</pre><p>And finally an exploration boost:</p><pre>new + low engagement<br>→ +10</pre><p>So:</p><pre>finalScore =<br>engagement<br>+<br>recency<br>+<br>relationship<br>+<br>source<br>+<br>exploration</pre><p>This isn’t meant to be Instagram’s real formula.</p><p>It’s our <strong>learning scaffold</strong>.</p><p>The important thing is that we’re now building the same conceptual pipeline that later allows us to replace this formula with ML.</p><h3>Example</h3><p>Suppose Post A has:</p><pre>likes = 100<br>comments = 10<br>age = 2 hours<br>following = true<br>source = following</pre><p>Its score might be:</p><pre>engagement<br>= 100 + (10 × 3)<br>= 130</pre><p>Then:</p><pre>recency<br>≈ 10</pre><p>Relationship:</p><pre>+15</pre><p>Source:</p><pre>+10</pre><p>Total:</p><pre>≈ 165</pre><p>Another post might score:</p><pre>87</pre><p>So:</p><pre>Post A → 165<br>Post B → 87<br>Post C → 64</pre><p>and we sort descending.</p><h3>Why Build a Heuristic Before ML?</h3><p>Because this gives us a clean architecture.</p><p>Eventually:</p><pre>heuristic ranking</pre><p>becomes:</p><pre>ML ranking</pre><p>without rebuilding the entire feed.</p><p>That’s a huge architectural advantage.</p><p>Our pipeline becomes:</p><pre>Candidate generation<br>        ↓<br>Feature extraction<br>        ↓<br>Ranking<br>        ↓<br>Re-ranking</pre><p>The ranking component can evolve independently.</p><h3>V6.6 — Re-ranking and Diversity</h3><p>There’s another problem.</p><p>Suppose the ranking model produces:</p><pre>Post A — Creator X<br>Post B — Creator X<br>Post C — Creator X<br>Post D — Creator X<br>Post E — Creator X</pre><p>Technically, these might all have excellent scores.</p><p>But that’s a terrible user experience.</p><p>You don’t want:</p><pre>X<br>X<br>X<br>X<br>X</pre><p>over and over.</p><p>So we add a <strong>re-ranking layer</strong>.</p><h3>Diversity Rules</h3><p>For our implementation, we can enforce rules such as:</p><pre>Maximum 2 consecutive posts<br>from the same author</pre><p>and:</p><pre>Maximum 3 posts from the same author<br>in the top 20</pre><p>We can also consider:</p><pre>source diversity<br>content type diversity<br>fresh content</pre><p>So instead of:</p><pre>Creator A<br>Creator A<br>Creator A<br>Creator B<br>Creator A<br>Creator A</pre><p>we might produce:</p><pre>Creator A<br>Creator B<br>Creator C<br>Creator A<br>Creator D<br>Creator A</pre><p>while preserving the original ranking as much as possible.</p><h3>Why Separate Ranking and Re-ranking?</h3><p>Because they solve different problems.</p><h3>Ranking</h3><p>Answers:</p><blockquote><em>“How valuable is this candidate?”</em></blockquote><h3>Re-ranking</h3><p>Answers:</p><blockquote><em>“Given the ranked candidates, how should we construct the final feed?”</em></blockquote><p>So:</p><pre>ML score<br>    ↓<br>ranking<br>    ↓<br>diversity constraints<br>    ↓<br>final feed</pre><p>This separation becomes extremely useful later.</p><h3>V7 — Event / Feedback Pipeline</h3><p>Now we’ve reached the most important stage before machine learning.</p><p>We have:</p><pre>candidate generation<br>        ↓<br>ranking<br>        ↓<br>feed</pre><p>But the system currently doesn’t really <strong>learn from the user</strong>.</p><p>We need to know what happens after we show a post.</p><h3>What Is an Event?</h3><p>An event represents something the user did.</p><p>For example:</p><pre>impression<br>like<br>comment<br>save<br>share</pre><p>For Reels/video later, we can have:</p><pre>watch_25<br>watch_50<br>watch_75<br>watch_100<br>rewatch<br>skip</pre><p>Our event model should be generic.</p><p>Something like:</p><pre>{<br>    user: userId,<br>    content: contentId,<br>    contentType: &quot;post&quot;,<br>    eventType: &quot;like&quot;,<br>    timestamp: new Date()<br>}</pre><p>This is better than creating completely separate systems for posts and Reels.</p><h3>The Most Important Event: Impression</h3><p>An <strong>impression</strong> means:</p><blockquote><em>The system actually showed this content to the user.</em></blockquote><p>For example:</p><pre>User requests feed<br>       ↓<br>Top 20 posts<br>       ↓<br>mobile app receives them<br>       ↓<br>impression events</pre><p>So:</p><pre>{<br>    &quot;user&quot;: &quot;U123&quot;,<br>    &quot;content&quot;: &quot;P456&quot;,<br>    &quot;contentType&quot;: &quot;post&quot;,<br>    &quot;eventType&quot;: &quot;impression&quot;<br>}</pre><h3>Why Impression Matters</h3><p>Suppose:</p><pre>Post A → user never saw it<br>Post B → user saw it but didn&#39;t like it</pre><p>If we simply say:</p><pre>not liked = negative</pre><p>we’d incorrectly treat both the same.</p><p>But:</p><pre>never seen</pre><p>doesn’t mean:</p><pre>disliked</pre><p>This becomes incredibly important when we build the training dataset.</p><h3>Connecting Impressions to Actions</h3><p>Suppose:</p><pre>10:00 → impression P1<br>10:02 → like P1<br>10:03 → save P1</pre><p>We can transform that into:</p><pre>P1:</pre><pre>like    = 1<br>comment = 0<br>save    = 1<br>share   = 0</pre><p>That’s the beginning of our V11 multi-objective training data.</p><h3>Avoiding Data Leakage</h3><p>There’s another subtle problem.</p><p>Imagine:</p><pre>10:00<br>Post has:</pre><pre>likes = 10<br>comments = 2</pre><p>The user sees it.</p><p>Then they like it.</p><p>Two days later:</p><pre>likes = 10,000<br>comments = 500</pre><p>If we build the training example using the <strong>current</strong> post statistics:</p><pre>likes = 10,000<br>comments = 500</pre><p>we’ve leaked future information into the training data.</p><p>The model is effectively being told the future.</p><p>Not good.</p><p>So ideally, the impression should capture the feature state <strong>at the time of ranking/impression</strong>.</p><p>For example:</p><pre>{<br>    &quot;eventType&quot;: &quot;impression&quot;,</pre><pre>    &quot;features&quot;: {<br>        &quot;likes&quot;: 10,<br>        &quot;comments&quot;: 2,<br>        &quot;postAgeHours&quot;: 1.5,<br>        &quot;isFollowingAuthor&quot;: true,<br>        &quot;source&quot;: &quot;following&quot;<br>    }<br>}</pre><p>Now our future training dataset can reconstruct what the model actually knew at that moment.</p><h3>The Complete V7 Data Flow</h3><p>We now have:</p><pre>USER<br>                    │<br>                    ↓<br>              Feed Request<br>                    │<br>                    ↓<br>          Candidate Generation<br>                    │<br>                    ↓<br>             Feature Extraction<br>                    │<br>                    ↓<br>                Ranking<br>                    │<br>                    ↓<br>               Re-ranking<br>                    │<br>                    ↓<br>                  Top 20<br>                    │<br>                    ↓<br>                  USER<br>                    │<br>           ┌────────┴────────┐<br>           ↓                 ↓<br>       impression         actions<br>           │                 │<br>           │       like/comment/save/share<br>           │                 │<br>           └────────┬────────┘<br>                    ↓<br>                Event Store<br>                    │<br>                    ↓<br>             Training Dataset<br>                    │<br>                    ↓<br>              Machine Learning</pre><p>And that brings us to the next stage.</p><h3>The Architecture After V7</h3><p>At this point, our system looks roughly like:</p><pre>┌───────────────┐<br>                         │   Mobile App  │<br>                         └───────┬───────┘<br>                                 │<br>                                 ↓<br>                         ┌───────────────┐<br>                         │   Express API │<br>                         └───────┬───────┘<br>                                 │<br>              ┌──────────────────┼──────────────────┐<br>              │                  │                  │<br>              ↓                  ↓                  ↓<br>           MongoDB             Redis             Events<br>              │                  │                  │<br>              │                  │                  ↓<br>              │                  │            Training Data<br>              │                  │<br>              │                  ↓<br>              │             Feed Candidates<br>              │                  │<br>              └──────────┬───────┘<br>                         ↓<br>                Candidate Generation<br>                         ↓<br>                 Feature Extraction<br>                         ↓<br>                      Ranking<br>                         ↓<br>                    Re-ranking<br>                         ↓<br>                       Top 20</pre><h3>What We’ve Actually Achieved</h3><p>It’s easy to look at this and think:</p><blockquote><em>“It’s just a feed.”</em></blockquote><p>But we’ve actually built the foundations of a recommendation system.</p><p>We started with:</p><pre>MongoDB<br>   ↓<br>sort by createdAt</pre><p>and evolved into:</p><pre>MongoDB + Redis<br>        ↓<br>candidate generation<br>        ↓<br>multiple candidate sources<br>        ↓<br>feature extraction<br>        ↓<br>ranking<br>        ↓<br>diversity<br>        ↓<br>user interaction events</pre><p>That’s a completely different architecture.</p><h3>The Evolution in One Picture</h3><pre>V1<br>MongoDB<br>  ↓<br>Chronological Feed</pre><pre>        ↓</pre><pre>V2<br>Cursor Pagination</pre><pre>        ↓</pre><pre>V3<br>Indexes</pre><pre>        ↓</pre><pre>V4<br>Load Testing<br>&amp; Benchmarking</pre><pre>        ↓</pre><pre>V5<br>Redis<br>+<br>Fanout-on-write</pre><pre>        ↓</pre><pre>V5.6<br>Hybrid Fanout<br>Small accounts → fanout<br>Large accounts → read-time</pre><pre>        ↓</pre><pre>V6<br>Candidate Generation</pre><pre>Following ──────┐<br>Trending ───────┼→ Candidates<br>Exploration ────┘</pre><pre>        ↓</pre><pre>V6.5<br>Feature Extraction<br>+<br>Heuristic Ranking</pre><pre>        ↓</pre><pre>V6.6<br>Re-ranking<br>+<br>Diversity</pre><pre>        ↓</pre><pre>V7<br>Events<br>+<br>Feedback Pipeline</pre><pre>        ↓</pre><pre>       ML</pre><h3>What’s Next?</h3><p>V7 is the point where the system becomes <strong>ready to learn</strong>.</p><p>The next evolution is:</p><pre>V8<br>Build training dataset</pre><p>Take:</p><pre>impressions<br>+<br>likes<br>+<br>comments<br>+<br>saves<br>+<br>shares</pre><p>and turn them into training examples.</p><p>Then:</p><pre>V9<br>Train a neural ranking model</pre><p>Instead of manually saying:</p><pre>likes × 1<br>comments × 3</pre><p>the model learns the relationships itself.</p><p>Then we can go even further:</p><pre>V10<br>User/Post embeddings<br>+<br>vector retrieval</pre><pre>V11<br>P(like)<br>P(comment)<br>P(save)<br>P(share)</pre><pre>V12<br>Long-term user representation<br>+<br>short-term user representation<br>+<br>real-time personalization</pre><p>and finally:</p><pre>V13<br>Exploration<br>+<br>Exploitation</pre><h3>Final Takeaway</h3><p>The biggest lesson from this project isn’t actually Redis, MongoDB, pagination, or even ML.</p><p>It’s <strong>progressive architecture</strong>.</p><p>You don’t start by trying to build Instagram’s recommendation engine.</p><p>You start with:</p><pre>&quot;Can I return posts?&quot;</pre><p>Then ask:</p><pre>&quot;Can I paginate them efficiently?&quot;</pre><pre>&quot;Can the database handle it?&quot;</pre><pre>&quot;Can I cache the expensive parts?&quot;</pre><pre>&quot;Can I avoid the celebrity fanout problem?&quot;</pre><pre>&quot;Where do candidates come from?&quot;</pre><pre>&quot;How do I rank them?&quot;</pre><pre>&quot;How do I prevent repetitive feeds?&quot;</pre><pre>&quot;What did the user actually do?&quot;</pre><pre>&quot;Can I learn from that behavior?&quot;</pre><p>Each question leads naturally to the next architectural version.</p><p>And that’s what makes the project interesting.</p><p>You’re not just building an Instagram clone anymore.</p><p>You’re building a <strong>progressively evolving recommendation system</strong>, where every version introduces a real systems or ML concept and gives you something measurable to improve.</p><p><strong>V1 → V7 is the foundation.<br>V8 → V13 is where it starts becoming an actual intelligent recommender.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79c58ce0c519" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Transactions, Rewards and Nodes to Our Blockchain]]></title>
            <link>https://medium.com/@preran248/adding-transactions-rewards-and-nodes-to-our-blockchain-c0bb83499ccc?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0bb83499ccc</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 12:56:08 GMT</pubDate>
            <atom:updated>2026-08-24T12:56:08.794Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous blogs, we created a simple blockchain using Python.</p><p>We understood how blocks work, how hashes connect the blocks, how Proof of Work works, and how miners find a valid hash.</p><p>But a blockchain by itself is not really a cryptocurrency.</p><p>A cryptocurrency needs <strong>transactions, wallets or identities, a way to reward miners, and a network of nodes that can communicate and agree on the same blockchain</strong>.</p><p>So in this blog, let’s take our previous blockchain and add these features step by step.</p><h3>1. Adding Transactions to the Block</h3><p>Previously, our block mainly contained things like:</p><pre>Block<br>├── Index<br>├── Timestamp<br>├── Proof<br>└── Previous Hash</pre><p>Now we add <strong>transactions</strong>.</p><pre>def create_block(self, proof, previous_hash):</pre><pre>    block = {<br>        &quot;index&quot;: len(self.chain) + 1,<br>        &quot;timestamp&quot;: str(datetime.datetime.now()),<br>        &quot;proof&quot;: proof,<br>        &quot;previous_hash&quot;: previous_hash,<br>        &quot;transactions&quot;: self.transactions<br>    }</pre><pre>    self.transactions = []<br>    self.chain.append(block)</pre><pre>    return block</pre><p>Now every block can contain multiple transactions.</p><p>For example:</p><pre>Block 5</pre><pre>Transaction 1<br>Alice → Bob : 2 coins</pre><pre>Transaction 2<br>Charlie → David : 5 coins</pre><pre>Transaction 3<br>John → Alice : 1 coin</pre><p>Once the block is created, the transactions are added to the block and our temporary transaction list is cleared so that new transactions can be collected for the next block.</p><h3>2. Creating a Transaction</h3><p>Now we need a way to create transactions.</p><pre>def add_transaction(self, sender, receiver, amount):</pre><pre>    self.transactions.append({<br>        &quot;amount&quot;: amount,<br>        &quot;sender&quot;: sender,<br>        &quot;receiver&quot;: receiver<br>    })</pre><pre>    previous_block = self.get_previous_block()</pre><pre>    return previous_block[&quot;index&quot;] + 1</pre><p>Whenever someone creates a transaction, we add it to the list of pending transactions.</p><p>For example:</p><pre>Alice → Bob<br>Amount = 10</pre><p>The transaction doesn’t immediately become part of the blockchain.</p><p>It first waits for a miner to include it in a block.</p><p>So we can imagine:</p><pre>Transaction<br>     ↓<br>Pending Transactions<br>     ↓<br>Miner<br>     ↓<br>Block<br>     ↓<br>Blockchain</pre><h3>3. Creating a Transaction API</h3><p>Now let’s create an API endpoint so users can send transactions.</p><pre>@app.route(&#39;/add_transaction&#39;, methods=[&#39;POST&#39;])<br>def add_transaction():</pre><pre>    json_data = request.get_json()</pre><pre>    transaction_keys = [&#39;sender&#39;, &#39;receiver&#39;, &#39;amount&#39;]</pre><pre>    if not all(key in json_data for key in transaction_keys):<br>        return &#39;Some elements of the transaction are missing&#39;, 400</pre><pre>    index = blockchain.add_transaction(<br>        json_data[&#39;sender&#39;],<br>        json_data[&#39;receiver&#39;],<br>        json_data[&#39;amount&#39;]<br>    )</pre><pre>    response = {<br>        &#39;message&#39;: f&#39;This transaction will be added to Block {index}&#39;<br>    }</pre><pre>    return jsonify(response), 201</pre><p>Now a user can send something like:</p><pre>{<br>    &quot;sender&quot;: &quot;Alice&quot;,<br>    &quot;receiver&quot;: &quot;Bob&quot;,<br>    &quot;amount&quot;: 10<br>}</pre><p>The API receives the transaction and adds it to the pending transaction list.</p><p>The response tells us which block the transaction is expected to be included in.</p><h3>4. Mining and the Mining Reward</h3><p>Now we connect transactions with mining.</p><p>When a miner successfully mines a block, the miner should receive a reward.</p><p>We can represent the mining reward as a special transaction.</p><p>For example:</p><pre>Miner → Miner<br>Amount = 1</pre><p>This is basically saying that the miner receives newly created coins as a reward for successfully mining the block.</p><p>In our simplified implementation, we create an identity for the node:</p><pre>node_address = str(uuid.uuid4()).replace(&quot;-&quot;, &quot;&quot;)</pre><p>Then we can use this identity as the miner’s address.</p><p>The mining process becomes:</p><pre>Pending Transactions<br>        ↓<br>Miner creates candidate block<br>        ↓<br>Proof of Work<br>        ↓<br>Valid hash found<br>        ↓<br>Block added to blockchain<br>        ↓<br>Miner receives reward</pre><p>In a real cryptocurrency, the exact reward mechanism and how the reward transaction is constructed are defined by the cryptocurrency’s protocol.</p><h3>5. Connecting Multiple Nodes</h3><p>So far, our blockchain exists only inside one Python program.</p><p>But a real blockchain is distributed.</p><p>We need multiple nodes that can communicate with each other.</p><p>This is why we add:</p><pre>self.nodes = set()</pre><p>The nodes variable stores the addresses of other blockchain nodes.</p><p>For example:</p><pre>Node A<br>   ↕<br>Node B<br>   ↕<br>Node C<br>   ↕<br>Node D</pre><p>Each node can maintain its own copy of the blockchain.</p><h3>6. Adding Nodes to the Network</h3><p>We create a function to add another node:</p><pre>def add_node(self, address):</pre><pre>    parsed_url = urlparse(address)<br>    self.nodes.add(parsed_url.netloc)</pre><p>This extracts the network address and stores it in our set of nodes.</p><p>We then create an API endpoint:</p><pre>@app.route(&#39;/connect_node&#39;, methods=[&#39;POST&#39;])<br>def connect_node():</pre><pre>    json_data = request.get_json()</pre><pre>    nodes = json_data.get(&#39;nodes&#39;)</pre><pre>    if nodes is None:<br>        return &quot;No node&quot;, 400</pre><pre>    for node in nodes:<br>        blockchain.add_node(node)</pre><pre>    response = {<br>        &#39;message&#39;: &#39;All the nodes are now connected&#39;,<br>        &#39;total nodes&#39;: list(blockchain.nodes)<br>    }</pre><pre>    return jsonify(response)</pre><p>Now one node can tell another node about the other nodes in the network.</p><p>For example:</p><pre>{<br>    &quot;nodes&quot;: [<br>        &quot;http://127.0.0.1:5001&quot;,<br>        &quot;http://127.0.0.1:5002&quot;<br>    ]<br>}</pre><p>The node now knows where the other nodes are.</p><h3>7. Why Do We Need Multiple Nodes?</h3><p>This brings us to one of the most important properties of blockchain.</p><p>Imagine we have:</p><pre>Node A → Blockchain<br>Node B → Blockchain<br>Node C → Blockchain<br>Node D → Blockchain</pre><p>If someone tries to modify the blockchain on Node A, the other nodes still have their own copies.</p><p>So the network can compare the different versions and follow the blockchain that satisfies the consensus rules.</p><p>This is the basic idea behind <strong>decentralization</strong>.</p><p>There is no single computer that owns the only copy of the ledger.</p><h3>8. Resolving Different Chains</h3><p>Now imagine that two nodes have different versions of the blockchain.</p><pre>Node A:</pre><pre>Block 1 → Block 2 → Block 3 → Block 4<br></pre><pre>Node B:</pre><pre>Block 1 → Block 2 → Block 3</pre><p>We need a way for the network to decide which chain should be followed.</p><p>This is where our replace_chain() function comes in.</p><p>The node asks the other nodes for their chains:</p><pre>def replace_chain(self):</pre><pre>    network = self.nodes</pre><pre>    longest_chain = None<br>    max_length = len(self.chain)</pre><pre>    for node in network:</pre><pre>        response = requests.get(<br>            f&#39;http://{node}/get_chain&#39;<br>        )</pre><pre>        if response.status_code == 200:</pre><pre>            length = response.json()[&#39;length&#39;]<br>            chain = response.json()[&#39;chain&#39;]</pre><pre>            if length &gt; max_length and self.check_valid_chain(chain):</pre><pre>                max_length = length<br>                longest_chain = chain</pre><pre>    if longest_chain:</pre><pre>        self.chain = longest_chain<br>        return True</pre><p>The node checks the chains maintained by other nodes.</p><p>If another valid chain is longer than its own, it can replace its chain with that chain.</p><p>In this simplified implementation, we use the <strong>longest valid chain</strong>.</p><p>Bitcoin’s actual rule is more precisely based on the chain with the <strong>most accumulated Proof of Work</strong>, rather than simply the greatest number of blocks.</p><h3>9. Getting the Blockchain</h3><p>We already created an endpoint to allow other nodes to request our blockchain.</p><pre>@app.route(&#39;/get_chain&#39;, methods=[&#39;GET&#39;])<br>def get_chain():</pre><pre>    response = {<br>        &#39;chain&#39;: blockchain.chain,<br>        &#39;length&#39;: len(blockchain.chain)<br>    }</pre><pre>    return jsonify(response), 200</pre><p>Now another node can request:</p><pre>/get_chain</pre><p>and receive our blockchain.</p><p>This is important because nodes need to communicate with each other to maintain a consistent view of the blockchain.</p><h3>10. Validating the Blockchain</h3><p>We also need to make sure that the blockchain received from another node is actually valid.</p><p>Our validation function checks things such as:</p><pre>Previous Hash<br>       ↓<br>Does it match?</pre><pre>Proof of Work<br>       ↓<br>Is it valid?</pre><pre>Next Block<br>       ↓<br>Does everything connect correctly?</pre><p>If someone sends us a modified or invalid blockchain, the node should reject it.</p><p>This prevents a node from simply accepting any blockchain another node sends.</p><h3>11. Complete Cryptocurrency Flow</h3><p>Now let’s put everything together.</p><p>Suppose Alice wants to send 10 coins to Bob.</p><pre>Alice<br>  ↓<br>Creates transaction<br>  ↓<br>Transaction enters pending transactions<br>  ↓<br>Miner selects transactions<br>  ↓<br>Miner creates candidate block<br>  ↓<br>Miner performs Proof of Work<br>  ↓<br>Valid hash found<br>  ↓<br>Block added to blockchain<br>  ↓<br>Miner receives reward<br>  ↓<br>Block propagated to other nodes<br>  ↓<br>Other nodes verify the block<br>  ↓<br>Blockchain is updated</pre><p>At the same time, every node maintains its own copy of the blockchain and communicates with other nodes.</p><p>So now we have:</p><pre>Transactions<br>     ↓<br>Mining<br>     ↓<br>Blocks<br>     ↓<br>Blockchain<br>     ↓<br>Multiple Nodes<br>     ↓<br>Consensus</pre><p>This is much closer to the basic architecture of a cryptocurrency.</p><h3>12. But Is This a Real Cryptocurrency?</h3><p>Not yet.</p><p>This is a <strong>learning implementation</strong> that demonstrates the basic ideas behind a cryptocurrency.</p><p>A real cryptocurrency needs many additional components, such as:</p><ul><li>Digital signatures</li><li>Private and public keys</li><li>Wallets</li><li>Transaction validation</li><li>Balance/state tracking</li><li>Secure peer-to-peer networking</li><li>Transaction propagation</li><li>Mempools</li><li>Consensus rules</li><li>Difficulty adjustment</li><li>Protection against double spending</li><li>Proper block rewards</li><li>Network security</li></ul><p>For example, our simplified transaction:</p><pre>{<br>    &quot;sender&quot;: &quot;Alice&quot;,<br>    &quot;receiver&quot;: &quot;Bob&quot;,<br>    &quot;amount&quot;: 10<br>}</pre><p>doesn’t prove that Alice actually owns those coins.</p><p>A real cryptocurrency uses <strong>cryptographic signatures</strong> to prove that the person creating the transaction is authorized to spend the funds.</p><p>That will be one of the next important steps if we want to turn this simple project into something much closer to a real cryptocurrency.</p><h3>Complete Code</h3><pre>import datetime<br>import hashlib<br>import json<br>import requests</pre><pre>from flask import Flask, jsonify, request<br>from uuid import uuid4<br>from urllib.parse import urlparse<br></pre><pre>class Blockchain:</pre><pre>    def __init__(self):<br>        self.chain = []<br>        self.transactions = []<br>        self.nodes = set()</pre><pre>        self.create_block(<br>            proof=1,<br>            previous_hash=&quot;0&quot;<br>        )</pre><pre>    def create_block(self, proof, previous_hash):</pre><pre>        block = {<br>            &quot;index&quot;: len(self.chain) + 1,<br>            &quot;timestamp&quot;: str(datetime.datetime.now()),<br>            &quot;proof&quot;: proof,<br>            &quot;previous_hash&quot;: previous_hash,<br>            &quot;transactions&quot;: self.transactions<br>        }</pre><pre>        self.transactions = []</pre><pre>        self.chain.append(block)</pre><pre>        return block</pre><pre>    def get_previous_block(self):<br>        return self.chain[-1]</pre><pre>    def proof_of_work(self, previous_proof):</pre><pre>        nonce = 1</pre><pre>        while True:</pre><pre>            hash_operation = hashlib.sha256(<br>                str(nonce ** 2 - previous_proof ** 2).encode()<br>            ).hexdigest()</pre><pre>            if hash_operation.startswith(&quot;0000&quot;):<br>                return nonce</pre><pre>            nonce += 1</pre><pre>    def hash(self, block):</pre><pre>        encoded_block = json.dumps(<br>            block,<br>            sort_keys=True<br>        ).encode()</pre><pre>        return hashlib.sha256(encoded_block).hexdigest()</pre><pre>    def check_valid_chain(self, chain):</pre><pre>        previous_block = chain[0]<br>        block_index = 1</pre><pre>        while block_index &lt; len(chain):</pre><pre>            block = chain[block_index]</pre><pre>            if block[&quot;previous_hash&quot;] != self.hash(previous_block):<br>                return False</pre><pre>            previous_proof = previous_block[&quot;proof&quot;]<br>            proof = block[&quot;proof&quot;]</pre><pre>            hash_operation = hashlib.sha256(<br>                str(proof ** 2 - previous_proof ** 2).encode()<br>            ).hexdigest()</pre><pre>            if not hash_operation.startswith(&quot;0000&quot;):<br>                return False</pre><pre>            previous_block = block<br>            block_index += 1</pre><pre>        return True</pre><pre>    def add_transaction(self, sender, receiver, amount):</pre><pre>        self.transactions.append({<br>            &quot;sender&quot;: sender,<br>            &quot;receiver&quot;: receiver,<br>            &quot;amount&quot;: amount<br>        })</pre><pre>        previous_block = self.get_previous_block()</pre><pre>        return previous_block[&quot;index&quot;] + 1</pre><pre>    def add_node(self, address):</pre><pre>        parsed_url = urlparse(address)</pre><pre>        self.nodes.add(parsed_url.netloc)</pre><pre>    def replace_chain(self):</pre><pre>        network = self.nodes<br>        longest_chain = None<br>        max_length = len(self.chain)</pre><pre>        for node in network:</pre><pre>            response = requests.get(<br>                f&quot;http://{node}/get_chain&quot;<br>            )</pre><pre>            if response.status_code == 200:</pre><pre>                length = response.json()[&quot;length&quot;]<br>                chain = response.json()[&quot;chain&quot;]</pre><pre>                if (<br>                    length &gt; max_length<br>                    and self.check_valid_chain(chain)<br>                ):<br>                    max_length = length<br>                    longest_chain = chain</pre><pre>        if longest_chain:</pre><pre>            self.chain = longest_chain<br>            return True</pre><pre>        return False<br></pre><pre>app = Flask(__name__)</pre><pre>node_address = str(uuid4()).replace(&quot;-&quot;, &quot;&quot;)</pre><pre>blockchain = Blockchain()<br></pre><pre>@app.route(&quot;/mine_block&quot;, methods=[&quot;GET&quot;])<br>def mine_block():</pre><pre>    previous_block = blockchain.get_previous_block()</pre><pre>    previous_proof = previous_block[&quot;proof&quot;]</pre><pre>    proof = blockchain.proof_of_work(previous_proof)</pre><pre>    previous_hash = blockchain.hash(previous_block)</pre><pre>    blockchain.add_transaction(<br>        sender=node_address,<br>        receiver=&quot;network_reward&quot;,<br>        amount=1<br>    )</pre><pre>    block = blockchain.create_block(<br>        proof,<br>        previous_hash<br>    )</pre><pre>    response = {<br>        &quot;message&quot;: &quot;Congratulations, you just mined a block!&quot;,<br>        &quot;index&quot;: block[&quot;index&quot;],<br>        &quot;timestamp&quot;: block[&quot;timestamp&quot;],<br>        &quot;proof&quot;: block[&quot;proof&quot;],<br>        &quot;previous_hash&quot;: block[&quot;previous_hash&quot;],<br>        &quot;transactions&quot;: block[&quot;transactions&quot;]<br>    }</pre><pre>    return jsonify(response), 200<br></pre><pre>@app.route(&quot;/get_chain&quot;, methods=[&quot;GET&quot;])<br>def get_chain():</pre><pre>    response = {<br>        &quot;chain&quot;: blockchain.chain,<br>        &quot;length&quot;: len(blockchain.chain)<br>    }</pre><pre>    return jsonify(response), 200<br></pre><pre>@app.route(&quot;/add_transaction&quot;, methods=[&quot;POST&quot;])<br>def add_transaction():</pre><pre>    json_data = request.get_json()</pre><pre>    transaction_keys = [<br>        &quot;sender&quot;,<br>        &quot;receiver&quot;,<br>        &quot;amount&quot;<br>    ]</pre><pre>    if not all(<br>        key in json_data<br>        for key in transaction_keys<br>    ):<br>        return &quot;Some elements of the transaction are missing&quot;, 400</pre><pre>    index = blockchain.add_transaction(<br>        json_data[&quot;sender&quot;],<br>        json_data[&quot;receiver&quot;],<br>        json_data[&quot;amount&quot;]<br>    )</pre><pre>    response = {<br>        &quot;message&quot;: f&quot;This transaction will be added to Block {index}&quot;<br>    }</pre><pre>    return jsonify(response), 201<br></pre><pre>@app.route(&quot;/connect_node&quot;, methods=[&quot;POST&quot;])<br>def connect_node():</pre><pre>    json_data = request.get_json()</pre><pre>    nodes = json_data.get(&quot;nodes&quot;)</pre><pre>    if nodes is None:<br>        return &quot;No node&quot;, 400</pre><pre>    for node in nodes:<br>        blockchain.add_node(node)</pre><pre>    response = {<br>        &quot;message&quot;: &quot;All the nodes are now connected&quot;,<br>        &quot;total_nodes&quot;: list(blockchain.nodes)<br>    }</pre><pre>    return jsonify(response), 201<br></pre><pre>@app.route(&quot;/is_valid&quot;, methods=[&quot;GET&quot;])<br>def is_valid():</pre><pre>    valid = blockchain.check_valid_chain(<br>        blockchain.chain<br>    )</pre><pre>    if valid:</pre><pre>        response = {<br>            &quot;message&quot;: &quot;All good. The Blockchain is valid.&quot;<br>        }</pre><pre>    else:</pre><pre>        response = {<br>            &quot;message&quot;: &quot;Houston, we have a problem. &quot;<br>                       &quot;The Blockchain is not valid.&quot;<br>        }</pre><pre>    return jsonify(response), 200<br></pre><pre>app.run(<br>    host=&quot;0.0.0.0&quot;,<br>    port=5000<br>)</pre><p>This version is still intentionally simplified. The important part is that we can now see how <strong>transactions, mining rewards, nodes, and consensus fit on top of the blockchain we built in the previous blog</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0bb83499ccc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nonce Range, Mempool,Mining Hardware]]></title>
            <link>https://medium.com/@preran248/nonce-range-mempool-mining-hardware-35b3e8ec13ec?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b3e8ec13ec</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 15:28:35 GMT</pubDate>
            <atom:updated>2026-08-22T15:32:57.615Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous blogs, we discussed how mining works, how miners find a valid hash, and how blocks are added to the blockchain.</p><p>Now let’s go one level deeper and understand <strong>nonce range, how miners select transactions, CPU vs GPU vs ASIC, mempool, orphan blocks, and finally the 51% attack</strong>.</p><h3>1. Nonce Range</h3><p>As we already know, the <strong>nonce</strong> is a number that miners change to generate different hashes.</p><p>In our simplified explanation, let’s consider the nonce range to be:</p><pre>0 → 4,294,967,295</pre><p>That’s around <strong>4.29 billion possible values</strong>.</p><p>The miner keeps changing the nonce and calculating the hash:</p><pre>Nonce = 0<br>   ↓<br>Hash<br>   ↓<br>Valid? (no)</pre><pre>Nonce = 1<br>   ↓<br>Hash<br>   ↓<br>Valid? (no)</pre><pre>Nonce = 2<br>   ↓<br>Hash<br>   ↓<br>Valid? (no)</pre><pre>...<br>   <br>Nonce = 4,294,967,295<br>   ↓<br>Hash<br>   ↓<br>Valid? ✓ (yesh)</pre><p>But what happens if a miner has so much computational power that it can go through the entire nonce range very quickly?</p><p>We need another way to change the input of the block.</p><p>This is where the <strong>timestamp</strong> becomes useful.</p><h3>2. Timestamp</h3><p>A block also contains a timestamp.</p><p>For example:</p><pre>Block<br>├── Block Number<br>├── Timestamp<br>├── Transactions<br>├── Previous Hash<br>└── Nonce</pre><p>If the miner exhausts the available nonce values, it can construct a new candidate block template with a different timestamp and start trying nonce values again.</p><p>Why does this work?</p><p>Because even a small change in the block’s input produces a completely different hash due to the <strong>avalanche effect</strong>.</p><pre>Timestamp  →  Hash A<br>Nonce 0    →  Hash A</pre><pre>Timestamp changes<br>       ↓<br>New block input<br>       ↓<br>Completely different hashes<br>       ↓<br>Nonce 0 → Hash B<br>Nonce 1 → Hash C<br>Nonce 2 → Hash D<br>...</pre><p>So the miner can search through the nonce space again with a different block header.</p><p>In real Bitcoin mining, miners also have other fields they can vary, such as the <strong>coinbase transaction and its extraNonce</strong>, which gives them a much larger search space than just the 32-bit nonce.</p><h3>3. How Do Miners Pick Transactions?</h3><p>Now let’s understand where the transactions inside a block come from.</p><p>Suppose Alice wants to send Bitcoin to Bob.</p><pre>Alice<br>  ↓<br>Transaction<br>  ↓<br>Bitcoin Network</pre><p>The transaction is broadcast to the network.</p><p>Nodes verify the transaction according to the Bitcoin protocol. If it is valid, it can be placed into the node’s <strong>mempool</strong>.</p><p>The mempool is basically a waiting area for valid transactions that have not yet been included in a block.</p><pre>Transactions<br>     ↓<br>   Nodes<br>     ↓<br>  Mempools<br>     ↓<br> Waiting</pre><p>An important point is that there is <strong>not one single global mempool</strong>. Each node maintains its own local mempool, so the contents can be slightly different from node to node.</p><h3>4. How Does a Miner Select Transactions?</h3><p>Now the miner looks at the transactions available in its mempool.</p><p>A block has limited space, so the miner cannot simply include every transaction.</p><p>Miners generally prefer transactions with a higher <strong>fee rate</strong>, because these transactions provide more fees for the limited block space they consume.</p><p>For example:</p><pre>Transaction A → 10 sat/vB<br>Transaction B → 2 sat/vB<br>Transaction C → 50 sat/vB<br>Transaction D → 20 sat/vB</pre><p>The miner would generally prefer:</p><pre>Transaction C<br>Transaction D<br>Transaction A<br>Transaction B</pre><p>based on fee rate, subject to the block’s other rules and constraints.</p><p>So the miner creates a candidate block:</p><pre>Mempool<br>   ↓<br>Select transactions<br>   ↓<br>Create candidate block<br>   ↓<br>Start Proof of Work<br>   ↓<br>Find valid hash<br>   ↓<br>Broadcast block</pre><h3>5. What If the Miner Runs Out of Nonces?</h3><p>Let’s connect this with our previous section.</p><p>Suppose a miner has gone through the entire nonce range without finding a valid hash.</p><p>The miner doesn’t just give up.</p><p>It can change the block template.</p><p>For example, the miner can modify the <strong>transactions included in the candidate block</strong>.</p><p>Suppose the block currently contains:</p><pre>Transaction A → High fee<br>Transaction B → High fee<br>Transaction C → Low fee</pre><p>The miner could create a different candidate block by replacing a transaction with another transaction from its mempool.</p><p>Now the block data has changed.</p><p>Because the input has changed, the resulting hash changes completely.</p><p>The miner can then start searching the nonce range again:</p><pre>New block template<br>       ↓<br>Nonce = 0<br>       ↓<br>Nonce = 1<br>       ↓<br>Nonce = 2<br>       ↓<br>...<br>Nonce = 4,294,967,295</pre><p>This gives miners a huge number of possible combinations to search.</p><h3>6. CPU vs GPU vs ASIC</h3><p>Now comes the interesting part.</p><p>Why can’t we simply use a normal computer to mine Bitcoin?</p><p>Let’s compare <strong>CPU, GPU, and ASIC</strong>.</p><h3>CPU — Central Processing Unit</h3><p>A CPU is designed to handle many different types of tasks.</p><p>It is very flexible and good at handling sequential and complex operations, but it has relatively few powerful cores compared with a GPU.</p><p>Because Bitcoin mining requires performing an enormous number of repeated hash calculations, CPUs are not efficient for modern Bitcoin mining.</p><h3>GPU — Graphics Processing Unit</h3><p>GPUs were originally designed mainly for graphics processing and gaming.</p><p>But GPUs are also very good at <strong>parallel computation</strong>.</p><p>Instead of doing one calculation at a time, they can perform many similar calculations simultaneously.</p><p>This makes GPUs much better suited for certain types of cryptocurrency mining than CPUs.</p><p>However, Bitcoin mining uses the <strong>SHA-256</strong> algorithm, and specialized hardware is far more efficient for this task.</p><h3>ASIC — Application-Specific Integrated Circuit</h3><p>ASIC stands for <strong>Application-Specific Integrated Circuit</strong>.</p><p>Unlike a CPU or GPU, an ASIC is designed for a specific purpose.</p><p>Bitcoin mining ASICs are specifically designed to perform <strong>SHA-256 hashing</strong> extremely efficiently.</p><p>So:</p><pre>CPU<br>↓<br>General purpose<br>↓<br>Less efficient for Bitcoin mining</pre><pre>GPU<br>↓<br>Highly parallel<br>↓<br>Better for certain mining algorithms</pre><pre>ASIC<br>↓<br>Built specifically for SHA-256<br>↓<br>Extremely efficient for Bitcoin mining</pre><p>This is why modern Bitcoin mining is dominated by <strong>ASIC miners</strong> rather than CPUs or GPUs.</p><h3>7. What Happens to Orphaned/Stale Blocks?</h3><p>Now let’s return to a problem we discussed earlier.</p><p>Imagine two miners find valid blocks at almost exactly the same time.</p><pre>→ Block A<br>Block 100 →<br>             → Block B</pre><p>Both blocks are valid, so different parts of the network may temporarily see different versions of the chain.</p><p>Now suppose another miner finds the next block on top of <strong>Block A</strong>:</p><pre>Block 100 → Block A → Block C</pre><p>The chain with the greater accumulated Proof of Work becomes the canonical chain under Bitcoin’s consensus rules.</p><p>Block B is then no longer part of the canonical chain and is commonly called a <strong>stale block</strong>.</p><pre>Block 100 → Block A → Block C<br>                ↑<br>        Canonical chain</pre><pre>Block 100 → Block B<br>                ↑<br>          Stale block</pre><p>The transactions from the stale block are not automatically “sent back to the mempool” as one big operation. Transactions that are still valid and are not already included in the canonical chain may become eligible for inclusion in future blocks, depending on the node’s mempool rules.</p><p>Also, the miner of the stale block <strong>does not receive the Bitcoin block subsidy for that stale block</strong>.</p><p>This is why miners try to stay connected to the network and minimize the delay between finding a block and having other nodes receive it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b3e8ec13ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptocurrency Intuition]]></title>
            <link>https://medium.com/@preran248/cryptocurrency-intuition-7c548984f95f?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c548984f95f</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[transaction-fees]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 03:11:39 GMT</pubDate>
            <atom:updated>2026-08-20T03:11:39.831Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous blogs, we understood how blockchain works, how mining works, Proof of Work, and how the network reaches consensus.</p><p>Now let’s move one step further and understand <strong>what Bitcoin actually is, how its monetary system works, and how transactions reach miners</strong>.</p><h3>What is Bitcoin?</h3><p>To understand Bitcoin, let’s look at it in three layers.</p><h3>Layer 1 — Blockchain</h3><p>At the bottom, we have the <strong>blockchain</strong>.</p><p>A blockchain is the distributed ledger where transactions are stored inside blocks. These blocks are connected to each other using cryptographic hashes, creating a chain.</p><pre>Block → Block → Block → Block → Block</pre><p>The blockchain gives us the underlying system for storing and verifying the records.</p><h3>Layer 2 — Protocols / Blockchain Networks</h3><p>On top of the basic blockchain concept, different blockchain networks implement their own rules and protocols.</p><p>Some examples are:</p><ul><li><strong>Bitcoin</strong></li><li><strong>Ethereum</strong></li><li><strong>Solana</strong></li><li><strong>Monero</strong></li></ul><p>Each network has its own rules for things like consensus, transactions, validation, and how the network operates.</p><p>For example, <strong>Bitcoin uses Proof of Work</strong>, while Ethereum currently uses <strong>Proof of Stake</strong>.</p><h3>Layer 3 — Tokens and Applications</h3><p>On top of some blockchain protocols, we can build <strong>tokens and applications</strong>.</p><p>For example, Ethereum allows developers to create tokens using smart contracts. These tokens can represent currencies, assets, governance rights, and many other things.</p><pre>Tokens / Applications<br>                 ↑<br>          Blockchain Protocol<br>                 ↑<br>             Blockchain</pre><p>Bitcoin is slightly different from Ethereum in this regard. <strong>BTC is Bitcoin’s native asset</strong>, and Bitcoin was primarily designed as a decentralized digital currency and payment network.</p><h3>Bitcoin’s Monetary Principle — The Halving</h3><p>Now comes one of the most interesting parts of Bitcoin: <strong>the halving mechanism</strong>.</p><p>Whenever a miner successfully mines a block, the Bitcoin protocol gives the miner a <strong>block subsidy</strong> — newly created BTC — along with transaction fees.</p><p>But this block subsidy doesn’t remain the same forever.</p><p>Approximately every <strong>210,000 blocks</strong>, the block subsidy is cut in half.</p><p>Historically:</p><pre>2009  → 50 BTC<br>2012  → 25 BTC<br>2016  → 12.5 BTC<br>2020  → 6.25 BTC<br>2024  → 3.125 BTC<br>2028  → 1.5625 BTC (approximately)<br>        ↓<br>       ...<br>        ↓<br>       0</pre><p>So, as time passes, the amount of newly created Bitcoin approaches zero.</p><p>We can visualize the block subsidy roughly like this:</p><pre>Bitcoin<br>Block<br>Reward</pre><pre>50 | ████████████████████████████████████████<br>   |<br>25 | ████████████████████<br>   |<br>12 | ██████████<br>   |<br> 6 | █████<br>   |<br> 3 | ██<br>   |<br> 1 | █<br>   |<br> 0 |________________________________________<br>      Time →</pre><p>The important thing is that the <strong>total Bitcoin supply is not halved</strong>.</p><p>Only the <strong>new Bitcoin created for each successfully mined block</strong> is reduced.</p><p>This mechanism is one of the reasons Bitcoin has a maximum supply of approximately <strong>21 million BTC</strong>.</p><h3>But What Happens When the Block Reward Approaches Zero?</h3><p>This gives us an important question.</p><p>If miners are spending electricity and computational power to mine blocks, what happens when the newly created Bitcoin reward becomes extremely small and eventually reaches zero?</p><p>This is where <strong>transaction fees</strong> become increasingly important.</p><p>Today, a miner’s potential revenue comes from two major components:</p><pre>Miner Revenue<br>      │<br>      ├── Block Subsidy<br>      │<br>      └── Transaction Fees</pre><p>As the block subsidy decreases:</p><pre>Block Subsidy ↓<br>        +<br>Transaction Fees<br>        ↓<br>Miner Revenue</pre><p>Eventually, the block subsidy will become zero. At that point, miners will rely on <strong>transaction fees</strong> as their primary source of revenue.</p><p>So Bitcoin’s monetary system gradually moves from:</p><pre>New Bitcoin Creation<br>        ↓<br>Block Subsidy<br>        ↓<br>Transaction Fees</pre><p>The transaction-fee market provides an economic incentive for miners to continue securing the network even after the block subsidy disappears.</p><h3>How Do Transactions Reach the Miners?</h3><p>Now let’s understand what happens when someone wants to make a Bitcoin transaction.</p><p>Imagine Alice wants to send some BTC to Bob.</p><p>The transaction is first broadcast to the Bitcoin network.</p><pre>Alice<br>  ↓<br>Transaction<br>  ↓<br>Bitcoin Network</pre><p>The transaction is then received and checked by nodes.</p><p>If the transaction is valid, it is placed into the node’s <strong>mempool</strong>.</p><p>The mempool is basically a waiting area for valid transactions that have <strong>not yet been included in a block</strong>.</p><pre>Transaction<br>     ↓<br>   Node<br>     ↓<br>  Mempool<br>     ↓<br>Waiting for a miner</pre><p>One important clarification: <strong>each node can have its own mempool</strong>. There isn’t one single global mempool shared by the entire Bitcoin network.</p><h3>How Do Miners Choose Transactions?</h3><p>Now the miner has a collection of transactions available to include in a block.</p><p>The miner selects transactions from its mempool and constructs a candidate block.</p><p>Transaction fees are important here.</p><p>For example:</p><pre>Transaction A → Fee: 0.001 BTC<br>Transaction B → Fee: 0.0001 BTC<br>Transaction C → Fee: 0.005 BTC</pre><p>A miner generally prefers transactions that provide a higher <strong>fee rate</strong>, because a block has limited space.</p><p>So the miner selects a suitable set of transactions and puts them into a candidate block.</p><pre>Mempool<br>   ↓<br>Select Transactions<br>   ↓<br>Candidate Block<br>   ↓<br>Proof of Work<br>   ↓<br>Valid Hash<br>   ↓<br>Broadcast Block<br>   ↓<br>Network Verification<br>   ↓<br>Blockchain</pre><p>The miner then performs Proof of Work by repeatedly changing the nonce and calculating the block’s hash until they find a hash that satisfies the current difficulty target.</p><p>Once a miner finds a valid block, they broadcast it to the network.</p><p>Other nodes verify the block and, if it follows the Bitcoin protocol’s rules, accept it and add it to their copy of the blockchain.</p><p>So the complete intuition is:</p><pre>User creates transaction<br>          ↓<br>Transaction broadcast<br>          ↓<br>Nodes verify transaction<br>          ↓<br>Transaction enters mempool<br>          ↓<br>Miner selects transactions<br>          ↓<br>Miner creates candidate block<br>          ↓<br>Miner performs Proof of Work<br>          ↓<br>Valid block found<br>          ↓<br>Block broadcast to network<br>          ↓<br>Nodes verify the block<br>          ↓<br>Block added to blockchain<br>          ↓<br>Miner receives block subsidy + fees</pre><p>This is the basic flow of how a Bitcoin transaction goes from <strong>your wallet → mempool → miner → block → blockchain</strong>.</p><h3>Upcoming Blogs</h3><ul><li>How miners pick transactions from the mempool</li><li>What is the nonce range?</li><li>CPU vs GPU vs ASIC — what is the difference?</li><li>Why does Bitcoin use ASICs instead of GPUs?</li><li>How ASICs make Bitcoin mining more efficient</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c548984f95f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Blockchain Sample in Python]]></title>
            <link>https://medium.com/@preran248/creating-a-blockchain-sample-in-python-bf44c5d28170?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf44c5d28170</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[demo]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 02:39:50 GMT</pubDate>
            <atom:updated>2026-08-20T02:39:50.933Z</atom:updated>
            <content:encoded><![CDATA[<p>Now let’s create a simple blockchain in Python and see how the concepts work together.</p><p>Before getting into the code, let’s briefly understand <strong>Proof of Work</strong>.</p><p><strong>Proof of Work is a mechanism used to verify that a miner has performed the required computational work to find a valid hash that follows the rules of the blockchain.</strong> The miner keeps trying different values until they find a hash that satisfies the required condition.</p><p>Now let’s break the code into small sections and understand what each part does.</p><h3>1. Importing the Required Libraries</h3><pre>import datetime<br>import hashlib<br>import json</pre><pre>from flask import Flask, jsonify</pre><p>We use three main Python libraries:</p><ul><li>datetime — to store the timestamp of each block.</li><li>hashlib — to generate SHA-256 hashes.</li><li>json — to convert block data into a consistent format before hashing.</li><li>Flask — to create a simple API for interacting with our blockchain.</li></ul><h3>2. Creating the Blockchain Class</h3><pre>class Blockchain:</pre><pre>    def __init__(self):<br>        self.chain = []<br>        self.create_block(proof=1, previous_hash=&quot;0&quot;)</pre><p>Here, we create a Blockchain class.</p><p>The chain variable stores all the blocks:</p><pre>chain = [Block 1, Block 2, Block 3, ...]</pre><p>Initially, the chain is empty.</p><p>Then we create the first block. This is the <strong>Genesis Block</strong>, so it doesn’t have a previous block. Therefore, we use &quot;0&quot; as its previous hash.</p><h3>3. Creating a Block</h3><pre>def create_block(self, proof, previous_hash):</pre><pre>    block = {<br>        &quot;index&quot;: len(self.chain) + 1,<br>        &quot;timestamp&quot;: str(datetime.datetime.now()),<br>        &quot;proof&quot;: proof,<br>        &quot;previous_hash&quot;: previous_hash<br>    }</pre><pre>    self.chain.append(block)<br>    return block</pre><p>This function creates a new block.</p><p>Our block contains:</p><ul><li>index → The block number.</li><li>timestamp → When the block was created.</li><li>proof → The Proof of Work found by the miner.</li><li>previous_hash → The hash of the previous block.</li></ul><p>For example:</p><pre>Block 2<br>├── index: 2<br>├── timestamp: ...<br>├── proof: 10452<br>└── previous_hash: 0000abc...</pre><p>Once the block is created, we add it to our blockchain using:</p><pre>self.chain.append(block)</pre><h3>4. Getting the Previous Block</h3><pre>def get_previous_block(self):<br>    return self.chain[-1]</pre><p>The chain is a Python list.</p><p>[-1] gives us the <strong>last element</strong> of the list.</p><p>Since the newest block is always at the end of the chain, this function gives us the previous block when we are trying to create a new one.</p><h3>Proof of Work</h3><p>In our example, we consider a hash that <strong>starts with </strong><strong>0000</strong> to be a valid hash, meaning it falls within the required <strong>target range</strong>.</p><pre>if hash_operation[:4] == &quot;0000&quot;:<br>    check_proof = True</pre><p>So, the miner keeps changing the nonce and calculating the hash until the hash starts with 0000.</p><p>For example:</p><pre>Hash 1 → 8a72... ❌<br>Hash 2 → 4f91... ❌<br>Hash 3 → 00ab... ❌<br>Hash 4 → 0000a7... ✓</pre><p>Once the miner finds a hash that starts with 0000, the Proof of Work is considered valid.</p><p>Now we come to the most interesting part — <strong>mining</strong>.</p><pre>def proof_of_work(self, previous_proof):</pre><pre>    nonce = 1<br>    check_proof = False</pre><pre>    while check_proof is False:</pre><pre>        hash_operation = hashlib.sha256(<br>            str(nonce**2 - previous_proof**2).encode()<br>        ).hexdigest()</pre><pre>        if hash_operation[:4] == &quot;0000&quot;:<br>            check_proof = True<br>        else:<br>            nonce += 1</pre><pre>    return nonce</pre><p>The idea here is very similar to what we discussed earlier.</p><p>We keep changing a number called the <strong>nonce</strong> and calculate a new hash each time.</p><pre>nonce = 1<br>   ↓<br>calculate hash<br>   ↓<br>Does hash start with 0000?<br>   ↓<br>No → nonce = 2<br>   ↓<br>calculate hash<br>   ↓<br>Does hash start with 0000?<br>   ↓<br>No → nonce = 3<br>   ↓<br>...</pre><p>We continue until we find a hash that satisfies our condition:</p><pre>hash_operation[:4] == &quot;0000&quot;</pre><p>In this simplified blockchain, we are using four leading zeros as our <strong>Proof-of-Work difficulty</strong>.</p><p>Once we find a valid nonce, we return it:</p><pre>return nonce</pre><p>This is the basic intuition behind mining that we discussed earlier.</p><h3>6. Hashing a Block</h3><p>Now we need a function that generates the hash of a block.</p><pre>def hash(self, block):</pre><pre>    encoded_hash = json.dumps(<br>        block,<br>        sort_keys=True<br>    ).encode()</pre><pre>    return hashlib.sha256(encoded_hash).hexdigest()</pre><p>First, we convert the block into JSON:</p><pre>json.dumps(block, sort_keys=True)</pre><p>sort_keys=True makes sure that the keys are always arranged in the same order.</p><p>Then we convert the result into bytes:</p><pre>.encode()</pre><p>Finally, we generate the SHA-256 hash:</p><pre>hashlib.sha256(encoded_hash).hexdigest()</pre><p>The result will look something like:</p><pre>0000a83f7c91b2...</pre><p>This hash acts like the <strong>digital fingerprint of the block</strong>.</p><h3>7. Checking Whether the Blockchain Is Valid</h3><p>Now we need a way to check whether someone has tampered with our blockchain.</p><pre>def check_valid_chain(self, chain):</pre><pre>    previous_block = chain[0]<br>    block_index = 1</pre><pre>    while block_index &lt; len(chain):</pre><pre>        block = chain[block_index]</pre><pre>        if block[&quot;previous_hash&quot;] != self.hash(previous_block):<br>            return False</pre><pre>        previous_proof = previous_block[&quot;proof&quot;]<br>        proof = block[&quot;proof&quot;]</pre><pre>        hash_operation = hashlib.sha256(<br>            str(proof**2 - previous_proof**2).encode()<br>        ).hexdigest()</pre><pre>        if not hash_operation.startswith(&quot;0000&quot;):<br>            return False</pre><pre>        previous_block = block<br>        block_index += 1</pre><pre>    return True</pre><p>We start from the first block and check every block after it.</p><p>First, we check whether the current block’s previous_hash matches the actual hash of the previous block:</p><pre>if block[&quot;previous_hash&quot;] != self.hash(previous_block):<br>    return False</pre><p>If someone changes the data inside an earlier block, its hash changes.</p><p>Then the next block’s previous_hash will no longer match.</p><pre>Block 1 → Block 2 → Block 3</pre><pre>Change Block 2<br>     ↓<br>Block 2&#39;s hash changes<br>     ↓<br>Block 3&#39;s previous_hash doesn&#39;t match<br>     ↓<br>Blockchain becomes invalid</pre><p>We also verify the Proof of Work:</p><pre>if not hash_operation.startswith(&quot;0000&quot;):<br>    return False</pre><p>If any block fails these checks, the function returns:</p><pre>False</pre><p>Otherwise:</p><pre>return True</pre><p>This means the blockchain is valid according to our simplified rules.</p><h3>8. Creating the Flask Application</h3><pre>app = Flask(__name__)</pre><pre>blockchain = Blockchain()</pre><p>Now we create our Flask application and create an instance of our Blockchain class.</p><pre>blockchain = Blockchain()</pre><p>This initializes our blockchain and creates the Genesis Block.</p><h3>9. Mining a Block</h3><p>Now let’s create an API endpoint for mining.</p><pre>@app.route(&#39;/mine_block&#39;, methods=[&#39;GET&#39;])<br>def mine_block():</pre><pre>    previous_block = blockchain.get_previous_block()</pre><pre>    previous_proof = previous_block[&#39;proof&#39;]</pre><pre>    proof = blockchain.proof_of_work(previous_proof)</pre><pre>    previous_hash = blockchain.hash(previous_block)</pre><pre>    block = blockchain.create_block(<br>        proof,<br>        previous_hash<br>    )</pre><pre>    response = {<br>        &#39;message&#39;: &#39;Congratulations, you just mined a block!&#39;,<br>        &#39;index&#39;: block[&#39;index&#39;],<br>        &#39;timestamp&#39;: block[&#39;timestamp&#39;],<br>        &#39;proof&#39;: block[&#39;proof&#39;],<br>        &#39;previous_hash&#39;: block[&#39;previous_hash&#39;]<br>    }</pre><pre>    return jsonify(response), 200</pre><p>When we call:</p><pre>/mine_block</pre><p>the following happens:</p><pre>Get previous block<br>        ↓<br>Get previous proof<br>        ↓<br>Perform Proof of Work<br>        ↓<br>Calculate previous block hash<br>        ↓<br>Create new block<br>        ↓<br>Add block to blockchain<br>        ↓<br>Return the block information</pre><p>This is essentially our simplified <strong>mining process</strong>.</p><h3>10. Getting the Entire Blockchain</h3><pre>@app.route(&#39;/get_chain&#39;, methods=[&#39;GET&#39;])<br>def get_chain():</pre><pre>    response = {<br>        &#39;chain&#39;: blockchain.chain,<br>        &#39;length&#39;: len(blockchain.chain)<br>    }</pre><pre>    return jsonify(response), 200</pre><p>This endpoint allows us to see the entire blockchain.</p><p>It returns:</p><ul><li>The complete chain.</li><li>The number of blocks in the chain.</li></ul><p>For example:</p><pre>{<br>    &quot;length&quot;: 3,<br>    &quot;chain&quot;: [<br>        Block 1,<br>        Block 2,<br>        Block 3<br>    ]<br>}</pre><h3>11. Checking the Blockchain</h3><p>Finally, we create an endpoint to check whether our blockchain is valid.</p><pre>@app.route(&#39;/is_valid&#39;, methods=[&#39;GET&#39;])<br>def is_valid():</pre><pre>    valid = blockchain.check_valid_chain(<br>        blockchain.chain<br>    )</pre><pre>    if valid:<br>        response = {<br>            &#39;message&#39;: &#39;All good. The Blockchain is valid.&#39;<br>        }<br>    else:<br>        response = {<br>            &#39;message&#39;: &#39;Houston, we have a problem. &#39;<br>                       &#39;The Blockchain is not valid.&#39;<br>        }</pre><pre>    return jsonify(response), 200</pre><p>This calls our validation function:</p><pre>blockchain.check_valid_chain(blockchain.chain)</pre><p>If everything is correct, we get:</p><pre>All good. The Blockchain is valid.</pre><p>If someone has modified the blockchain:</p><pre>Houston, we have a problem.<br>The Blockchain is not valid.</pre><h3>12. Running the Application</h3><pre>app.run(host=&#39;0.0.0.0&#39;, port=5000)</pre><p>Finally, we start the Flask server on port 5000.</p><p>Now we can interact with our blockchain through API endpoints such as:</p><pre>/mine_block<br>/get_chain<br>/is_valid</pre><p>And that’s it — we have created a <strong>simple blockchain in Python</strong> with blocks, hashing, Proof of Work, mining, and blockchain validation.</p><blockquote><strong><em>Note:</em></strong><em> This is a learning implementation, not a production blockchain. Real blockchains contain many additional components such as transactions, digital signatures, peer-to-peer networking, consensus rules, difficulty adjustment, wallets, and more.</em></blockquote><h3>Complete Code</h3><pre>import datetime<br>import hashlib<br>import json<br>from flask import Flask, jsonify<br></pre><pre>class Blockchain:</pre><pre>    def __init__(self):<br>        self.chain = []<br>        self.create_block(proof=1, previous_hash=&quot;0&quot;)</pre><pre>    def create_block(self, proof, previous_hash):</pre><pre>        block = {<br>            &quot;index&quot;: len(self.chain) + 1,<br>            &quot;timestamp&quot;: str(datetime.datetime.now()),<br>            &quot;proof&quot;: proof,<br>            &quot;previous_hash&quot;: previous_hash<br>        }</pre><pre>        self.chain.append(block)<br>        return block</pre><pre>    def get_previous_block(self):<br>        return self.chain[-1]</pre><pre>    def proof_of_work(self, previous_proof):</pre><pre>        nonce = 1<br>        check_proof = False</pre><pre>        while check_proof is False:</pre><pre>            hash_operation = hashlib.sha256(<br>                str(nonce**2 - previous_proof**2).encode()<br>            ).hexdigest()</pre><pre>            if hash_operation[:4] == &quot;0000&quot;:<br>                check_proof = True<br>            else:<br>                nonce += 1</pre><pre>        return nonce</pre><pre>    def hash(self, block):</pre><pre>        encoded_hash = json.dumps(<br>            block,<br>            sort_keys=True<br>        ).encode()</pre><pre>        return hashlib.sha256(encoded_hash).hexdigest()</pre><pre>    def check_valid_chain(self, chain):</pre><pre>        previous_block = chain[0]<br>        block_index = 1</pre><pre>        while block_index &lt; len(chain):</pre><pre>            block = chain[block_index]</pre><pre>            if block[&quot;previous_hash&quot;] != self.hash(previous_block):<br>                return False</pre><pre>            previous_proof = previous_block[&quot;proof&quot;]<br>            proof = block[&quot;proof&quot;]</pre><pre>            hash_operation = hashlib.sha256(<br>                str(proof**2 - previous_proof**2).encode()<br>            ).hexdigest()</pre><pre>            if not hash_operation.startswith(&quot;0000&quot;):<br>                return False</pre><pre>            previous_block = block<br>            block_index += 1</pre><pre>        return True<br></pre><pre>app = Flask(__name__)</pre><pre>blockchain = Blockchain()<br></pre><pre>@app.route(&#39;/mine_block&#39;, methods=[&#39;GET&#39;])<br>def mine_block():</pre><pre>    previous_block = blockchain.get_previous_block()<br>    previous_proof = previous_block[&#39;proof&#39;]</pre><pre>    proof = blockchain.proof_of_work(previous_proof)</pre><pre>    previous_hash = blockchain.hash(previous_block)</pre><pre>    block = blockchain.create_block(<br>        proof,<br>        previous_hash<br>    )</pre><pre>    response = {<br>        &#39;message&#39;: &#39;Congratulations, you just mined a block!&#39;,<br>        &#39;index&#39;: block[&#39;index&#39;],<br>        &#39;timestamp&#39;: block[&#39;timestamp&#39;],<br>        &#39;proof&#39;: block[&#39;proof&#39;],<br>        &#39;previous_hash&#39;: block[&#39;previous_hash&#39;]<br>    }</pre><pre>    return jsonify(response), 200<br></pre><pre>@app.route(&#39;/get_chain&#39;, methods=[&#39;GET&#39;])<br>def get_chain():</pre><pre>    response = {<br>        &#39;chain&#39;: blockchain.chain,<br>        &#39;length&#39;: len(blockchain.chain)<br>    }</pre><pre>    return jsonify(response), 200<br></pre><pre>@app.route(&#39;/is_valid&#39;, methods=[&#39;GET&#39;])<br>def is_valid():</pre><pre>    valid = blockchain.check_valid_chain(<br>        blockchain.chain<br>    )</pre><pre>    if valid:<br>        response = {<br>            &#39;message&#39;: &#39;All good. The Blockchain is valid.&#39;<br>        }<br>    else:<br>        response = {<br>            &#39;message&#39;: &#39;Houston, we have a problem. &#39;<br>                       &#39;The Blockchain is not valid.&#39;<br>        }</pre><pre>    return jsonify(response), 200<br></pre><pre>app.run(host=&#39;0.0.0.0&#39;, port=5000)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf44c5d28170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How mining works ??]]></title>
            <link>https://medium.com/@preran248/how-mining-works-f9fda78d8161?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9fda78d8161</guid>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 09:46:28 GMT</pubDate>
            <atom:updated>2026-08-18T09:46:28.427Z</atom:updated>
            <content:encoded><![CDATA[<p>Before reading, if you want to understand the basics of blockchain, kindly refer to <a href="https://medium.com/@preran248/starting-blockchain-649c130b9b04">this</a>.</p><h4>Part 1 of How Mining Works</h4><p>As we all know, a block contains <strong>data, the previous block hash, and the hash of the current block</strong>. So, mining is all about calculating the hash of the block, and if we find the <strong>correct hash</strong>, we can add the block to the blockchain. I know you will have this question: what do you mean by the “correct hash”? We’ll cover that in the next few sections.</p><p>But before getting into mining, remember that a <strong>hash is just a number</strong>.</p><p>In order to calculate the hash, we need to give some input to the hash algorithm. Till now, we know that a block contains <strong>data, the previous block hash, and the hash of the current block</strong>.</p><p>In order to get the current hash, we need to keep changing something in the input so that the hash algorithm produces a different output each time. We keep doing this and stop once we get the <strong>correct hash</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*ZQYH80tf9CiyeNFWS0dwvQ.png" /></figure><p>Mining is used to find the hash of the block, so we cannot simply change the hash. Next, we have the previous block hash, which we also cannot change. Finally, we have the data, which we should not change because that would mean tampering with the data.</p><p>So, what else does a block contain? It contains the <strong>block number</strong> and a <strong>Nonce</strong>. The nonce is a number that miners can change. By changing the nonce, the input to the hash algorithm changes, and due to the <strong>avalanche effect</strong>, the complete hash changes. Miners keep changing the nonce until they find a hash that satisfies the required condition.</p><p>So, in our simplified example, to calculate the hash of the block, we use:</p><p><strong>(Block Number, Nonce, Previous Hash, Data)</strong></p><p>There are many more things in a real block, which we will discuss later.</p><h3>How Mining Works: The Cryptographic Puzzle</h3><h3>Mining — Part 2</h3><p>In the previous section, we discussed what is used to calculate the hash of the block.</p><p>We were talking about the <strong>current hash</strong>.</p><p>So, we may imagine that mining is just calculating the hash of the block. But if miners are doing this all over the world, why do we need so much computational power? Everything will be clarified here.</p><p>The current hash needs to be <strong>below a specific target</strong> to be considered valid. If the hash is above the target, it is not valid.</p><p>The target is determined by the blockchain’s <strong>consensus rules and difficulty</strong>. It is not simply chosen arbitrarily; the difficulty is adjusted according to the rules of the blockchain to control how difficult it is to find a valid hash.</p><p>So miners keep changing the nonce and calculating new hashes until one of them finds a hash below the target. The miner who finds a valid hash can propose the block and, after the network accepts it, receive the applicable <strong>block reward</strong>.</p><p>(We will see how rewards work in upcoming sections. If you’re curious, check out <strong>PoW and PoS</strong>.)</p><p>You may also hear people casually call a successful hash a <strong>“golden hash”</strong>, meaning that the miner has found a hash that satisfies the target condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3O2dx-fhhyJunostDygHg.png" /></figure><p>As already mentioned, the <strong>nonce</strong> is just a number that can be changed. We calculate the hash of the block using the nonce, and as you can see in the image below, we might think that we can just keep increasing the nonce and eventually get the correct hash.</p><p>But we are wrong — it is <strong>completely unpredictable</strong>. We might find it at nonce = 1, or at nonce = 99,956,562, or at some other value. There is no way to predict which nonce will produce a valid hash.</p><p>So, in order to find the <strong>golden hash</strong>, all the miners use their computational power and electricity to try different nonce values and find a valid hash.</p><p>Now, we might have a question: <strong>Why would someone do this?</strong> Why not just calculate the hash of the block and insert it into the blockchain?</p><p>If it were this simple, anyone could create multiple blocks or even create multiple chains, which would lead to confusion and allow people to manipulate the blockchain. This is exactly why miners are doing this work in the first place. By requiring miners to solve a difficult computational puzzle, the network makes block creation expensive and time-consuming. This cost acts as a security mechanism: it prevents spam, stops attackers from easily rewriting history, and ensures that no single participant can dominate the system. Instead, miners must compete fairly using computational power, and the longest valid chain becomes the trusted version of the blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8aO47GKGeUcowDBitoT6rQ.png" /></figure><p>so golden hash is something which is golden hash≤ target hash</p><h3>Byzantine Fault Tolerance (BFT)</h3><p>Let’s take a simple example :)</p><p>Here’s a simple explanation matching your image and suitable for your blog:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y55TZhUF7PPKA-xiHDzGuQ.png" /></figure><p>Imagine <strong>four commanders</strong> surrounding a castle. The commander at the top-left is the <strong>main commander</strong>, and the other three commanders receive his message.</p><p>The main commander sends a message to attack the castle. The two honest commanders receive the same message and agree with it.</p><p>But there is <strong>one traitor</strong> among the commanders. The traitor sends different messages to the other commanders — for example, he may tell one commander <strong>“Attack”</strong> and another <strong>“Retreat.”</strong> This is shown by the <strong>red arrows</strong> in the image.</p><p>The honest commanders communicate with each other and compare the messages they received. Since they can see that the messages do not agree, they can identify that something is wrong and still reach an agreement based on the messages from the honest commanders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89WCSZDXDxSDGUfCDtxwZg.png" /></figure><p>Now comes the important part: <strong>the main commander himself can also be the traitor.</strong> In that case, he could send <strong>“Attack”</strong> to one commander and <strong>“Retreat”</strong> to another. The other commanders still need to reach a common decision even though the commander sending the original message cannot be trusted.</p><p>This is the basic idea behind <strong>Byzantine Fault Tolerance (BFT)</strong> — a distributed system should be able to reach an agreement even when some participants are <strong>faulty or malicious</strong>.</p><h3>Blockchain example</h3><p>In a blockchain, the commanders can be thought of as <strong>nodes/validators</strong>, and the message can be thought of as a <strong>transaction or proposed block</strong>.</p><p>If one validator is malicious and tries to tell other validators that an invalid block is valid, the honest validators communicate and follow the rules of the consensus mechanism to determine whether the block should be accepted.</p><p>So, just like the commanders in the image need to agree on whether to <strong>attack or retreat</strong>, blockchain participants need to agree on <strong>which transactions and blocks are valid</strong>.</p><h3>Consensus Protocols</h3><h3>Challenge 1: What if a hacker attaches a block to the end of the chain?</h3><p>Whenever a miner successfully mines a valid block, they can receive the <strong>block reward and transaction fees</strong> associated with that block. This creates an incentive for miners to follow the rules of the network.</p><p>If a miner or hacker tries to add an <strong>invalid block</strong> to the end of the chain, the other nodes will verify the block and reject it. In that case, the miner will <strong>not receive the block reward or the transaction fees</strong>.</p><p>The miner would still have spent their own <strong>computational power and electricity</strong> trying to mine the block, so they would bear the cost without receiving the reward.</p><p>This creates an incentive for miners to play fairly and follow the consensus rules of the blockchain.</p><p>below are the some rules which are performed by the nodes before adding them to the chain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*GkGuXaLWt_IIRE8phFTStA.png" /></figure><p>these are the checks performed before adding the block to the chain</p><h3>Challenge 2: What Happens If Two Nodes Mine a Block at the Same Time?</h3><p>Let’s say two miners find a valid block <strong>at almost the same time</strong>.</p><p>Both miners have solved the Proof-of-Work puzzle, so both blocks are valid. But both blocks point to the same previous block.</p><pre>→ Block A<br>Block 100 →<br>→ Block B</pre><p>Now we have a <strong>temporary fork</strong> because different parts of the network may receive different blocks first.</p><p>For example, some nodes may receive Block A first:</p><pre>Block 100 → Block A</pre><p>while other nodes receive Block B first:</p><pre>Block 100 → Block B</pre><p>So, which block will become part of the main blockchain?</p><p>Let’s say another miner finds the next block and builds on <strong>Block A</strong>:</p><pre>Block 100 → Block A → Block C</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*ATXABAhS-JCG2_FSNonSvA.png" /></figure><p>As we can see in the image, there are two different chains being created. The <strong>orange blocks</strong> represent one chain, while the <strong>purple blocks</strong> represent another chain.</p><p>Initially, both chains are valid because different miners found valid blocks at almost the same time. This creates a <strong>temporary fork</strong> in the blockchain.</p><p>Now, suppose miners continue mining on both chains. The chain that gets the <strong>next valid block first</strong> will have more accumulated Proof of Work. In our example, the orange chain gets the next block first, so it becomes the <strong>main (canonical) chain</strong>.</p><p>The purple blocks are no longer part of the main chain and become <strong>stale blocks</strong>.</p><p>So, in simple terms:</p><p><strong>Two valid blocks → temporary fork → one chain gets more accumulated Proof of Work → that chain becomes the canonical chain → the other block becomes stale(</strong>Orphan blocks )<strong>.</strong></p><p>We’ll see what happens to <strong>orphan blocks</strong> later.</p><p>Just for clarification, the miner who mined the purple (orphaned/stale) block will generally <strong>not receive the block reward</strong>. The transactions from that block may be returned to the <strong>mempool</strong> and can be included in a future block if they are still valid.</p><p>We’ll discuss this in detail in the upcoming sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbuQXyNmQ3QSkNrUwg5FYg.png" /></figure><h3>Upcoming</h3><ul><li>Cryptocurrency Intuition</li><li>Cryptocurrency Transactions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9fda78d8161" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[starting blockchain ?? :(]]></title>
            <link>https://medium.com/@preran248/starting-blockchain-649c130b9b04?source=rss-6111607ccc1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/649c130b9b04</guid>
            <category><![CDATA[blockchain-web3]]></category>
            <dc:creator><![CDATA[Preran]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 17:05:25 GMT</pubDate>
            <atom:updated>2026-08-17T17:05:25.879Z</atom:updated>
            <content:encoded><![CDATA[<p>A blockchain is a continuously growing list of records that are linked and secured using <strong>cryptography and a consensus mechanism</strong>.</p><p>Basically, what does a <strong>block</strong> contain?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*7yuieFetsw19JfdS.png" /></figure><ul><li>data</li><li>hash of the current block</li><li>hash of the previous block</li></ul><p>These are the three main basic elements of a block. :) Leveling up!</p><p>So, as mentioned, when you see the word <strong>“hash of the previous block”</strong>, you may wonder: what about the first block? How will it have a previous hash?</p><p>The answer is that the first block of a blockchain is called the <strong>“Genesis Block”</strong>. It doesn’t have a previous block, so we can imagine its previous hash as 00000000....</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*ILJY8gglSM4wi8mG.jpg" /><figcaption>sequence of blockchain blocks</figcaption></figure><p>As you can see in the image, every block has its own hash and stores the hash of the previous block. Just don’t think about the other parts of the block; we’ll cover them later.</p><p><strong>UNDERSTANDING HOW SHA256 WORKS</strong></p><p>SHA-256 stands for <strong>Secure Hash Algorithm 256</strong>, where 256 represents the number of bits in the hash output. It produces a <strong>256-bit (32-byte) hash</strong>, represented as a <strong>64-character hexadecimal string</strong>.</p><p>As we all know, each person has a unique fingerprint, which can be used as an identifier. Similarly, SHA-256 can be used to create a <strong>hash (digital fingerprint)</strong> for any data you give it. It will produce a 64-character hexadecimal hash.</p><p>If you wish to see how SHA-256 works <a href="https://emn178.github.io/online-tools/sha256.html">click here →</a></p><p>SHA-256 was developed by the <strong>NSA</strong> as part of the SHA-2 family, and its specification is publicly available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*kSPbjQt9pt-SRvNC.png" /></figure><p>Any digital document can be hashed using SHA-256, and it produces a <strong>64-character hexadecimal output</strong>.</p><p>You might also have noticed that whenever we hash something, we get a specific hash value. Even if we change a single character, the <strong>entire hash changes</strong>. We’ll talk about this behaviour later.</p><h4>5 Requirements of Hash Algorithms</h4><ul><li><strong>One-way</strong> — Using the hash value, we cannot get the original document/value back.</li><li><strong>Deterministic</strong> — For the same input, we will always get the same output.</li><li><strong>Fast computation</strong> — The hash should be quick to compute.</li><li><strong>Avalanche effect</strong> — If we change even a small part of the input, the resulting hash changes significantly.</li><li><strong>Collision resistance</strong> — Since SHA-256 produces a fixed-size 256-bit hash, collisions are theoretically possible. A good hash algorithm makes it extremely difficult to find two different inputs that produce the same hash.</li></ul><h3><strong>IMMUTABLE LEDGER</strong></h3><p>Let’s take an example :)</p><p>Let’s consider you buy a house and need to register it in the government ledger. There will be a record maintained by the government where they register your house number with the owner’s name. After some days, many other people buy houses, and the number of records in the ledger keeps increasing.</p><p>Now, let’s say on a random day, someone wants to change a record in the record book. They can simply remove the page and replace it with a manipulated record, and there you go — since the record was manipulated, you now don’t own the house. :(</p><p>So, here comes the <strong>blockchain</strong>, where we have a chain of blocks that contain transactions.</p><p>Let’s take the same example. When we buy a house, instead of recording it in a physical record book, we create a <strong>transaction for buying the house</strong>, and these transactions are stored on the blockchain. After some more days, the number of transactions increases, and the number of blocks in the chain increases as well.</p><p>As already discussed, a block contains <strong>data</strong>. For now, we will imagine that this data is filled with some transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxBzYV_xw-1DaKxgGlgpmw.png" /></figure><p>So, when someone wants to change a record in the blockchain, they have to find the block that contains the transaction. If they tamper with or change the data, according to the <strong>avalanche effect</strong>, the hash of that block changes. Then, the next block’s previous hash doesn’t match, which causes a problem.</p><p>Later, we’ll see how this problem will be resolved in the next section. The conclusion of this section will be covered in the next sections. :)</p><h3><strong>DISTRIBUTED P2P NETWORK</strong></h3><p>So, in the previous section, we saw that if the hacker has enough computational power, they may be able to modify all the future blocks and change the records of the chain, potentially allowing them to claim the property.</p><p>But we have something additional in the blockchain. A blockchain is a chain of blocks where a copy of the blockchain is maintained across different nodes around the world. Here, we have shown only 5 or 6 nodes for simplicity.</p><p>So, let’s say when the hacker changes the value of a block, the block’s hash changes, and the previous hash stored in the next block no longer matches. Even if the hacker is able to change the complete chain from that block onward, the altered chain still needs to be accepted by the rest of the network.</p><h4>How does a P2P network work?</h4><p>Let’s say whenever a miner mines a block (we’ll see what miners are and what their role is in blockchain in upcoming blogs), the block is added to the chain. The same block is then propagated across the network, where other nodes <strong>verify it before accepting it into their copy of the blockchain</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hzCxPlatb4qapAnXgGLJg.png" /></figure><p>So, after a block has been added to all the nodes, more blocks will be added over time. Let’s say a hacker tries to tamper with the data in one blockchain and changes all the blocks after a certain point. The network will verify the blockchain and compare it with the chains maintained by other nodes.</p><p>Since the hacked node’s blockchain is different from the majority of the network, the valid chain will be accepted instead of the corrupted one.</p><p>So, in order to actually change the blockchain, the hacker would need to control a <strong>majority of the network’s consensus power</strong>. This is extremely difficult because there can be thousands of nodes, and controlling enough of the network would require enormous computational or financial resources, depending on the blockchain’s consensus mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wv8wZ2FAhBe0zn33DZVbMA.png" /></figure><h3>Upcoming Blogs</h3><ul><li>How mining works, Byzantine Fault Tolerance, and blockchain demo</li><li>Creating a blockchain in Python</li><li>Cryptocurrency intuition</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649c130b9b04" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>