<?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 prajjwal singh on Medium]]></title>
        <description><![CDATA[Stories by prajjwal singh on Medium]]></description>
        <link>https://medium.com/@tricksbusinnes?source=rss-97faa03fd462------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QDBNx_7EOWMh-vBG</url>
            <title>Stories by prajjwal singh on Medium</title>
            <link>https://medium.com/@tricksbusinnes?source=rss-97faa03fd462------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:07:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tricksbusinnes/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[Why MD5 Failed Me: Understanding Image Hashing Before Building Duplicate Image Detection]]></title>
            <link>https://medium.com/@tricksbusinnes/why-md5-failed-me-understanding-image-hashing-before-building-duplicate-image-detection-49574ee6e1d8?source=rss-97faa03fd462------2</link>
            <guid isPermaLink="false">https://medium.com/p/49574ee6e1d8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[prajjwal singh]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 06:34:59 GMT</pubDate>
            <atom:updated>2026-07-10T07:08:53.835Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why MD5 Fails for Duplicate Images (And How dHash Fixes It)</h3><h3>Introduction</h3><p>Have you ever tried detecting duplicate images using an MD5 hash?</p><p>I did.</p><p>At first it seemed obvious. Two identical files should have the same hash.</p><pre>photo.jpg ──&gt; [ MD5 ] ──&gt; c8e4f1cbb2e...</pre><p>Then I discovered something surprising. Changing only the brightness by 2%, resizing the image, or saving it again as a PNG completely changed the hash — even though the image looked identical to my eyes.</p><p>That was when I realized there are actually two different problems:</p><ul><li><strong>Detecting identical files</strong></li><li><strong>Detecting visually identical images</strong></li></ul><p>Those are not the same thing. In this article we’ll understand:</p><ul><li>How hashing actually works</li><li>Why MD5 fails for duplicate images</li><li>What perceptual hashing (dHash) is</li><li>How dHash works internally</li><li>How to compare two images</li><li>Where dHash succeeds and where it fails</li></ul><p>We’ll also build everything from scratch in Python.</p><h3>The Duplicate Image Problem</h3><p>Imagine you have this image:</p><p>holiday.jpg</p><p>Someone uploads:</p><p>holiday.png</p><p>Same photo. Different format. Should it be considered a duplicate? <strong>Absolutely.</strong></p><p>Now another person uploads holiday.jpg but resized to 800×600. Still the same photo. Now someone increases brightness by 5%. Still the same.</p><p>But your application stores three different copies. That’s wasted storage. That’s exactly the problem I was trying to solve.</p><h3>My First Thought: Use MD5</h3><p>The first solution everyone thinks of is:</p><ul><li>Read file</li><li>Generate hash</li><li>Store hash in DB</li><li>If another uploaded image has the same hash ──&gt; <strong>Duplicate found!</strong></li></ul><p>Python makes this incredibly easy:</p><p>Python</p><pre>import hashlib</pre><pre>def generate_md5(file_path):<br>    hasher = hashlib.md5()<br>    with open(file_path, &quot;rb&quot;) as f:<br>        while chunk := f.read(8192):<br>            hasher.update(chunk)<br>    return hasher.hexdigest()</pre><p>Looks perfect. Until reality hits.</p><h3>What Exactly Is a Hash?</h3><p>Think of a hash function like a machine:</p><pre>Any data<br>     │<br>     ▼<br>+---------------+<br>| Hash Function |<br>+---------------+<br>     │<br>     ▼<br>32-character string</pre><p>For example:</p><blockquote><strong><em>“Hello”</em></strong><em> ──&gt; </em><em>8b1a9953c4611296a827abf8c47804d7</em></blockquote><p>A tiny input change:</p><blockquote><strong><em>“hello”</em></strong><em> ──&gt; </em><em>5d41402abc4b2a76b9719d911017c592</em></blockquote><p>Only one capital letter changed. The output became completely different. This behavior is intentional. It is called the <strong>Avalanche Effect</strong>.</p><h3>The Avalanche Effect</h3><p>Hash functions are designed so that Input A and Input B (even if just 1 byte different) produce completely unrelated outputs.</p><ul><li><strong>Original image</strong> ──&gt; MD5 ──&gt; ABCD1234...</li><li><strong>Increase brightness by just one pixel</strong> ──&gt; MD5 ──&gt; F9A8E772...</li></ul><p>Nothing matches anymore.</p><p>That is exactly what cryptographic hashes are supposed to do. Why? Imagine passwords. If changing one letter only changed one digit of the hash, attackers could guess passwords much more easily.</p><p>So cryptographic hashes intentionally make similar inputs produce completely different outputs. <strong>Great for security. Terrible for image similarity.</strong></p><h3>Images Are Just Bytes</h3><p>An image file is nothing more than bytes: FFD8FFE000104A46...</p><p>MD5 doesn’t understand:</p><ul><li>Colors</li><li>Objects</li><li>People</li><li>Cats</li><li>Mountains</li></ul><p>It only understands bytes. Change even one byte, and the entire MD5 changes.</p><h3>Example</h3><p>Suppose photo.jpg has a size of <strong>2.3 MB</strong>. Now you resize it to photo_resized.jpg. It still looks identical to the human eye.</p><p>But internally, <strong>millions of bytes changed</strong>. Therefore:</p><p>Markdown</p><pre>### Example<br>Suppose `photo.jpg` has a size of **2.3 MB**. Now you resize it to `photo_resized.jpg`. It still looks identical to the human eye. </pre><pre>But internally, **millions of bytes changed**. Therefore:</pre><pre>**MD5(original) ≠ MD5(resized)**</pre><pre>### So What Do We Actually Need?</pre><h3>So What Do We Actually Need?</h3><p>We don’t care if the bytes match. We care whether the pictures look the same. Humans compare shapes, colors, edges, and objects — not bytes.</p><p>This is where perceptual hashing comes in.</p><h3>Enter dHash (Difference Hash)</h3><p>Instead of hashing bytes, <strong>dHash hashes the appearance of the image.</strong> That changes everything.</p><h3>The Pipeline</h3><pre>Original Image ──&gt; Convert to Grayscale ──&gt; Resize to 9×8 ──&gt; Compare Adjacent Pixels ──&gt; Generate 64-bit Hash</pre><p>Now even if brightness changes, resolution changes, or you convert from PNG to JPG, the final hash usually stays very similar.</p><h3>1. Why Convert to Grayscale?</h3><p>Color isn’t very important for duplicate detection. A <strong>Red Car</strong> and a <strong>Blue Car</strong> still have the exact same shape. So dHash ignores color.</p><pre>RGB ──&gt; Grayscale (Only brightness remains)</pre><h3>2. Why Resize to 9×8?</h3><p>A normal image may be $4000 \times 3000$ pixels. That’s 12 million pixels — way too much data. Instead, dHash compresses everything into $9 \times 8 = 72 \text{ pixels}$. That tiny version still keeps the overall structure.</p><h3>3. Why 9 Columns Instead of 8?</h3><p>Because dHash compares neighboring pixels.</p><p>For example, if you have a row of pixels with these brightness values: 10 20 50 60 70</p><p>To get your pairs, you compare:</p><ul><li>10 vs 20</li><li>20 vs 50</li><li>50 vs 60</li><li>60 vs 70</li></ul><p>To successfully compare <strong>8 pairs</strong>, you naturally need <strong>9 pixels</strong>.</p><h3>Building the Hash</h3><p>Imagine one row of pixels:</p><pre>[ 10 ]   [ 30 ]   [ 25 ]   [ 50 ]</pre><p>Compare neighbors left-to-right:</p><ul><li>10 &gt; 30 ? <strong>No</strong> ──&gt; 0</li><li>30 &gt; 25? <strong>Yes</strong> ──&gt; 1</li><li>25 &gt; 50 ? <strong>No</strong> ──&gt; 0</li></ul><p>The binary sequence for this row becomes: 010</p><p>Do this for every single row. Eventually, you get a continuous string of bits:</p><pre>011010010... (64 bits)</pre><p>Convert those bits to hexadecimal, and you get your final dHash string: 8f34ac12...</p><h3>Comparing Two Images</h3><p>Unlike MD5, we don’t check for strict equality. Instead, we compare the bits directly. This is called the <strong>Hamming Distance</strong>.</p><p>[Image illustrating Hamming Distance comparison between two binary sequences highlighting differing bits]</p><p>Here is how we do it in Python:</p><p>Python</p><pre>def hamming_distance(hash1, hash2):<br>    return (int(hash1, 16) ^ int(hash2, 16)).bit_count()</pre><p>If you have:</p><ul><li><strong>Hash A:</strong> 10110010</li><li><strong>Hash B:</strong> 10110011</li></ul><p>Only one bit changed. The distance is 1. They are virtually identical.</p><h3>My Complete Implementation</h3><p>Here is the complete code to generate a dHash and compare two images using the standard library and Pillow:</p><p>Python</p><pre>from PIL import Image</pre><pre>def dhash(image_path):<br>    # 1. Open image and convert to grayscale<br>    img = Image.open(image_path).convert(&#39;L&#39;)<br>    <br>    # 2. Resize to 9x8 (9 columns, 8 rows)<br>    img = img.resize((9, 8), Image.Resampling.LANCZOS)<br>    pixels = list(img.getdata())<br>    <br>    # 3. Compare adjacent pixels<br>    difference = []<br>    for row in range(8):<br>        for col in range(8):<br>            pixel_left = pixels[row * 9 + col]<br>            pixel_right = pixels[row * 9 + col + 1]<br>            difference.append(pixel_left &gt; pixel_right)<br>            <br>    # 4. Convert boolean array to hex string<br>    decimal_value = 0<br>    for bit in difference:<br>        decimal_value = (decimal_value &lt;&lt; 1) | bit<br>        <br>    return f&quot;{decimal_value:016x}&quot;</pre><pre>def compare_images(img1_path, img2_path):<br>    hash1 = dhash(img1_path)<br>    hash2 = dhash(img2_path)<br>    <br>    import hashlib<br>    def get_md5(path):<br>        h = hashlib.md5()<br>        with open(path, &#39;rb&#39;) as f:<br>            while chunk := f.read(8192): h.update(chunk)<br>        return h.hexdigest()[:8] + &quot;...&quot;<br>        <br>    distance = hamming_distance(hash1, hash2)<br>    <br>    print(f&quot;Image 1 MD5: {get_md5(img1_path)}&quot;)<br>    print(f&quot;Image 2 MD5: {get_md5(img2_path)}&quot;)<br>    print(f&quot;Exact match: {&#39;Yes&#39; if get_md5(img1_path) == get_md5(img2_path) else &#39;No&#39;}&quot;)<br>    print(f&quot;dHash distance: {distance}&quot;)<br>    print(f&quot;Visual similarity: {&#39;High&#39; if distance &lt;= 10 else &#39;Low&#39;}&quot;)</pre><pre># Example usage:<br># compare_images(&quot;images/photo3.jpg&quot;, &quot;images/hotspot3.png&quot;)</pre><h3>Example Output</h3><p>Plaintext</p><pre>Image 1 MD5: e18d...<br>Image 2 MD5: 9fc1...<br>Exact match: No<br>dHash distance: 2<br>Visual similarity: High</pre><p>Exactly what I wanted.</p><h3>Choosing a Threshold</h3><p>A common guideline for interpreting the Hamming Distance is:</p><p><strong>Hamming DistanceInterpretation0</strong>Identical appearance<strong>1–5</strong>Almost identical<strong>6–10</strong>Similar<strong>11–20</strong>Probably different<strong>&gt;20</strong>Completely different</p><p><em>Note: The exact threshold depends on your specific use case and should be tuned using your own real-world images.</em></p><h3>Strengths and Limitations</h3><h3>Where dHash Works Well</h3><ul><li>Resized images</li><li>Brightness changes</li><li>Contrast changes</li><li>Format changes (PNG ↔ JPG)</li><li>Minor compression artifacts</li></ul><h3>Where dHash Fails</h3><p>It struggles with larger, structural visual changes, such as:</p><ul><li>Rotated images</li><li>Heavy cropping</li><li>Mirrored images</li><li>Large text overlays</li><li>Different viewpoints of the same object</li></ul><p>For these complex scenarios, feature embeddings from models like CLIP or SigLIP are much more robust because they compare semantic content rather than simple, local pixel relationships.</p><h3>What I Learned</h3><p>I started with a simple assumption: <em>“Generate an MD5 hash and compare it.”</em> That assumption turned out to be completely wrong for image deduplication. The key lesson was understanding the fundamental difference between cryptographic hashing and perceptual hashing:</p><ul><li><strong>MD5/SHA-256 answers:</strong> <em>“Are these files exactly the same bytes?”</em></li><li><strong>dHash answers:</strong> <em>“Do these images look the same to a human?”</em></li></ul><p>Once I stopped comparing file bytes and started comparing visual structure, duplicate detection became incredibly effective.</p><p>added visual represntation so can get more contest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rM8_pg0B_VohmieHJCtSgw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49574ee6e1d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Concurrency Control, Isolation Levels, and Distributed Locking — A Complete Guide]]></title>
            <link>https://medium.com/@tricksbusinnes/understanding-concurrency-control-isolation-levels-and-distributed-locking-a-complete-guide-e6d04a4e9fbe?source=rss-97faa03fd462------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6d04a4e9fbe</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[prajjwal singh]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 17:28:07 GMT</pubDate>
            <atom:updated>2026-06-17T17:28:07.438Z</atom:updated>
            <content:encoded><![CDATA[<p>When building software, one of the biggest challenges is ensuring that multiple users, threads, or services can access and modify data safely without causing inconsistencies.</p><p>Many developers learn synchronization using primitives like synchronized, Mutex, or ReentrantLock and assume concurrency is solved. However, those mechanisms only work within a single process. Once we move to databases, multiple application instances, microservices, or distributed systems, the problem becomes significantly more complex.</p><p>This article provides a comprehensive deep dive into:</p><ul><li><strong>Why concurrency problems occur</strong></li><li><strong>Database isolation levels</strong> (and the anomalies they prevent)</li><li><strong>Optimistic vs. Pessimistic Concurrency Control</strong></li><li><strong>The reality of Distributed Locking</strong></li></ul><h3>Why Do We Need Concurrency Control?</h3><p>Consider a simple bank account table:</p><h3>Accounts Table</h3><p><strong>IdBalance</strong>11000</p><p>Now imagine two transactions accessing the same record simultaneously. Without proper concurrency control, chaos ensues:</p><ul><li><strong>Lost Updates:</strong> Updates can silently overwrite each other.</li><li><strong>Ghost Data:</strong> Users may see incorrect or completely fictitious data.</li><li><strong>Corrupted Logic:</strong> Inventory counts drop below zero, reports become inconsistent, and financial transactions produce incorrect balances.</li></ul><p>To solve these issues, databases rely on <strong>ACID</strong> properties. While Atomicity, Consistency, and Durability handle safety and crashes, this article focuses heavily on <strong>Isolation</strong> — determining how much one transaction can see the changes made by another concurrent transaction.</p><pre>The Trade-Off Rule:<br> - Higher Isolation: Better consistency -&gt; More locking -&gt; Lower concurrency.<br> - Lower Isolation: Better performance  -&gt; Higher concurrency -&gt; More chances of inconsistent reads.</pre><h3>The Three Great Read Anomalies</h3><p>To understand isolation levels, we must first understand the three core problems they are designed to prevent.</p><h3>1. The Dirty Read</h3><p>A <strong>Dirty Read</strong> occurs when a transaction reads data that has been modified by another transaction but <strong>not yet committed</strong>.</p><h4>The Scenario:</h4><ul><li><strong>Initial Data:</strong> Account Balance = 1000</li><li><strong>Transaction T1:</strong> Begins, updates the balance to 5000, but <em>does not commit</em>.</li><li><strong>Transaction T2:</strong> Reads the balance and sees 5000.</li><li><strong>Transaction T1:</strong> Encounters an error and executes a ROLLBACK;.</li></ul><h4>The Conflict:</h4><p>The actual value reverts to 1000. However, <strong>T2</strong> acted on the assumption that the balance was 5000—a value that never permanently existed.</p><blockquote><strong><em>Why Is This Dangerous?</em></strong><em> Imagine an inventory system where available stock is 10. One transaction temporarily holds/changes stock to zero during a calculation. Another transaction reads it, displays </em><strong><em>“Out Of Stock”</em></strong><em> to a customer, and the first transaction rolls back. You just lost a sale over data that wasn’t real.</em></blockquote><h3>2. The Non-Repeatable Read</h3><p>A <strong>Non-Repeatable Read</strong> occurs when the same row is read twice within a single transaction, but returns different values because another transaction modified and committed it in the interim.</p><h4>The Scenario:</h4><ul><li><strong>Initial Data:</strong> Account Balance = 1000</li><li><strong>Transaction T1:</strong> Reads the balance $\rightarrow$ Result: 1000</li><li><strong>Transaction T2:</strong> Updates the balance to 2000 and executes COMMIT;</li><li><strong>Transaction T1:</strong> Reads the balance again $\rightarrow$ Result: 2000</li></ul><p>Plaintext</p><pre>[Inside Transaction T1]<br>First Read  = 1000<br>Second Read = 2000  &lt;-- The value shifted under its feet!</pre><blockquote><strong><em>Why Is This Dangerous?</em></strong><em> Suppose a reporting service is generating an end-of-day financial statement. Halfway through the generation, a user changes their profile details or balance. The final report becomes structurally inconsistent because it used two completely different versions of the exact same row.</em></blockquote><h3>3. The Phantom Read</h3><p>A <strong>Phantom Read</strong> occurs when entirely new rows appear or disappear between two executions of the same query within a transaction.</p><p><em>Note: Unlike a Non-Repeatable Read (where an existing row’s data changes), a Phantom Read deals with a change in the </em><strong><em>number of rows</em></strong><em> returned by a range query.</em></p><h4>The Scenario:</h4><ul><li><strong>Transaction T1:</strong> Queries employees with a salary over 4000. It finds <strong>2 rows</strong>.</li><li><strong>Transaction T2:</strong> Inserts a <em>new</em> employee with a salary of 7000 and executes COMMIT;.</li><li><strong>Transaction T1:</strong> Runs the exact same query again. It now finds <strong>3 rows</strong>.</li></ul><blockquote><strong><em>Why Is This Dangerous?</em></strong><em> Consider a payroll distribution microservice. The first query calculates the total budget for 100 employees. The second query distributes the funds, but suddenly 101 employees are present. The math breaks down entirely.</em></blockquote><h3>Database Isolation Levels Explained</h3><p>The SQL standard defines four distinct isolation levels to combat these anomalies.</p><h3>1. Read Uncommitted</h3><p>The lowest isolation level. Transactions operate with virtually no safety barriers.</p><ul><li><strong>Dirty Reads:</strong> Possible</li><li><strong>Non-Repeatable Reads:</strong> Possible</li><li><strong>Phantom Reads:</strong> Possible</li></ul><h3>2. Read Committed</h3><p>Only committed data can be read. This is the default setting for many popular relational databases (like PostgreSQL).</p><ul><li><strong>Dirty Reads:</strong> <strong>Prevented</strong> (Uncommitted changes remain invisible)</li><li><strong>Non-Repeatable Reads:</strong> Possible</li><li><strong>Phantom Reads:</strong> Possible</li></ul><h3>3. Repeatable Read</h3><p>Ensures that if a transaction reads a row, it will see the exact same values for that row throughout its entire lifecycle.</p><ul><li><strong>Dirty Reads:</strong> <strong>Prevented</strong></li><li><strong>Non-Repeatable Reads:</strong> <strong>Prevented</strong> (The transaction reads from a consistent snapshot)</li><li><strong>Phantom Reads:</strong> Possible <em>(Though databases like MySQL/InnoDB use Next-Key locking to prevent them even at this level)</em></li></ul><h3>4. Serializable</h3><p>The gold standard of safety. Transactions are executed in a way that yields the exact same results as if they were run strictly one after another (sequentially).</p><ul><li><strong>Dirty Reads:</strong> <strong>Prevented</strong></li><li><strong>Non-Repeatable Reads:</strong> <strong>Prevented</strong></li><li><strong>Phantom Reads:</strong> <strong>Prevented</strong></li></ul><h3>Summary Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13ivp9eULM8n5XY6KWMwQw.png" /></figure><h3>Concurrency Control Strategies: Optimistic vs. Pessimistic</h3><p>When designing application code to interact with databases, developers generally split into two philosophical camps.</p><h3>Strategy A: Optimistic Concurrency Control (OCC)</h3><p>OCC assumes that data conflicts are rare. Instead of blocking other operations, transactions proceed normally and validate changes right before they commit.</p><h4>How it Works (Version-Based):</h4><ul><li>Read the row along with its current version number (e.g., Version = 1).</li><li>Perform the business logic in application memory.</li><li>Attempt to update the row <em>only</em> if the version hasn’t changed.</li></ul><p>SQL</p><pre>UPDATE accounts <br>SET balance = 1500, version = 2 <br>WHERE id = 1 AND version = 1;</pre><p>If User A and User B both read Version = 1, User A&#39;s update will succeed and bump the version to 2. When User B tries to commit, the WHERE version = 1 clause fails to match any rows. The application detects this and triggers a retry.</p><ul><li><strong>Advantages:</strong> High throughput, no actual database locks, incredible for read-heavy workloads.</li><li><strong>Disadvantages:</strong> High write-contention causes a massive spike in retries, wasting CPU cycles.</li></ul><h3>Strategy B: Pessimistic Concurrency Control (PCC)</h3><p>PCC assumes the worst: conflicts are highly likely. It prevents anomalies by explicitly locking records before any modifications begin.</p><h4>How it Works:</h4><p>You explicitly tell the database to lock the row using a blocking mechanism:</p><p>SQL</p><pre>SELECT * FROM accounts WHERE id = 1 FOR UPDATE;</pre><ul><li><strong>Advantages:</strong> Strict data consistency, zero retry logic needed in application code, completely predictable behavior.</li><li><strong>Disadvantages:</strong> Severely reduces system concurrency, can cause thread starvation, and introduces the risk of <strong>Deadlocks</strong>.</li></ul><blockquote><em>🛑 </em><strong><em>The Deadlock Trap:</em></strong><em> A deadlock occurs when Transaction 1 locks Account A and waits for Account B, while Transaction 2 has locked Account B and is waiting for Account A. They will wait forever. Modern databases resolve this by maintaining a </em>Wait-For Graph<em>, detecting the cyclic dependency, and intentionally killing one of the transactions.</em></blockquote><h3>Moving Beyond a Single Process: Distributed Locking</h3><p>A common pitfall for software engineers is trying to solve these issues using language-level tools.</p><p>Java</p><pre>// This ONLY works if you have exactly one application instance running!<br>synchronized(lock) {<br>    updateBalance();<br>}</pre><p>In modern cloud architecture, your application likely runs across <strong>Server A, Server B, and Server C</strong>. Because each server operates on its own independent memory heap, Server A has absolutely no knowledge of a lock held by Server B. synchronized blocks are entirely useless here.</p><p>To coordinate across distributed application instances, you must pull the locking mechanism out of the application and into a <strong>shared infrastructure layer</strong>.</p><h3>Common Production Solutions:</h3><ul><li><strong>Redis-Based Locks (Redlock):</strong> High performance, relies on TTL (Time-To-Live) values to ensure locks eventually expire if a node crashes.</li><li><strong>Consensus-Based (ZooKeeper / etcd):</strong> Highly reliable, utilizes sequential ephemeral nodes or leases to ensure strong consistency even during network partitions.</li><li><strong>Database Backed:</strong> Using dedicated lock tables with unique constraints.</li></ul><h3>Final Takeaways</h3><ul><li><strong>Isolation levels</strong> act as a dial allowing you to balance absolute data consistency against system performance.</li><li><strong>OCC</strong> is your best friend for scalable, web-scale applications where users rarely collide on the exact same record.</li><li><strong>PCC</strong> is non-negotiable when dealing with high-risk financial balances or critical inventory systems where integrity trumps speed.</li><li><strong>Distributed systems change the rules.</strong> The moment your application scales past a single running container, standard language synchronization must be upgraded to a distributed coordinator (like Redis or ZooKeeper).</li></ul><p><em>What strategies does your team use to handle high concurrency? Let me know in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6d04a4e9fbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Node.js]]></title>
            <link>https://medium.com/@tricksbusinnes/understanding-node-js-d616f0cc3a62?source=rss-97faa03fd462------2</link>
            <guid isPermaLink="false">https://medium.com/p/d616f0cc3a62</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[prajjwal singh]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 05:49:33 GMT</pubDate>
            <atom:updated>2026-06-08T05:49:33.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Node.js Concurrency: Event Loop, Promises, Worker Threads, Child Processes, and Clusters</h3><p>When I started learning Node.js concurrency, I had several questions:</p><ul><li>When should I use Promises vs Worker Threads?</li><li>Does setTimeout() create a new thread?</li><li>Why are file operations non-blocking but CPU-heavy calculations block the application?</li><li>Why can’t Node automatically move heavy computations to another thread?</li><li>How do Worker Threads communicate?</li><li>What’s the difference between Worker Threads, Child Processes, and Clusters?</li></ul><p>This article summarizes the answers.</p><h3>Node.js Is Single-Threaded… But Not Exactly</h3><p>People often say:</p><blockquote><em>“Node.js is single-threaded.”</em></blockquote><p>This is only partially true.</p><p>JavaScript execution happens on a single main thread, but Node.js itself uses:</p><ul><li>Event Loop</li><li>libuv</li><li>Thread Pool</li><li>Operating System APIs</li></ul><p>to perform asynchronous work.</p><h3>Understanding I/O Operations</h3><p>Consider:</p><pre>const fs = require(&#39;fs&#39;);</pre><pre>fs.readFile(&#39;data.txt&#39;, (err, data) =&gt; {<br>  console.log(data.toString());<br>});</pre><pre>console.log(&#39;Done&#39;);</pre><p>Output:</p><pre>Done<br>[file contents]</pre><p>Why doesn’t readFile() block?</p><p>Because Node delegates the work.</p><pre>JavaScript Thread<br>       |<br>       v<br>      libuv<br>       |<br>       v<br> OS / Thread Pool<br>       |<br>       v<br> Callback Queue<br>       |<br>       v<br> Event Loop<br>       |<br>       v<br> JavaScript Thread</pre><p>The JavaScript thread asks the OS or libuv to read the file and continues executing other code.</p><p>When the file is ready, the callback is pushed back to the Event Loop.</p><h3>Why Promises Don’t Create Threads</h3><p>Many developers think:</p><pre>await fetchData();</pre><p>creates another thread.</p><p>It doesn’t.</p><p>A Promise is simply a way to handle asynchronous operations.</p><p>For example:</p><pre>const data = await fetch(url);</pre><p>The network request is handled by the OS.</p><p>The Promise only represents the future result.</p><pre>Promise<br>     ≠<br>Thread</pre><p>Promises help with asynchronous I/O, not parallel CPU execution.</p><h3>Does setTimeout Create a New Thread?</h3><p>Consider:</p><pre>setTimeout(() =&gt; {<br>  console.log(&#39;Hello&#39;);<br>}, 0);</pre><p>Many beginners assume this runs in a background thread.</p><p>It doesn’t.</p><p>setTimeout() only schedules a callback.</p><p>Flow:</p><pre>Main Thread<br>     |<br>     | Register Timer<br>     |<br>     v<br> Timer Queue<br>     |<br>     v<br> Event Loop<br>     |<br>     v<br> Main Thread executes callback</pre><p>The callback eventually runs on the same JavaScript thread.</p><h3>Why Heavy Calculations Still Block</h3><p>Example:</p><pre>setTimeout(() =&gt; {<br>  for (let i = 0; i &lt; 1e10; i++) {}<br>}, 0);</pre><p>The timer callback executes later, but once it starts running, it still uses the main thread.</p><pre>Event Loop<br>      |<br>      v<br>Heavy Calculation<br>      |<br>      v<br>Everything else waits</pre><p>This is why setTimeout() is not a solution for CPU-intensive work.</p><h3>Why Can’t Node Automatically Move Heavy Computation?</h3><p>Suppose:</p><pre>let count = 0;</pre><pre>function calculate() {<br>  count++;<br>}</pre><p>If Node automatically moved this function to another thread:</p><pre>Main Thread<br>    count = 0</pre><pre>Worker Thread<br>    count++</pre><p>Questions arise:</p><ul><li>Who owns count?</li><li>What if multiple threads modify it?</li><li>What if one thread reads while another writes?</li></ul><p>These are race conditions.</p><p>Node avoids these problems by running JavaScript code on a single thread unless the developer explicitly creates Worker Threads.</p><h3>Worker Threads</h3><p>Worker Threads allow JavaScript to run in parallel.</p><p>Example:</p><pre>const { Worker } = require(&#39;worker_threads&#39;);</pre><pre>const worker = new Worker(&#39;./worker.js&#39;);</pre><p>Architecture:</p><pre>Process<br>   |<br>   +-- Main Thread<br>   +-- Worker Thread</pre><p>Each worker has:</p><ul><li>Its own V8 engine</li><li>Its own Event Loop</li><li>Its own execution context</li></ul><p>Worker Threads are ideal for:</p><ul><li>PDF generation</li><li>Image processing</li><li>Video processing</li><li>Large JSON processing</li><li>Data analytics</li><li>Encryption</li></ul><h3>How Worker Threads Communicate</h3><p>Most commonly using message passing.</p><p>Main Thread:</p><pre>worker.postMessage(data);</pre><p>Worker:</p><pre>parentPort.on(&#39;message&#39;, (data) =&gt; {<br>  // process data<br>});</pre><p>Return result:</p><pre>parentPort.postMessage(result);</pre><p>Flow:</p><pre>Main Thread<br>      |<br>      v<br>Worker Thread<br>      |<br>      v<br>Main Thread</pre><h3>Shared Memory with SharedArrayBuffer</h3><p>Normally, Worker Threads do not share JavaScript objects.</p><p>Instead, data is copied.</p><p>For large numeric datasets, Node provides:</p><pre>const shared = new SharedArrayBuffer(size);</pre><p>This allows multiple workers to access the same memory.</p><pre>Worker 1<br>      \<br>       Shared Memory<br>      /<br>Worker 2</pre><p>When multiple workers write to shared memory, Atomics should be used to avoid race conditions.</p><h3>Processing Large JSON Files</h3><p>Suppose you have:</p><pre>10 million records</pre><p>Instead of processing everything on one thread:</p><pre>processLargeJson();</pre><p>Split the work:</p><pre>Worker 1 -&gt; Records 1-2.5M<br>Worker 2 -&gt; Records 2.5M-5M<br>Worker 3 -&gt; Records 5M-7.5M<br>Worker 4 -&gt; Records 7.5M-10M</pre><p>Each worker returns a partial result.</p><p>Main thread combines them.</p><p>This is a common approach for large-scale data processing.</p><h3>Child Processes</h3><p>Child Processes are different from Worker Threads.</p><p>Example:</p><pre>const { spawn } = require(&#39;child_process&#39;);</pre><p>Architecture:</p><pre>Main Process<br>      |<br>      +-- Child Process</pre><p>Each child process has:</p><ul><li>Separate memory</li><li>Separate V8 engine</li><li>Separate Event Loop</li><li>Separate Process ID (PID)</li></ul><h3>When to Use Child Processes</h3><p>Child Processes are useful when running external programs.</p><p>Examples:</p><pre>spawn(&#39;python&#39;, [&#39;script.py&#39;]);</pre><pre>spawn(&#39;ffmpeg&#39;, [&#39;input.mp4&#39;]);</pre><pre>spawn(&#39;git&#39;, [&#39;clone&#39;, repo]);</pre><p>Worker Threads cannot directly replace these use cases.</p><h3>Worker Threads vs Child Processes</h3><p>FeatureWorker ThreadChild ProcessUnitThreadProcessMemory UsageLowerHigherShared MemoryYesNoCommunicationFastIPCRun External ProgramsNoYesStartup CostLowHigherBest ForCPU-heavy JS workRunning external tools</p><h3>Clusters</h3><p>Clusters help scale Node.js applications across CPU cores.</p><p>Example:</p><pre>const cluster = require(&#39;cluster&#39;);</pre><p>Architecture:</p><pre>Master Process<br>      |<br>      +-- Worker Process 1<br>      +-- Worker Process 2<br>      +-- Worker Process 3<br>      +-- Worker Process 4</pre><p>Each worker is actually a separate process.</p><p>Clusters are commonly used for web servers.</p><p>If a machine has 8 CPU cores:</p><pre>Core 1 -&gt; Worker 1<br>Core 2 -&gt; Worker 2<br>Core 3 -&gt; Worker 3<br>...<br>Core 8 -&gt; Worker 8</pre><p>This allows the server to handle more requests simultaneously.</p><h3>Worker Threads vs Clusters</h3><p>FeatureWorker ThreadClusterCreatesThreadsProcessesMemoryShared possibleSeparatePurposeCPU-heavy tasksScale request handlingCommunicationFastIPCTypical UsePDF generation, analyticsHTTP server scaling</p><h3>Quick Decision Guide</h3><h3>Database Query</h3><pre>await db.query(...)</pre><p>Use:</p><pre>Promises / Async-Await</pre><h3>API Call</h3><pre>await axios.get(...)</pre><p>Use:</p><pre>Promises / Async-Await</pre><h3>Read File</h3><pre>fs.readFile(...)</pre><p>Use:</p><pre>Async I/O</pre><h3>Generate Large PDF</h3><pre>generateHugePDF()</pre><p>Use:</p><pre>Worker Thread</pre><h3>Run Python Script</h3><pre>spawn(&#39;python&#39;, [&#39;script.py&#39;])</pre><p>Use:</p><pre>Child Process</pre><h3>Scale API Across Multiple CPU Cores</h3><p>Use:</p><pre>Cluster</pre><h3>Final Rule of Thumb</h3><ul><li><strong>Waiting for something external (DB, API, file, Redis)</strong> → Use Promises and Async/Await.</li><li><strong>Need delayed execution</strong> → Use setTimeout().</li><li><strong>Need heavy JavaScript computation</strong> → Use Worker Threads.</li><li><strong>Need to run another program (Python, FFmpeg, Git)</strong> → Use Child Processes.</li><li><strong>Need to scale a server across CPU cores</strong> → Use Clusters.</li></ul><p>Understanding this distinction is one of the biggest steps toward mastering Node.js internals and performing well in backend interviews.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d616f0cc3a62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Distributed Systems: Distributed Locks, Two-Phase Commit, and Saga Pattern]]></title>
            <link>https://medium.com/@tricksbusinnes/understanding-distributed-systems-distributed-locks-two-phase-commit-and-saga-pattern-375e96e62d72?source=rss-97faa03fd462------2</link>
            <guid isPermaLink="false">https://medium.com/p/375e96e62d72</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[prajjwal singh]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 13:30:14 GMT</pubDate>
            <atom:updated>2026-06-02T13:30:14.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When I first dipped my toes into the world of distributed systems, one burning question kept keeping me up at night:</p><blockquote><strong><em>How do engineering giants like Netflix, Amazon, Uber, and Airbnb keep their data perfectly consistent when managing hundreds of interconnected services?</em></strong></blockquote><p>In a traditional monolithic application, handling transactions is relatively straightforward. You wrap your database queries in a single block, and the transaction either completely succeeds or fails. It’s all-or-nothing.</p><p>However, in a distributed system, a single business operation can span multiple independent services. If one service succeeds but another fails downstream, maintaining consistency becomes a massive headache.</p><p>Take a standard e-commerce checkout workflow, for example:</p><ol><li><strong>Order Service</strong> creates an order.</li><li><strong>Payment Service</strong> charges the customer.</li><li><strong>Inventory Service</strong> reserves the stock.</li><li><strong>Notification Service</strong> sends a confirmation email.</li></ol><p>What happens if the payment goes through successfully, but the inventory reservation fails because the item just sold out? You can’t easily “roll back” a database charge that happened over a network API call.</p><p>This is exactly where design patterns like <strong>Distributed Locks</strong>, <strong>Two-Phase Commit (2PC)</strong>, and the <strong>Saga Pattern</strong> become essential. Let’s break them down.</p><h3>What is a Distributed System?</h3><p>A distributed system consists of multiple independent services working together over a network to achieve a common goal. Think of platforms like Netflix, Amazon, Uber, or Airbnb.</p><p>In a true microservices architecture, each service typically owns:</p><ul><li>Its own dedicated business logic.</li><li>Its own private database (Database-per-Service pattern).</li><li>Its own independent deployment lifecycle.</li></ul><h3>The Trade-offs</h3><p>While moving to a distributed architecture brings massive benefits, it comes with a steep learning curve.</p><ul><li><strong>The Benefits:</strong> Better horizontal scalability, independent deployments, fault isolation, and faster team development cycles.</li><li><strong>The Challenges:</strong> Data consistency, service coordination, complex failure handling, and unpredictable network communication issues.</li></ul><h3>1. Distributed Locks</h3><h3>The Problem: Race Conditions</h3><p>Imagine an online store with exactly <strong>one</strong> item left in stock. Two users, User A and User B, hit the “Buy Now” button at the exact same millisecond.</p><p>Without any coordination, the following happens:</p><ol><li>User A reads stock count from the database ($Stock = 1$).</li><li>User B reads stock count from the database ($Stock = 1$).</li><li>User A places the order and updates stock ($Stock = 0$).</li><li>User B places the order and updates stock ($Stock = -1$).</li></ol><p>Suddenly, you’ve oversold your inventory, leaving you with an inconsistent database and an unhappy customer.</p><h3>The Solution</h3><p>A <strong>Distributed Lock</strong> ensures that only one process or service instance can access or mutate a shared resource at any given time.</p><p>Plaintext</p><pre>Service A ──&gt; [Acquire Lock]  Success<br>Service B ──&gt; [Waiting...]     Blocked</pre><pre>Service A ──&gt; Updates Inventory Stock<br>Service A ──&gt; [Release Lock]  🔓 Released</pre><pre>Service B ──&gt; [Acquire Lock]  Success (Reads Stock = 0, Fails gracefully)</pre><p>By forcing services to serialize their access to the inventory, you completely eliminate race conditions.</p><h3>Popular Technologies Used:</h3><ul><li><strong>Redis:</strong> The most popular choice for distributed locking, often utilizing the <strong>Redlock</strong> algorithm for multi-master setups.</li><li><strong>ZooKeeper:</strong> Provides strong consistency, leader election, and robust distributed coordination.</li><li><strong>etcd:</strong> A distributed key-value store widely used in the Kubernetes ecosystem for configuration management and coordination.</li></ul><blockquote><em>⚠️ </em><strong><em>Handle with Care:</em></strong><em> Locks introduce synchronous bottlenecks. If overused, they can severely reduce your system’s scalability, increase latency, and introduce the risk of deadlocks. Use them only for highly sensitive, short-lived operations.</em></blockquote><h3>2. Two-Phase Commit (2PC)</h3><h3>The Problem: Atomic Distributed Transactions</h3><p>Consider a banking app moving money from Account A to Account B.</p><ul><li><strong>Step 1:</strong> Debit $100 from Account A (on Ledger Service 1).</li><li><strong>Step 2:</strong> Credit $100 to Account B (on Ledger Service 2).</li></ul><p>Both operations <em>must</em> succeed together. If Step 1 succeeds but Step 2 fails due to a network glitch, $100 vanishes into thin air.</p><h3>What is Two-Phase Commit?</h3><p>Two-Phase Commit (2PC) is a strict, consensus-based distributed transaction protocol. It relies on a central <strong>Coordinator</strong> component to guarantee atomicity across multiple databases.</p><h4>Phase 1: Prepare Phase</h4><p>The coordinator asks every participating service: <em>“Are you ready to safely commit this change?”</em></p><p>Plaintext</p><pre>[Coordinator]<br>       /     |     \<br>      /      |      \<br>     v       v       v<br>[Order]  [Payment]  [Inventory]<br> (Yes)     (Yes)       (Yes)</pre><p>Each service checks its local resources, locks the necessary rows, and responds with a <strong>YES</strong> or <strong>NO</strong>.</p><h4>Phase 2: Commit Phase</h4><ul><li><strong>Scenario A (Everyone voted YES):</strong> The coordinator sends a COMMIT command. All services finalize their changes and release their resource locks.</li><li><strong>Scenario B (Any service voted NO):</strong> The coordinator sends a ROLLBACK command. All services undo their temporary changes.</li></ul><h3>Why Modern Microservices Avoid 2PC</h3><p>While 2PC provides strong, immediate consistency, it has severe architectural drawbacks:</p><ul><li><strong>It is highly blocking:</strong> If the coordinator crashes mid-transaction, participating services are left in limbo, holding onto resource locks indefinitely.</li><li><strong>Performance Bottlenecks:</strong> Every service must wait for the slowest network participant before finalizing, which skyrockets system latency.</li><li><strong>Poor Scalability:</strong> It creates tight coupling. As you add more services, the mathematical probability of a transaction failing or timing out increases exponentially.</li></ul><blockquote><strong><em>Where is it actually used?</em></strong><em> 2PC is still heavily utilized within clustered enterprise databases (like Oracle or IBM systems) and strict financial ledger architectures where data correctness trumps performance.</em></blockquote><h3>3. The Saga Pattern</h3><p>To overcome the performance and blocking limitations of 2PC, modern distributed systems embrace <strong>Eventual Consistency</strong> using the <strong>Saga Pattern</strong>.</p><p>Instead of wrapping multiple network calls into one massive, blocking transaction, a Saga breaks the business workflow down into a sequence of <strong>local transactions</strong>. Each service executes its own transaction, updates its database, and immediately releases its locks.</p><p>Plaintext</p><pre>[Create Order] ──&gt; [Process Payment] ──&gt; [Reserve Inventory] ──&gt; [Send Email]</pre><h3>Handling Failures: Compensating Transactions</h3><p>Because local transactions commit immediately, you cannot simply “roll back” the database if a later step fails. Instead, you must explicitly design <strong>Compensating Transactions</strong> to forward-undo previous actions.</p><p>Imagine the <em>Inventory Reservation</em> fails:</p><ul><li><strong>Order Service</strong> creates an order (Succeeded).</li><li><strong>Payment Service</strong> charges the card (Succeeded).</li><li><strong>Inventory Service</strong> finds the item is out of stock (<strong>Failed</strong>).</li></ul><p>The Saga triggers the compensation workflow:</p><ul><li><strong>Payment Service</strong> issues a <em>Refund Payment</em> action.</li><li><strong>Order Service</strong> changes status to <em>Order Cancelled</em>.</li></ul><h3>Two Ways to Implement a Saga</h3><p>There are two primary architectural styles for managing a Saga: <strong>Choreography</strong> and <strong>Orchestration</strong>.</p><h3>1. Choreography Saga (Decentralized)</h3><p>In a choreography-based Saga, there is no central boss. Services interact implicitly by listening to and publishing events over a message broker (like Apache Kafka or RabbitMQ).</p><p>Plaintext</p><pre>[Order Service] ──(Order Created Event)──&gt; [Payment Service]<br>                                                  │<br>[Inventory Service] &lt;──(Payment Success Event)────┘</pre><ul><li><strong>Advantages:</strong> Highly decoupled, incredibly scalable, and natively fits event-driven architectures.</li><li><strong>Challenges:</strong> As your system grows, tracking the end-to-end business flow across dozens of services becomes incredibly difficult to visualize, debug, and maintain.</li><li><strong>Real-World Usage:</strong> Netflix and Uber lean heavily on decentralized event streams for high-throughput, asynchronous service coordination.</li></ul><h3>2. Orchestration Saga (Centralized)</h3><p>In an orchestration-based Saga, a centralized service — the <strong>Orchestrator</strong> — acts as the conductor of the orchestra. It explicitly tells each service what to do and when.</p><p>Plaintext</p><pre>[Orchestrator Orchestrator]<br>             /       │            │       \<br>            v        v            v        v<br>    [Order Serv] [Payment Serv] [Inventory] [Notification]</pre><p>If the <em>Inventory</em> step fails, the Orchestrator is explicitly responsible for catching the error and firing off the compensation commands to the <em>Payment</em> and <em>Order</em> services.</p><ul><li><strong>Advantages:</strong> The entire workflow logic is centralized in one readable place, making debugging, logging, and complex state management vastly simpler.</li><li><strong>Challenges:</strong> Introduces an extra architectural component to maintain, and risks becoming a centralized point of failure or logic bloat if not designed carefully.</li><li><strong>Real-World Usage:</strong> Many companies use stateful workflow engines like <strong>Temporal</strong>, <strong>Cadence</strong>, or <strong>Camunda</strong> to manage complex, long-running business sagas. This approach is highly favored by companies like Uber, Airbnb, and DoorDash.</li></ul><h3>Summary: Choosing the Right Tool for the Job</h3><p><strong>Scenario / Use CaseRecommended Solution</strong>Preventing duplicate API requests or cron job overlaps<strong>Distributed Lock</strong>Strong database-level consistency across legacy infrastructure<strong>Two-Phase Commit (2PC)</strong>Modern microservices requiring scale and fault isolation<strong>Saga Pattern</strong>Complex business workflows requiring clear visibility and sequencing<strong>Orchestration Saga</strong>Highly decoupled, high-throughput event-driven microservices<strong>Choreography Saga</strong></p><h3>Final Thoughts</h3><p>The single biggest takeaway from diving into distributed systems architecture is that <strong>there is no silver bullet.</strong> Every decision is an intentional trade-off.</p><ul><li><strong>Distributed locks</strong> secure individual shared resources but threaten throughput.</li><li><strong>Two-Phase Commit</strong> ensures absolute consistency but sacrifices performance and availability.</li><li><strong>Sagas</strong> offer incredible scale and resilience but require you to embrace eventual consistency and design complex compensation logic.</li></ul><p>Understanding these foundational patterns is what bridges the gap between writing simple code and engineering highly resilient, industrial-grade systems.</p><p><em>What has been your experience dealing with distributed data consistency? Do you lean toward Orchestration or Choreography in your architecture? Let’s discuss in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=375e96e62d72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the Thundering Herd: A Junior Developer’s Cache Odyssey]]></title>
            <link>https://medium.com/@tricksbusinnes/taming-the-thundering-herd-a-junior-developers-cache-odyssey-e18430c10e07?source=rss-97faa03fd462------2</link>
            <guid isPermaLink="false">https://medium.com/p/e18430c10e07</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[system-desig]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[prajjwal singh]]></dc:creator>
            <pubDate>Tue, 26 May 2026 05:34:23 GMT</pubDate>
            <atom:updated>2026-05-26T05:34:23.470Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Unexpected Production Crisis</strong></p><p>While working on an education platform at McGraw Hill, I recently encountered one of the most interesting production issues I had ever seen as a junior developer: a <strong>cache stampede</strong>. This wasn’t a typical bug; it was a high-scale performance issue that only reared its head during specific traffic spikes — specifically when thousands of students attempted to start assessments at the exact same time.</p><p>At first glance, everything seemed normal. However, during these peak periods, we began to observe several critical red flags:</p><ul><li><strong>High API latency</strong>.</li><li><strong>Sudden spikes in database CPU usage</strong>.</li><li><strong>Increased response times</strong> and heavy database load during specific windows.</li></ul><p><strong>Identifying the Root Cause</strong></p><p>By analyzing production metrics in Datadog, I noticed that database traffic increased abnormally whenever certain cached APIs expired. The pattern became clear:</p><ol><li>Thousands of students requested the same assessment data simultaneously.</li><li>The cache key for that data would expire.</li><li>Every single request resulted in a “cache miss” at the same moment.</li><li><strong>Thousands of parallel requests hit the database at once</strong>, causing the CPU to spike.</li></ol><p>This phenomenon is known as the <strong>cache stampede</strong> or <strong>thundering herd</strong> problem.</p><p><strong>Why This Was a Challenge to Debug</strong></p><p>As a junior developer, the most difficult part was realizing that the database itself wasn’t “broken”. Initially, the symptoms looked like typical infrastructure issues, such as slow queries or network latency.</p><p>The real challenge was request synchronization. The issue was nearly impossible to reproduce locally because it required high concurrency that only happened in production. I had to rely on production monitoring to connect the dots and understand why only specific APIs were affected at certain times.</p><p><strong>The Solution: A Two-Pronged Approach</strong></p><p>To stabilize the system, I implemented two key strategies to reduce database pressure:</p><ol><li><strong>Asynchronous Cache Rebuilding</strong>: Instead of forcing every request to wait for a database fetch when a cache expired, the application began rebuilding the cache asynchronously. This prevented every user from being a “victim” of the cache miss.</li><li><strong>Mutex Locking</strong>: I added a mutex-based locking mechanism. This ensured that only <strong>one</strong> request was allowed to rebuild the cache, while all other simultaneous requests waited for that single update to complete instead of hitting the database themselves.</li></ol><p><strong>The Results and Key Takeaways</strong></p><p>After deploying these fixes, the impact was immediate: database spikes were reduced, API latency improved, and the system became far more predictable during high-traffic assessment windows.</p><p>This experience taught me several invaluable lessons about engineering:</p><ul><li><strong>Cache problems are database problems:</strong> A failure in your caching strategy can take down your entire data layer almost instantly.</li><li><strong>Patterns over Logs:</strong> Production debugging is often more about observing high-level metrics and patterns than just reading error logs.</li><li><strong>The Environment Matters:</strong> Concurrency issues rarely appear in development; monitoring tools are your best friend in distributed systems.</li><li><strong>Theory vs. Reality:</strong> I had read about the “thundering herd” in system design books, but seeing it happen in real-time gave me a completely different understanding of scalability.</li></ul><p>Solving a problem that directly impacted production performance at scale was a major milestone in my journey, proving that with the right investigation, even junior developers can tackle complex engineering hurdles,.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e18430c10e07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Algorithm Behind Google Docs Collaboration That Completely Hooked Me]]></title>
            <link>https://medium.com/@tricksbusinnes/the-algorithm-behind-google-docs-collaboration-that-completely-hooked-me-3a17d2350588?source=rss-97faa03fd462------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a17d2350588</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[prajjwal singh]]></dc:creator>
            <pubDate>Wed, 20 May 2026 05:17:51 GMT</pubDate>
            <atom:updated>2026-05-20T05:32:04.441Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I was working on an InDesign Server-based system where multiple authors edited .indd files simultaneously.</p><p>The workflow followed a traditional publishing structure. Authors would:</p><ul><li>Make edits in the InDesign file</li><li>Save changes persistently</li><li>Check in their updates</li><li>Publish changes later</li></ul><p>But one thing kept bothering me: <strong>The updates were not syncing instantly for everyone in real-time.</strong></p><p>At first, I thought, <em>“Why are they doing check-in/check-out instead of directly syncing edits live like Google Docs?”</em> I didn’t fully know the business constraints behind their choice, but something felt fishy from an engineering perspective. That curiosity slowly turned into an obsession. Another, deeper question hit me:</p><blockquote><em>“How do systems like Google Docs even allow multiple people to type simultaneously without corrupting the document?”</em></blockquote><p>Think about it. What happens if:</p><ul><li>Two users edit the same line?</li><li>One user deletes text while another inserts?</li><li>Updates arrive in different orders because of network delays?</li><li>Multiple people are typing at the exact same millisecond?</li></ul><p>How does the document not completely break?</p><p>That curiosity pushed me into the rabbit hole of system design for collaborative editors. While reading about it, I discovered an algorithm so elegant that it genuinely hooked me into distributed systems: <strong>Operational Transformation (OT)</strong>.</p><p>The idea behind it is brilliant.</p><h3>The Core Problem</h3><p>Imagine a document containing just two words:</p><p>Hello World</p><p>Now, two users edit it simultaneously.</p><ul><li><strong>User A (Deletes “World”):</strong> Delete(6,5) Document becomes: Hello</li><li><strong>User B (Inserts “Beautiful “):</strong> Insert(6,&quot;Beautiful &quot;) Document becomes: Hello Beautiful World</li></ul><p>Now here’s the dangerous part. Because of network latency, some users may receive the <em>delete</em> command first, while others receive the <em>insert</em> command first. Without synchronization logic, every client could end up with a completely different, corrupted document state.</p><p>That’s the exact problem OT solves.</p><h3>What is Operational Transformation?</h3><p>Operational Transformation is an algorithm that transforms operations <em>before</em> applying them to the document.</p><p>In simple words: <strong>OT adjusts operations based on already-applied concurrent edits so all users eventually see the exact same document.</strong></p><p>At the heart of OT is one core function:</p><p>transform(op1, op2)</p><p>It essentially asks: <em>“How should operation 1 change if operation 2 has already happened?”</em> It’s a simple concept, but an extremely hard engineering problem.</p><h3>Scenario 1: Insert vs. Insert</h3><p>Let’s look at how this plays out. Initial document:</p><p>ABCDEFG</p><ul><li><strong>User A:</strong> Insert(1,&quot;X&quot;) result: AXBCDEFG</li><li><strong>User B:</strong> Insert(3,&quot;Y&quot;) result: ABCYDEFG</li></ul><p>Both operations happen concurrently. If clients directly apply the remote operations as they arrive, the documents will diverge.</p><p>To fix this, OT transforms the operations before applying them using a simple rule: <em>If another insert happened before my position, my position should shift to the right.</em></p><p>JavaScript</p><pre>function transformInsertInsert(op1, op2) {<br>  if (op2.pos &lt; op1.pos) {<br>    op1.pos += op2.text.length;<br>  }<br>  return op1;<br>}</pre><h3>Scenario 2: Delete vs. Insert</h3><p>This is where things start becoming really interesting. Initial document:</p><p>ABCDEFG</p><ul><li><strong>User A (Deletes “CD”):</strong> Delete(2,2) Result: ABEFG</li><li><strong>User B (Inserts “X” at position 5):</strong> Insert(5,&quot;X&quot;)</li></ul><p>But after User A’s deletion, the document became shorter. The positions shifted left.</p><p>To compensate, User B’s operation must be transformed:</p><p>Insert(5,&quot;X&quot;) becomes Insert(3,&quot;X&quot;)</p><p>Final converged result for both: ABEXFG</p><p>And suddenly, I realized: <strong>OT is basically rebasing text operations in real-time.</strong> It is incredibly similar to how version control systems (like Git) rebase commits.</p><h3>The Hardest Part: Delete vs. Delete</h3><p>This completely blew my mind. Initial document:</p><p>ABCDEFGH</p><ul><li><strong>User A:</strong> Delete(2,4) (Deletes: CDEF)</li><li><strong>User B:</strong> Delete(4,3) (Deletes: EFG)</li></ul><p>Notice something important here: EF was <em>already</em> deleted by User A. Therefore, User B&#39;s transformed operation should only delete G.</p><p>This means the algorithm has to dynamically:</p><ul><li>Detect overlaps</li><li>Shrink delete ranges</li><li>Shift positions</li><li>Preserve user intention</li><li>Ensure every client eventually converges on the exact same string</li></ul><p>At this point, it stopped feeling like “text editing.” This was a full-blown distributed systems problem.</p><h3>Why This Hooked Me</h3><p>I started with a simple curiosity while looking at InDesign collaboration workflows. But that curiosity slowly pulled me into a massive web of advanced engineering concepts:</p><ul><li>Collaborative system design</li><li>Concurrency control</li><li>Synchronization engines</li><li>Distributed consistency</li><li>Real-time communication systems</li></ul><p>From the user interface, Google Docs looks effortless. We take it for granted every day. But underneath the hood, there’s a sophisticated synchronization engine working tirelessly to ensure multiple humans can create together without chaos.</p><p>And that is pretty amazing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a17d2350588" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>