<?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 Tothagata Bhattacharjee on Medium]]></title>
        <description><![CDATA[Stories by Tothagata Bhattacharjee on Medium]]></description>
        <link>https://medium.com/@toth2000?source=rss-f18a3a13c398------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Pq2AcpV4WGNISuk6</url>
            <title>Stories by Tothagata Bhattacharjee on Medium</title>
            <link>https://medium.com/@toth2000?source=rss-f18a3a13c398------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:15:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@toth2000/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[Microservices Architecture: 2-Phase Commit vs. Saga Pattern for Distributed Transactions]]></title>
            <link>https://blog.stackademic.com/microservices-architecture-2-phase-commit-vs-saga-pattern-for-distributed-transactions-9e28c4ce5d5d?source=rss-f18a3a13c398------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e28c4ce5d5d</guid>
            <category><![CDATA[distributed-transaction]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Tothagata Bhattacharjee]]></dc:creator>
            <pubDate>Sun, 24 May 2026 10:45:55 GMT</pubDate>
            <atom:updated>2026-05-25T09:00:47.260Z</atom:updated>
            <content:encoded><![CDATA[<p>In a traditional monolithic system, maintaining data consistency is straightforward. If a user places an order, the application opens a single database transaction, charges the customer, updates the stock, and commits everything at once. If any step fails, the database handles the rollback automatically. This is the beauty of <strong>ACID</strong> properties.</p><p>However, in a distributed microservices architecture, things get complicated quickly. When different services run on different machines and manage their own isolated databases, you can no longer rely on a single, global database transaction.</p><p>Consider a modern e-commerce system:</p><ol><li><strong>Payment Service:</strong> Processes transactions and stores payment states in a Payment DB.</li><li><strong>Inventory Service:</strong> Tracks stock allocations in an Inventory DB.</li><li><strong>Notification Service:</strong> Triggers order confirmation emails or SMS alerts once a purchase is successfully finalized.</li></ol><p>How do you guarantee consistency across these distinct databases when a network call drops or a service crashes or a service transaction fails? There are two primary architectural approaches to solving distributed transaction consistency: <strong>2-Phase Commit (2PC)</strong> and the <strong>Saga Pattern</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*60gqZF6ajXG2oC2I" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve A Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. The Two-Phase Commit (2PC) Approach</h3><p>The Two-Phase Commit protocol relies on a centralized <strong>Coordinator</strong> component to manage the lifecycle of the transaction across multiple services. It operates in two distinct phases:</p><h3>Phase 1: Prepare</h3><ul><li>The Coordinator sends a “Prepare” event to the Payment, Inventory, and Notification services.</li><li>Each service opens a local transaction, <strong>acquires a database lock</strong>, and validates if it <em>can</em> execute the task.</li><li><strong>Crucial Detail:</strong> The services make the changes locally to ensure they are valid, but <strong>they do not commit</strong>. They remain in a state of limbo and reply to the coordinator with an acknowledgment (ACK).</li></ul><h3>Phase 2: Commit / Rollback</h3><ul><li>If the coordinator receives a successful ACK from <strong>all</strong> services, it sends a global “Commit” command. The databases permanently write the data and release their locks simultaneously.</li><li>If <em>any</em> service fails or times out during the Prepare phase, the coordinator sends a “Rollback” command, causing all services to discard their uncommitted changes.</li></ul><h3>Clarifying the Concurrency Paradox: How Locks Work Under the Hood</h3><blockquote><strong><em>The Deep-Dive Question:</em></strong><em> </em>If transactions are supposed to be isolated, how does holding a stock item in one transaction stop another user from checking out? And how do we ensure a card isn’t charged prematurely if the inventory update fails?</blockquote><p>This gets to the exact heart of database engine design. In 2PC, isolation is enforced by making competing transactions wait using <strong>explicit database row locks</strong>, rather than hiding the data entirely.</p><p>When a service executes Phase 1 (Prepare), it runs a specific SQL query designed to lock the targeted rows, such as:</p><pre>SELECT * FROM inventory WHERE item_id = &#39;XYZ&#39; FOR UPDATE;</pre><p>The FOR UPDATE clause tells the database engine to apply an exclusive lock to the row immediately. Because Transaction A holds this lock, when Transaction B tries to buy the exact same item half a second later, the database engine forces Transaction B to pause and wait. It doesn&#39;t see Transaction A&#39;s uncommitted data; it simply sits in a blocked state until Transaction A either commits or rolls back in Phase 2.</p><p>Furthermore, 2PC perfectly handles the payment problem by separating <em>execution</em> from <em>commitment</em>. During Phase 1, the Payment Service only talks to the payment gateway (like Stripe) to <strong>authorize</strong> or place a temporary hold on the funds — it does not finalize the charge. At the exact same time, the Inventory Service validates and holds the stock. If the inventory step fails, Phase 1 aborts, the coordinator sends a rollback, and the payment gateway simply releases the temporary hold. The card is never actually charged.</p><blockquote><strong><em>Do we need a Distributed Lock here?</em></strong><em> In a standard application-level 2PC, you do not need an external lock manager (like Redis or ZooKeeper) because you rely entirely on the local databases’ native storage engine locks. The coordinator simply manages the timing of those local locks. However, in deeply integrated systems like </em><strong><em>Google Spanner</em></strong><em> or </em><strong><em>YugabyteDB</em></strong><em>, the database engine itself handles distributed consensus protocols (like Paxos or Raft) to manage these locks across different physical shards natively.</em></blockquote><h3>Why 2PC is Avoided in Modern Microservices</h3><p>While 2PC provides <strong>Strong Consistency</strong> (all systems match instantly), it introduces massive engineering bottlenecks:</p><ul><li><strong>The Synchronous Blocking Problem:</strong> All participating databases must hold onto row locks from the moment Phase 1 starts until Phase 2 finishes. No other user can touch those database rows during this window.</li><li><strong>The Coordinator SPOF:</strong> If the coordinator crashes right after Phase 1, all microservices are left completely stuck with open, pending transactions and active database locks, completely paralyzing system throughput.</li><li><strong>Performance Degradation:</strong> The entire transaction speed is strictly bottlenecked by your slowest service. If the Notification Service takes 3 seconds to spin up an email handler, your payment and inventory databases stay locked and blocked for those 3 seconds.</li></ul><h3>2. The Saga Pattern Approach</h3><p>Because locking databases across network boundaries introduces crippling latency, modern distributed systems rely on the <strong>Saga Pattern</strong>.</p><p>Instead of trying to force a global lock, a Saga breaks the workflow down into a sequence of <strong>independent, local transactions</strong>. Each service updates its own database and commits the change immediately. There are no global locks.</p><h3>Handling Failures with Compensating Actions</h3><p>Because changes are committed instantly, a traditional database rollback is impossible if a subsequent step fails. Instead, the Saga pattern relies on <strong>Compensating Actions</strong> — explicit application logic written to “undo” a previous step and bring the system to a state of <strong>Eventual Consistency</strong>.</p><p>For example, in a baseline Saga execution:</p><ul><li>The <strong>Payment Service</strong> completely charges the customer’s card and commits the entry.</li><li>The <strong>Inventory Service</strong> goes to deduct stock, but discovers the item is sold out and fails.</li><li>The system cannot perform a standard rollback because the money has already left the user’s account. Instead, it triggers a <strong>Compensating Action</strong>: The Payment Service is commanded to <strong>issue a refund</strong>.</li></ul><p>Let’s look at how these compensating actions are coordinated across the two Saga implementation models: <strong>Choreography</strong> and <strong>Orchestration</strong>.</p><h3>Implementation Strategy A: Choreography (The Event-Driven Model)</h3><p>Choreography relies on a decentralized, pub/sub architecture (typically powered by a message broker like Apache Kafka or RabbitMQ). There is no central boss controlling the workflow; every service listens to events and acts independently.</p><pre>[Payment Service] ──&gt; (Publishes: PaymentSuccess)──&gt; [Inventory Service]<br>│                                                   │<br>│ (If Inventory Fails, Publishes: InventoryFailed)  │<br>└─────────────────────── &lt; ────────── ───────┘</pre><ul><li><strong>The Happy Path:</strong> The Payment Service processes the payment, commits it, and emits a PaymentSuccess event. The Inventory Service consumes this event, allocates stock, and emits InventoryUpdated, which prompts the Notification Service to send an email.</li><li><strong>The Failure Path:</strong> If the Inventory Service fails to allocate stock, it emits an InventoryDeductionFailed event. The Payment Service listens specifically for this failure and executes its compensating action: <strong>issuing a refund</strong>.</li></ul><blockquote><strong><em>The Architectural Catch:</em></strong><em> While Choreography is highly decoupled, it quickly degrades into a “spaghetti architecture” as you add more microservices. Tracking which service is listening to which event becomes incredibly complex to map out and debug.</em></blockquote><h3>Implementation Strategy B: Orchestration (The Centralized State Machine)</h3><p>To solve the tracking complexity of Choreography, <strong>Orchestration</strong> introduces a dedicated <strong>Orchestrator Service</strong> (often implemented as a centralized state machine) that owns, commands, and directs the entire workflow. The participating microservices do not know about each other; they only listen to the Orchestrator.</p><pre>                 ┌─── 1. Command: Process Payment ───&gt; [Payment Service]<br>                 |<br>[Orchestrator] ──|─── 2. Command: Deduct Inventory ───&gt; [Inventory Service] (FAILS!)<br>                 |<br>                 └─── 3. Compensate: Issue Refund ───&gt; [Payment Service]</pre><ul><li>The <strong>Orchestrator</strong> sends a direct command to the <strong>Payment Service</strong>: <em>“Charge the card”</em>.</li><li>The Payment Service finishes successfully and replies back: <em>“Payment Done”</em>.</li><li>The <strong>Orchestrator</strong> updates its internal state machine and commands the <strong>Inventory Service</strong>: <em>“Deduct the stock”</em>.</li><li>The Inventory Service encounters an error (out of stock) and replies back: <em>“Deduction Failed”</em>.</li><li>The <strong>Orchestrator</strong> evaluates its workflow rules. It knows that because the inventory step failed, it must halt the sequence and systematically trigger the compensating actions for all previously completed steps.</li><li>The <strong>Orchestrator</strong> issues a direct command to the <strong>Payment Service</strong>: <em>“Execute compensating action: Issue a refund for transaction ID X”</em>.</li></ul><h3>Why an Orchestrator Isn’t a Single Point of Failure (SPOF) Like a 2PC Coordinator</h3><p>At first glance, a Saga Orchestrator sounds exactly like a 2PC Coordinator — both are centralized components managing a multi-service workflow. Yet, a 2PC coordinator crash paralyzes your system, while a Saga orchestrator recovers gracefully.</p><p>The difference comes down to <strong>State Persistence vs. Database Locking</strong>:</p><ul><li><strong>The 2PC Coordinator is a Structural SPOF:</strong> During Phase 1, participating databases open live connections and hold active rows locked in memory. If the coordinator crashes before Phase 2, those core database engines freeze indefinitely to protect ACID integrity, paralyzing system throughput.</li><li><strong>The Saga Orchestrator is a Recoverable State Machine:</strong> In a Saga, each microservice commits its local transaction immediately, instantly releasing database locks. To track the workflow, orchestration engines (like Temporal, AWS Step Functions, or Camunda) rely on their own underlying <strong>persistent database</strong> (such as PostgreSQL or an optimized event log).</li></ul><p>Before sending any network command to a microservice, the orchestrator writes the intended state transition directly to its private database disk.</p><p>If the orchestrator loses power mid-flight, <strong>no business databases are locked</strong>. As soon as your infrastructure spins up a backup instance of the orchestrator, it simply reads the persistent state log and resumes right where it left off:</p><blockquote>“Order #999 history shows the payment step was committed as ‘Successful’, but there is no entry for the inventory step. Resuming workflow: pinging Inventory Service now.”</blockquote><p>In short: A 2PC coordinator crash causes an <strong>infrastructure deadlock</strong> because state lives in volatile database memory locks. A Saga orchestrator crash causes a <strong>temporary operational delay</strong> because state safely lives as cold data rows on a physical disk.</p><h3>Architectural Pro-Tip: Leveraging Authorizations to Avoid Refunds</h3><p>Now that we understand standard compensating actions, we can look at how to optimize them. In the standard failure paths described above, a failure means processing a true refund. Moving actual money back across banking networks takes days, looks messy on bank statements, and incurs transaction processing fees.</p><p>If your payment gateway allows it, you can design your Saga to mimic 2PC’s safety net by utilizing a two-step payment flow: <strong>Authorize — &gt; Capture</strong>.</p><p>Instead of capturing the money immediately in Step 1, your Payment Service merely <em>authorizes</em> (holds) the funds. If a downstream service like Inventory fails later in the Saga chain, your compensating action changes from an expensive <strong>Issue Refund</strong> to a simple, instantaneous, and free <strong>Void/Cancel Authorization</strong>.</p><blockquote><strong>The Catch (Why it isn’t <em>always</em> used):</strong> Authorizations have an expiration time that varies on payment method (usually a few days for credit cards). If you have a highly complex, long-running Saga that takes days to fulfill (e.g., waiting for a third-party vendor to manually verify stock or a physical delivery chain), the authorization might expire before you can capture it.</blockquote><h3>2PC vs. Saga Pattern: A Quick Review</h3><ol><li><strong>Consistency Model:</strong></li></ol><ul><li><strong>2-Phase Commit (2PC):</strong> <em>Strong Consistency.</em> All databases are perfectly synced at the exact same moment.</li><li><strong>Saga Pattern:</strong> <em>Eventual Consistency.</em> Data stabilizes across different services over a short window of time.</li></ul><p><strong>2. Locking Mechanism:</strong></p><ul><li><strong>2-Phase Commit (2PC):</strong> <em>Highly Blocking.</em> Holds global database row locks until every single service in the chain responds.</li><li><strong>Saga Pattern:</strong> <em>Non-Blocking.</em> Local transactions commit immediately, maximizing application throughput.</li></ul><p><strong>3. Error Handling:</strong></p><ul><li><strong>2-Phase Commit (2PC):</strong> <em>Infrastructure-level Rollback.</em> Data is never permanently written if a failure happens during the execution chain.</li><li><strong>Saga Pattern:</strong> <em>Application-level Compensating Actions.</em> Explicit code logic is executed to manually undo a finalized transaction (e.g., issuing a refund).</li></ul><h3>Summary</h3><p>When designing large-scale software systems, engineering is fundamentally an exercise in navigating trade-offs. If your domain strictly mandates absolute, immediate synchronization across databases and can tolerate the latency of distributed row locking, a database-level <strong>2-Phase Commit</strong> might be necessary.</p><p>However, for modern, highly scalable e-commerce backends and fast-moving SaaS applications, holding global locks over network boundaries simply doesn’t scale. Embracing the <strong>Saga Pattern</strong> — specifically via an <strong>Orchestrator</strong> — allows you to build highly responsive, fault-tolerant systems that maintain data integrity without sacrificing performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e28c4ce5d5d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/microservices-architecture-2-phase-commit-vs-saga-pattern-for-distributed-transactions-9e28c4ce5d5d">Microservices Architecture: 2-Phase Commit vs. Saga Pattern for Distributed Transactions</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Single Entry Point Paradox: High-Availability Without a Single Point of Failure]]></title>
            <link>https://blog.stackademic.com/the-single-entry-point-paradox-high-availability-without-a-single-point-of-failure-120c6a30130c?source=rss-f18a3a13c398------2</link>
            <guid isPermaLink="false">https://medium.com/p/120c6a30130c</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Tothagata Bhattacharjee]]></dc:creator>
            <pubDate>Sat, 02 May 2026 18:59:15 GMT</pubDate>
            <atom:updated>2026-05-07T13:36:52.352Z</atom:updated>
            <content:encoded><![CDATA[<h3>The “Single Entry Point” Paradox: Building High-Availability Systems Without a Single Point of Failure</h3><p>In system design, we often talk about having a single entry point for a client. Whether it’s an API Gateway or a Load Balancer, this entry point acts as the front door to your entire ecosystem of services.</p><p>But this raises a critical question: <strong>If everything goes through one door, isn’t that a Single Point of Failure (SPOF)?</strong></p><p>The short answer is no — but the “how” involves a clever combination of DNS tricks, distributed infrastructure, and health management. Here is a breakdown of how modern architectures handle traffic distribution and resilience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KdYmn8chYWPRdHT8" /><figcaption>Photo by <a href="https://unsplash.com/@pechka?utm_source=medium&amp;utm_medium=referral">Dima Pechurin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. The Entry Point: Gateway or Load Balancer?</h3><p>When a client makes a request, it first hits an entry point. Depending on the complexity of your architecture, this is usually one of two things:</p><ul><li><strong>Load Balancer (LB):</strong> Primarily focuses on distributing incoming network traffic across multiple backend servers.</li><li><strong>API Gateway:</strong> A more advanced “front door” that handles not just routing, but also <strong>Rate Limiting, Authentication logic, and Request Transformation.</strong></li></ul><p>While a Load Balancer like AWS ELB can route requests to different services based on request path or host headers, it is technically not a Gateway because it lacks these specialized “application-aware” features.</p><h3>2. Solving the SPOF: The DNS Layer</h3><p>If we point our domain (e.g., api.myapp.com) to a single IP address, and that machine dies, our system goes dark. To prevent this, we use <strong>DNS-level distribution.</strong></p><p>When you use a service like AWS ELB, you aren’t pointing your domain to a single machine. You are pointing it to a DNS name (e.g., my-load-balancer-123.aws.com).</p><h4>How DNS Distributes Traffic:</h4><ol><li><strong>Multiple IPs:</strong> Behind that one DNS name, there are actually multiple Load Balancer instances running on different physical machines in different data centers.</li><li><strong>Round Robin:</strong> When a client asks DNS for the IP of api.myapp.com, the DNS server returns a list of IPs (e.g., 3.14.x.x, 5.8.x.x, 17.65.x.x).</li><li><strong>Client Selection:</strong> The client (browser or mobile app) typically picks one of these IPs to initiate the connection.</li></ol><p>By rotating which IP is listed first (Round Robin), different users are sent to different physical Load Balancer instances.</p><h3>3. What Happens When a Node Dies?</h3><p>No hardware is immortal. Eventually, a Load Balancer instance will fail. Systems remain “Highly Available” through a process of <strong>Health Checks.</strong></p><ul><li><strong>Detection:</strong> AWS or your infrastructure provider constantly “pings” the Load Balancer nodes.</li><li><strong>Removal:</strong> If a node stops responding, its IP is immediately removed from the DNS response. New clients will no longer receive the IP of the dead node.</li><li><strong>The “Cache” Problem:</strong> Browsers often cache DNS lookups. If a browser has cached the IP of a dead node, the request might temporarily fail. DNS records have a “lifespan.” If the TTL is set to 60 seconds, the browser will check for a fresh IP every minute. High TTL means fewer DNS lookups (faster for the user) but longer downtime if a node fails. Low TTL means faster recovery but more overhead.</li></ul><h3>4. The Path of a Request</h3><p>To visualize the whole flow, imagine a user logging into an app:</p><ol><li><strong>Client → DNS:</strong> The client resolves myapp.com and gets three healthy IPs.</li><li><strong>Client → Load Balancer:</strong> The client picks one IP and hits an LB instance.</li><li><strong>LB → API Gateway:</strong> The LB sends the request to the Gateway, which checks if the user is hitting the “Rate Limit” or needs “Authentication.”</li><li><strong>Gateway → Auth Service:</strong> If it’s a /login request, the Gateway routes it to the specific <strong>Auth Service</strong>.</li><li><strong>Gateway → Email Service:</strong> Once logged in, the user wants to send an email. The <strong>Email Service</strong> will handle this.</li></ol><h3>Conclusion</h3><p>A “Single Entry Point” is a functional concept, not a physical one. By distributing that entry point across multiple machines and using DNS to point to them dynamically, we gain the simplicity of a single URL with the power of a distributed, fault-tolerant system.</p><p>Whether you are using an AWS ELB for simple routing or a full-scale API Gateway for complex logic, the underlying principle remains: <strong>Redundancy is the only cure for failure.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=120c6a30130c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-single-entry-point-paradox-high-availability-without-a-single-point-of-failure-120c6a30130c">The Single Entry Point Paradox: High-Availability Without a Single Point of Failure</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>