<?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 Jagdishraut on Medium]]></title>
        <description><![CDATA[Stories by Jagdishraut on Medium]]></description>
        <link>https://medium.com/@jagdishraut2004?source=rss-c50ea993de2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mNpKrLbOHRqwIqw9</url>
            <title>Stories by Jagdishraut on Medium</title>
            <link>https://medium.com/@jagdishraut2004?source=rss-c50ea993de2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:16:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jagdishraut2004/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[Do We Really Need to Lock Everything? A Story of Optimistic and Pessimistic Locking]]></title>
            <link>https://medium.com/@jagdishraut2004/do-we-really-need-to-lock-everything-a-story-of-optimistic-and-pessimistic-locking-ca50f1788a42?source=rss-c50ea993de2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca50f1788a42</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[deadlock]]></category>
            <category><![CDATA[pessimistic-locking]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[optimistic-locking]]></category>
            <dc:creator><![CDATA[Jagdishraut]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 19:18:00 GMT</pubDate>
            <atom:updated>2026-11-25T19:18:00.263Z</atom:updated>
            <content:encoded><![CDATA[<p>Whenever a deadlock or a data inconsistency due to concurrency shows up in production, the first thing that comes to a developer’s mind is: <strong>“Let’s lock the resource.”</strong></p><p>Give access to the resource one request at a time, and everything is safe. It is the simplest solution, and it feels right.</p><p>But have you ever thought about what happens in the background when you apply that lock?</p><h4>The Night at the Ticket Counter</h4><p>Imagine a small railway ticket counter with a single register book. Only one clerk can hold the book at a time. While Clerk A is writing in it, Clerk B, Clerk C and everyone else stand in line and wait, even if they only wanted to <em>look</em> at the book.</p><p>This is <strong>pessimistic locking</strong>. The system assumes the worst: “Someone is going to conflict with me, so let me lock the resource first and then work.” The database locks the row (for example, with SELECT ... FOR UPDATE), and nobody else can write to it until the transaction commits or rolls back.</p><pre>BEGIN;<br>SELECT * FROM accounts WHERE id = 101 FOR UPDATE;<br>-- no one else can modify this row now<br>UPDATE accounts SET balance = balance - 500 WHERE id = 101;<br>COMMIT;</pre><p>For a bank transferring money, this is a good choice. The cost of an inconsistency is huge, and conflicts are frequent. Safety matters more than speed.</p><h4>But Is Every System a Bank?</h4><p>Here is the thing: <strong>concurrency does not always mean inconsistency.</strong></p><p>Think about a product page on an e-commerce site. Ten thousand people are <em>reading</em> the product description, price and reviews. Once in a while, maybe once a day, an admin updates the description. The chance that two people edit the same product at exactly the same moment is tiny.</p><p>Now ask yourself: do we really need strict locking here?</p><p>If we lock the row every time, we make thousands of readers and writers wait for something that almost never happens. It’s like closing the whole highway because two cars <em>might</em> collide someday.</p><h4>Enter Optimistic Locking</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3E-Cm-_eD3ptHQTLdt3WA.png" /></figure><p>Optimistic locking takes the opposite approach. It says: “Conflicts are rare. Let everyone work freely, and I’ll check for a conflict only at the moment of saving.”</p><p>How does it work? With a <strong>snapshot</strong>, usually a version number (or a timestamp) stored with the record.</p><ol><li>Admin A opens the product. The record has version = 5.</li><li>Admin B opens the same product. It also shows version = 5.</li><li>Admin A saves first. The update succeeds, and the version becomes 6.</li><li>Admin B tries to save, still holding the old version = 5.</li></ol><pre>UPDATE products<br>SET description = &#39;New description&#39;, version = version + 1<br>WHERE id = 42 AND version = 5;</pre><p>For Admin B, this query updates <strong>zero rows</strong>, because the version in the database is now 6. The snapshot doesn’t match. The system understands that someone else changed the data in between, so it rejects the change (or rolls it back), and Admin B is asked to reload the latest data and try again.</p><p>No lock was held, no one was blocked, and no data was corrupted.</p><h4>A Small Example in Code</h4><p>If you use JPA/Hibernate in Java, it’s as easy as adding one field:</p><pre><br>  @Entity<br>public class Product {<br>    @Id<br>    private Long id;<br><br>    private String description;<br><br>    @Version<br>    private Long version;<br>}</pre><p>If two transactions try to update the same row, the second one throws an OptimisticLockException. You can catch it and retry, or tell the user to refresh.</p><h4>So Which One Should You Choose?</h4><p>It’s not about which is better. It’s about knowing your workload.</p><p>Pessimistic LockingOptimistic LockingAssumptionConflicts are commonConflicts are rareHow it worksLocks the record upfrontChecks the version at save timeBest forBanking, payments, inventory with high contentionRead-heavy systems, content updates, profile editsDownsideBlocking, slower, risk of deadlocksFailed updates need retry logicPerformanceLower throughputHigher throughput</p><p><strong>Use pessimistic locking</strong> when conflicts are frequent and the cost of a failed update is high.</p><p><strong>Use optimistic locking</strong> when your system is read-heavy, writes are rare, and an occasional retry is cheaper than blocking everyone all the time.</p><h4>The Takeaway</h4><p>Locking is not wrong. It’s just expensive. Next time you hit a concurrency problem, don’t jump straight to locking the whole resource. Pause and ask yourself:</p><blockquote>How often will two people really write at the same time?</blockquote><p>If the answer is “almost never,” then take a snapshot, let everyone work, and if there’s a mismatch, simply revert the change. Sometimes the smartest way to handle a conflict is to trust your system and be ready to fix the rare exception.</p><p><em>Thanks for reading! If you enjoyed this, follow me for more stories from the backend world.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca50f1788a42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How PostgreSQL Handles Concurrency: MVCC Explained]]></title>
            <link>https://medium.com/@jagdishraut2004/how-postgresql-handles-concurrency-mvcc-explained-89f8cc4e068b?source=rss-c50ea993de2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f8cc4e068b</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[mvcc]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Jagdishraut]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 14:55:47 GMT</pubDate>
            <atom:updated>2026-10-20T14:55:47.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture this: It’s Friday night at 11:59 PM. Your background worker is generating a massive monthly financial report, running heavy queries that touch millions of rows. At the exact same time, thousands of eager customers are frantically transferring money or checking out carts.</p><p>In a naive database world, your system would instantly grind to a halt. Readers would block writers, writers would block readers, and your support team would brace for a flood of angry tweets.</p><p>Yet, PostgreSQL handles this effortlessly. Why? Because of <strong>MVCC (Multi-Version Concurrency Control)</strong>.</p><p>The core philosophy of MVCC is wonderfully simple: <strong>readers never block writers, and writers never block readers.</strong> Instead of locking a row or overwriting data in place, PostgreSQL keeps multiple versions of history, letting each transaction travel back to the exact timeline it needs.</p><h4>How MVCC Works Internally: The Secret Life of Rows</h4><p>When you look at a table in Postgres, you see current data. But under the hood, every single row version (called a <em>tuple</em>) carries hidden system columns that act like timestamped backstage passes:</p><p>Under the hood, PostgreSQL tracks xmin column acts like a birth certificate by recording the ID of the transaction that created that specific version, while xmax acts like an expiration marker for when the row is deleted or replaced (or zero if it is still live).</p><p>When an UPDATE query is executed, PostgreSQL deliberately avoids modifying or overwriting the existing data in-place on the disk. Instead, it stamps the old row version&#39;s xmax column with the current transaction ID to expire it, and immediately inserts a brand-new row version right alongside it with a fresh xmin.</p><p>Because multiple versions of the same row temporarily coexist, concurrent transactions can read the exact row version that aligns with their specific timeline snapshot. This structural design allows readers and writers to operate simultaneously without blocking one another.</p><h4>Choosing Your Isolation Level</h4><p>PostgreSQL gives you four SQL isolation levels, though they map to three distinct behaviors:</p><ul><li><strong>Read Committed (Default):</strong> Every single <em>query</em> inside your transaction gets a fresh snapshot. If someone else commits data halfway through your transaction, your next query will see it.</li><li><strong>Repeatable Read:</strong> Your <em>entire transaction</em> locks into a single snapshot taken at the very beginning. No surprises, no phantom reads.</li><li><strong>Serializable:</strong> The gold standard of safety. Postgres tracks conflicts under the hood and ensures the end state is identical to running transactions completely one-by-one.</li></ul><h4>Snapshots: Choosing Your Timeline</h4><p>When a transaction starts, it takes a <strong>snapshot</strong> a frozen guest list of which transactions were already committed at that exact millisecond.</p><p>A row version is visible to your transaction if and only if:</p><ol><li>It was created by a transaction that committed <strong>before</strong> your snapshot was taken.</li><li>It hasn’t been deleted, or its deletion happened <em>after</em> your snapshot.</li></ol><p>This is why two concurrent transactions can look at the exact same table and see completely different realities without stepping on each other’s toes.</p><h4>The Flow: How Two Concurrent Requests Get Processed</h4><p>Let’s look under the hood at what happens when concurrent transactions try to interact with the same row at the same time using a higher isolation level (like <em>Repeatable Read</em> or <em>Serializable</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngZdmzgBkq51Bq6QNFRt3w.png" /></figure><h4>Step-by-Step Flow:</h4><ul><li><strong>Transaction 1 (XID 100)</strong> starts at T1, takes a snapshot, and reads the original row <strong>&quot;Alice&quot;</strong> (xmin: 99, xmax: 100).</li><li><strong>Transaction 2 (XID 101)</strong> starts later, updates the name to <strong>“Alice Smith”</strong>, which expires the first row (xmax: 100) and creates a new version (xmin: 100, xmax: 101) that Tx 2 sees.</li><li><strong>Transaction 3 (XID 102)</strong> updates the name again to <strong>“Alice Johnson”</strong>, expiring the second row and generating the current active version (xmin: 101, xmax: NULL) that Tx 3 reads.</li><li><strong>The Result:</strong> Because of MVCC snapshots, all three transactions run concurrently without blocking each other, each seeing a different version of reality based on when they started.</li></ul><h3>Conclusion</h3><p>MVCC is the secret sauce that allows PostgreSQL to handle heavy read traffic while write operations hum along in the background.</p><ul><li><strong>UPDATE is an </strong><strong>INSERT under the hood:</strong> Old versions pile up as dead tuples until background maintenance processes (VACUUM) clean them up.</li><li><strong>Snapshots dictate reality:</strong> Visibility is entirely governed by transaction IDs (xmin, xmax) and your transaction&#39;s timeline snapshot.</li><li><strong>Conflicts are caught, not blocked:</strong> Instead of locking readers out or letting writers silently overwrite data, Postgres detects cross-transaction collisions and relies on application-level retries to ensure correctness.</li></ul><p>Ultimately, understanding MVCC shifts PostgreSQL from a mysterious black box into a predictable, robust system. It empowers you to reason about concurrency, data isolation, and performance with absolute confidence in any backend application you build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f8cc4e068b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>