<?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 Saahid on Medium]]></title>
        <description><![CDATA[Stories by Saahid on Medium]]></description>
        <link>https://medium.com/@saahid?source=rss-15506854fe01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sYUWLbw0SAC9V7MzQHdWow.jpeg</url>
            <title>Stories by Saahid on Medium</title>
            <link>https://medium.com/@saahid?source=rss-15506854fe01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:23:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saahid/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[Database Replication Patterns]]></title>
            <link>https://medium.com/@saahid/database-replication-patterns-2261e7b89616?source=rss-15506854fe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/2261e7b89616</guid>
            <category><![CDATA[database-replication]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Saahid]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 18:04:15 GMT</pubDate>
            <atom:updated>2025-12-23T18:04:15.088Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide covers the fundamental replication patterns.</p><p>Replication means keeping a copy of the same data on multiple machines that are connected via a network. The major reasons for replication are:</p><ul><li><strong>High Availability</strong>: Keeping the system running even when one machine (node) goes down.</li><li><strong>Latency</strong>: Placing data geographically closer to users.</li><li><strong>Scalability</strong>: Increasing read throughput by handling more read requests than a single machine can.</li></ul><h3>1. Overview of Frameworks</h3><p>There are three main approaches to replication:</p><ol><li><strong>Single-Leader</strong>: One node accepts writes; all others replicate.</li><li><strong>Multi-Leader</strong>: Multiple nodes accept writes; they replicate to each other.</li><li><strong>Leaderless</strong>: No central leader; writes are sent to multiple nodes directly.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yoeuj0paJLP8zMu8GZKnjQ.png" /></figure><h3>2. Single-Leader Replication</h3><p>In this pattern (also known as active-passive or master-slave), one replica is designated as the <strong>leader</strong> (master/primary). The others are <strong>followers</strong> (read replicas/slaves/secondaries).</p><h3>How It Works</h3><ol><li>Clients send all writes to the <strong>leader</strong>.</li><li>The leader writes the change to its <strong>Write-Ahead Log (WAL)</strong> first (on disk, for durability).</li><li>The leader applies the change to its in-memory data structures (and eventually to the data files).</li><li>The leader sends the WAL entries to all <strong>followers</strong>.</li><li>Followers write to their own WAL, then apply the changes in the same order as the leader.</li><li>Reads can be served by the leader or any follower.</li></ol><h3>Replication Methods</h3><p>Different databases implement replication in different ways:</p><ol><li><strong>Statement-Based Replication</strong>: The leader logs every SQL statement (INSERT, UPDATE, DELETE) and sends it to followers.</li></ol><p><strong>Pros</strong>: Compact (SQL statements are usually smaller than the data they modify), simple to understand.</p><p><strong>Cons</strong>:</p><ul><li>Nondeterministic functions (NOW(), RAND(), UUID()) produce different values on each replica</li><li>Statements with auto-incrementing columns or those that depend on existing data can produce different results</li><li>Statements with side effects (triggers, stored procedures, UDFs) may behave differently on each replica</li><li>Requires followers to execute the same statements in the exact same order</li></ul><p><strong>Used by</strong>: MySQL (before 5.1), older versions of PostgreSQL</p><p>2.<strong> Write-Ahead Log (WAL) Shipping</strong>: The leader sends the exact sequence of bytes written to the WAL (physical replication).</p><p><strong>Pros</strong>:</p><ul><li>Exact replica — followers guaranteed to have identical data structures</li><li>No ambiguity about what should be replicated</li><li>Efficient for high write throughput</li></ul><p><strong>Cons</strong>:</p><ul><li>Very low-level (describes data at the level of disk blocks and byte offsets)</li><li>Tightly coupled to the storage engine — different storage engine versions may not be compatible</li><li>Zero-downtime upgrades are difficult (can’t replicate between different database versions)</li><li>Can’t replicate between different database systems</li></ul><p><strong>Used by</strong>: PostgreSQL (physical replication), Oracle (physical standby)</p><p>3.<strong> Logical (Row-Based) Replication</strong>: Uses a logical log format describing inserts, updates, and deletes at the row/document granularity (logical replication).</p><p><strong>Pros</strong>:</p><ul><li>Decoupled from storage engine internals — leaders and followers can run different database versions</li><li>Can replicate between different storage engines or even different database systems</li><li>Easier to parse by external applications (for change data capture, data warehousing, custom indexes)</li><li>Allows selective replication (e.g., only certain tables or certain types of changes)</li></ul><p><strong>Cons</strong>:</p><ul><li>May be larger in size compared to physical WAL (especially for operations that modify many rows)</li><li>Slightly more CPU overhead to produce logical log entries</li></ul><p><strong>Used by</strong>: MySQL binlog (row-based mode), PostgreSQL (logical replication), MongoDB (oplog), Oracle (logical standby)</p><h3>Key Concepts</h3><h4><strong>Synchronous vs. Asynchronous Replication</strong></h4><ul><li><em>Synchronous Replica</em>: The leader waits for the replica’s acknowledgment (ACK ✓) before reporting success to the client. This provides <strong>strong consistency</strong> between the leader and synchronous replica, guaranteeing durability. However, writes block if the replica is slow or down.</li><li><em>Asynchronous Replica</em>: The leader reports success immediately without waiting for acknowledgment. This is fast but provides only <strong>eventual consistency</strong>. Data can be lost if the leader fails before replicating.</li><li><em>Semi-Synchronous</em>: One replica is synchronous (for durability), while others are asynchronous (for availability). This is the most common production setup.</li></ul><h4><strong>Handling Failures</strong></h4><ul><li><em>Follower Failure</em>: <strong>Catch-up recovery</strong>. Each follower keeps a log of data changes received from the leader. If a follower crashes or the network is interrupted, it can recover by connecting to the leader and requesting all changes that occurred during disconnection (using the last processed position in the log).</li><li><em>Leader Failure</em>: <strong>Failover</strong> (the trickiest case). The process involves:</li></ul><ol><li><strong>Detecting leader failure</strong>: Most systems use timeout-based detection (if the leader doesn’t respond for 30 seconds, it’s assumed dead). But timeout-based detection is problematic because there’s no foolproof way to detect a failure — network issues can look like node failures.</li><li><strong>Choosing a new leader</strong>: Election via consensus algorithm or appointed by a previously elected controller node. The best candidate is usually the replica with the most up-to-date data changes.</li><li><strong>Reconfiguring the system</strong>: Clients must send writes to the new leader. The old leader must recognize that it’s no longer the leader when it comes back (to prevent split-brain scenarios).</li></ol><h4><strong>Replication Lag Issues</strong></h4><ul><li>With asynchronous replication, followers may be seconds or even minutes behind the leader. This leads to several consistency problems:</li><li><em>Read-After-Write Consistency</em> (also called read-your-writes): Users should always see their own updates immediately after writing. Solutions include:</li><li>Reading user’s own profile from the leader, other users’ profiles from followers</li><li>Tracking the timestamp of the last update and ensuring reads from replicas sufficiently up-to-date</li><li>Client remembering the timestamp of its most recent write and ensuring the replica has processed updates at least until that timestamp</li><li><strong><em>Monotonic Reads</em>:</strong> If a user makes several reads, they should not see time go backward (seeing data, then refreshing and not seeing it). This can happen if different reads are routed to different replicas. Solution: Each user always reads from the same replica (e.g., hash user ID to choose replica).</li><li><strong><em>Consistent Prefix Reads</em>: </strong>Users should see causality preserved (questions before answers, cause before effect). This is a problem in partitioned databases where different partitions operate independently. If writes happen in a certain order, anyone reading should see them in that same order.</li></ul><h3>Pros &amp; Cons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DZ1TEY0muNdfPspr6IOXg.png" /></figure><h3>When to Choose</h3><p>✅ <strong>Choose Single-Leader when:</strong></p><ul><li>You have a read-heavy workload (can scale reads by adding followers).</li><li>Your application requires simple, strong consistency guarantees.</li><li>You are using standard relational databases (PostgreSQL, MySQL, SQL Server) which default to this mode.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFUVluEZz5StXnQMXd8Fhg.png" /></figure><h3>3. Multi-Leader Replication</h3><p>Also known as master-master or active-active replication. Multiple nodes are allowed to accept writes. Each node that accepts writes must forward that data change to all other nodes.</p><h3>How It Works</h3><ul><li>Typically used in <strong>multi-datacenter</strong> setups (e.g., Datacenter 1 in US East, Datacenter 2 in EU West, Datacenter 3 in Asia).</li><li>Each datacenter has its own “leader” that accepts writes locally from nearby clients.</li><li>Within each datacenter, the leader replicates to local followers.</li><li><strong>Cross-DC Replication</strong>: Leaders replicate to each other asynchronously across datacenters, forming a mesh topology.</li></ul><h3>Key Concepts</h3><ul><li><strong>Write Conflicts</strong>: ⚠️ The biggest challenge. Since multiple leaders can update the same record concurrently, conflicts <strong>will</strong> happen. In single-leader systems, the leader determines the order of writes, so there are no conflicts. But in multi-leader, concurrent writes can conflict.</li><li><strong>Detecting Conflicts</strong>: A conflict exists when two operations are <strong>concurrent</strong> (neither happened before the other in the causal order). To detect this, we need <strong>version vectors</strong> (or vector clocks) — each replica keeps track of version numbers for itself and other replicas.</li><li><strong>Conflict Resolution Strategies</strong>:</li><li><em>Last Write Wins (LWW)</em>: Assign each write a timestamp or unique ID, and the highest timestamp wins. Simple but prone to data loss because concurrent writes are not truly concurrent in wall-clock time. Used by Cassandra and Riak.</li><li><em>Merge Conflicts On Read</em>: Store all conflicting versions (siblings) and present them to the application/user to resolve. The application merges the values and writes back the result. Used by Riak, CouchDB (revision trees).</li><li><em>Custom Merge Logic</em>: Application code automatically merges values using domain-specific rules. For example, merging shopping cart items or collaborative text editing.</li><li><em>Conflict-Free Replicated Data Types (CRDTs)</em>: Data structures that automatically resolve conflicts in sensible ways (e.g., sets, counters, registers). CRDTs can be merged without any conflict resolution logic.</li><li><em>Operational Transformation</em>: Conflict resolution algorithm for concurrent edits to ordered lists (used in Google Docs, Figma).</li><li><strong>Topologies</strong>:</li><li><em>All-to-all</em>: Every leader talks to every other leader (shown in diagram). Most general but can result in some writes overtaking others due to different network delays.</li><li><em>Circular</em>: Each node forwards writes to the next node in the ring. If one node fails, it can break the circle.</li><li><em>Star</em>: One designated root node forwards writes to all other leaders. If the root fails, it breaks replication.</li></ul><h3>Pros &amp; Cons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6h0S-j9wP2sbeUwIq56zEQ.png" /></figure><h3>When to Choose</h3><p>✅ <strong>Choose Multi-Leader when:</strong></p><ul><li>You have a <strong>multi-datacenter</strong> deployment and need to tolerate entire datacenter failures.</li><li>Your users are geographically distributed and need low write latency.</li><li>Your application needs to work <strong>offline</strong> (e.g., mobile apps syncing when online).</li><li>You are using databases suited for this, such as <strong>CouchDB</strong> or <strong>MongoDB</strong> (in multi-master mode).</li><li>You are willing to implement complex conflict resolution logic.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VMp3MenLKvkTnBeMoa1-g.png" /></figure><h3>4. Leaderless Replication</h3><p>Also known as Dynamo-style replication (used by Amazon Dynamo, Cassandra, Riak, Voldemort). <strong>No Single Leader!</strong> All nodes are equal. The client sends writes to <strong>multiple replicas</strong> concurrently.</p><h3>How It Works</h3><ol><li><strong>Quorums</strong>: To ensure consistency, we use the formula W + R &gt; N (Write quorum + Read quorum &gt; Total replicas).</li></ol><p><strong>Example:</strong> With N=5 total nodes, W=3 write quorum, R=3 read quorum:</p><ul><li>Client sends PUT to all 5 nodes in parallel.</li><li>Write succeeds when 3 nodes acknowledge (W=3 satisfied).</li><li>Client reads from 3 nodes (R=3). Since 3 + 3 = 6 &gt; 5, at least one node is guaranteed to have the latest version.</li><li><strong>Why W + R &gt; N works</strong>: If W + R &gt; N, the write and read quorums must overlap (have at least one node in common). This guarantees that at least one of the nodes you read from must have seen the most recent write.</li><li><strong>Tuning quorums</strong>: You can vary W and R to make reads or writes faster. For example, W=N, R=1 makes reads very fast (only need to read from one node) but writes slow. W=1, R=N makes writes fast but reads slow. Common choices: W=R=(N+1)/2 (rounded up).</li></ul><p>2. <strong>Sloppy Quorum &amp; Hinted Handoff</strong>:</p><p>Traditional quorums are not fault-tolerant — if too many nodes are unavailable, you can’t reach a quorum. <strong>Sloppy quorums</strong> relax the requirement: writes and reads still require W and R successful responses, but they may be from nodes that are not among the designated N “home” nodes for a value. When a temporarily unavailable node comes back online, any writes that were sent to a substitute node are sent back to the original “home” nodes (<strong>hinted handoff</strong>). This improves write availability at the cost of consistency — you may read stale data even if W + R &gt; N because the values may have been written to different nodes than you’re reading from.</p><p>3. <strong>Detecting Concurrent Writes</strong>:</p><p>Even with quorums, you can get conflicts. If two clients concurrently write to the same key (or if the write is handled by different nodes that then replicate), you need to determine which write happened first. This requires <strong>version vectors</strong> (generalizing version numbers to multiple replicas). Each replica increments its own version number when processing a write, and keeps track of the version numbers it has seen from every other replica.</p><p>4. <strong>Repairing Data</strong>:</p><ul><li><em>Read Repair</em>: When a client reads from multiple nodes and detects stale data (e.g., version v1 vs v2), it writes the newer version back to the stale nodes immediately. Works well for frequently read values.</li><li><em>Anti-Entropy</em>: A background process (often using a <strong>Gossip protocol</strong>) constantly compares data between nodes and syncs missing data. Uses <strong>Merkle trees</strong> (hash trees) to efficiently detect differences between replicas. Essential for values that are rarely read.</li></ul><h3>Pros &amp; Cons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MYun5mh1tY__impOECLkdA.png" /></figure><h3>When to Choose</h3><p>✅ <strong>Choose Leaderless when:</strong></p><ul><li><strong>High Availability</strong> is your #1 priority (system must never reject a write).</li><li>You can tolerate <strong>eventual consistency</strong>.</li><li>You need to withstand chaotic network conditions or high node failure rates.</li><li>Common in big data / NoSQL stores (Cassandra, DynamoDB).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJK4rPcBrhPirvJDeqXESA.png" /></figure><h3>Quorum Operations in Detail</h3><p>The diagram below shows a complete write and read cycle with read repair:</p><ol><li><strong>Write Operation (W=3)</strong>: Client sends PUT key=user:123, value=data, version=v2 to all 5 nodes. Three nodes (N1, N2, N3) acknowledge, satisfying the write quorum.</li><li><strong>Read Operation (R=3)</strong>: Client sends GET key=user:123 to nodes N1, N3, N4. N1 and N3 return v2 (latest), but N4 returns v1 (stale).</li><li><strong>Read Repair</strong>: Client detects the version conflict, returns v2 to the application, and triggers an update to N4 to repair the stale data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STQmwxw-iPtLUFcepabJ2Q.png" /></figure><h3>5. Other Architectures</h3><h3>Chain Replication</h3><p>Arranges nodes in a chain. Writes go to the <strong>Head</strong>, propagate through <strong>Middle nodes</strong>, and end at the <strong>Tail</strong>. Reads always come from the <strong>Tail</strong>.</p><p><strong>Write Flow:</strong></p><ol><li>Write Client sends PUT to the <strong>Head Node</strong>.</li><li>Head processes the write and forwards to Middle Node 1.</li><li>Middle nodes apply updates and forward down the chain.</li><li><strong>Tail Node</strong> applies the update and sends ACK back to the client.</li><li>Only when the Tail acknowledges is the write considered committed.</li></ol><p><strong>Read Flow:</strong></p><ul><li>Read Client always queries the <strong>Tail Node</strong>.</li><li>The Tail always has the latest committed data, providing <strong>strong consistency guarantee</strong>.</li></ul><p><strong>How Chain Replication Ensures Consistency:</strong></p><ul><li>Writes propagate from head to tail in order. The tail sends acknowledgment only after all nodes in the chain have applied the write.</li><li>Since all reads go to the tail, and the tail only acknowledges writes that have been applied everywhere, reads are always linearizable (clients always read the latest committed value).</li><li>If a node fails in the middle of the chain, the system can reconfigure: remove the failed node from the chain and let updates flow around it.</li></ul><p><strong>CRAQ (Chain Replication with Apportioned Queries)</strong>:</p><p>An enhancement that allows reads from any node in the chain (not just the tail), improving read throughput while maintaining strong consistency. Nodes in the chain maintain both “clean” (committed) and “dirty” (uncommitted) versions. A read from a non-tail node can return a clean version if it has one; otherwise, it queries the tail for the latest committed version.</p><p><strong>Trade-offs:</strong></p><ul><li><strong>Pros</strong>: Strong consistency (linearizable reads), high read throughput (CRAQ allows reading from any node), simple consistency model, good for write-once-read-many workloads.</li><li><strong>Cons</strong>: Higher write latency (must traverse entire chain), head and tail are critical points (failure requires reconfiguration).</li><li><strong>Use Case</strong>: Object storage systems (e.g., Azure Storage, CRAQ), blob stores, immutable data storage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2JC8-4jLEjvSA9R31-rvw.png" /></figure><h3>Consensus-Based (Raft/Paxos)</h3><p>Uses a consensus algorithm (like Raft) to agree on a sequence of values (the replicated log). Provides strong consistency with automatic failover.</p><p><strong>Normal Operation (Raft Consensus):</strong></p><ol><li>Client sends PUT to the <strong>Leader</strong>.</li><li>Leader appends the entry to its local log.</li><li>Leader sends <strong>AppendEntries RPC</strong> to all followers.</li><li>Followers append to their logs and send ACK.</li><li>When a <strong>majority acknowledges</strong> (e.g., 3/5 nodes), the entry is <strong>committed</strong>.</li><li>Leader responds to the client and notifies followers of the commit.</li></ol><p><strong>Leader Failure Scenario:</strong></p><ol><li>Leader fails 💥.</li><li><strong>Election timeout</strong> triggers on followers.</li><li>A follower becomes a <strong>candidate</strong> and sends <strong>RequestVote RPC</strong> to all nodes.</li><li>If it receives a <strong>majority of votes</strong> (e.g., 3/5), it becomes the new leader.</li><li>System continues with the new leader.</li></ol><p><strong>Key Mechanisms in Raft:</strong></p><ul><li><strong>Terms (Epochs)</strong>: Logical clocks that divide time into numbered periods. Each term has at most one leader. When a leader fails, a new term begins with a new election. This prevents split-brain scenarios where two leaders exist simultaneously.</li><li><strong>Log Matching Property</strong>: If two logs contain an entry with the same index and term, then they are identical in all preceding entries. This is enforced by the AppendEntries RPC consistency check.</li><li><strong>Leader Completeness</strong>: If a log entry is committed in a given term, then that entry will be present in the logs of the leaders for all higher-numbered terms. This ensures no committed data is lost.</li><li><strong>State Machine Safety</strong>: If a server has applied a log entry at a given index to its state machine, no other server will ever apply a different log entry for the same index.</li></ul><p><strong>Why Consensus is Expensive:</strong></p><ul><li>Every write requires at least two network round-trips: one to propose, one to commit.</li><li>Cannot make progress if a majority of nodes are unavailable. In a 5-node cluster, losing 3 nodes means the cluster cannot accept writes (it can still serve reads from remaining nodes).</li><li>More complex than primary-backup replication (single-leader).</li></ul><p><strong>Trade-offs:</strong></p><ul><li><strong>Pros</strong>: Strong consistency (linearizable), automatic leader election with safety guarantees, proven safety (formal verification), fault-tolerant (survives minority failures).</li><li><strong>Cons</strong>: Performance overhead (consensus rounds, at least 2 RTTs per write), complexity, requires majority for progress (cannot tolerate majority failures — 5 nodes can only tolerate 2 failures).</li><li><strong>Use Case</strong>: Configuration stores (etcd, ZooKeeper, Consul), coordination services, distributed locks, leader election, metadata storage. Not suitable for high-throughput data storage due to performance overhead.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giZllP-L7om3eThvYC-5sg.png" /></figure><h3>Summary: Which one should I choose?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfTDtUqCPzmMLaPE7WfGGQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2261e7b89616" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vector clock]]></title>
            <link>https://medium.com/@saahid/vector-clock-ce420e7910e2?source=rss-15506854fe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce420e7910e2</guid>
            <category><![CDATA[vector-clocks]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Saahid]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 12:09:00 GMT</pubDate>
            <atom:updated>2025-12-19T12:09:00.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Fundamental Challenge</h3><p>In a distributed system like Amazon Dynamo (or Cassandra/Riak), we want <strong>High Availability</strong>. This means the system must accept writes even if the network is broken and nodes cannot talk to each other.</p><p>However, if two different nodes accept writes for the same shopping cart at the same time (while disconnected), we end up with two different versions of the truth.</p><h3>Why Timestamps Fail</h3><p>You might think: “Just keep the one with the latest timestamp!” (Last Write Wins).</p><p><strong>The Trap</strong>: Server clocks are unreliable. Server A might think it is 12:00:01 while Server B thinks it is 12:00:00.</p><p><strong>The Consequence</strong>: If you use timestamps, a customer might add an item to their cart, and the system might silently delete it because a “later” timestamp from a lagging server overwrote it.</p><h4>Example of Timestamp Failure</h4><pre>Time: 12:00:00 - User adds &quot;Laptop&quot; to cart on Server A (clock shows 12:00:01)<br>Time: 12:00:05 - User adds &quot;Mouse&quot; to cart on Server B (clock shows 11:59:59 - clock drift!)</pre><pre>Last Write Wins uses timestamps:<br>- Server A timestamp: 12:00:01<br>- Server B timestamp: 11:59:59<br>- System keeps: &quot;Laptop&quot; (discards &quot;Mouse&quot;)<br>- Result: User&#39;s mouse disappeared!</pre><h3>The Solution: Vector Clocks</h3><p>Instead of using wall-clock time (“It is 12:00 PM”), we use <strong>Logical Time</strong> (“This is the 3rd update Node A has seen”).</p><p>A <strong>Vector Clock</strong> is simply a list of counters that tracks history.</p><ul><li><strong>Format</strong>: [NodeA: 1, NodeB: 2]</li><li><strong>Meaning</strong>: “This version of the data is the result of 1 update on Node A and 2 updates on Node B.”</li></ul><h3>2. Vector Clock Components</h3><h3>What is a Vector Clock?</h3><p>A vector clock is a data structure that tracks causality:</p><pre>Vector Clock = { node_id → counter }</pre><pre>Example: [A:3, B:2, C:1]<br>- Node A has performed 3 operations<br>- Node B has performed 2 operations<br>- Node C has performed 1 operation</pre><h3>Core Concepts</h3><h4>1. Causality</h4><ul><li><strong>Purpose</strong>: Track which events happened before others</li><li><strong>Mechanism</strong>: Each node increments its own counter on every write</li><li><strong>Example</strong>: If version V1 has [A:1] and V2 has [A:2], then V1 happened before V2</li></ul><h4>2. Concurrency</h4><ul><li><strong>Purpose</strong>: Detect when two updates happened independently</li><li><strong>Mechanism</strong>: Compare all counters between two vector clocks</li><li><strong>Example</strong>: [A:1, B:1] and [A:1, C:1] are concurrent (neither dominates)</li></ul><h4>3. Conflict Detection</h4><ul><li><strong>Purpose</strong>: Identify when manual reconciliation is needed</li><li><strong>Result</strong>: When two versions are concurrent, both are kept as “siblings”</li><li><strong>Resolution</strong>: Application layer decides how to merge</li></ul><h3>Operations</h3><h4>Increment</h4><p>When a node performs a write:</p><pre>1. Take current vector clock<br>2. Increment own counter<br>3. Attach new vector clock to data</pre><h4>Compare</h4><p>To determine relationship between two vector clocks:</p><pre>Clock A vs Clock B:</pre><pre>If all counters in A ≤ B: A is ancestor (B is newer)<br>If all counters in A ≥ B: A is descendant (A is newer)<br>Otherwise: Concurrent (conflict!)</pre><h3>🎯 Scenario 1: The Happy Path (Sequential Updates)</h3><p>A user is shopping for Black Friday. The network is healthy. All requests are routed to Node A (the Coordinator).</p><h3>Steps</h3><ol><li><strong>Write 1</strong>: User creates cart and adds “Kindle”</li></ol><ul><li>Node A handles it</li><li>Creates first version with Vector Clock: [A:1]</li></ul><p>2. <strong>Write 2</strong>: User adds “Echo Dot”</p><ul><li>Node A handles it</li><li>Sees old clock [A:1], increments own counter to 2</li><li>New Clock: [A:2]</li></ul><p>3. <strong>Check</strong>: Since 2 &gt; 1, system knows Version 2 is child of Version 1</p><ul><li>No conflict</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*1jb1ih9D_GGKQcNB0Vr-vQ.png" /></figure><h3>Key Takeaways</h3><ul><li>Sequential updates on same node simply increment that node’s counter</li><li>Newer versions always have higher counters for the updating node</li><li>Easy to determine causality: all counters increase monotonically</li><li>No conflicts occur in sequential execution</li></ul><h3>🔀 Scenario 2: The Fork (Concurrent Updates)</h3><p>A network partition occurs! Node B and Node C are isolated from each other, but both are still running. The user (or their phone app) talks to both.</p><h3>Steps</h3><ol><li><strong>Base State</strong>: Both nodes start with last known cart</li></ol><ul><li>Cart: {Kindle, Echo Dot}</li><li>Clock: [A:2]</li></ul><p>2. <strong>Branch 1 (The Phone)</strong>: User on phone adds “Headphones”</p><ul><li>Request hits Node B</li><li>Node B takes [A:2], adds itself [B:1]</li><li>New Clock: [A:2, B:1]</li><li>Cart: {Kindle, Echo Dot, Headphones}</li></ul><p>3. <strong>Branch 2 (The Laptop)</strong>: User on laptop adds “Charger”</p><ul><li>Request hits Node C</li><li>Node C takes [A:2], adds itself [C:1]</li><li>New Clock: [A:2, C:1]</li><li>Cart: {Kindle, Echo Dot, Charger}</li></ul><p>4. <strong>The Conflict</strong>: System now has two valid “latest” versions</p><ul><li>Version X: [A:2, B:1, C:0] (implicit zero for C)</li><li>Version Y: [A:2, B:0, C:1] (implicit zero for B)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*Uy2YMq0E24X0IkOucQpS5Q.png" /></figure><h3>Key Takeaways</h3><ul><li>Network partitions cause concurrent writes on different nodes</li><li>Each node increments its own counter independently</li><li>Neither version dominates the other (B:1 &gt; B:0 but C:0 &lt; C:1)</li><li>System must keep both versions as siblings</li><li>Conflicts are detected, not resolved automatically</li></ul><h3>🔗 Scenario 3: The Reconciliation (The Merge)</h3><p>The network heals. The user refreshes their cart. The system reads the data and finds two conflicting versions (siblings).</p><h3>Steps</h3><ol><li><strong>Read</strong>: Node A reads database and sees both objects</li><li><strong>Compare Clocks</strong>:</li></ol><ul><li>Clock 1: [A:2, B:1, C:0] (implicit zero for C)</li><li>Clock 2: [A:2, B:0, C:1] (implicit zero for B)</li></ul><p>3. <strong>Logic</strong>: Does Clock 1 beat Clock 2?</p><ul><li>No (B:1 &gt; B:0, but C:0 &lt; C:1)</li><li>Result: They are <strong>Concurrent</strong></li></ul><p>4. <strong>Return to App</strong>: Database returns both shopping carts to application</p><p>5. <strong>Semantic Reconciliation</strong>: Application logic (client side) merges</p><ul><li>Looks at items: “User wanted Headphones AND Charger”</li><li>Merges sets: {Kindle, Echo Dot, Headphones, Charger}</li></ul><p>6. <strong>Write Back</strong>: Application writes merged object to Node A</p><ul><li>Node A creates new clock dominating both previous ones</li><li>Final Clock: [A:3, B:1, C:1]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*deerHXDydRiU8LkYYGboqg.png" /></figure><h3>Key Takeaways</h3><ul><li>System detects conflicts automatically using vector clocks</li><li>Application receives all conflicting versions (siblings)</li><li>Application logic performs semantic merge based on domain knowledge</li><li>Merged version has vector clock that dominates all siblings</li><li>Final write creates new version with incremented coordinator counter</li></ul><h3>📋 The Rules of Comparison</h3><p>How does the computer strictly decide if there is a conflict? It compares the counters for every node ID.</p><h4>Comparison Rules</h4><p>RelationshipRuleMeaningAction<strong>Descendant</strong>All counters in A ≤ BA is an older version of BOverwrite: Safely discard A, keep B<strong>Ancestor</strong>All counters in A ≥ BA is a newer version of BOverwrite: Safely discard B, keep A<strong>Conflict (Sibling)</strong>A has some counters &gt; B, BUT B has some counters &gt; AThey branched off separatelyKeep Both: Return both to app</p><h4>Example Checks</h4><h4>Example 1: Clear Descendant</h4><pre>Clock A: [Node1: 1, Node2: 1]<br>Clock B: [Node1: 1, Node2: 2]</pre><pre>Check: 1 ≤ 1 and 1 ≤ 2<br>Result: B is newer (A is ancestor)<br>Action: Discard A, keep B</pre><h4>Example 2: Conflict</h4><pre>Clock X: [Node1: 1, Node2: 2]<br>Clock Y: [Node1: 2, Node2: 1]</pre><pre>Check:<br>- Node1: 1 &lt; 2 (favors Y)<br>- Node2: 2 &gt; 1 (favors X)</pre><pre>Result: Conflict (concurrent updates)<br>Action: Keep both X and Y as siblings</pre><h4>Example 3: Clear Ancestor</h4><pre>Clock A: [Node1: 3, Node2: 2, Node3: 1]<br>Clock B: [Node1: 2, Node2: 1, Node3: 1]</pre><pre>Check: 3 ≥ 2 and 2 ≥ 1 and 1 ≥ 1<br>Result: A is newer (B is ancestor)<br>Action: Discard B, keep A</pre><h3>🌍 Real World Use Cases</h3><h4>A. Shopping Carts (Amazon Dynamo)</h4><p><strong>Use Case</strong>: User adds items to cart from multiple devices simultaneously</p><p><strong>Why Vector Clocks</strong>:</p><ul><li>High availability is critical (can’t block shopping during network issues)</li><li>Cart merging is simple: union of items from all versions</li><li>False positives (showing duplicate items) are acceptable</li></ul><p><strong>Implementation</strong>:</p><ul><li>Each cart update increments the handling node’s counter</li><li>On read, merge all sibling carts</li><li>User sees all items they added from any device</li></ul><h4>B. Distributed Databases (Riak, Cassandra)</h4><p><strong>Riak</strong>: Uses vector clocks for conflict detection on every key</p><p><strong>Implementation</strong>:</p><ul><li>Each PUT operation updates vector clock</li><li>GET returns all siblings if conflicts exist</li><li>Application chooses resolution strategy:</li><li>Last-write-wins (simple but loses data)</li><li>Custom merge logic (e.g., CRDT-like merging)</li></ul><p><strong>Cassandra</strong>: Uses timestamps (Last-Write-Wins) by default, but allows application-level conflict resolution</p><h4>C. Collaborative Editing (Conceptual)</h4><p><strong>Problem</strong>: Multiple users editing same document offline</p><p><strong>Vector Clock Application</strong>:</p><ul><li>Track which operations each user has seen</li><li>Detect concurrent edits</li><li>Present conflicts to users for manual resolution</li></ul><p><strong>Note</strong>: Modern systems use CRDTs (Conflict-free Replicated Data Types) which automatically merge without conflicts</p><h4>D. Distributed File Systems (Ceph, GlusterFS)</h4><p><strong>Use Case</strong>: File metadata synchronization across replicas</p><p><strong>Why Vector Clocks</strong>:</p><ul><li>Detect when file modifications happened concurrently</li><li>Prevent accidental overwrites</li><li>Allow administrators to resolve conflicts manually</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce420e7910e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raft — Consensus]]></title>
            <link>https://medium.com/@saahid/raft-consensus-12e388c53f48?source=rss-15506854fe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/12e388c53f48</guid>
            <category><![CDATA[consensus-algorithm]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Saahid]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 08:03:12 GMT</pubDate>
            <atom:updated>2025-12-19T08:03:12.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raft — Consensus</h3><h3>The Motivation</h3><p>While Paxos guarantees safety, it is notoriously difficult to implement correctly. In 2014, Diego Ongaro and John Ousterhout published the Raft paper with a specific goal: <strong>Understandability</strong>.</p><p>Raft achieves the same fault tolerance as Paxos (N/2 + 1 quorum) but decomposes the problem into two separate, easier-to-manage sub-problems:</p><ol><li><strong>Leader Election</strong>: Select one distinguishable node as the Leader.</li><li><strong>Log Replication</strong>: The Leader accepts log entries from clients and replicates them across the cluster.</li></ol><h3>The “Strong Leader” Constraint</h3><p>Unlike Paxos (where any node can theoretically propose a value at any time), Raft enforces a stricter model:</p><ul><li><strong>Data Flow is Unidirectional</strong>: Data only flows from Leader → Followers.</li><li><strong>Leader Completeness</strong>: The system guarantees that if a node is elected Leader, it holds all previously committed entries.</li></ul><h3>The Three States</h3><p>At any given time, a node in Raft is in one of three states:</p><ol><li><strong>Follower</strong>: Passive. Responds to requests from Leaders and Candidates.</li><li><strong>Candidate</strong>: Active. Used to elect a new Leader.</li><li><strong>Leader</strong>: Active. Handles all client requests and replicates logs.</li></ol><h3>Raft Components</h3><h4>Terms</h4><ul><li><strong>Term</strong>: A logical clock (monotonically increasing integer) that divides time into periods</li><li>Each term begins with an election</li><li>At most one leader per term</li><li>Terms are used to detect stale information</li></ul><h3>Roles</h3><h4>1. Leader</h4><p><strong>Purpose</strong>: Manages log replication and handles all client requests</p><p><strong>Actions</strong>:</p><ul><li>Receives client requests</li><li>Appends entries to its log</li><li>Replicates entries to followers via AppendEntries RPC</li><li>Sends periodic heartbeats to maintain authority</li></ul><p><strong>Example</strong>: The active database master that processes writes</p><h4>2. Follower</h4><p><strong>Purpose</strong>: Passively replicates data from the leader</p><p><strong>Actions</strong>:</p><ul><li>Responds to AppendEntries from leader</li><li>Responds to RequestVote from candidates</li><li>Redirects client requests to leader</li><li>Times out and becomes candidate if no heartbeat received</li></ul><p><strong>Example</strong>: Database replicas waiting for updates</p><h4>3. Candidate</h4><p><strong>Purpose</strong>: Temporary state during leader election</p><p><strong>Actions</strong>:</p><ul><li>Increments term number</li><li>Votes for itself</li><li>Requests votes from other nodes</li><li>Becomes leader if receives majority votes</li><li>Returns to follower if discovers current leader or higher term</li></ul><p><strong>Example</strong>: Node competing to become the new leader</p><h3>Core Rules</h3><ol><li><strong>Election Safety</strong>: At most one leader per term</li><li><strong>Leader Append-Only</strong>: Leader never overwrites or deletes entries</li><li><strong>Log Matching</strong>: If two logs contain an entry with same index and term, all preceding entries are identical</li><li><strong>Leader Completeness</strong>: If a log entry is committed in a term, it will be present in all future leaders</li><li><strong>State Machine Safety</strong>: If a server applies a log entry at an index, no other server will apply a different entry for that index</li></ol><h3>🎯 Scenario 1: The Happy Path (Log Replication)</h3><p><strong>Context</strong>: Node A is the established Leader. Nodes B and C are Followers. The cluster is healthy.</p><h3>Steps</h3><ol><li><strong>Client Request</strong>: Client sends SET x=5 to Leader (Node A)</li><li><strong>Log Append</strong>: Node A writes entry to its local log (Status: Uncommitted)</li><li><strong>Replication</strong>: Node A sends AppendEntries messages to Followers (B and C)</li><li><strong>Acknowledgment</strong>: Nodes B and C write entry to their logs and reply “Success”</li><li><strong>Commit</strong>: Node A sees majority (itself + 1 other) has the entry</li></ol><ul><li>Marks entry as Committed</li><li>Executes it</li><li>Returns “Success” to client</li></ul><p>6<strong>. Notify Followers</strong>: In next heartbeat, Node A tells B and C the entry is committed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*2aVrsr45AbsWEPP55visNQ.png" /></figure><h3>Key Takeaways</h3><ul><li>Leader never commits entries from previous terms directly</li><li>Entries are committed when stored on a majority of servers</li><li>Followers learn about commits through AppendEntries heartbeats</li><li>Log replication is unidirectional: Leader → Followers only</li></ul><h3>⚡ Scenario 2: The Election (Leader Failure)</h3><p><strong>Context</strong>: Node A (Leader) crashes. Nodes B and C stop receiving Heartbeats.</p><h3>Steps</h3><ol><li><strong>Timeout</strong>: Node B’s “Election Timeout” expires first (randomized)</li><li><strong>State Change</strong>: Node B switches from Follower → Candidate</li></ol><ul><li>Increments Term to Term 2</li><li>Votes for itself</li></ul><p>3.<strong> Request Votes</strong>: Node B sends RequestVote RPCs to Node A (dead) and Node C</p><p>4.<strong> Vote Granted</strong>: Node C receives the request</p><ul><li>Check: “Is Term 2 &gt; my current Term?” (Yes)</li><li>Check: “Have I voted for anyone else in Term 2?” (No)</li><li>Reply: “Vote Granted”</li></ul><p>5. <strong>Victory</strong>: Node B receives the vote (has 2/3 votes = Majority)</p><p>6. <strong>Coronation</strong>: Node B becomes Leader and immediately sends Heartbeats to assert authority</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*9cQjWxBAMpph0qp-Eg62Uw.png" /></figure><h3>Key Takeaways</h3><ul><li>Election timeout is randomized (e.g., 150–300ms) to avoid split votes</li><li>Candidate needs majority of votes to become leader</li><li>Higher term numbers always take precedence</li><li>Nodes vote for at most one candidate per term (first-come-first-served)</li></ul><h3>🤝 Scenario 3: The Split Vote</h3><p><strong>Context</strong>: Leader dies. Nodes B and C timeout at the exact same time.</p><h3>Steps</h3><ol><li><strong>Simultaneous Rise</strong>: Both B and C become Candidates</li></ol><ul><li>Both increment to Term 2</li></ul><p>2. <strong>Self-Voting</strong>: B votes for B. C votes for C</p><p>3. <strong>The Deadlock</strong>:</p><ul><li>B asks C for vote; C rejects (already voted for C)</li><li>C asks B; B rejects (already voted for B)</li></ul><p>4. <strong>Result</strong>: No one gets majority (1 vote each). Election fails.</p><p>5. <strong>The Fix (Randomized Backoff)</strong>:</p><ul><li>Raft forces candidates to wait random time (e.g., 150ms–300ms)</li><li>Node C wakes up first, increments to Term 3, asks for votes</li><li>Node B sees Term 3 &gt; Term 2, concedes and votes for C</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*5VkrWZcmuitsFkbIOWeZDA.png" /></figure><h3>Key Takeaways</h3><ul><li>Split votes occur when multiple candidates start elections simultaneously</li><li>Randomized election timeouts prevent repeated split votes</li><li>Nodes always defer to higher term numbers</li><li>Elections are retried automatically until a leader emerges</li></ul><h3>🔄 Scenario 4: Log Consistency</h3><p><strong>Context</strong>: Node A was Leader but got partitioned. While alone, it accepted write “X=9” (Uncommitted). Meanwhile, Node B became new Leader and committed “X=10”. The partition heals.</p><h3>Steps</h3><ol><li><strong>The Conflict</strong>: Node A rejoins</li></ol><ul><li>Thinks it is Leader (Term 1)</li><li>Has data “X=9”</li></ul><p>2. <strong>The Discovery</strong>: Node B sends Heartbeat with Term 2</p><p>3. <strong>Step Down</strong>: Node A sees Term 2 &gt; Term 1</p><ul><li>Immediately steps down to Follower state</li></ul><p>4. <strong>Log Check</strong>: Node B sends AppendEntries saying &quot;My last entry is X=10&quot;</p><p>5. <strong>Truncation</strong>: Node A realizes its log (X=9) conflicts with Leader’s committed log (X=10)</p><p>6. <strong>Healing</strong>: Node A deletes uncommitted entry “X=9” and copies “X=10” from Node B</p><ul><li>Raft enforces: <strong>Leader is always right</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*ZZviC7bs5KBv6xmtcUn8mA.png" /></figure><h3>Key Takeaways</h3><ul><li>Uncommitted entries can be overwritten</li><li>Leader’s log is the source of truth</li><li>Followers always defer to the current leader’s log</li><li>This ensures all committed entries are preserved across leader changes</li></ul><h3>🌍 Real World Use Cases</h3><h4>1. Service Discovery &amp; Configuration</h4><p><strong>Etcd</strong>: The brain of Kubernetes. Uses Raft to store cluster state (which pods are running where). If the Raft leader fails, Kubernetes cannot schedule new pods until a new leader is elected.</p><p><strong>Consul</strong>: Uses Raft to maintain the list of active services in a microservice mesh.</p><p><strong>Real-World Systems</strong>:</p><ul><li><strong>Kubernetes (via Etcd)</strong>: Stores all cluster configuration and state</li><li><strong>Consul</strong>: Service mesh coordination</li><li><strong>Nomad</strong>: Job scheduling and orchestration</li></ul><h4>2. NewSQL Databases</h4><p><strong>CockroachDB / TiKV</strong>: These databases shard data into small chunks (Ranges). Each chunk is a miniature Raft cluster of 3 nodes. This allows them to scale horizontally while maintaining strong consistency.</p><p><strong>Real-World Systems</strong>:</p><ul><li><strong>CockroachDB</strong>: Distributed SQL database with Raft per range</li><li><strong>TiKV</strong>: Distributed key-value store (foundation of TiDB)</li><li><strong>YugabyteDB</strong>: PostgreSQL-compatible distributed database</li></ul><h4>3. Message Queues</h4><p><strong>Kafka (KRaft Mode)</strong>: Modern Kafka removed Zookeeper and replaced it with an internal Raft implementation (KRaft) to manage metadata partition leadership.</p><p><strong>Real-World Systems</strong>:</p><ul><li><strong>Kafka (KRaft)</strong>: Metadata management without Zookeeper</li><li><strong>RabbitMQ (Quorum Queues)</strong>: Raft-based queue replication</li><li><strong>NATS JetStream</strong>: Distributed streaming with Raft</li></ul><h3>📋 The Raft Protocol: Complete Reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiHaqKlYgLTWzugI6Oqj9Q.png" /></figure><h3>🧠 The Five Guarantees of Raft</h3><h4>1. Election Safety</h4><p><strong>Only one leader can be elected per term</strong></p><p>Why: Each node votes for at most one candidate per term. A candidate needs majority votes to win.</p><h4>2. Leader Append-Only</h4><p><strong>A leader never overwrites or deletes entries in its log</strong></p><p>Why: Leaders only append new entries. They never modify past entries.</p><h4>3. Log Matching</h4><p><strong>If two logs contain an entry with the same index and term, then all preceding entries are identical</strong></p><p>Why: Leaders send previous log index/term in AppendEntries. Followers reject if they don&#39;t match.</p><h4>4. Leader Completeness</h4><p><strong>If a log entry is committed in a term, it will be present in the logs of all leaders for all higher-numbered terms</strong></p><p>Why: Candidates with incomplete logs cannot win elections. Voters reject candidates whose logs are less up-to-date.</p><h4>5. State Machine Safety</h4><p><strong>If a server has applied a log entry at a given index to its state machine, no other server will ever apply a different log entry for the same index</strong></p><p>Why: Follows from Leader Completeness and the commit rules.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12e388c53f48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paxos — Consensus]]></title>
            <link>https://medium.com/@saahid/paxos-consensus-707dc608f8a3?source=rss-15506854fe01------2</link>
            <guid isPermaLink="false">https://medium.com/p/707dc608f8a3</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[consensus-algorithm]]></category>
            <dc:creator><![CDATA[Saahid]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 11:29:41 GMT</pubDate>
            <atom:updated>2025-12-17T11:32:38.423Z</atom:updated>
            <content:encoded><![CDATA[<h3>Paxos — Consensus</h3><h3>The Problem: Consensus in Asynchronous Systems</h3><h4>The Fundamental Challenge</h4><p>In distributed computing, we often replicate data across multiple servers (nodes) to ensure the system remains available even if some hardware fails. This architecture is known as <strong>State Machine Replication</strong>.</p><p>To maintain data integrity, every node in the cluster must agree on the same sequence of operations (e.g., “Write X”, then “Delete Y”) in the exact same order. This agreement is called <strong>Consensus</strong>.</p><h4>The Constraints (Why it is hard)</h4><p>Achieving consensus is trivial on a single machine. It becomes mathematically difficult in a distributed environment due to three inherent unreliabilities:</p><ol><li><strong>Asynchronous Networks</strong>: Messages sent between nodes may be arbitrarily delayed, dropped, duplicated, or reordered. There is no global clock to order these events reliably.</li><li><strong>Crash-Recovery Failures</strong>: Nodes may crash (stop processing) at any moment and potentially restart later with their memory wiped (relying only on disk storage).</li><li><strong>Network Partitions</strong>: The network may sever, creating isolated groups of nodes that cannot communicate with each other but are still running.</li></ol><h4>The Failure Scenario: “Split Brain”</h4><p>Without a rigorous consensus algorithm, a simple failure can lead to catastrophic data corruption:</p><p><strong>Scenario</strong>: A 3-node database cluster (N1, N2, N3) is writing to a log.</p><p><strong>The Event</strong>: A network glitch temporarily isolates the Leader (N1) from the others.</p><p><strong>The Divergence</strong>:</p><ul><li>N1 (thinking it is still the leader) accepts a write from Client A: SET balance = 100</li><li>N2 and N3 (thinking N1 is dead) elect a new leader and accept a write from Client B: SET balance = 0</li></ul><p><strong>The Result</strong>: The system has two contradictory “committed” states. When the network heals, the database is corrupted.</p><h4>The Solution: The Paxos Protocol</h4><p>Paxos is a fault-tolerant consensus protocol designed to solve this specific problem. It guarantees <strong>Safety (Consistency)</strong> under these conditions:</p><ol><li><strong>Validity</strong>: Only a value that was actually proposed can be chosen.</li><li><strong>Agreement</strong>: All nodes that decide on a value must decide on the same value.</li><li><strong>Termination</strong>: If a majority of nodes are accessible, a value will eventually be chosen.</li></ol><p>Paxos achieves this by separating the decision process into two phases: a <strong>Prepare Phase</strong> (to lock the cluster logically) and an <strong>Accept Phase</strong> (to write the value).</p><h3>🎯 Cluster of Nodes</h3><p>A distributed system with three nodes (Node A, Node B, Node C) that must agree on a single value.</p><h4>Components</h4><ul><li><strong>Nodes</strong>: Three servers (A, B, C) in a distributed cluster</li><li><strong>Proposal Numbers</strong>: Unique IDs that establish priority (higher numbers win)</li><li><strong>Value</strong>: The data that all nodes need to agree on</li></ul><h3>Paxos Roles</h3><p>Each node in Paxos can play one or more of these roles:</p><h4>1. Proposer</h4><p><strong>Purpose</strong>: Initiates consensus by proposing values</p><p><strong>Actions</strong>:</p><ul><li>Generates unique proposal numbers</li><li>Sends Prepare messages to acceptors</li><li>Sends Accept messages once promises are received</li></ul><p><strong>Example</strong>: In a leader election, a candidate node acts as proposer</p><h4>2. Acceptor</h4><p><strong>Purpose</strong>: Votes on proposals to achieve consensus</p><p><strong>Actions</strong>:</p><ul><li>Responds to Prepare with Promise (or rejects)</li><li>Accepts values in Accept phase (or rejects)</li><li>Persists accepted values to durable storage</li></ul><p><strong>Example</strong>: All nodes in the cluster typically act as acceptors</p><h4>3. Learner</h4><p><strong>Purpose</strong>: Learns which value was chosen</p><p><strong>Actions</strong>:</p><ul><li>Receives notifications when consensus is reached</li><li>Does not participate in voting</li><li>Can serve read requests with the chosen value</li></ul><p><strong>Example</strong>: Read replicas or client applications</p><p><strong>Note</strong>: In practice, a single node often plays all three roles simultaneously.</p><h3>Core Rules</h3><ol><li><strong>Unreliable Network</strong>: Messages can be lost or delayed</li><li><strong>Node Failures</strong>: Any node can crash at any time</li><li><strong>Majority Agreement</strong>: A value is chosen when a majority (2 out of 3) agrees</li><li><strong>Ordering</strong>: Higher proposal numbers always take precedence</li></ol><h3>The Paxos Protocol: Two Phases</h3><h4>Phase 1: Prepare/Promise</h4><p><strong>Proposer</strong> sends Prepare(n) with proposal number n</p><p><strong>Acceptors</strong> respond with:</p><ul><li>Promise(n) if n is higher than any previously promised proposal (includes any previously accepted values)</li><li>NACK (Negative Acknowledgment) if n is lower than a previously promised proposal</li></ul><h4>Phase 2: Accept/Accepted</h4><p><strong>Proposer</strong> sends Accept(n, value)</p><p><strong>Acceptors</strong> respond with:</p><ul><li>Accepted(n, value) if n matches their promise</li><li>NACK if they&#39;ve promised a higher proposal number</li></ul><p><strong>NACK (Negative Acknowledgment)</strong>: A rejection message indicating the proposal number is too low. The acceptor may include the higher proposal number it has promised, allowing the proposer to retry with an even higher number.</p><h3>🎯 Scenario 1: The Happy Path (Normal Success)</h3><p>Node A proposes value <strong>“Tax Cut”</strong>. Network is stable, no competing proposals.</p><h3>Steps</h3><ol><li>Node<strong> A generates proposal #100</strong></li><li>Node<strong> A </strong>sends<strong> </strong><strong>Prepare(100)</strong> to Nodes B and C</li><li>Nodes<strong> B </strong>and<strong> C </strong>respond<strong> </strong><strong>Promise(100) — </strong>No previously accepted values</li><li>Node<strong> A </strong>receives majority<strong> (2 out of 3)</strong></li><li>Node<strong> A </strong>sends<strong> </strong><strong>Accept(100, &quot;Tax Cut&quot;)</strong></li><li>Nodes<strong> B </strong>and<strong> C </strong>write value and respond <strong>Accepted(100)</strong></li></ol><p>✅ <strong>Result</strong>: Consensus achieved on “Tax Cut”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*5AvFEfXqz5xO7i-7ytoWjg.png" /></figure><h3>Key Takeaways</h3><ul><li>Paxos requires two round trips: Prepare/Promise and Accept/Accepted</li><li>In the happy path, Paxos completes in 2 RTT with no contention</li><li>This is the baseline performance when there are no failures or competing proposals</li></ul><h3>⚔️ Scenario 2: The Race Condition (Competing Proposals)</h3><p>Two nodes (A and B) simultaneously try to propose different values. Node A wants <strong>“Blue”</strong>, Node B wants <strong>“Red”</strong>.</p><h3>Steps</h3><ol><li>Node <strong>A</strong> sends <strong>Prepare(100) — </strong>Node <strong>C</strong> responds Promise(100)</li><li>Node <strong>B</strong> sends<strong> </strong><strong>Prepare(101)</strong> (higher proposal number)</li><li>Node<strong> C </strong>receives higher proposal<strong> #101 — </strong>Node <strong>C</strong> responds to <strong>B</strong>: Promise(101) , Breaks previous promise to A</li><li>Node <strong>A</strong> sends<strong> </strong><strong>Accept(100, &quot;Blue&quot;) — </strong>Node <strong>C</strong> rejects (already promised #101)</li><li>Node <strong>B</strong> sends <strong>Accept(101, &quot;Red&quot;) — </strong>Node <strong>C</strong> accepts and writes “Red”</li></ol><p>🏆 <strong>Result</strong>: Node B wins with higher proposal number</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*jna54sHqtGA7cm10HTiQeA.png" /></figure><h3>Key Takeaways</h3><ul><li>Higher proposal numbers always win</li><li>This prevents split-brain (two different values being committed)</li><li>Demonstrates liveness vs safety trade-off: safety is preserved, but rejected proposers must retry</li><li>Failed proposers generate higher proposal numbers and restart the process</li></ul><h3>Node A Recovery</h3><ol><li>Detects rejection (NACK or timeout)</li><li>Generates higher proposal number (#102)</li><li>Retries Prepare phase</li><li>Must adopt existing value “Red” if already chosen</li></ol><h3>👻 Scenario 3: Node Failure After Promise</h3><p>Node A receives promises but crashes before sending the accept message. System is blocked until recovery.</p><h3>Steps</h3><ol><li>Node <strong>A</strong> gets<strong> </strong><strong>Promise(100) </strong>from<strong> B </strong>and<strong> C</strong></li><li><strong>💥 </strong>Node <strong>A</strong> crashes</li><li>Nodes <strong>B</strong> and <strong>C</strong> wait <strong>— </strong>Locked on proposal #100, No value arrives</li><li>Node <strong>C</strong> times out (e.g., 5 seconds) <strong>— </strong>Generates higher proposal #200</li><li>Node <strong>C</strong> sends<strong> </strong><strong>Prepare(200) </strong>to Node <strong>B — B</strong> responds: Promise(200) (no value for #100)</li><li>Node <strong>C</strong> sends<strong> </strong><strong>Accept(200, &quot;New Value&quot;) — </strong>System recovers</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*IDyN3ycNvHJtCZnLhNbrTA.png" /></figure><h3>Key Takeaways</h3><ul><li>Timeouts enable recovery from failures</li><li>Any node can propose with a higher number to break deadlock</li><li>Paxos is wait-free: no single node failure permanently blocks progress</li><li>Leadership can transfer to any node through the timeout mechanism</li></ul><h3>Configuration</h3><ul><li><strong>Timeout</strong>: 5–10 seconds</li><li><strong>Retry</strong>: Exponential backoff</li><li><strong>Heartbeat</strong>: Periodic proposal refresh</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707dc608f8a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>