<?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 ranga_vamsi on Medium]]></title>
        <description><![CDATA[Stories by ranga_vamsi on Medium]]></description>
        <link>https://medium.com/@rangavamsi5?source=rss-58562903b723------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*8RcKyNFf-SOUkg6Uj7xz-g.jpeg</url>
            <title>Stories by ranga_vamsi on Medium</title>
            <link>https://medium.com/@rangavamsi5?source=rss-58562903b723------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:26:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rangavamsi5/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[Consistent Hashing]]></title>
            <link>https://medium.com/@rangavamsi5/consistent-hashing-a5b3f4ef4149?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b3f4ef4149</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[consistent-hashing]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 14:51:58 GMT</pubDate>
            <atom:updated>2025-01-13T14:51:58.607Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Keeping Things Even in Distributed Systems</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K-Ym0gd6mxMgD5_A" /><figcaption>Photo by <a href="https://unsplash.com/@chloechristinemarketing?utm_source=medium&amp;utm_medium=referral">Chloe Christine</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Picture a scenario where you run a large e-commerce platform with thousands of products and millions of users. Every time someone searches for a product or adds an item to their cart, you need to retrieve the information quickly and efficiently. However, as your user base grows and traffic spikes during sale events, managing this data becomes increasingly complex.</p><p>One of the biggest challenges is <strong>how to distribute the workload across multiple servers effectively</strong>. Traditional data distribution methods can lead to problems like uneven load balancing and costly data migrations when servers are added or removed. This can result in slow response times and frustrated users, which is the last thing you want when you’re trying to keep your customers happy.</p><p>So, how can we create a system that effortlessly adjusts to these changes? How can we ensure that as servers come and go, the data remains accessible and balanced?</p><h3>The Challenge</h3><p>In any system where data needs to be distributed across multiple servers, the key challenge is <strong>how to efficiently assign data to those servers</strong>.</p><p>Initially, this might seem like a simple task. Let’s say you have a set of servers, and you’re assigning user data (like session info, shopping cart contents, or cached pages) to those servers. A common approach is to use a <strong>hash function </strong>to map each piece of data to a specific server. For example, you could hash a user’s ID and use that value to determine which server stores their data.</p><p>This approach works fine when your system is stable and the number of servers is constant. But as your applications grows, you’ll inevitably run into some real-world challenges:</p><h4>The Impact of Adding or Removing Servers: Rehashing</h4><p>Let’s say your e-commerce platform is doing a big sale, and you need to add more servers to handle the traffic. In a traditional hash-based system, adding just one new server means <strong>redistributing most of your existing data</strong> across all the servers. This is because your hash function will now map the data differently with the new set of servers, and nearly all previous assignments will break, <strong>forcing a massive data migration</strong>. This is expensive, time-consuming, and can lead to service disruptions.</p><p>Likewise, when you remove a server — whether it’s for maintenance or due to a hardware failure — you again face the the issue of reassigning data, leading to similar disruptions.</p><p><em>For example, let’s say we have 3 Servers S1, S2, S3, and hash function as </em><strong>server = hash(key) mod N</strong><em>, where N is the size of the pool, and the distribution looks as below:</em></p><pre>Name       Hash     Server(Hash%3)<br>john       89           2(S3)<br>cook       30           0(S1)<br>adam       47           2(S3)<br>smith      52           1(S2)<br>alex       75           0(S1)<br>bob        22           1(S2)</pre><p><em>Now, imagine that one server, </em><strong><em>S3</em></strong><em>, crashes and is no longer able to accept requests. If you use the same hash function but only have 2 servers left (S1 and S2), the data distribution would change as follows:</em></p><pre>Name       Hash      Server(Hash%2)<br>john       89            1(S2)<br>cook       30            0(S1)<br>adam       47            1(S2)<br>smith      52            0(S1)<br>alex       75            1(S2)<br>bob        22            0(S1)</pre><p><em>As you can see, </em><strong><em>most of the keys are remapped (</em></strong><em>not only for the keys from S3), even though only one server was removed. This constant remapping of data with every change in the server pool leads to instability and inefficiency.</em></p><h4>Load Imbalance: Hotspots</h4><p>Another common issue is<strong> Load Balancing</strong>. If your hash function doesn’t distribute data evenly across servers, you might have some servers working harder than others. This creates <strong>hotspots</strong>, where some servers become overloaded while others sit idle. The result? Some users experience lag, while others don’t, leading to an inconsistent experience.</p><p>These two major challenges — <strong>data rebalancing</strong> when servers are added/removed, and <strong>uneven data distribution</strong> — payed the way for the solution: <strong>Consistent Hashing. </strong>Let’s see this through a scalable distributed system.</p><h3>Building a Content Delivery Network (CDN)</h3><p>Say, we are building a CDN system where clients can request and fetch various types of content like images, videos, and documents. The service exposes the following APIs to users:</p><ul><li><strong>/upload</strong> to upload the content</li><li><strong>/fetch</strong> to fetch and return the content</li></ul><p>Behind the scenes, the CDN has multiple <strong>Cache Servers</strong> on which the content is stored and accessed. These servers expose functions like <strong>store_content</strong> and <strong>fetch_content</strong> that save the content and retrieve it from the disk. When a client makes a request, these functions are invoked, and the CDN server sends the response back to the main API server, which then forwards it to the client.</p><pre>class CacheServer:<br>    def __init__(self, server_id):<br>        self.server_id = server_id<br>        self.storage = {}<br><br>    def store_content(self, content_id, content):<br>        self.storage[content_id] = content<br>        print(f&quot;Content &#39;{content_id}&#39; - Server {self.server_id}&quot;)<br><br>    def fetch_content(self, content_id):<br>        return self.storage.get(content_id, None)</pre><p>To handle the initial load, the system starts with <strong>3 Cache Servers</strong>. These servers store content in a distributed manner, ensuring that the storage is evenly spread across the system. By distributing content, no single server is overwhelmed with too much traffic.</p><p>When the client invokes the <strong>upload</strong> function, the system first needs to identify which cache server will be responsible for storing the content. To do so, we use a<strong> hash function </strong>on the content identifier (eg., file name, URL) to get a numeric value. This value determines the index of the cache server that will hold the content. The hash function used here takes the hash of the content ID, and applies a modulo operation with the number of server (eg., 3). This gives an index in the range of [0,2]. Once we know the cache server, we store the content there using the <strong>store_content</strong> function.</p><pre>import hashlib<br><br>class CDNApplication:<br>    def __init__(self, num_servers):<br>        self.servers = [CacheServer(i) for i in range(num_servers)]<br><br>    def hash_function(self, content_id):<br>        # Hash function: hash the content and modulo by number of servers<br>        hash_value = int(hashlib.md5(content_id.encode()).hexdigest(), 16)<br>        return hash_value % len(self.servers)<br><br>    def upload(self, content_id, content):<br>        server_index = self.hash_function(content_id)<br>        server = self.servers[server_index]<br>        server.store_content(content_id, content)<br><br>    def fetch(self, content_id):<br>        server_index = self.hash_function(content_id)<br>        server = self.servers[server_index]<br>        content = server.fetch_content(content_id)<br>        if content:<br>            print(f&quot;Content &#39;{content_id}&#39; retrieved from server {server_index}&quot;)<br>            return content<br>        else:<br>            print(f&quot;Content &#39;{content_id}&#39; not found.&quot;)<br>            return None</pre><p>Say we have 5 content items: image_1 , video_1 , doc_1 , audio_1 , and image_2 . If we apply the hash function to these items, they will be distributed across the cache servers as follows:</p><pre>cdn = CDNApplication(3)<br><br># Uploading files to the CDN<br>cdn.upload(&#39;image_1&#39;, &#39;This is image 1&#39;)<br>cdn.upload(&#39;video_1&#39;, &#39;This is video 1&#39;)<br>cdn.upload(&#39;doc_1&#39;, &#39;This is doc 1&#39;)<br>cdn.upload(&#39;audio_1&#39;, &#39;This is audio 1&#39;)<br>cdn.upload(&#39;image_2&#39;, &#39;This is image 2&#39;)<br><br>print(&quot;\n&quot;)<br><br># Fetching files from the CDN<br>cdn.fetch(&#39;image_1&#39;)<br>cdn.fetch(&#39;video_1&#39;)<br>cdn.fetch(&#39;doc_1&#39;)<br>cdn.fetch(&#39;audio_1&#39;)<br>cdn.fetch(&#39;image_2&#39;)</pre><p><strong>The Output will look like this: </strong>python3 traditional_hashing.py</p><pre>Content &#39;image_1&#39; - Server 2<br>Content &#39;video_1&#39; - Server 1<br>Content &#39;doc_1&#39; - Server 2<br>Content &#39;audio_1&#39; - Server 2<br>Content &#39;image_2&#39; - Server 2<br><br>Content &#39;image_1&#39; retrieved from server 2<br>Content &#39;video_1&#39; retrieved from server 1<br>Content &#39;doc_1&#39; retrieved from server 2<br>Content &#39;audio_1&#39; retrieved from server 2<br>Content &#39;image_2&#39; retrieved from server 2</pre><h4>The Problem: Scaling Up or Down</h4><p>Now, let’s say the system gains popularity, and we need to add <strong>more cache servers</strong> to handle the growing traffic. We will add <strong>2 new servers</strong>, making a total of <strong>5 Cache Servers</strong>. This means we need to change the hash function to use modulo 5 (instead of 3), so we can distribute content across all 5 servers.</p><p>However, changing the hash function causes a problem: the mapping of content to servers will change drastically. Even though we only added 2 new servers, the hash function now remaps almost all content to different servers.</p><p><strong>Output after rehashing:</strong></p><pre>Content &#39;image_1&#39; - Server 3<br>Content &#39;video_1&#39; - Server 0<br>Content &#39;doc_1&#39; - Server 3<br>Content &#39;audio_1&#39; - Server 0<br>Content &#39;image_2&#39; - Server 3<br><br>Content &#39;image_1&#39; retrieved from server 3<br>Content &#39;video_1&#39; retrieved from server 0<br>Content &#39;doc_1&#39; retrieved from server 3<br>Content &#39;audio_1&#39; retrieved from server 0<br>Content &#39;image_2&#39; retrieved from server 3</pre><p>As you can see, <strong>every single piece of content </strong>has been assigned to a new cache server. This requires <strong>moving all the existing content </strong>to new servers, which is highly inefficient and disruptive. Not only does this cause downtime during the migration, but it also consumes a lot of network resources to move data between servers.</p><h4>What Do We Need to Mitigate This Problem?</h4><p>We need a solution that minimises data movement when scaling the system. In a ideal world, when adding or removing servers, only a small portion of the content should need to be moved. This is where <strong>Consistent Hashing </strong>comes into play.</p><h3>The Need for Consistent Hashing</h3><p>In traditional hashing systems, the association between content and servers (or storage nodes) <strong>depends directly</strong> on the <strong>hash function</strong> and the <strong>number of available servers</strong>. This dependency becomes problematic during scale-up or scale-down operations, as even minor changes in the number of servers can lead to significant reshuffling of data, causing inefficiency and instability in the system.</p><blockquote>Traditional hashing systems suffer from a rigid dependency on both the hash function and the number of servers, leading to widespread data remapping during scaling events.</blockquote><h4>How It Solves the Problem</h4><p>Consistent hashing solves the scaling issue by <strong>decoupling the hash function from the number of servers</strong>. Instead of depending on server count, the system operates within a fixed, large hash space (like <strong>[0, 2^128–1]</strong>), mapping both servers and content into this space.</p><p>Content is then associated with the <strong>closest server moving clockwise</strong> in this space. This approach allows the system to maintain the <strong>same relative distribution of content</strong>, regardless of how many servers are added or removed.</p><h4>Naive Implementation: A Circular Array</h4><p>A straightforward implementation of consistent hashing could involve creating a large array representing the hash space, with servers and content directly placed at their corresponding hash positions. When searching for the correct server for a content item, you would iterate from the content’t hash position to the right, looking for the next available server. If no server is found by the end of the array, the search wraps to the start of the array. While this approach is simple, it suffers from two major drawbacks:</p><ul><li><strong>Memory Overhead:</strong> Requires a massive array for representing the entire hash space.</li><li><strong>Time Complexity: </strong>Searching for the nearest server by iterating through the array is inefficient and can take <strong>O(hash_space)</strong> time in the worst case.</li></ul><h4>Optimised Implementation: Two Sorted Arrays</h4><p>A more efficient implementation uses two sorted arrays. One array <strong>nodes[]</strong> holds the server identifiers, while the other <strong>keys[]</strong> stores the hash positions of these servers. The two arrays are sorted based on the server hash positions.</p><p><em>For example, if we have 3 servers (Server A, B and C) and their hash values are </em><em>20 , </em><em>60 and </em><em>120 respectively, then:</em></p><pre>nodes[] = [A, B, C]<br>keys[] = [20, 60, 120] // SORTED order</pre><h4><strong>How Lookup Works:</strong></h4><ul><li>We hash the content to determine its position in the hash space.</li><li>We then use <strong>binary search</strong> on the <strong>keys[]</strong> array to quickly find the nearest server hash that is greater than or equal to the content’s hash value.</li></ul><p><em>For example, if the content hashes to </em><em>65 , we perform a binary search on </em><em>keys[] and find that </em><em>60 is the closest position on the left, and </em><em>120 is the next position. Therefore, Server C (at position </em><em>120) will store the content.</em></p><p>The optimised approach offers<strong> “faster lookup”</strong> by using binary search to find the correct server in <strong>O(log n)</strong> time, significantly improving efficiency compared to iterating every slot. Additionally, it uses “<strong>less memory”</strong> by only storing the hash positions of servers, avoiding the need for a large array to represent the entire hash space.</p><h3>Hash Function in Consistent Hashing</h3><p>In consistent hashing, the hash function is integral to how data is distributed among servers, ensuring that the system remains efficient and adaptable during scaling. We define a <strong>hash space</strong> that is typically very large, such as <strong>2^256</strong> , which allows both data and server identifiers to be consistently mapped.</p><p>The hash function can be implemented using a hashing algorithm like <strong>SHA-256</strong> , followed by a modulo operation with the size of the hash space.</p><pre>import hashlib<br><br>def hash_fn(key: str, hash_space_size: int) -&gt; int:<br>    &quot;&quot;&quot;<br>    Generates an integer hash value for a given key using SHA-256,<br>    followed by a modulo operation with the size of the hash space.<br>    &quot;&quot;&quot;<br>    hsh = hashlib.sha256()<br>    hsh.update(key.encode(&#39;utf-8&#39;))<br>    return int(hsh.hexdigest(), 16) % hash_space_size</pre><p>By utilising a constant, expansive hash space, the function operates without being affected by changes in server count.</p><h3>Initial Setup of Algorithm</h3><p>We need to first set up the nodes in the hash space. This step is key as it defines how data will be evenly distributed across the system.</p><h4>1. Define the Hash Space</h4><p>Imagine the hash space as a <strong>large circular “ring”</strong> where every position is a unique point in a defined range, typically from 0 to some large number. <em>For example, if we define our hash space to have 256 positions, each node and each item will map to one of these positions, ranging from </em><em>0 to </em><em>255 .</em></p><p>The <strong>size</strong> of the hash space — <strong>determines how finely we can distribute both nodes and items</strong>, so choosing a large enough space ensures we minimise collisions and distribute data evenly. A common practice is to use a power of two, like 2^8 (256 positions), 2^16 (65536 positions), etc.</p><h4>2. Hash Each Node</h4><p>Each node in the system (such as a server or storage instance) needs to be placed somewhere on this hash ring. But how do we decide where a node goes? This is where the <strong>hash function </strong>comes in.</p><p>The hash function takes the unique identifier of a node (like its name, IP address, or any unique string) and produces a number that represents the node’s position on the hash ring.</p><p><em>For example, Node A, B and C might get hashed to positions 39, 170 and 136 respectively.</em></p><h4>3. Insert Nodes into the Hash Ring</h4><p>Once we’ve hashed the nodes and determined their positions. We ned to store these positions in a sorted list. This makes the process of finding the correct node for any item efficient, as we’ll be able to use binary search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*TwCI4gyAoSYCR3ZSwcyEDg.png" /><figcaption>Initial Hash Ring</figcaption></figure><h3>Associating an Item to a Node</h3><p>Now that we have the nodes set up on our hash ring, the next step is to figure out how to associate an item (like a piece of content or a user request) with one of the nodes in the system.</p><h4>1. Hash the Item</h4><p>Just like we did with the nodes, we first hash the item. The hash function takes some unique aspect of the item, such as its ID, and generates a number that represents its position on the hash ring. This could be anything — a file name, user ID, or content key — depending on what you’re storing.</p><p><em>For example, let’s say we hash an item called </em><em>video_1 , and it lands at position </em><strong><em>58</em></strong><em>on the ring.</em></p><h4>2. Find the Nearest Node</h4><p>Once we know where the item falls on the ring, the next task is to find the node that will store and serve the item. We want to assign the item to the first node that appears to the right (<strong>clockwise</strong>) of the item’s position.</p><p>To do this, we perform a binary search on the list of node positions (which we keep sorted). This allows us to efficiently find the node that is closest but greater than the item’s hashed position.</p><p><em>For example, if the item lands at position </em><em>58, and the nodes are at positions </em><em>39, </em><em>136and </em><em>170, then the node at position </em><em>136will be the one to handle this item.</em></p><pre># binary search<br>def _find_insert_position(self, position: int) -&gt; int:<br>    &quot;&quot;&quot;Finds the index where the new node should be inserted.&quot;&quot;&quot;<br>    low, high = 0, len(self.keys)<br>    while low &lt; high:<br>        mid = (low + high) / 2<br>        if self.keys[mid] &lt; position:<br>            low = mid + 1<br>        else:<br>            high = mid<br>    return low</pre><p>If the item’s hash value is higher than the last node on the ring (say it hashes to 250, and the highest node position is 170), the item wraps around and is assigned to the first node in the list. <em>In our example, that would be the node at position </em><em>39.</em></p><p>This process of finding the correct node is extremely efficient because it relies on binary search, which operates in <strong>O(log n</strong>) time, where <strong>n</strong> is the number of nodes.</p><pre>def assign_item(self, item: str) -&gt; str:<br>    # Hash the item to determine its position in the hash space<br>    position = hash_fn(item, self.hash_space_size)<br>    index = self._find_insert_position(position) % len(self.keys)<br>    return self.nodes[index]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRESdGByjdzUzYiYuJw6RQ.png" /></figure><h3>Scaling Up: Adding a New Node</h3><p>What happens when we want to add new node to our hash ring?</p><h4>1. Determine the Node’s Position</h4><p>Start by hashing the new node’s identifier (such as its name or IP address) using the same hash function we’ve implemented. This hash will determine the position of the new node on the hash ring.</p><p><em>For example, if we add a new node </em><em>Node D , and the hash function places it at position </em><em>121 on the ring.</em></p><h4>2. Insert the Node into the Hash Ring</h4><p>Once we have the node’s position, we insert it (only if it doesn’t already exist) into our list of nodes and keep the list sorted based on the hashed positions.</p><pre>def add_node(self, node: str):<br>    # Hash the new node to find its position in the hash space<br>    position = hash_fn(node, self.hash_space_size)<br><br>    if node in self.nodes:<br>        raise Exception(f&quot;Node &#39;{node}&#39; already exists in the system.&quot;)<br><br>    # Handle edge case when there are no nodes<br>    if not self.keys:<br>        self.nodes.append(node)<br>        self.keys.append(position)<br>        print(f&quot;Added first node: {node} at position: {position}&quot;)<br>        return<br><br>    # Use binary insertion to keep keys sorted<br>    index = self._find_insert_position(position)<br>    self.nodes.insert(index, node)<br>    self.keys.insert(index, position)<br>    print(f&quot;Added node &#39;{node}&#39; at position {position}&quot;)<br><br>    # Reassign affected data<br>    self.reassign_data(index)</pre><h4>3. Reassign Data</h4><p>After adding the new node, we need to adjust the key ranges of the existing nodes. This includes items whose hashed values fall between the new node’s position and the position of the next node in the <strong>anti-clockwise</strong> direction.</p><p><strong>The best part? </strong>All the other nodes and their content stay exactly where they are, meaning you don&#39;t have to worry about a major data shuffle.</p><p><em>In our example,</em></p><pre>Node A: Handles the range 0–39, 171-255<br>Node B: Handles the range 137–170<br>Node C: Handles the range 40-136</pre><p><em>When we add Node D at position 121, the ranges would adjust as follows:</em></p><pre>Node A: 0–39, 171-255 (remains unchanged)<br>Node B: 137–170 (remains unchanged)<br>Node D: 40–121 (new range assigned)<br>Node C: 122–136 (updated range)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjW9HAZBvI6eg_cHtDcaZQ.png" /></figure><h3>Scaling Down: Removal of a Node</h3><p>Suppose if we want to remove a node — be it due to maintenance, upgrades or unexpected failures from a hash ring</p><h4>1. Identify the Node’s Position</h4><p>When we decide to remove a node, the first step is to identify which node we want to remove (let’s say <strong>Node B</strong>). We then hash its identifier to determine its position on the hash ring.</p><p><em>In our example, the </em><em>Node B is hashed at position </em><em>170 on the ring.</em></p><h4>2. Remove the Node from the Hash Ring</h4><p>After locating the node’s position, remove it from the list of nodes. Ensure the list remains sorted based on the hashed positions after the removal.</p><pre>def remove_node(self, node: str):<br>    if node not in self.nodes:<br>        raise Exception(f&quot;Node &#39;{node}&#39; does not exist in the system.&quot;)<br><br>    # Hash the node to find its position in the hash space<br>    position = hash_fn(node, self.hash_space_size)<br>    index = self.keys.index(position)<br><br>    # Determine the next node in the clockwise direction<br>    next_node_index = (index + 1) % len(self.keys)<br>    next_node_position = self.keys[next_node_index]<br><br>    # Reassign affected data<br>    self.reassign_data(index)<br><br>    # Remove the node and its position<br>    self.nodes.pop(index)<br>    self.keys.pop(index)<br>    print(f&quot;Removed node &#39;{node}&#39; from position {position}&quot;)</pre><h4>3. Reassign Data</h4><p>Next, we need to adjust the key ranges of the remaining nodes. This includes reassigning items whose hashed values fell within the range that the removed node used to handle.</p><p><em>If our existing nodes are:</em></p><pre>Node A: Handles the range 0–39, 171-255<br>Node B: Handles the range 137–170<br>Node C: Handles the range 122–136<br>Node D: Handles the range 40–121</pre><p><em>Removing the Node B at position will leave us with:</em></p><pre>Node A: 0–39, 137-255 (updated range)<br>Node C: 122–136 (remains unchanged)<br>Node D: 40–121 (remains unchanged)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XE13F6fn9WkMPoHFHWaIoQ.png" /></figure><p>In our <strong>hash ring algorithm</strong>, nodes are dynamically managed by hashing their identifiers to determine their positions, ensuring a balanced distribution of responsibilities. When adding a new node, existing nodes adjust their key ranges accordingly, while the removal of a node triggers the reassignment of its range to neighbouring nodes. Items are associated with nodes by hashing their identifiers and assigning them to the nearest node in a clockwise direction. This efficient approach utilises binary search for quick node location, minimising data movement during updates.</p><p>The source code implementation in Python can be found <a href="https://gist.github.com/vamc-stash/7f472ade79e9f66e1423cd6861601b13"><strong>here</strong></a><strong>.</strong></p><h3>More About Consistent Hashing</h3><h4>Average Number of Keys</h4><p>When we think about how keys are distributed across our nodes, there’s a simple way to look at it: on average, each node holds about <strong>k/N</strong> keys, where <strong>k</strong> is the total number of keys and <strong>N</strong> is the number of nodes. This means that if we have a good number of nodes and keys, each one gets its fair share, which helps keep things running smoothly. By spreading the keys evenly, we not only improve retrieval times but also reduce the chances of overloading any single node. It’s all about balance in our system!</p><h4>Virtual Nodes</h4><p>In a consistent hash ring, it’s possible for nodes to become <strong>unevenly distributed</strong>. When this happens, nodes that experience a high volume of traffic can turn into hotspots, potentially leading to <strong>cascading failures</strong> throughout the system.</p><p>To tackle this challenge, we use “<strong>virtual nodes”</strong>. By hashing the node Ids with different hash functions, we assign <strong>each physical node to multiple positions on the hash ring</strong>.</p><p>The number of virtual positions assigned to each node is based on its capacity — <strong>more powerful nodes get assigned more positions</strong>. This way, we can optimise resource utilisation and ensure that no single node bears the brunt of the workload.</p><p>Additionally, to minimise data movement when a node crashes or when a new node is added, data objects <strong>can be replicated to adjacent nodes</strong>. This replication strategy enhances the system’s resilience and responsiveness.</p><h4>Self-Balancing Binary Search Tree</h4><p>When it comes to implementing consistent hashing, a self-balancing binary search tree (BST) is our go-to data structure for storing the positions of nodes on the hash ring.</p><p>Now, where do we store this BST? One option is to keep it on a centralised, highly available service. Alternatively, we can store the BST on each node itself, with state information synchronised across the nodes using a Gossip protocol.</p><p>A better explanation can be found <a href="https://highscalability.com/consistent-hashing-algorithm/"><strong>here</strong></a>.</p><h3>Few Examples</h3><h4>1. CDNs</h4><p>CDNs, such as <strong>Akamai</strong> and <strong>Cloudflare</strong>, use consistent hashing to distribute content across multiple edge servers. When a user requests a specific piece of content, the hash of that content can determine which server should serve it.</p><h4>2. Distributed Databases (e.g., Amazon DynamoDB)</h4><p>Amazon DynamoDB, a fully managed NoSQL database service, employs consistent hashing to distribute data across multiple partitions. Each item in the database is hashed to determine its partition location, which helps in efficiently balancing the load. If the workload increases and new partitions are added, consistent hashing ensures that only a small number of items need to be moved to maintain balance across the system.</p><h4>3. Peer-to-Peer Networks (e.g., BitTorrent)</h4><p>In peer-to-peer networks like BitTorrent, consistent hashing helps manage data distribution among peers. Each piece of a file is assigned a unique hash, and peers use these hashes to locate and share data efficiently.</p><h4>4. Microservices Architecture</h4><p>In modern micro-services architectures, consistent hashing can be used for routing requests to different service instances. For instance, when a user makes a request, the request’s identifier can be hashed to determine which service instance should handle it.</p><h3>Consistent Hashing Optimisations</h3><p>Some of the popular variants of Consistent Hashing:</p><h4>1. Multi-Probe Consistent Hashing</h4><p>In this approach, each node has a single position on the hash ring, eliminating the need for virtual nodes. While it offers a linear space complexity of <strong>O(n)</strong> for storing node positions, it excels in efficiency with constant <strong>O(1)</strong> time complexity for adding or removing nodes.</p><p>The idea is to hash the data object multiple times using different hash functions, allowing us to find the closest node in a clockwise direction for data retrieval. However, keep in mind that key lookups can be a bit slower.</p><h4>2. Consistent Hashing with Bounded Loads</h4><p>This variant introduces an upper limit on the load a node can handle, based on the average load across the hash ring. This means that while nodes generally distribute requests evenly, when one node gets overloaded, incoming requests can be redirected to a designated fallback node.</p><p>What’s cool is that these fallback nodes are consistent for the same request hash, so the same “second choice” nodes handle popular items. If a node overloads, requests can then spread across multiple fallback nodes, rather than overwhelming a single one.</p><h3>The Yin and Yang of Consistent Hashing</h3><p>On the plus side, it’s incredibly scalable. we can <strong>easily add or remove nodes</strong> without causing major disruptions, as only a small fraction of keys needs to be redistributed. This feature also helps with<strong> load balancing</strong> since it distributes keys evenly across nodes, preventing any single node from becoming a hotspot and ensuring a more balanced workload.</p><p>Another benefit is its<strong> fault tolerance</strong>. If a node fails, only the keys assigned to that node need to be reassigned, which enhances reliability and minimises the risk of data loss.</p><p>However, it’s not without its complexities. Implementing consistent hashing <strong>can be trickier than simpler hashing techniques</strong>, especially when introducing virtual nodes to manage the distribution of keys. While these virtual nodes improve load balancing, they can also <strong>add overhead in terms of memory and processing</strong>.</p><p>Additionally, if certain keys are accessed far more frequently than others, we <strong>might still end up with uneven load distribution</strong>, which can lead to some nodes being overloaded. Lastly, in some variations, like multi-probe consistent hashing, the process of looking up keys can become slower since it requires multiple hashing attempts to find the nearest node.</p><h3>In Conclusion</h3><p><em>By minimising data movement during node changes and allowing for dynamic load balancing, it addresses many challenges associated with traditional hashing methods. However, it’s essential to remain aware of its limitations, such as potential hotspots and the complexity of implementation.</em></p><p>Thanks for your time, and happy learning!</p><h3>References</h3><ul><li><a href="https://highscalability.com/consistent-hashing-algorithm/">Consistent hashing algorithm - High Scalability -</a></li><li><a href="https://arpitbhayani.me/blogs/consistent-hashing/">Consistent Hashing - explanation and implementation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b3f4ef4149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counting the Uncountable]]></title>
            <link>https://medium.com/@rangavamsi5/counting-the-uncountable-02fbe979cbab?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/02fbe979cbab</guid>
            <category><![CDATA[probabilistic-computing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[hyperloglog]]></category>
            <category><![CDATA[estimations]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 18:10:57 GMT</pubDate>
            <atom:updated>2025-01-10T18:10:57.810Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The Mechanics of View Counts</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cApwLyoRzbAp8fRZ" /><figcaption>Photo by <a href="https://unsplash.com/@barefootcommunications?utm_source=medium&amp;utm_medium=referral">Barefoot Communications</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you’re scrolling through your favourite social media platform and come across a video or post that’s gone viral. The view count is skyrocketing, climbing into the millions within minutes. Ever wondered how platforms like Reddit, YouTube, Instagram, Twitter and Google manage to <strong>calculate these view counts so quickly, especially when millions of users are engaging simultaneously?</strong></p><h3>The Complexity of Counting a Viewˀ</h3><p>On the surface, counting views <strong>might seem straightforward</strong> — just increase the counter every time someone watches a video or reads a post. However, the <strong>reality is far more complex</strong>. Platforms <strong>must ensure</strong> that views are <strong>unique</strong>, <strong>avoid</strong> bots and fake engagements, and handle millions of requests per second without crashing.</p><p>While designing such a sophisticated system, we must take into certain requirements into considerations to ensure its effectiveness and reliability.</p><ul><li><strong>Real-time Updates:</strong> First, the counts must be updated in<strong> </strong>real-time or near-real-time, avoiding reliance on aggregated data that updates hourly or daily.</li><li><strong>Unique User Counts: </strong>It’s essential that each user should only be counted once within a short time window to <strong>prevent inflated numbers</strong>.</li><li><strong>Accuracy:</strong> The displayed count needs to be highly accurate, closely matching the actual view count within a <strong>small margin of error</strong>.</li><li><strong>Scalability: </strong>Moreover, the system must operate efficiently at a production scale, processing vast amounts of data within seconds, all while keeping operational costs in check.</li></ul><h3>From Click to Count</h3><ol><li><strong>Triggering a View Event: </strong>The first step in counting a view is detecting the user’s interaction. This can range from simply loading a video to more specific criteria, such as watching it for a certain duration (e.g., YouTube often requires users to watch for a few seconds before counting it as a view)</li><li><strong>Filtering and Validation:</strong> Not all interactions are counted. Platforms need to filter out bots, duplicate views from the same user within a short time frame, and other forms of non-genuine engagement. This involves analysing user behaviour, checking IP addresses, and sometimes using machine learning to detect unusual patterns.</li><li><strong>Updating the View Count:</strong> Once a valid view is detected, the platform must update the view count. This might seem straightforward, <strong>but when millions of views are happening simultaneously</strong>, the system must ensure that these updates are <strong>synchronised across all servers</strong> and visible to users in real time.</li></ol><h3>Mechanics of Counting Views</h3><h3>1. HashSet</h3><p>In this approach, a Direct Mapping table is used to track user interactions with posts or videos.</p><p>Each entry in the table includes a composite key with the post ID and a timestamp. The <strong>user_ids</strong> field stores a comma-separated list of user IDs who viewed the post during that specific time window.</p><pre>CREATE TABLE view_counts (<br>    post_id INT NOT NULL,<br>    timestamp DATETIME NOT NULL,<br>    user_ids TEXT, -- Store a comma-separated list of user_ids<br>    PRIMARY KEY (post_id, timestamp)<br>); </pre><p><strong>Calculating Unique viewers:</strong></p><ul><li>Query the table to fetch the <strong>user_ids</strong> for the post ID within the desired time range: SELECT user_ids FROM view_counts WHERE post_id = 1 AND timestamp BETWEEN ‘2024-09-01 12:00:00’ AND ‘2024-09-01 12:59:59’</li><li>Split the <strong>user_ids</strong> string into a list and deduplicate it using a <strong>Set</strong>.</li><li>Count the number of unique IDs.</li></ul><p>As view counts increase, managing and querying the data becomes problematic.<strong> <em>For instance</em></strong><em>, if a post is viewed by 1 million unique users and each user ID takes up 8 bytes, storing these IDs requires 8 MB per minute. Over a day with 1,440 minutes, this amounts to 11.52 GB just for one post. </em>Merging these large sets to compute unique views across multiple time windows adds significant computational overhead (operations like set merging and uniqueness checks), making the system inefficient as the number of posts and views increases.</p><h3>2. Bitmap</h3><p>Bitmaps <strong>map input elements to a binary representation </strong>using a <strong>hash function</strong> where each unique element corresponds to a single bit in a bit field.</p><p><strong><em>For example</em></strong><em>, Consider 3 users view the post. Initially, the bitmap is </em><strong><em>00000000</em></strong><em>. As users interact: User 1 sets the bit at position 1 to </em><strong><em>10000000</em></strong><em>, User 2 sets the bit at position 4 to </em><strong><em>10010000</em></strong><em> and User 3 sets the bit at position 6 to </em><strong><em>10010100</em></strong><em>, The final bitmap </em><strong><em>10010100</em></strong><em> indicates that 3 unique users have viewed the post, with each bit representing a unique user position.</em></p><p>Traditionally, counting 1 billion unique user IDs requires <strong>8 GB</strong> of memory (8 bytes per ID). Using a bitmap, you can <strong>reduce this</strong> to just <strong>120 MB </strong>by representing each ID with a single bit.</p><pre>= 1,000,000,000 bits // 1 billion<br>= (1,000,000,000/8) bytes ~ 125MB</pre><p>This approach produces zero collisions, and reduces the space required to count each unique element to 1 bit — <strong>each unique element is mapped to a distinct bit</strong>.</p><p>However, if you need to maintain multiple bitmaps for different sets (e.g., views per post across various time windows),<strong> </strong>memory usage can still<strong> </strong>escalate. <strong>Sparse bitmaps</strong> address this by <strong>storing only the non-zero bits</strong>, which saves space when interactions are infrequent or scattered. However, their effectiveness depends on the density of bit positions.</p><h3>3. Linear Probabilistic Counter</h3><p>The Linear Probabilistic Counter is a <strong>space-efficient </strong>way for estimating the number of unique elements in a dataset. Unlike directly storing user IDs (like the HashSet approach) or setting individual bits for each user (like the Bitmap approach), this method uses a<strong> probabilistic model </strong>to make an educated guess about the number of unique elements, saving a lot of memory in the process with a trade-off in accuracy.</p><h4><strong>Here’s how it works:</strong></h4><h4>I. Initialisation &amp; Hashing</h4><ul><li>A bitmap is initialised with all bits set to zero: <strong>0000000</strong>. For each entry in the dataset, a <strong>hash function</strong> maps the entry to a specific bit position in the bitmap, and that bit is set to 1.</li></ul><h4>II. <strong>Set Bits Based on User Interactions</strong>:</h4><ul><li>For instance, when a user interacts with a post, a hash function maps their user ID to a specific position in the bitmap, and that bit is flipped to 1.</li></ul><pre>For example, say,<br>User 1 hashes to position 1 → Bitmap becomes 10000000.<br>User 2 hashes to position 4 → Bitmap becomes 10010000.<br>User 3 hashes to position 6 → Bitmap becomes 10010100</pre><ul><li>At the end of this process, the bitmap represents all the positions touched by unique users.</li></ul><h4>III. <strong>Estimate Unique Users</strong>:</h4><ul><li>Instead of storing user IDs, this method estimates the total number of unique users based on how many bits remain <strong>0</strong> in the bitmap.<br>The fewer <strong>0</strong>s<strong> </strong>left, the more unique users have interacted with the post.</li></ul><h4>Why This Works</h4><p>The magic lies in probability. When a hash function spreads users evenly across the bitmap, the number of empty bits directly correlates with the number of unique users.</p><ul><li>If many bits are still 0, it suggests fewer unique users have been hashed.</li><li>If most bits are 1, it indicates that a lot of unique users have interacted.</li></ul><p>The estimate to calculate the number of unique users relies on the mathematical <strong>relationship</strong> between the <strong>fraction of empty bits</strong> and the total <strong>number of unique users</strong>.</p><h4>Mathematical Representation</h4><p>If a bitmap has <strong>m</strong> bits and <strong>V</strong> is the fraction of empty bits, the estimated number of unique users, <strong>n</strong>, is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xaEIFMecPrArSCG3eiNX9g.png" /></figure><p>This formula stems from probabilistic reasoning about how hash functions distribute user IDs across the bitmap.</p><p><strong>Why the above formula makes sense</strong>: When you hash user IDs uniformly, the number of empty bits in the bitmap reflects the density of unique elements. As more users interact with the post, the probability of a bit staying 0 decreases, allowing the system to infer the total number of unique elements.</p><p>A more refined derivation using probabilistic analysis:</p><ul><li><em>The </em><strong><em>expected number of empty bits (</em>Vn/m<em>) </em></strong><em>is related to the probability that a bit remains </em><strong><em>0</em></strong><em>, which is given by </em><strong>(1–1/m)^n</strong><em>, where </em><strong><em>n</em></strong><em> is the number of unique elements and </em><strong><em>m</em></strong><em> is size of the bitmap.</em></li><li><em>For large </em><strong><em>m</em></strong><em> and small probabilities, </em><strong>(1–1/m)^n<em> </em></strong><em>can be approximated by</em><strong><em> </em>e^(-n/m)) =&gt; Vn/m = e^(-n/m))</strong></li><li><em>Rearranging,</em><strong><em> </em>n = -m * ln(Vn/m)</strong></li></ul><h4>An Example in Action</h4><p>Imagine you’re working with a bitmap of size <strong>1 million bits</strong> (about <strong>125 KB</strong> of memory). Over time, you hash <strong>10 million </strong>user interactions to this bitmap. After hashing, you find that 20% of the bits (200,000 out of 1 million) remain 0. Using the formula:</p><pre>Estimate = -bitmap_size × ln(fraction_of_empty_bits)<br><br>Here, the fraction of empty bits is 200,000 / 1,000,000 = 0.2<br><br>Estimate = -1,000,000 × ln(0.2) ≈ 1.6 million unique users</pre><p>So, without storing a single user ID, you’ve estimated that <strong>1.6 million</strong> unique users viewed the post, saving a massive amount of memory.</p><h4>Trade-offs and Considerations</h4><p>The Linear Probabilistic Counter isn’t perfect — it’s a compromise. By design, it accepts a margin of error in exchange for massive memory savings. The accuracy of the estimate depends on:</p><ol><li><strong>The size of the bitmap</strong>: Larger bitmaps reduce collisions and improve precision.</li><li><strong>The quality of the hash function</strong>: A well-distributed hash ensures uniformity.</li></ol><p>This method also works best when the dataset has many unique elements. In sparsely populated datasets, other methods like sparse bitmaps may perform better.</p><h3>4. HyperLogLog</h3><p>HyperLogLog(HLL) is an <strong>advanced probabilistic algorithm</strong> designed for efficient cardinality estimation, meaning it can approximate the number of distinct elements in a large dataset with very low memory usage.</p><h4>4.1 A Simple Estimator</h4><p>Imagine you have a hypothetical dataset of random numbers.</p><pre>3, 3, 7, 7, 15, 15, 15, 23, 30</pre><p>Some numbers are repeated, and then the dataset is shuffled. Our <strong>goal is to estimate the number of unique numbers in this list</strong>.</p><p>To get an estimate, we can use the smallest number in the dataset. If the numbers are uniformly distributed, the smallest value <strong>Xmin</strong>, can be used to approximate the total number of unique entries. Specifically, the estimate is calculated as <strong>1/Xmin</strong>.</p><p>However, working directly with raw data can be cumbersome, especially with larger datasets. This is where hashing becomes useful. A<strong> hash function converts each number into a fixed-size value</strong> between 0 and 1, ensuring <strong>uniform distribution</strong> of these values.</p><pre>x       =&gt; 3,     3,     7,   7,    15,   15,   15,   23,   30<br>hash(x) =&gt; 0.30, 0.30, 0.70, 0.70, 0.85, 0.85, 0.85, 0.95, 1.00<br><br>Smallest hash value =&gt; 0.30<br>Number of unique entries ≈ 1 / 0.30 ≈ 3.33  ~ 3<br><br>// So, we estimate about 3 unique entries in the original dataset.</pre><p><em>This approach works because,</em></p><blockquote>With a uniform distribution, the smallest number is inversely related to the number of unique entries.</blockquote><p><em>However, </em><strong><em>this method can have high variance</em></strong><em>. If the smallest hash value happens to be unusually small, it can inflate our estimate, leading to inaccuracies.</em></p><h4>4.2 Probabilistic Counting Algorithm</h4><p>Probabilistic counting is a technique that uses patterns observed in hashed values to estimate the number of distinct elements in a dataset. This method focuses on <strong>counting the number of leading zeros</strong> in these hashed values.</p><h4><strong>Concept of Leading Zeroes</strong></h4><ul><li>In a given binary string, the probability of getting certain number of leading zeroes is tied to how<strong> “rare”</strong> that pattern is.</li><li>When a number is hashed, the result is a binary string. The probability of a binary string having exactly <strong>k</strong> leading zeroes is <strong>((1/2)^k)</strong>.<strong> </strong>This means that, on average, a sequence of k consecutive zeros will appear once in every <strong>((1/2)^k) </strong>distinct entries.</li></ul><pre>For instance, the probability of a hash value having exactly 3 leading zeros is <br>calculated as <br>= (1/2) * (1/2) * (1/2) = (1/2)^3</pre><ul><li>If a <strong>hash value</strong> consistently shows a <strong>high number of leading zeroes</strong>, it means that this <strong>pattern occurring frequently</strong>.</li><li>In a large dataset with many unique items, the distribution of hash values is more uniform. Hence, if the hash values frequently exhibit a high number of leading zeros, it suggests that these patterns are rare, and the dataset might not be very large. Conversely, if many hashed values have only a <strong>few leading zeros</strong>, it indicates a higher density of hash values, suggesting a <strong>larger number of unique items</strong>.</li></ul><blockquote>Fewer leading zeros generally indicate more unique items.</blockquote><h4><strong>Estimating Cardinality</strong></h4><p>To estimate the number of unique entries, we <strong>focus on the longest sequence of leading zeros observed across all hash values</strong>. <em>Mathematically</em>, if<strong> 𝜌(xi) </strong>represents the number of consecutive zeros in the hash value of entry <strong>xi</strong>, then,</p><p>The estimated cardinality of the set <strong>= 2^R</strong></p><p><em>where </em><strong><em>R</em></strong><em> is the maximum number of leading zeros observed among all hashed values</em>.</p><p><strong><em>For example,</em></strong></p><pre>Hash Values   =&gt; 0001, 0010, 0100, 1000<br>Leading Zeros =&gt; 3, 2, 1, 0<br><br>The maximum number of leading zeros is 3.<br>So, Estimated Number of Unique Entries = 2^3 = 8</pre><h4><strong>Advantages:</strong></h4><ul><li>This method only requires storing the maximum number of leading zeros observed. For instance, tracking up to 32 leading zeros requires only 5 bits of storage.</li></ul><h4><strong>Disadvantages:</strong></h4><ul><li><strong>Power of 2 Estimates</strong>: <em>The resulting estimates are limited to powers of two</em><strong><em> </em></strong><em>(1, 2, 4, 8, 16, etc.), nothing in between, which may not always provide the granularity needed for precise estimates.</em></li><li><strong>High Variability: </strong><em>A single hash value with an unusually long sequence of leading zeros can significantly inflate the estimate, leading to a potentially inaccurate count.</em></li></ul><h4>4.3 LogLog Algorithm</h4><p>To improve the accuracy of cardinality estimates, the LogLog algorithm <strong>utilises multiple estimators</strong> (hash functions) rather than relying on a single one. By averaging results from several independent estimators, the algorithm reduces variance and provides a more accurate estimate.</p><p>For<strong> each entry</strong> in the dataset, you apply <strong>several hash functions </strong>and record the maximum number of leading zeros for each hash. By <strong>averaging these maximum values</strong>, you obtain a more accurate estimate of the number of unique entries.</p><h4>Here’s how it works,</h4><ol><li><strong>Multiple Hash Functions</strong>: Instead of using a single hash function, the algorithm applies <strong>𝑚</strong> independent hash functions: {h1(x), h2(x), ..., hm(x)} to each entry. Each function produces a hash value for an entry.</li><li><strong>Compute Leading Zeros</strong>: For each hash value, calculate the number of leading zeros. This yields a series of values: {R1, R2, ..., Rm(x)} , <em>where</em> Ri<em>is the number of leading zeros for the hash produced by</em> hi .</li><li><strong>Average and Estimate</strong>: Average these maximum values using the <strong>Arithmetic mean(AM)</strong> to obtain a more accurate estimate of the number of unique entries. (<em>Note that the arithmetic mean is used here, but the Geometric Mean(GM) can also be used to balance the effects of large and small values, providing a stable estimate by mitigating the impact of extreme values</em>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nmv3nVK_ibPreJeQcUEnMg.png" /></figure><h4><strong>Efficient Implementation with Buckets:</strong></h4><p>Using multiple hash functions can be computationally expensive. To mitigate this, <strong>Durand and Flajolet</strong> propose <strong>using a single hash function with multiple buckets. </strong>Here’s how:</p><p><strong>Hash and Bucket Indexing:</strong></p><ul><li><strong>Hashing</strong>: First, hash your input data using a single hash function, which generates a long binary string. <em>For example, let’s say our hash function outputs the binary string</em> <strong>1011000001101100110</strong></li><li><strong>Bucket Indexing</strong>: Use a portion of the hash output to determine the bucket index.<em> For instance, if we use the first </em>4<em> bits of the hash value, </em><strong>1011</strong><em>(which is </em><strong>11</strong> <em>in decimal), we select bucket number </em>11<em>.</em> This step simulates the effect of having multiple hash functions by directing <strong>each input to just one bucket</strong> based on the initial bits of the hash value.</li><li><strong>Extract Remaining Bits:</strong> After determining the bucket index, examine the remaining bits of the hash string. <em>In our example, the remaining bits are</em> <strong>000001101100110</strong></li><li><strong>Count Leading Zeros:</strong> Calculate the number of leading zeros in these remaining bits. <em>Here, the longest sequence of leading zeros is</em> <em>5</em>. <em>Update bucket 11 with this count of leading zeros.</em></li></ul><pre>Bucket Index:    0, 1, 2, ..., 11, ..., N<br>Bucket Values:   1, 2, 0, ..., 5,  ..., 3 <br><br>// Here, bucket 11 holds the value 5, indicating the longest sequence of <br>// leading zeros encountered for that bucket.</pre><p><em>By using bucket indexing, the method effectively simulates multiple hash functions without the computational overhead. Each bucket stores the maximum number of leading zeros observed for the hashed values assigned to it.</em></p><h4><strong>Formula:</strong></h4><p>The LogLog estimator uses the following formula to estimate the number of unique entries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6baaxkvUEvggtxgL3R0-w.png" /></figure><p><strong>Durand</strong> and <strong>Flajolet</strong> derived a <strong>constant</strong> of <strong>0.79402</strong> to correct the estimator’s bias, improving its accuracy.</p><p><em>For example, with 2000 buckets where each bucket uses 5 bits (= max. number of leading zeroes value is 32), you can estimate cardinalities up to </em><strong><em>2²⁷(</em></strong><em>with a 32-bit hash and 5 bits for bucket indexing, leaving 27 bits for leading zeros</em><strong><em>,</em></strong><em> 2^R is the formula</em><strong><em>)</em></strong><em> with an average error of about 2.8 percent. This efficient use of memory (1.25 KB </em><em>= 2000buckets * 5bits/bucketin total) making the LogLog algorithm both efficient and practical for large-scale data analysis.</em></p><h4>4.4 HyperLogLog Algorithm</h4><p>While the LogLog algorithm is quite effective, we can achieve even better accuracy with a few additional refinements. Two key improvements contribute to the enhanced precision of the <strong>HyperLogLog (HLL)</strong> estimator:</p><h4>1. Handling Outliers:</h4><p>Durand and Flajolet observed that outliers —<strong> extremely large values </strong>— can significantly <strong>impact the accuracy </strong>of the estimator.</p><p>To address this, they proposed an approach called <strong>SuperLogLog</strong>. This method involves discarding the largest values before averaging to reduce the influence of outliers.</p><p>Specifically, instead of averaging all bucket values, <strong>SuperLogLog</strong> <strong>retains</strong> only the smallest<strong> 70%</strong> of values and <strong>ignores</strong> the remaining 30%. This adjustment improves the accuracy of the estimate from <strong>1.3/sqroot(m)</strong> to approx. <strong>1.05/sqroot(m)</strong></p><p>This means that by filtering out extreme values, we obtain a more reliable estimate of the cardinality.</p><h4>2. Using Harmonic Mean</h4><p>HyperLogLog further refines the accuracy by using a different type of averaging. <strong>Instead of the Arithmetic/Geometric mean</strong> employed by LogLog,<strong> HLL uses the Harmonic Mean(HM)</strong> in its estimation function. This adjustment reduces the error to slightly less than <strong>1.04/sqroot(m)</strong> without increasing the storage requirements.</p><h4>Formula</h4><p>By integrating the improvements from SuperLogLog and Harmonic Mean averaging, HLL provides a more accurate estimator for the number of distinct values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aqWqx3yx7yg-HXhSCY6jA.png" /></figure><h3>Distributed HLL Counters</h3><p>When dealing with<strong> data spread across multiple machines</strong>, merging HyperLogLog (HLL) counters is essential for accurate cardinality estimation. Each machine processes a subset of the data and maintains its own local HLL counter. To estimate the overall cardinality, these local counters are merged without transferring the raw data to a central location.</p><p>The HLL algorithm supports this merging process effectively. <strong>To combine </strong>two HLL counters, <strong>simply take the maximum value from each corresponding bucket</strong>. This merging method is straightforward and lossless, ensuring that the global estimate accurately reflects the union of the datasets. Essentially, it’s like processing the combined dataset in a single HLL from the beginning.</p><p>By using the same hash function and bucket configuration, data can be processed independently across multiple machines.</p><h3>HyperLogLog in Action</h3><h4><strong>Redis</strong></h4><p>Redis offers HyperLogLog as a highly memory-efficient way to approximate the number of unique elements.</p><ul><li><strong>PFADD key element [element ...]</strong>adds elements to a HyperLogLog data structure stored at key.</li><li><strong>PFCOUNT key [key ...]</strong>returns the approximated cardinality of the HyperLogLog stored at key.</li><li><strong>PFMERGE destkey sourcekey [sourcekey ...]</strong> merges multiple HyperLogLog structures into a single one.</li></ul><pre>PFADD user_views1 1 2 3<br>PFADD user_views2 4 5 6<br>PFMERGE merged_user_views user_views1 user_views2<br>PFCOUNT merged_user_views</pre><h4>Presto</h4><p>In Presto, a <strong>distributed SQL query engine</strong>, HyperLogLog is used to estimate cardinality efficiently within SQL queries. The function <strong>approx_distinct(expression)</strong> provides an approximate count of unique values for a given expression.</p><p>This method allows you to <strong>perform cardinality estimation directly in your SQL queries</strong>, making it suitable for large-scale data analysis and distributed computing.</p><pre>SELECT approx_distinct(user_id) FROM user_logs;</pre><h4>Other Options:</h4><ul><li><strong>Apache Druid</strong>: Utilises HyperLogLog for cardinality estimation in its real-time analytics engine. Druid offers functions like <strong>hyperUnique</strong> to estimate unique counts.</li><li><strong>Google BigQuery</strong>: Supports approximate distinct count using HyperLogLog through the <strong>APPROX_COUNT_DISTINCT</strong> function, which provides a trade-off between accuracy and performance.</li><li><strong>Elasticsearch</strong>: Uses HyperLogLog in its <strong>cardinality</strong> aggregation to estimate the number of unique values in large datasets.</li></ul><p><em>In conclusion, as you navigate through viral content on social media, remember that the complex challenge of counting unique views is tackled using advanced algorithms. Whether it’s the straightforward hash sets, space-efficient bitmaps, or sophisticated HyperLogLog techniques, these methods ensure accurate and swift processing of massive datasets.</em></p><p><strong>Thanks for your time. Happy Learning !</strong></p><h3>References:</h3><p><a href="https://engineering.fb.com/2018/12/13/data-infrastructure/hyperloglog/">HyperLogLog in Presto: A significantly faster way to handle cardinality estimation</a></p><p><a href="https://highscalability.com/big-data-counting-how-to-count-a-billion-distinct-objects-us/">https://highscalability.com/big-data-counting-how-to-count-a-billion-distinct-objects-us/</a></p><p><a href="https://redis.io/docs/latest/develop/data-types/probabilistic/hyperloglogs/">https://redis.io/docs/latest/develop/data-types/probabilistic/hyperloglogs/</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2PlrMCiUN_s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2PlrMCiUN_s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2PlrMCiUN_s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/53340c151f2f49d81f8316adaa6d6608/href">https://medium.com/media/53340c151f2f49d81f8316adaa6d6608/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02fbe979cbab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Systems in Sync]]></title>
            <link>https://medium.com/@rangavamsi5/distributed-systems-in-sync-0bccd669e8dc?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bccd669e8dc</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[master-slave-replication]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[gossip-protocol]]></category>
            <category><![CDATA[eventual-consistency]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 14:16:45 GMT</pubDate>
            <atom:updated>2025-01-08T14:17:35.948Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Data Gets Around?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1XYfdSbYgfi86dVr" /><figcaption>Photo by <a href="https://unsplash.com/@amutiomi?utm_source=medium&amp;utm_medium=referral">Miguel A Amutio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever wondered how a change made on one server in a distributed system eventually makes its way to every other server, even when they’re scattered across different regions? How does our data, stored in multiple places, stay in sync without slowing things down?</p><p>Some systems use traditional methods like <strong>Master-Slave Replication</strong>, where one server leads and others follow. Others rely on <strong>Quorum-Based Replication</strong>, where a majority vote ensures updates get through. But in large, sprawling systems, there’s an even more intriguing approach: <strong>Gossip Protocols</strong>. Here, updates spread much like a rumour — one server “whispers” the change to another, and the news travels until everyone knows.</p><p>So, how exactly do these protocols help massive systems stay fast and responsive without losing their consistency?</p><h3>I. Master-Slave Replication: Centralised Control</h3><p>In a <strong>Master-Slave Replication</strong> setup, there’s a clear hierarchy: one node acts as the <strong><em>Master</em></strong>, while the rest follow as <strong><em>Slaves</em></strong>. The master node is the central hub where all data updates happen first. These updates are then propagated to the slave nodes, either synchronously (real-time) or asynchronously (with a delay).</p><h4>Why It Works: Simplicity and Consistency</h4><p>This model offers simplicity. With one node in control, there’s no confusion over which version of the data is correct. The master is the single source of truth, which eliminates data conflicts. For systems <strong>where maintaining strong consistency is crucial</strong>, this structure can be a reliable choice.</p><p>However, this simplicity comes with its own set of challenges.</p><h4>The Achilles’ Heel: Single Point of Failure</h4><p>One of the biggest drawbacks of the Master-Slave approach is the heavy reliance on the master node. If the master node goes down, the entire system can grind to a halt. <em>Imagine a scenario, where the system becomes </em><strong><em>read-only</em></strong><em> because there’s no longer a central node to handle write operations</em>. Without a failover mechanism to promote a slave to master, we’re left in a vulnerable position.</p><h4>Scaling Woes: More Slaves, More Problems</h4><p>As the system grows, scaling this setup becomes tricky. <strong>The more slaves we have, the more work the master has to do,</strong> continuously syncing updates to an ever-growing list of followers. This central bottleneck can limit performance and scalability, especially for systems with high write traffic or large distributed environments.</p><h4>When It Shines: Small, Read-Heavy Systems</h4><p>Master-Slave Replication is often a great fit for smaller systems or applications where the master node is highly available and designed to be failure-resistant<strong>.</strong> It works well in environments where <strong>reads far outweigh writes, </strong>and<strong> strong consistency is a must</strong>. But as systems scale and the demands on the master node increase, this centralised control can become a bottleneck.</p><h3>II. Quorum-Based Replication: The Democratic Approach</h3><p>Moving a step away from centralisation,<strong> Quorum-Based Replication</strong> relies on a more democratic approach.</p><h4>How It Works: Majority Rules</h4><p>In a Quorum system, when a client writes data, the update is sent to a subset of nodes. The write is considered successful once a majority (quorum) of these nodes acknowledge it. The same applies to read operations: the client reads from a quorum of nodes, and once it gets enough responses to form a consistent view, the read is deemed complete.</p><p><em>For example, in a system with 5 nodes, a quorum might be set at 3. If three nodes confirm the update, it’s committed — even if the remaining two haven’t yet received the change.</em></p><h4>Quorum Selection: Static vs. Dynamic</h4><p>The selection of which nodes participate in the quorum can be:</p><ul><li><strong>Static:</strong> The client can be configured with a predefined set of nodes that are always part of the quorum. This approach requires prior knowledge of the cluster’s structure and can simplify the selection logic but reduces flexibility.</li><li><strong>Dynamic (runtime)</strong>: Quorum membership is determined at runtime, considering factors like node availability, load, and latency. This approach ensures robustness but requires additional coordination<em>. For example, a system might dynamically select the closest or most reliable nodes based on real-time metrics to form the quorum.</em></li></ul><h4>How Non-Quorum Nodes get Updates</h4><p>Nodes outside the quorum still need to stay updated to maintain consistency across the system. Typically, these nodes receive updates through:</p><ul><li><strong>Replication</strong>: Once a decision is finalised, quorum nodes replicate the state or decision to non-quorum nodes.</li><li><strong>Gossip Protocol:</strong> Updates can propagate using a gossip protocol, where quorum nodes share the updates with their neighbours, which further propagate them.</li><li><strong>Background Synchronisation:</strong> Non-quorum nodes periodically pull updates from the quorum or designated replica nodes to stay consistent.</li></ul><h4>The Power of Flexibility: Tune the Consistency</h4><p>One of the greatest strengths of Quorum-Based Replication is its flexibility. We can tune the system’s behaviour by <strong>adjusting the size of the quorum for reads and writes</strong>:</p><ul><li><strong>Strong Consistency:</strong> Set both read and write quorums to a majority (eg., 3 out of 5 nodes). This ensures that any read reflects the most recent write, but it can slow down operations.</li><li><strong>Eventual Consistency:</strong> Lower the quorum for reads or writes (eg., 2 out of 5). This speeds up operations but increase the chances of reading outdated data.</li></ul><h4>Avoiding Stalls: Fault Tolerance at its Core</h4><p>If a few nodes go down, as long as a quorum is reached, the system can continue functioning. The decentralised decision making reduces the risk of a complete system stall.</p><p><em>Consider a global ride-hailing service that uses a Quorum-Based system to manage active ride data. When a driver accepts a ride, the system needs to quickly update the driver’s status across the network. The service is distributed across five data centres, with a quorum set to three for both reads and writes.</em></p><p><em>Now, imagine that two of these data centres go offline due to a network issue. Despite the failures, the system remains operational because it can still reach a quorum with the three remaining data centres. As long as three out of five nodes confirm the ride acceptance, the system continues to function, allowing drivers and passengers to proceed without disruption.</em></p><h4>Trade-offs: Latency vs. Consistency</h4><p>The downside of this flexibility is that we may have to deal with increased latency. If the <strong>quorum is spread across multiple data centres </strong>or if some nodes are slow to respond, operations might take longer to complete. This model also introduces the challenge of <strong>consistency lag</strong> — if only a quorum of nodes acknowledges an update, the remaining nodes might still hold outdated versions of the data until they catch up.</p><h4>Where It Shines: Distributed and Fault-Tolerant Systems</h4><p>Quorum-Based Replication is ideal for large, distributed systems where both fault tolerance and flexibility are critical. By carefully tuning the quorum thresholds, this method provides a sweet spot between high availability and data accuracy, making it a popular choice for systems like <strong>Cassandra</strong> and <strong>DynamoDB</strong>.</p><h3>III. Gossip Protocols: Whispers Across the Cluster</h3><p>In the world of distributed systems, ensuring every node in a network stays up-to-date can be a daunting task, especially as the system scales to hundreds or thousands of nodes. This is where <strong>Gossip Protocols</strong> shine — much like how information spreads through casual conversation in a social group, nodes in a system <strong>“gossip” </strong>about updates, ensuring the entire network eventually becomes consistent.</p><h4>How It Works: Decentralised Communication</h4><p>At its core, Gossip Protocols rely on <strong>decentralised communication</strong>. Here’s how it works:</p><ol><li><strong>Periodic Communication:</strong> Each node periodically selects a small, random subset of other nodes to exchange information with. This could include state updates, node health, or data changes. <em>For instance, User A updates their profile picture. The server responsible for User A’s profile (Node 1) processes the change and begins the gossiping process.</em></li><li><strong>Spreading Information: </strong>When a node receives new information from its peers, it incorporates that into its own state and, in the next round, <strong>passes this information to the nodes it communicates with</strong>. This process repeats until all nodes have received the update. <em>In our example, Node 1 selects a few random nodes (eg., Node 2 and Node 3) and sends the update. In the next round, Node 2 gossips this update to Nodes 4 and 5, while Node 3 shares it with Nodes 6 and 7.</em></li><li><strong>Redundant but Resilient: </strong>The same information may spread redundantly across different paths, but this redundancy ensures high resilience. If a node or network path goes down temporarily, the update still spreads through other routes. <em>Eventually, all nodes (eg., Node 8 and Node 9) receive the update through multiple paths.</em></li></ol><h4>Characteristics to Highlight</h4><ul><li><strong>Decentralisation: </strong>Every node plays an equal role in spreading updates, making the system highly fault-tolerant. If some nodes go offline, others continue spreading the data, ensuring eventual consistency.</li><li><strong>Scalability:</strong> Gossip scales almost effortlessly. Since each node only communicates with a random subset of peers, the amount of traffic per node remains manageable, even as the number of nodes increases. This makes Gossip Protocols ideal for massive, geographically distributed systems where other replication strategies might struggle with coordination overhead.</li></ul><p><em>Imagine </em><strong><em>Cassandra</em></strong><em> running in a cluster of 500 nodes. When a user updates data, the node receiving the update doesn’t immediately inform all other nodes in the cluster (which would be inefficient). Instead, it gossips the change to a few of its peers. These peers then gossip to others, and eventually, the entire cluster knows about the update.</em></p><h4>Push vs. Pull Gossip</h4><p>In some systems, gossip works in a <strong>“push”</strong> model, where nodes send updates proactively to their peers. This is <strong>efficient when data changes frequently</strong> and updates need to be disseminated quickly.</p><p>In other systems, gossip works in a <strong>“pull”</strong> model, where nodes request updates from their peers. This is useful when nodes are intermittently available or when the network needs to <strong>minimise unnecessary data transmission</strong>. It also helps when the rate of updates is relatively low, as nodes can periodically check for changes instead of constantly receiving updates.</p><h4>When Does Gossip Stop?</h4><p>Gossip stops once all nodes agree on the latest version of the data. This is achieved through a predefined number of gossip rounds or by tracking versions or timestamps.</p><p>But what if some nodes didn’t get the update initially? The gossip continues until all nodes have received the latest update. If a node misses the update in one round, it’s very likely to get in the next.</p><p><em>Imagine a distributed system with 5 nodes: </em><em>Node A ,</em><em>Node B,</em><em>Node C,</em><em>Node D and </em><em>Node E . These nodes store a shared variable, say </em><em>X , which has an initial value of </em><em>10 . Let’s say the value of </em><em>X is updated to </em><em>20 on </em><em>Node A . Now, </em><em>Node A needs to propagate this change to the other nodes in the cluster.</em></p><ul><li><strong><em>Gossip Starts: </em></strong><em>Node A sends the update of new value </em><em>X=20 to nodes </em><em>Node Band </em><em>Node C</em></li><li><strong><em>Second Round of Gossip: </em></strong><em>In the next round, </em><em>Node B sends the updated value to </em><em>Node D while </em><em>Node C sends to </em><em>Node E</em></li><li><strong><em>Third Round of Gossip:</em></strong><em> To ensure full propagation, </em><em>Node D might talk to </em><em>Node A (even though </em><em>Node A already knows about the change) and </em><em>Node E might talk to </em><em>Node B</em></li><li><strong><em>Termination:</em></strong><em> After the third round, all five nodes have the updated value </em><em>X=20 . Each node keeps a version or timestamp of the update. When </em><em>Node A notices that all its peers (through gossip rounds) have the same version for </em><em>X=20 , it knows that gossiping about this update is no longer necessary.</em></li></ul><h4>Handling Node Joins and Leaves: Dynamic Membership</h4><p>The protocol allows nodes to join or leave without requiring a central coordinator or complex rebalancing.</p><p><strong>When Nodes Join:</strong> The newly joined node either pulls updates from its peers or receives a push from other nodes. Within a few gossip rounds, the new node synchronises with the current state of the system.</p><p><em>In continuation of the prior example, let’s say a new node </em><em>Node F joins the cluster. If </em><em>Node F uses a pull-based protocol, it will ask a few of the existing nodes (say </em><em>Node C and </em><em>Node D) to send their current version of </em><em>X . If the protocol is push-based, the </em><em>Node A or another node that notices </em><em>Node F ‘s arrival can push the latest value of </em><em>X to </em><em>Node F directly.</em></p><p><strong>When Nodes Leave:</strong> Nodes leaving (either deliberately or through failure) don’t interrupt the gossip process. Remaining nodes can continue to spread updates without relying on the failed node.</p><p><em>Now, let’s say </em><em>Node C goes offline unexpectedly while the system is still gossiping about </em><em>X=20 . Other nodes will continue gossiping the update without trying to contact </em><em>Node C , once they detect that </em><em>Node C is unresponsive. If </em><em>Node C comes back online later, it can either pull or receive a push from another node to get the latest value of </em><em>X .</em></p><p><strong>New nodes will get caught up with the rest of the cluster, and failed nodes are simply excluded from future gossip rounds.</strong></p><h4>Fault Tolerance and Recovery</h4><p>In the event of <strong>node failures</strong>, Gossip Protocols are incredibly resilient. Let’s say 2 nodes in a 100-node system go offline. Even if some updates don’t immediately reach these nodes, the system will eventually self-heal when those nodes come back online. <strong>As soon as they reconnect, they begin receiving state updates from their peers,</strong> quickly syncing with the rest of the system.</p><p>In the case of a <strong>network partition</strong> (where the cluster is divided into two disconnected subgroups), gossip will continue within each subgroup. Once the partition resolves, the nodes from both groups will re-synchronise with each other, ensuring eventual consistency across the entire cluster.</p><p>This capability makes Gossip protocols particularly attractive for systems that need to be highly available, such as<em> distributed databases </em>or c<em>loud infrastructure services</em>, where nodes can go offline at any moment without crashing the entire system.</p><h4>In Action: Cassandra and DynamoDB</h4><p>One of the most well-known implementations of gossip protocols is in <strong>Apache Cassandra</strong>, a highly available distributed database. Cassandra uses gossip for several critical functions:</p><ul><li><strong>Node Health</strong>: Each node gossips information about its status (up or down) to other nodes, enabling the system to handle node failures gracefully.</li><li><strong>Cluster Membership</strong>: Gossip helps nodes in the Cassandra cluster keep track of which nodes are currently part of the system, enabling smooth scaling when nodes are added or removed.</li><li><strong>Data Distribution</strong>: Gossip ensures that data is evenly distributed across the cluster by spreading information about which nodes are responsible for which parts of the data.</li></ul><p>Similarly, <strong>Amazon DynamoDB</strong>, another distributed database, uses gossip to maintain consistency across its clusters, detect node failures, and synchronise state information.</p><h3>Choosing the Right Propagation Mechanism</h3><p>When selecting a propagation mechanism for a distributed system, the choice depends on the application’s needs for <strong>Scalability</strong>, <strong>Fault Tolerance</strong>, and <strong>Consistency</strong>.</p><ul><li><strong>Master-Slave Replication</strong> is simple and easy to implement, but it lacks fault tolerance and scalability. It works well for smaller systems or <strong>read-heavy applications</strong>. A single point of failure in the master node can cause bottlenecks, impacting availability and performance.</li><li><strong>Quorum-Based Replication</strong> provides <strong>strong consistency guarantees</strong> but can introduce performance overhead in large systems, as it requires coordination among multiple nodes to meet the quorum. The trade-off is between <strong>latency</strong> and <strong>consistency</strong>.</li><li><strong>Gossip Protocols</strong>, on the other hand, are highly scalable and fault-tolerant, making them <strong>ideal for large, decentralised systems</strong> like Cassandra, where nodes may frequently fail or go offline.</li></ul><p><em>Each method has trade-offs, but choosing the right one depends on how much we prioritise speed, consistency, and fault tolerance in our system.</em></p><h3>In Conclusion</h3><p><em>In distributed systems, keeping data consistent across multiple servers is a complex task. The challenge lies in ensuring that when data is updated on one server, it is propagated efficiently and accurately to all others. This requires balancing speed, reliability, and fault tolerance. Systems must manage delays, potential failures, and varying speeds of communication between nodes. The goal is to ensure that all parts of the system eventually receive updates, even in the face of network issues or node failures, while minimising inconsistencies and maintaining performance.</em></p><p><strong>Thanks for your time, and happy learning!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bccd669e8dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eventual Consistency]]></title>
            <link>https://medium.com/@rangavamsi5/eventual-consistency-423744066919?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/423744066919</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[eventual-consistency]]></category>
            <category><![CDATA[consistency]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 07:21:31 GMT</pubDate>
            <atom:updated>2024-12-22T07:21:31.468Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When “Good Enough” is perfectly fine</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kg0CF_hps3z8ilpP" /><figcaption>Photo by <a href="https://unsplash.com/@tjholowaychuk?utm_source=medium&amp;utm_medium=referral">Tj Holowaychuk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine tossing a stone into a calm lake. At first, ripples spread out unevenly, disturbing the water’s surface. But over time, those ripples fade, and the lake returns to stillness. This is much like how distributed systems work under the principle of eventual consistency. When changes (like updates to data) are made, they don’t instantly synchronise across the system, leading to temporary differences or “ripples” in data state.</p><p>In the world of distributed systems, not everything needs to be perfectly in sync at every moment. Often, it’s enough to know that, given time, everything will eventually align. But how do we ensure that a system stabilises, even when multiple changes are constantly being made? And what trade-offs are we making in the process?</p><h3>How Eventual Consistency Works</h3><p>Eventual consistency is a consistency model used in distributed systems that <strong>ensures all nodes will eventually reach the same state, but not necessarily at the same time</strong>. This model is critical in large-scale, globally distributed systems where maintaining strict synchronisation across all replicas in real-time can be inefficient or even impossible due to latency, network partitions, or node failures.</p><p>Here’s a breakdown of how it works:</p><h4>Local Update First</h4><p>When an update is made in a distributed system — such as adding an item to a shopping cart — the <strong>update typically happens on the local replica </strong>(the node closest to the user or the node that initially received the request). This is done to provide low-latency responses to users, ensuring quick feedback without waiting for the change to propagate across the entire system.</p><p>The local node processes the change and returns a response to the user. At this point, only the local node has the updated data. The other nodes, which might be spread across different data centres or geographic locations, still hold the previous version of the data.</p><h4>Propagation to Other Nodes</h4><p>Once the local node processes the change, it <strong>asynchronously propagates this update to other replicas</strong> in the system. This propagation can happen in various ways, depending on the underlying architecture:</p><ul><li><strong>Gossip Protocols:</strong> Nodes communicate with a subset of other nodes periodically, spreading the update through multiple rounds of communication. Over time, every node receives the update.</li><li><strong>Master-Slave Replication: </strong>The local node (acting as a master) sends the update to designated replica nodes (slaves) for eventual synchronisation.</li><li><strong>Quorum-Based Replication: </strong>The update is sent to a quorum (a majority or a subset of nodes), and once a quorum acknowledges the update, it’s considered committed.</li></ul><p>However, this propagation is not instantaneous. Depending on the system’s load, network conditions, and the number of replicas, there could be significant delay before all nodes receive the update.</p><h4>Handling Network Partitions and Failures</h4><p>In a distributed system, failures are inevitable. Nodes can go down, and network partitions (where different parts of the system cannot communicate) can occur. Eventual consistency is designed to be resilient to these challenges.</p><ul><li><strong>Network Partitioning (Split-Brain Problem):</strong> Imagine a scenario where the system is split into two partitions due to a network failure. One partition continues receiving updates, while the other remains isolated. In eventual consistency,<strong> the partition that can still reach a majority of nodes continues operating normally, while the isolated partition holds stale data</strong>. Once the network is restored, the nodes in the previously isolated partition will synchronise with the rest of the system by receiving missed updates.</li><li><strong>Node Failures and Rejoins:</strong> If a node goes down while changes are being propagated, it will miss those updates. When the node comes back online, it will need to synchronise with the other nodes to catch up on all the changes it missed. This is often handled using mechanisms like <strong>“hinted handoff”</strong> (where updates meant for an offline node are temporarily stored on another node until the offline node returns) or “<strong>read repair” </strong>(where inconsistencies are detected and corrected during read operations)</li></ul><h4>Conflict Resolution</h4><p>When updates are happening asynchronously, conflicts can arise. For example, <strong>if two nodes receive updates to the same data at nearly the same time, they might each have different versions of the data</strong>. Eventual Consistency systems must have mechanisms to resolve these conflicts.</p><p>There are a few common strategies for conflict resolution:</p><ul><li><strong>Last-Write-Wins (LWW):</strong> The system resolves conflicts by choosing the version with the most recent timestamp. This is simple but can lead to lost updates if timestamps are not accurately synchronised.</li><li><strong>Vector Clocks: </strong>Each update carries a vector clock, a data structure that tracks the casual history of updates. This allows the system to detect conflicts and merge them based on the update history.</li><li><strong>Application-Level Resolution:</strong> In some systems, conflicts are resolved at the application level. <em>For example, in an e-commerce system, conflicting inventory updates might require manual intervention or domain-specific logic to resolve discrepancies</em>.</li></ul><h4>Read Consistency Levels</h4><p>In eventual consistency systems, users might read outdated or stale data before the system has fully synchronised. To mitigate this, many systems allow <strong>configurable read consistency levels</strong>:</p><ul><li><strong>Read From any Node (Eventual Consistency)</strong>: The system returns the data from any node, even if that node hasn’t yet received the latest update. This provides <strong>fast reads but at the risk of reading stale data</strong>.</li><li><strong>Read From a Quorum (Monotonic Read):</strong> The system reads from a quorum of nodes to ensure that the most up-to-date data is returned. This <strong>introduces some latency</strong> but reduces the likelihood of stale reads.</li><li><strong>Read From a Master (Strong Consistency): </strong>The system always reads from the master or leader node, ensuring that the latest data is returned. This guarantees up-to-date reads but <strong>sacrifices availability during failures</strong>.</li></ul><h4>Convergence and Healing</h4><p>One of the critical properties of eventual consistency is that, over time, all replicas will converge to the same state. This process, often called <strong>convergence, </strong>ensures that no matter the number of nodes or the level of asynchrony, the system will eventually achieve a consistent state. Systems achieve convergence through:</p><ul><li><strong>Anti-Entropy Protocols: </strong>Nodes periodically compare their data with other nodes and reconcile any differences. This is akin to background data repair to ensure eventual consistency.</li><li><strong>Tunable Consistency: </strong>Some systems allow users to configure how much consistency they want (eg., how many nodes must acknowledge a write before it’s considered successful), providing a balance between availability and consistency based on the applications needs.</li></ul><h3>Eventual Consistency In Action</h3><p>In the world of distributed systems, <strong>eventual consistency</strong> often strikes the perfect balance between availability and responsiveness. Lets see how this principle operates in practice.</p><p>Take <strong>social media feeds</strong>, for example. When you scroll through your timeline, you might notice that <strong>updates from friends and followers don’t always appear at the exact same moment for everyone</strong>. You might post a status update, and while your close friends see it right away, others may experience a slight delay. This isn’t a bug; it’s how these platforms are designed to work. Users are perfectly fine with a few seconds of lag because the experience remains engaging and interactive.</p><p>Now, think about how <strong>caching systems</strong> work, particularly in e-commerce. When you search for a product, you expect results to appear instantly. Behind the scenes, the <strong>system might be pulling information from a cache that hasn’t yet updated</strong> to reflect the latest stock levels. If a popular item just sold out, you might still see listed as available for a moment. However, this slight delay doesn’t ruin your shopping experience because the system provides fast responses without making you wait for the database to sync up.</p><p>Next, let’s consider the <strong>Domain Name System (DNS)</strong>. When you enter a web address in your browser, DNS translates that into an IP address so you can access the website. However, changes to DNS records — like moving a site to a new server — can take time to propagate across the internet. <strong>Some users may still be directed to the old server for a while</strong>, but that doesn’t prevent them from accessing the website.</p><p>On the flip side, there are scenarios where strong consistency is non-negotiable. Take <strong>banking and stock trading systems</strong>. In these cases,<strong> real-time accuracy is critical </strong>to avoid issues like double spending or incorrect account balances. Imagine trying to withdraw cash from an ATM while another transaction is simultaneously processed. If the system were to rely on eventual consistency, it could allow both transactions to succeed, leading to significant financial discrepancies.</p><p><em>Each use case highlights the inherent trade-offs: in some scenarios, users value speed and responsiveness, while in others, accuracy and reliability take precedence.</em></p><h3><em>In Conclusion</em></h3><p><em>Eventual consistency is a powerful model for distributed systems where availability and performance are critical, even in the face of network failures, high latency, or massive scale. By relaxing the strict requirement of immediate consistency, these systems ensure that services remain responsive and available, even though users might temporarily see different versions of data. However, this approach is not without challenges — conflicts, stale reads, and delayed convergence can arise.</em></p><p><strong>Thanks for your time, and happy learning!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=423744066919" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Consensus Algorithms]]></title>
            <link>https://medium.com/@rangavamsi5/the-consensus-algorithms-aa40f29fcdeb?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa40f29fcdeb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[consensus-algorithm]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[consensus]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 12:37:02 GMT</pubDate>
            <atom:updated>2024-12-15T12:37:02.142Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The Behind-the-Scenes Negotiators</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2XP8k-WL4OtvG4jb" /><figcaption>Photo by <a href="https://unsplash.com/@larisabirta?utm_source=medium&amp;utm_medium=referral">Larisa Birta</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a distributed world, the challenge isn’t just about storing and serving data —<strong> it’s about making sure every piece of the system agrees on what’s true, even when chaos strikes</strong>. Picture this: servers in different corners of the globe are constantly talking to each other, ensuring that the actions you take are faithfully recorded. But what happens when a few servers go offline or lose communication? How do the remaining servers still maintain agreement, ensuring consistency across the system?</p><p>This is where <strong>consensus algorithms</strong> come in. They’re not about keeping systems fast or available — they’re about making sure everyone eventually agrees on the state of the data, no matter how scattered or unpredictable the environment becomes.</p><h3>Why Consensus?</h3><p>Imagine a global system that spans hundreds or thousands of servers. In a Distributed System, each server (or <strong>node</strong>) operates independently but is part of a larger network. They collaborate to handle requests, share data, and maintain a consistent state. A user’s request to update or retrieve information can hit any server in the network. How do we ensure that every server agrees on what happened last, even if some parts of the network go down or experience delays? This is the essence of <strong>Consensus</strong>.</p><h4>In distributed systems,</h4><ul><li><strong>Multiple nodes</strong> need to agree on a decision.</li><li><strong>Failures</strong> will inevitably happen.</li><li><strong>Consistency</strong> of data is critical to ensure users aren’t met with conflicting information.</li></ul><p>At its core, consensus ensures that even when parts of the system become unreliable, a unified decision can emerge, preserving the integrity of the entire network.</p><p><em>Consider a scenario with a popular online banking service. When a user initiates a money transfer, the request can be processed by any server in the network. If one server fails or if network communication is disrupted, consensus algorithms help ensure that the remaining servers can agree on the transaction’s status. This prevents issues like double spending, ensuring the user receives accurate and consistent information.</em></p><h4>Challenges of Consensus</h4><ol><li><strong>Node Failures</strong>: A server could crash or go offline. Consensus algorithms must ensure that the remaining nodes can still agree on a decision, even without full participation.</li><li><strong>Message Delays and Partitions:</strong> Some nodes may experience delayed communication due to network issues, leading to potential splits in the network (partitions). Consensus needs to tolerate these delays while ensuring that the system remains operational and can eventually reach agreement.</li><li><strong>Conflicting Proposals:</strong> Multiple nodes might propose different values at the same time. The system must ensure only one value is chosen and agreed upon by all.</li></ol><p><strong><em>Consensus algorithms</em></strong><em> like </em><strong><em>Paxos</em></strong><em> and </em><strong><em>Raft</em></strong><em> tackle these challenges head-on. They provide structured methods for nodes to reach agreement in the face of failure, delays, and conflicting inputs.</em></p><h3>Paxos: The Old Guard of Consensus</h3><p>Developed by <strong><em>Leslie Lamport </em></strong>in the late 20th century, <strong>Paxos</strong> is often the first algorithm people hear about when they dive into consensus. While widely known, it’s also infamous for being difficult to understand due to its intricate and format proofs.</p><p>However, when you strip away the complexity, Paxos has a surprisingly simple idea: <strong>ensure that a majority of nodes agree on a decision, and you can tolerate some failures while guaranteeing consensus</strong>.</p><h4>How Paxos Works</h4><p>Paxos operates through a series of well-defined roles and phases that facilitate agreement among distributed nodes.</p><h4><strong>Roles in Paxos</strong></h4><p>It is divided into <strong>three roles</strong> that nodes can play at different times.</p><ol><li><strong>Proposers</strong>: Nodes that initiate proposals for a value.</li><li><strong>Acceptors</strong>: Nodes that receive proposals and decide whether to accept them based on certain criteria.</li><li><strong>Learners</strong>: Nodes that learn the final value that has been agreed upon by the majority.</li></ol><h4><strong>Phases of Paxos</strong></h4><p>It operates in two main phases: <strong>Prepare</strong> and <strong>Accept. </strong>To better understand these phases, let’s consider a <em>simplified example involving a </em><strong><em>distributed configuration management system</em></strong><em> used by a company that operates multiple services across different servers.</em></p><h4><strong>I. Prepare Phase:</strong></h4><ul><li>A Proposer selects a proposal number, say N, and sends a Prepare request with this number to a quorum (a majority) of Acceptors.</li><li>The Acceptors respond in one of two ways: <strong>(1) </strong>If they have not accepted any proposals with a higher number, they promise not to accept any lower-numbered proposals Or, <strong>(2)</strong> they can acknowledge the highest-numbered proposal they have accepted so far (if any).</li></ul><p><em>For instance, Imagine four friends: Alex, Bella, Charlie, and Dana, deciding on dinner plans. Alex, acting as the </em><strong><em>Proposer</em></strong><em>, suggests Italian food (Proposal 1). He checks with Charlie and Dana, who are the </em><strong><em>Acceptors</em></strong><em>.</em></p><p><em>Charlie, having no prior commitments to a dinner plan, promises not to consider any other suggestions until this one is resolved.<br>Dana, on the other hand, remembers that they had discussed Thai food earlier. So, she responds by saying, “I already considered Thai food, but I’ll wait before making a final choice.”<br>In this analogy, Charlie and Dana are making promises about whether they will accept any new proposals before considering Alex’s.</em></p><h4><strong>II. Accept Phase:</strong></h4><ul><li>If the Proposer receives a promise from a majority of Acceptors, it can propose a value. The value can be the one <strong>it initially suggested or the highest one </strong>it received from Acceptors in the previous step.</li><li>The Proposer sends an <strong>Accept request</strong> with this value to the Acceptors.</li><li>If a majority agrees, the value is accepted and communicated to all Learners.</li></ul><p><em>If the Proposer (Alex) receives a majority of promises from the Acceptors, it can then propose a value. The Proposer can either suggest the same value it originally wanted (Italian food) or adopt the highest value it received from the Acceptors (in this case, Thai food if Dana had mentioned it).</em></p><p><em>Since Charlie and Dana both agreed to at least consider Italian food, Alex decides to propose it again. He sends out an </em><strong><em>Accept request</em></strong><em>, asking, “Are we all good with Italian food now?”</em></p><p><em>If Charlie and Dana agree (forming a majority), the group settles on Italian food, and the decision is communicated to the rest of the group (other friends).</em></p><h4><strong>Handling Conflicts:</strong></h4><p>In a distributed system, there may be scenarios where <strong>multiple Proposers</strong> try to propose values simultaneously. This could lead to conflicts if two proposals are competing at the same time.</p><p><em>Now, suppose Bella wakes up late and decides to propose sushi (Proposal 2). She sends her own Prepare request to Charlie and Dana. Since Bella’s proposal number (2) is higher than Alex’s (1), Charlie and Dana might now agree to consider Bella’s suggestion of sushi.</em></p><p><em>Here, Bella’s higher-numbered proposal might preempt Alex’s earlier one, depending on whether a majority of Acceptors support it.</em></p><h4><strong>Resolving Issues:</strong></h4><p>If a Proposer doesn’t receive a majority of promises, it can try again with a higher proposal number. This mechanism helps prevent infinite loops of conflicting proposals.</p><p><em>If Bella’s proposal for sushi is ignored, it could be because Paxos has already locked in Alex’s previous proposal for Italian food after gaining majority acceptance. Once a quorum of Acceptors commits to a proposal, it becomes locked, and further proposals can’t override it unless they build on the previous consensus. Bella could try again later with a higher proposal number (say, Proposal 3). Over time, consensus will be reached when a majority accepts the highest-numbered proposal, ensuring that the group agrees on a single restaurant.</em></p><p>This process ensures that even if some servers go down during this decision-making process, <strong>as long as a majority of servers remain operational, the consensus can be achieved</strong> without conflicting configurations across the system.</p><h4>Why Paxos is Hard to Implement</h4><p>Despite its conceptual simplicity, implementing Paxos is notoriously challenging for several reasons:</p><ul><li><strong>Complexity of Failures</strong>: Handling various failure scenarios (e.g., network partitions, node crashes) while maintaining consensus adds layers of complexity. <em>For instance, if Server A crashes after sending a </em>Prepare<em> request but before it can propose a value, how do the other servers proceed? This requires careful design to ensure that they can still reach consensus.</em></li><li><strong>Message Complexity:</strong> The number if messages exchanged can grow rapidly, especially in larger systems, making performance a concern. In a system with many nodes, each proposer can initiate multiple proposals, leading to a significant increase in the message overhead.</li><li><strong>Interleaved Operations:</strong> The roles of Proposers, Acceptors, and Learners can change dynamically, leading to potential confusion about the state of the system at any given time. <em>For example, if a node that was previously an Acceptor suddenly becomes a Proposer, it must still adhere to the rules of the protocol.</em></li></ul><h4>Paxos In Action</h4><p>Let’s see few real-world applications that employ Paxos.</p><h4><strong>Example I: Google Chubby</strong></h4><p><em>A</em><strong> </strong><em>distributed lock service that uses Paxos to ensure that multiple processes can coordinate access to shared resources without conflicts. Chubby ensures that a lock is either acquired or released correctly by using Paxos to maintain a consistent state among its nodes.</em></p><p>Imagine a service called <strong>File Management Service (FMS),</strong> which needs to change the replication factor for certain files from 3 to 5 to improve redundancy. FMS acts as the <strong>client</strong> in this scenario.</p><p>There are several Chubby servers (A, B, C) that function as <strong>acceptors</strong>. They maintain the current state of locks and help coordinate the lock acquisition process.</p><h4><strong>Process of Lock Acquisition:</strong></h4><ol><li><strong>Requesting the Lock: </strong>FMS generates a proposal number (eg., N=1) to acquire a lock on a shared resource (eg., ReplicationConfigLock). It sends a Prepare(1, &quot;ReplicationConfigLock&quot;) message to a quorum of Chubby servers.</li><li><strong>Acceptors Respond:</strong> Each Chubby server (acceptor) receives the Prepare request and checks its state: <strong>Chubby Server A </strong>— <em>has not accepted any proposals yet and responds with a promise </em>Promise(1, None) , <strong>Chubby Server B</strong> — <em>has previously accepted a proposal for the replication factor of 3 with a lower proposal number. It responds with </em>Promise(0, &quot;ReplicationConfigLock&quot;) , <strong>Chubby Server C </strong>—<em> Did not provide a promise (or we can assume it did not respond in this scenario for simplicity).</em></li><li><strong>Client Receives Promises:</strong> FMS collects the responses from the acceptors. Since it received a majority (or quorum) of promises (from A and B), it can proceed to propose the lock acquisition.</li><li><strong>Proposing the Lock:</strong> FMS now proposes to acquire the lock onReplicationConfigLock and sends an Accept(1, &quot;ReplicationConfigLock&quot;) messages to the same chubby servers.</li><li><strong>Final Consensus: </strong>Each Chubby server checks if they can accept the proposal based on their previous promises. All three servers confirm the acceptance, and FMS is notified that is has successfully acquired the lock on ReplicationConfigLock</li><li><strong>Lock State Update:</strong> Chubby updates its internal state to reflect that ReplicationConfigLock is now help by FMS, ensuring that no other client can acquire the lock until it is released.</li></ol><h4><strong>Release of the Lock:</strong></h4><ul><li>When FMS finishes its work (eg., updating the replication factor from 3 to 5), it will send a release request, following a similar process to ensure that the lock is safely released for other clients to use.</li></ul><h4>Example II: Amazon DynamoDB</h4><p><em>A fully managed NoSQL database service, although primarily based on a different consensus model, incorporates Paxos like techniques for specific operations to maintain data integrity across nodes.</em></p><h4><strong>How Paxos is Used:</strong></h4><p>When multiple clients attempt to update the same item in DynamoDB, the first client to send an update request acts as a <strong>Proposer</strong>. It generates a proposal (eg., N=1) and sends an Update request to the nodes responsible for the data item as Update(1, &quot;item123&quot;, &quot;newValue&quot;)</p><p>DynamoDB employs a quorum-based approach to ensure that updates are consistent across nodes:</p><ul><li>Each node (acting as an <strong>Acceptor</strong>) receives the update request and checks whether it can accept the proposal based on the current state and the previous updates it has recorded.</li><li>Nodes respond with promises based on their states, Promise(1, &quot;oldValue&quot;)</li></ul><p>The Proposer collects responses from a majority of nodes. If a majority confirms the current value, the Proposer can finalise the update Accept(1, &quot;item123&quot;, &quot;newValue&quot;). Once the nodes receive the Accept request, they update their records to reflect the new value.</p><h4><strong>Handling Conflicts</strong></h4><p>DynamoDB uses <strong>versioning</strong> to manage conflicting update requests. Each item has a version number that increments with every successful update. <strong>When two clients send updates simultaneously</strong>, the first request is processed, and the version number is updated. The second request, carrying an outdated version, is rejected due to a mismatch, prompting the client to retry with the latest version.</p><h3>Raft: Consensus Made Understandable</h3><p>If Paxos is powerful but hard to grasp, <strong>Raft</strong> is its more approachable cousin. Created by <strong><em>Diego Ongaro</em></strong> and <strong><em>John Ousterhout</em></strong><em>, </em>Raft was designed with one key goal in mind: <strong>make consensus easier to understand and implement</strong>.</p><p>While Raft doesn’t fundamentally change how consensus works compared to Paxos, it organises the process in a more intuitive, leader-driven way, making it easier for developers to grasp.</p><h3>How Raft Works</h3><p>Raft centres around the concept of a <strong>leader</strong>. In Raft, there’s always one node designated as the <strong>leader</strong>, responsible for managing the system’s operations and ensuring data replication across the other nodes (known as <strong>followers</strong>). Raft can be broken down into <strong>three stages:</strong></p><h4><strong>I. Leader Election:</strong></h4><p>When the system starts, or if the current leader fails, nodes hold an election to choose a new leader. A candidate node becomes the leader by receiving a majority of votes from other nodes.</p><p>Each node begins as a follower. If a follower doesn’t hear from the leader within a defined timeout period, it assumes the leader has failed and becomes a <strong>candidate, </strong>initiating<strong> an election.</strong></p><p><em>For example, In a cluster of five nodes (A, B, C, D, E), if the current leader (Node A) fails, Node C might time out and start an election. It will ask the other nodes for votes, and if a majority (e.g., Nodes B, D, and E) vote for C, then C becomes the new leader.</em></p><h4><strong>II. Log Replication:</strong></h4><p>The leader handles all client requests (such as updates or reads) and replicates changes to its followers to maintain synchronisation.</p><p>When a client request involves updating data, the leader appends the change to its log and sends this update to the followers. The update is considered <strong>committed</strong> only after a majority of followers acknowledge the entry.</p><p>This process is akin to a <strong>two-phase commit protocol</strong>:</p><ol><li><strong>Prepare Phase:</strong> The leader replicates the log entry by sending it to followers.</li><li><strong>Commit Phase:</strong> Once a majority of followers confirm the replication, the leader commits the entry and notifies the client.</li></ol><p>This ensures data consistency and fault tolerance, as a majority quorum is always involved in the decision-making process.</p><h4><strong>III. Commitment:</strong></h4><p>After the leader successfully replicates changes to a majority of followers, it commits the changes and notifies the client that the operation is complete. This process ensures that even if some followers fail, as long as a majority are functional, the system can achieve consensus and provide consistent results.</p><h4>Safety and Liveness In Raft</h4><p>Raft guarantees both safety (avoiding conflicting decisions) and liveness (the system remains operational) even with some node failures through:</p><ul><li><strong>Election Safety:</strong> Raft ensures that at most one leader is elected in any given term, preventing conflicting decisions or split-brain scenarios. Only one node at a time holds the power to propose and commit changes.</li><li><strong>Leader Append-Only: </strong>The leader can only append new entries to the log; it cannot change or delete old entries.</li><li><strong>Follower Log Synchronisation:</strong> The leader ensures that followers logs are up-to-date by resending missing or out-of-sync log entries. This ensures consistency across nodes.</li><li><strong>Commit Guarantees:</strong> The leader doesn’t mark an entry as committed until it knows the majority of followers have replicated it.</li><li><strong>Timeouts and Heartbeats: </strong>To detect failed leaders, Raft uses timeouts. Leaders also send periodic “heartbeats” to followers to signal that they are still alive.</li></ul><p>Raft’s straightforward approach has made it a popular choice in modern distributed systems, including projects like <strong>Etcd</strong> and <strong>Consul</strong>, which use it as their consensus mechanism.</p><h3>Beyond Paxos and Raft: Modern Innovations</h3><p>While Paxos and Raft are two foundational consensus algorithms, newer approaches have emerged, designed to improve performance, scalability, and fault tolerance in the face of real-world challenges.</p><h4>Multi-Paxos and EPaxos (Paxos Variants)</h4><p>Paxos, in its basic form, is a consensus algorithm that does not explicitly require a leader to operate. The algorithm relies on a series of phases (Prepare, Promise, Accept, Commit) to achieve agreement among distributed nodes (Proposers, Acceptors, and Learners). Each Proposer can initiate the process of reaching consensus independently.</p><p>However, in practice, <strong>classical Paxos can face inefficiencies</strong> due to contention among multiple Proposers. Multiple Proposers initiating requests simultaneously can lead to conflicts, requiring repeated rounds of consensus to resolve them, which degrades performance.</p><p>To address these inefficiencies, <strong>Multi-Paxos</strong> introduces a leader:</p><ol><li>Once elected, the leader coordinates most of the proposal process, avoiding conflicts caused by multiple Proposers.</li><li>The leader handles client requests and ensures decisions are made quickly, bypassing certain phases of the Paxos protocol for efficiency.</li><li>By reducing contention and redundant message exchanges, Multi-Paxos achieves significantly better performance in real-world scenarios with high throughput demands.</li></ol><p><strong>EPaxos (Egalitarian Paxos)</strong>, on the other hand, minimises reliance on a leader. Instead of designating a single leader, EPaxos allows any node to propose commands. Dependency tracking and conflict resolution mechanisms ensure commands are executed in a consistent order, even if they are proposed concurrently by different nodes.</p><p>This leaderless approach improves system resilience and throughput in scenarios where a single leader might become a bottleneck or a single point of failure.</p><h4><strong>Chubby and ZAB (Zookeeper Atomic Broadcast)</strong></h4><p><strong>Chubby</strong>, Google’s distributed lock service, and <strong>ZAB</strong>, used by Apache Zookeeper, are systems designed for coordination in distributed systems. While not general-purpose consensus algorithms like Paxos or Raft, they solve similar problems by offering reliable leader election and strong consistency guarantees.</p><p><strong>ZAB</strong> uses a primary-backup model where one node (the leader) manages state updates while the rest act as backups. This system excels in environments where low-latency coordination and configuration management are critical.</p><h4>Viewstamped Replication</h4><p>Developed around the same time as Paxos, <strong>Viewstamped Replication (VR)</strong> uses a similar leader-based approach. It was rediscovered in recent years due to its simplicity and has been reimplemented in several modern systems, including <strong>Spanner</strong> (Google’s distributed database).</p><h4>Tendermint and Byzantine Fault Tolerance</h4><p>In some systems, especially those dealing with potential adversaries (such as blockchain networks), it’s necessary to tolerate <strong>Byzantine faults</strong> — where nodes may act maliciously or arbitrarily. <strong>Tendermint</strong> is an example of a consensus algorithm designed for such environments, ensuring consensus even when some nodes try to cheat or disrupt the process.</p><h4>Consensus in Shared and Partitioned Systems</h4><p>To improve scalability, some modern systems split data into shards or partitions, each with its own consensus group. In such systems, the challenge is maintaining global consistency across multiple consensus groups. For example, Google’s <strong>Spanner</strong> and <strong>CockroachDB</strong> use <strong>Truetime</strong> or synchronised clocks to ensure consistency across partitions. While these systems use Paxos or Raft like algorithms within each shard, the overall architecture requires more sophisticated coordination to ensure that globally consistent decisions are made.</p><h3>Bringing It All Together: When to Use What?</h3><p>Each consensus algorithm offers a unique balance of performance, fault tolerance, and complexity. The choice of which algorithm to use depends on the needs of the system you’re building:</p><ul><li><strong>Paxos</strong> is a solid choice if your primary focus is on achieving <strong>fault tolerance </strong>and<strong> strong consistency</strong>, even if it comes with some complexity. It’s well-suited for distributed databases that require high availability, like <strong><em>Google’s Chubby</em></strong>.</li><li><strong>Raft</strong> is ideal for applications that require quick recovery from failures, such as in configuration management systems like <strong><em>etcd</em></strong> or service discovery tools like <strong><em>Consul</em></strong>. Raft excels in situations where maintaining a clear and consistent state across distributed nodes is crucial with ease of implementation.</li><li>If <strong>security is a concern </strong>and you need protection against malicious nodes, consider using <strong>Byzantine Fault Tolerant (BFT)</strong> algorithms like Tendermint. These are ideal for environments like blockchains or financial systems where trust is a significant factor.</li><li>For decentralised, trust less environments, such as public blockchains, you might opt for consensus mechanisms like <strong>Proof of Work </strong>or <strong>Proof of Stake</strong>. <strong><em>Bitcoin</em></strong><em>, for example, operates on a Proof of Work basis, while </em><strong><em>Ethereum</em></strong><em> has transitioned to Proof of Stake.</em></li></ul><p>Understanding these algorithms is not just an academic exercise; it’s central to building systems that can survive real-world challenges, from network outages to malicious attacks.</p><p><em>In the end, consensus is the glue that holds distributed systems together. Whether it’s ensuring your payment is processed correctly, your document syncs seamlessly, or your online purchase goes through without a hitch, these algorithms are working tirelessly behind the scenes to make sure everything runs smoothly.</em></p><p>Thanks for your time, Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa40f29fcdeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The CAP Tango]]></title>
            <link>https://medium.com/@rangavamsi5/the-cap-tango-6c39353e2a65?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c39353e2a65</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[cap-theorem]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 16:11:20 GMT</pubDate>
            <atom:updated>2024-12-09T16:11:20.481Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Balancing the Triad of distributed systems</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cMllzDIhYwDghxV3" /><figcaption>Photo by <a href="https://unsplash.com/@georgebakos?utm_source=medium&amp;utm_medium=referral">George Bakos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you’re designing a distributed system to handle millions of users across the globe. Your data is spread across multiple servers, ensuring that no matter where your users are, they get a fast and reliable experience. Everything runs smoothly — until something goes wrong. A network partition occurs, and suddenly, some servers can’t communicate with others. You’re now facing a dilemma: <strong><em>Do you prioritise keeping your data consistent across all servers, or do you focus on keeping your system available to users, even if it means they might see outdated or inconsistent information?</em></strong></p><p>This is the essence of the <strong>CAP theorem</strong> — the unavoidable trade-off between Consistency, Availability and Partition Tolerance in distributed systems. What if I told you that no matter how brilliant your engineering is, <strong>you cannot have it all</strong> ? The trade-offs you make today will shape how your system survives tomorrow’s chaos.</p><h3>The Three Pillars</h3><p>The core elements of CAP theorem — <strong>Consistency</strong>, <strong>Availability</strong> and <strong>Partition Tolerance</strong>.</p><h4>Consistency: The Single Truth</h4><p>Imagine you’re editing a document with a colleague in real-time. You expect that no matter which device you’re on or how many changes are made, everyone sees the exact same version at any given moment.</p><blockquote><em>This is </em><strong><em>consistency</em></strong><em> </em>— “every node in the system has the same, up-to-date data after an operation is completed<em>”</em></blockquote><p>In technical terms, consistency guarantees that all reads to the system will return the most recent write. If you update a record, the next person (or system) querying that record will see your change immediately.</p><p><strong>The Trade-Off ?</strong> Forcing every part of the system to stay in sync can cause delays, especially if something goes wrong in the network or a node fails. While users expect systems to always return the most recent data, ensuring this across multiple servers or locations can come at the cost of performance or fault tolerance.</p><h4>Availability: Always On, Always Ready</h4><p>Now imagine that while editing the document, you lose connection for a moment. Yet, the application allows you to keep working, and as soon as you reconnect, your changes are uploaded without any issues.</p><blockquote><em>This is </em><strong><em>availability </em>— </strong>“the system remains operational and responsive, ensuring that every request gets a response, whether or not it can provide the most up-to-date data”.</blockquote><p>In a highly available system, even when parts of the network fail or some nodes go down, the system still serves requests.</p><p><strong>The Catch?</strong> You might not get the freshest data because not all parts of the system may be fully in sync. It prioritises uptime and responsiveness over ensuring that everyone sees the exact same data in real-time, but users don’t experience downtime even when things go wrong.</p><h4>Partition Tolerance: Surviving the Chaos</h4><p>Imagine you and your colleague are working on the same document but from different cities. Suddenly, there’s a network outrage in one region that cuts off communication between both of you. Despite this disruption, both of you continue editing your own copies of the document.</p><blockquote><em>This is </em><strong><em>partition tolerance</em></strong><em> </em>— “the system can still operate even when parts of the network become isolated and nodes cannot communicate with each other”.</blockquote><p>In technical terms, partition tolerance ensures that the distributed system remains functional, allowing users to continue reading and writing data, even when some nodes are unreachable.</p><p><strong>The Challenge?</strong> Each node holds a different version of the data due to their isolated operations. This can lead to inconsistencies that must be resolved once the network is restored.</p><h3>Why You Can’t Have It All</h3><p>The CAP theorem presents a challenge in balancing its three pillars. In practice, you can’t have all three at once. Depending on what your application needs, you might have to prioritise one over the others.</p><h4>Visualising the Triangle</h4><p>Imagine the triangle where each vertex represents one of the the pillars encapsulates the core challenge of distributed system design.</p><blockquote>When you push toward one corner, you often pull away from the others.</blockquote><ul><li><strong>Consistency</strong> is represented at the top of the triangle. When prioritised, systems ensure that every read returns the most recent write. However, this comes at a cost. In scenarios of network partitioning — like a temporary outage or a node failure — maintaining strict consistency might necessitate halting operations altogether, leading to unavailability for users.</li><li><strong>Availability</strong> sits at the bottom left of the corner. A system optimised for availability will respond to all requests, even if it means providing slightly outdated or inconsistent data. While this keeps users happy and engaged, it may lead to conflicts and inconsistencies that require eventual resolution once the network stabilises.</li><li><strong>Partition Tolerance</strong>, located at the bottom right corner, signifies the system’s ability to function even when parts of the network are unreachable.</li></ul><p>This model highlights a crucial insight: <strong>you can’t optimise for all three properties simultaneously</strong>. Each decision made at one vertex influences the others, requiring a nuanced understanding of the system’s goals and the user experience.</p><h4>Consistency vs. Availability: The Trade-Off</h4><p>In the world of distributed systems, the tug-of-war between consistency and availability often dictates design choices. Take financial services, for example: users expect immediate access to the most accurate data during transactions, making consistency crucial. This often results in systems that block requests until all nodes confirm they have the latest information, which can lead to delays or even downtime.</p><p>On the flip side, consider social media platforms, where user experience is paramount. Here, availability takes centre stage; users want to post updates and comments without interruptions, even if it means that the data might not be perfectly in sync.</p><p>This reflects a <strong>fundamental trade-off</strong>: prioritising consistency may enhance data integrity but can compromise user satisfaction due to latency. In contrast, prioritising availability might result in temporary inconsistencies that users can tolerate for a better experience.</p><blockquote>In high-stakes environments, consistency is critical; In user-centric scenarios, availability often prevails.</blockquote><h4>Partition Tolerance: The Non-Negotiable Necessity</h4><p>In the CAP theorem, <strong>Partition Tolerance (P)</strong> is often emphasised as the cornerstone of robust distributed systems. This prioritisation stems from the reality that network failures are not merely theoretical scenarios; they are everyday occurrences in the digital landscape. <em>As Martin Kleppmann explains</em>, <strong><em>“Network partitions can happen at any time, and a distributed system must remain functional despite them”.</em></strong><em> </em>This reality underscores the necessity for systems to tolerate partitions rather than attempting to eliminate them entirely.</p><p>The emphasis on partition tolerance leads to the understanding that maintaining consistency and availability becomes a balancing act. <em>For example, databases like </em><strong><em>Cassandra</em></strong><em> and </em><strong><em>DynamoDB</em></strong><em> prioritise availability and partition tolerance, allowing operations to proceed even when some nodes are unreachable. In contrast, systems like </em><strong><em>MongoDB</em></strong><em> and </em><strong><em>CockroachDB</em></strong><em> lean toward consistency, ensuring that transactions are synchronised across nodes but may sacrifice availability during partitions.</em></p><blockquote>In distributed systems, partition tolerance is not just a design consideration; it’s an essential requirement for maintaining functionality amid network unpredictability.</blockquote><h4>Finding Your Sweet Spot: Choosing the Right Approach</h4><p>Ultimately, the right balance between these three pillars depends on the specific needs of your applications. In practice, many systems will adopt a “<strong>CP</strong>” (Consistency and Partition Tolerance) or “<strong>AP</strong>” (Availability and Partition Tolerance) approach, depending on what they can compromise.</p><p>It’s important to note that achieving both <strong>Consistency</strong> and <strong>Availability</strong> (<strong>CA</strong>) simultaneously is impossible in the presence of network partitions, as stated by the CAP theorem. When a network partition occurs, a system must choose between maintaining consistency or ensuring availability. Systems that prioritise <strong>CA</strong> may become unavailable during network issues, resulting in a loss of functionality for users.</p><h3>CAP in Action</h3><p>Let’s see few real-world applications that exemplify the trade-offs between consistency, availability, and partition tolerance.</p><h4>Financial Services: Consistency First</h4><p>In industries such as banking and finance, <strong>consistency</strong> is paramount. Consider a payment processing system that ensures each transaction is recorded accurately across all nodes. For these systems, even a minor inconsistency could lead to significant financial discrepancies.</p><p>Banks often implement distributed databases with strong consistency guarantees, utilising<strong> “consensus algorithms”</strong> like <strong><em>Paxos</em></strong> or <strong><em>Raft</em></strong>. These approaches can lead to increased latency, particularly during network partitions, as systems may choose to block transactions until consensus is achieved.</p><h4>E-Commerce Platforms: A Balancing Act</h4><p>E-commerce platforms, like Flipkart, face a unique challenge where both consistency and availability is critical, but not always achievable. During high-traffic events such as Big-Billion-Days, these platforms prioritise availability to handle an influx of users. While users might see slightly outdated inventory levels, the system remains responsive, allowing transactions to proceed without disruption. Once the load stabilises, the system can reconcile any inconsistencies, ensuring that customers receive accurate order confirmations.</p><h4>Social Media: Emphasising Availability</h4><p>On the other end of the spectrum, social media platforms such as Twitter prioritise availability over consistency. Users expect to share updates instantly, even if this means their followers might not see the most current version of a tweet immediately.</p><p>In these systems, “<strong>eventual consistency”</strong> models are employed, allowing updates to propagate through the network at a pace that ensures a seamless user experience.</p><h4>Real-Time Collaboration Tools: The Dual Approach</h4><p>Applications like Google Docs exemplify a hybrid approach to the CAP theorem. While the system aims for strong consistency during collaborative editing sessions, it remains operational even amidst network partitions. Google employs sophisticated algorithms to manage concurrent edits, allowing users to work seamlessly while synchronising changes in the background.</p><h4>A Brief History of CAP</h4><p>The CAP theorem, also known as <strong>Brewer’s theorem</strong>, was first introduced by computer scientist <strong>Eric Brewer</strong> in the early 2000s. As distributed systems became increasingly vital for web-scale applications, Brewer’s insight into the inherent trade-offs between consistency, availability, and partition tolerance provided a foundational framework.</p><p>His work led to the realisation that <strong>in distributed systems, especially under failure conditions, you can only guarantee two of the three components</strong>. This has shaped how we design, manage, and scale modern systems today.</p><p><em>In Conclusion, whether it’s prioritising consistency in financial transactions or ensuring high availability for user-generated content, the </em><strong><em>challenge lies in finding the right equilibrium</em></strong><em>. The CAP theorem is not about limitations, but about making informed.</em></p><p>Thanks for your time. Happy Learning !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c39353e2a65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clockwork In Distributed Systems]]></title>
            <link>https://medium.com/@rangavamsi5/clockwork-in-distributed-systems-6788ba997479?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/6788ba997479</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[vector-clocks]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[lamport-timestamps]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Sat, 02 Nov 2024 06:01:06 GMT</pubDate>
            <atom:updated>2025-02-05T04:49:46.602Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Managing Event Order</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ygH9Cxf9dHkDpCSB" /><figcaption>Photo by <a href="https://unsplash.com/@olenichek?utm_source=medium&amp;utm_medium=referral">Daria Glakteeva</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a world where every person lives in a different time zone, each with their own clock, and these clocks may or may not be synchronised. Now, picture them collaborating on a project where the sequence of their actions is critical. This is the challenge distributed systems face with time: <strong>How can we order events when there’s no global clock to rely on?</strong></p><h3>Why Is Time Crucial?</h3><p>Time in distributed systems defines more than just the order of events; it also sets the boundaries of algorithms and helps distinguish between normal delays and system failures. Here’s are the core reasons:</p><ul><li><strong>Ordering of Events:</strong> In distributed databases, “<strong>serialisability”</strong> — ensuring that transactions appear to occur in a serial order — depends on the correct ordering of events. <em>If two nodes process the same data concurrently, the order in which they update that data becomes critical</em>.</li><li><strong>Contention Resolution: </strong>Time can also act as a “<strong>tie-breaker” </strong>when multiple nodes contend for the same resource. <em>For instance, if two customers simultaneously order the last available item in stock, the system must fulfil one order and cancel the other. Time allows the system to determine who ordered first.</em></li><li><strong>Boundary Conditions for Algorithms</strong>: Timeouts help systems define the “boundary between <strong>high latency</strong> and <strong>failure detection”</strong>. <em>If a node doesn’t respond within a given time, the system must decide whether the node is slow or has failed.</em></li></ul><p>A global clock would make ordering simple, but in its absence, systems must communicate to determine the relative order of events.</p><h3>Lamport Clocks: The Search for Order</h3><p>Without synchronised physical clocks, systems need a way to maintain an order of events that all nodes can agree on. This is where <strong>logical clocks </strong>like <strong>Lamport Clocks </strong>step in. They aren’t physical clocks but <strong>logical counters</strong> that track event order. Here’s how they work:</p><ol><li><strong>Local Increments:</strong> Every process (or node) maintains its own counter: local_counter Whenever an event occurs (e.g., a message is sent, a task is processed), the process increments this counter.</li><li><strong>Message Passing: </strong>When a process sends a message to another, it includes its current counter value.</li><li><strong>Merging: </strong>Upon receiving a message, the process updates its counter to: max(local_counter, received_counter) + 1</li></ol><p>Lamport clocks are designed <strong>not to synchronise clocks but to maintain the logical sequence </strong>over these disjointed<strong> </strong>events. Instead of focusing on real-time accuracy, these clocks give each event a timestamp that acts like a marker of <strong>relative order</strong>.</p><h4>Timestamps as a Ledger, Not a Clock</h4><p>Each event in the system is assigned a number, but that number isn’t tied to the real world. It’s a token of when something happened in relation to everything else on that node.</p><p>Imagine Lamport timestamps as entries in a ledger rather than traditional clocks. Each event is marked with a relative timestamp that reflects its position in the sequence of events, <strong>not absolute time</strong>.</p><p>This ledger-like approach means <strong>each node records its events in relation to others</strong>. As messages are exchanged, timestamps travel with them, and receiving nodes update their counters to ensure a consistent order. While we don’t know the exact timing of events, we understand their relative sequence, indicating which event happened before another.</p><blockquote>I may not know when exactly, but I know this happened after that.</blockquote><h4>Partial Understanding of Causality</h4><p>Lamport Clocks can’t actually tell you why something happened. They give you a sequence but no guarantees about the causal relationships between events. Consider this:</p><pre>Event A on Node 1 gets timestamp 3<br>Event B on Node 2 gets timestamp 5</pre><p>Event though Event A’s timestamp is smaller, Lamport Clocks can’t tell you if A caused B or if they’re unrelated events that just happened to occur close together. The system only knows that they are ordered relatively to same clock. This leads to <strong>partial causality</strong> — <em>an understanding of </em><strong><em>“happens-before”</em></strong><em> relationships but without the deeper connectivity between events</em>.</p><h4>Order Isn’t Enough</h4><p>Let’s imagine a scenario where several nodes in a distributed system are exchanging signals. For instance, <strong>Node A</strong> sends a message to <strong>Node B</strong>, which then forwards it to <strong>Node C</strong>. Using Lamport Clocks, we can easily track the order of events: <strong>A</strong> happened before <strong>B</strong>, and <strong>B</strong> happened before <strong>C</strong>. Simple enough, right?</p><p>But what happens if <strong>Node D</strong> also sends a message to <strong>Node C</strong>, but through a completely different path? Now, Node C is influenced by two separate events — one from the <strong>A-B-C</strong> chain and other from the the <strong>D-C</strong> chain. In this situation, <strong>Lamport Clocks lose sight of the broader context</strong>. The influence from Node D doesn’t appear in the same clock sequence, and this gap introduces a <strong>propagation delay</strong> that Lamport Clocks can’t detect.</p><p>Lamport clocks which rely on local counters, can only track events along a single path and in a single order. They aren’t designed to capture multiple, independent influences on a single node.</p><blockquote>Lamport clocks are good at showing local order, but they fail when multiple chains of events intersect or converge.</blockquote><h4>Concurrency Blind Spots</h4><p>Imagine two nodes may <strong>independently execute events</strong> at the same time, and Lamport Clocks will assign them <strong>different numbers</strong>, as they won’t know these events happened concurrently. For instance,</p><pre>Imagine two servers processing different transactions at the same time:<br><br>Server A processes a payment (timestamp 12).<br>Server B ships an order (timestamp 15).</pre><p>Even though these events are independent, <strong>Lamport Clocks create a perceived order that doesn’t exist</strong>. The payment might appear to precede the shipment, but in reality, there’s no casual link between them. This false sense of order is a fundamental limitation of Lamport Clocks — <strong>they can’t capture true concurrency</strong>.</p><h4>Tradeoff: Simplicity vs. Precision</h4><p>In practical terms, Lamport Clocks are useful when the <strong>exact order of independent events doesn’t matter</strong>, but the relative ordering of related events does. However, their simplicity comes at the cost of precision, especially when dealing with <strong>concurrent processes</strong> or multiple <strong>event chains</strong> converging on the same node.</p><p><strong><em>In a distributed chess game</em></strong><em>, each player (Player A and Player B) is on a separate device, or “node,” and can make moves independently. Since these devices are not synchronized, they rely on Lamport clocks to create a logical order of events. Each player’s node has its own Lamport clock, which ticks forward with every action they take.</em></p><p><em>Let’s say Player A makes a move, incrementing their Lamport clock to 3, while Player B’s Lamport clock reads 5 at the same time. When each player sends their move to the server, the server receives the moves with their respective Lamport timestamps. Even though the moves might have physically arrived at the server simultaneously, the Lamport timestamps help the server logically order them. Since Player A’s timestamp (3) is lower than Player B’s (5), the server applies Player A’s move first, ensuring the moves are processed in a consistent, conflict-free order.</em></p><p><em>This sequential processing based on Lamport timestamps ensures that moves are applied in the correct order, preventing conflicts and maintaining a consistent game state.</em></p><p>While Lamport Clocks help maintain a basic order of events, they struggle with more complex scenarios like concurrent actions or multiple paths influencing a single node. To address this, we need a system that can not only track the order of events but also<strong> capture the casual relationship</strong> between them. This is where <strong>Vector Clocks </strong>come in.</p><h3>Vector Clocks: Capturing Causality</h3><p>Vector Clocks extend the concept of Lamport Clocks to capture <strong>not just the order of events but also the casual relationships</strong> between them. Unlike Lamport Clocks, which use a single counter per node, Vector Clocks <strong>maintain a vector of counters, one for each node</strong> in the system.</p><h4><strong>I. Vector Representation:</strong></h4><p>Each node in the distributed system maintains a vector of counters, with each element representing the logical clock of a different node. If there are <strong>N</strong> nodes in the system, each node has a vector <strong>V_i</strong> of size <strong>N</strong> , where <strong>i</strong> denotes the node.</p><p>For node <strong>i</strong> , the vector <strong>V_i</strong> is:</p><blockquote><strong>V_i = (C_i1, C_i2,....,C_iN)</strong></blockquote><p>Where <strong>C_{ij}</strong> is the counter value of node <strong>j</strong> as known by node <strong>i</strong></p><h4><strong>II. Local Updates</strong></h4><p>When node <strong>i</strong> performs an event, it increments its own counter in its vector. If node <strong>i</strong> performs an event, its vector clock <strong>V_i</strong> is updated as follows:</p><blockquote>V_i = (C_i1,....,...<strong>C_ii+1</strong>......,C_iN)</blockquote><p>Where <strong>C_{ij}</strong> is incremented by 1.</p><h4><strong>III. Message Passing</strong></h4><p>When node <strong>i</strong> sends a message to node <strong>j</strong> , it includes its current vector clock <strong>V_i</strong> with the message. The message will look like:</p><blockquote>(V_i, message)</blockquote><h4><strong>IV. Vector Merging</strong></h4><p>Upon receiving a message, node <strong>j</strong> updates its vector clock <strong>V_j</strong> by merging the received vector clock <strong>V_i</strong> with its own. The merge operation involves taking the element wise maximum and incrementing its own counter.</p><blockquote>V_j = max(V_j, V_i) + 1</blockquote><p>Where the max operation is applied element-wise:</p><blockquote>max(V_j​,V_i​) = (max(c_j1​, c_i1​), max(c_j2​,c_i2​),…, max(c_jN,c_iN​))</blockquote><p><em>For instance, Consider a distributed </em><strong><em>document editing system </em></strong><em>where three users (nodes) A, B, and C are collaborating on a share document. Each user can make edits and send updates to each other.</em></p><pre>1. Initial State: <br>  At the start, all nodes have the following vector clocks (assuming there are no prior events)<br><br>  Node A: V_A = (0, 0, 0)<br>  Node B: V_B = (0, 0, 0)<br>  Node C: V_C = (0, 0, 0)<br><br>2. Node A performs an Edit: <br>  2.1 Change:  Node A adds the sentence &quot;The quick brown fox&quot; to the document.<br>  2.2 Clock Update: Node A makes an edit and increments its own counter: V_A = (1,0,0)<br>  2.3 Send Message: Node A sends this update to Node B<br><br>3. Node B receives the update from Node A:<br>  3.1 Receive Message: Node B receives the message with V_A = (1,0,0). <br>  3.2 Clock Merge: It merges this vector with its own clock:<br>    =&gt; Merged V_B = max(V_B, V_A) = max((0,0,0), (1,0,0)) = (1,0,0)<br>  3.3 Clock Update: Node B increments its own counter: V_B = (1,1,0)<br><br>4. Node C edits the document independently (while B is editing):<br>  4.1 Change: Node C writes &quot;A fox is quick&quot; at the top of the document. <br>  4.2 Clock Update: Node C increments its own counter: V_C = (0, 0, 1)<br>  4.3 Send Message: Node C sends this updates to Node A<br><br>5. Node A receives an update from Node C:<br>  5.1 Receive Message: Node A receives the message with V_C = (0,0,1)<br>  5.2 Conflict: Node A sees two different changes: its own version (&quot;The quick brown fox&quot;) <br>                and Node C&#39;s version (&quot;A fox is quick&quot;).<br>  5.3 Clock Merge: It merges this vector with its own clock:<br>      =&gt; Merged V_A = max(V_A, V_C) = max((1,0,0), (0,0,1)) = (1,0,1)<br>  5.4 Clock Update: Node A increments its own counter: V_A = (2,0,1)<br>  5.5 Conflict Resolution: <br>      =&gt; Node A decides to merge both edits, keeping both sentences in the document. <br>      =&gt; Why? A compares its own vector clock with Node C&#39;s clock and detects <br>         that both clocks have progressed independently (i.e., they are concurrent) <br>  5.6 Send Message: Node A sends the merged document with the updated vector clock <br>      to both Node B and Node C to ensure everyone gets the latest version..<br><br>6. Node B receives the update from Node A (merged version)<br>  6.1 Receive Message: Node B receives the message with V_A = (2,0,1)<br>      =&gt; Message: &quot;The quick brown fox. A fox is quick&quot;<br>      =&gt; Would B accept the message or not? it compares Node A’s vector clock<br>         with its own. It is compared that V_B ≤ V_A, and can be determined that<br>         changes from Node A are causally newer or concurrent. So, it accepts<br>         the change.<br>  6.2 Clock Merge: It merges this vector with its own clock:<br>      =&gt; Merged V_B = max(V_B, V_A) = max((1,1,0), (2,0,1)) = (2,1,1)<br>  6.3 Clock Update: Node B increments its own counter: V_B = (2,2,1)</pre><h4>Understanding Causality</h4><p>Vector clocks provide a richer model of causality than Lamport Clocks. They allow us to determine both the order and causal relationships of events:</p><h4><strong>Casual Order</strong></h4><p>If event <strong>A</strong> causally influences event <strong>B</strong> , then the vector clock of <strong>A</strong> is less than the vector clock of <strong>B</strong> in a partial order sense.</p><p>Mathematically, it is represented as<strong> VA​≤VB​</strong></p><p><em>Where, </em><strong>VA​≤VB</strong> means that for all <strong>k</strong> , <strong>VAk​ ≤ VBk </strong>and there exists at least one <strong>j</strong> such that <strong>VAj​ ≤ VBj</strong>.</p><p><strong><em>Example: </em></strong><em>Consider three events in a distributed system with nodes A, B and C:</em></p><p><strong><em>Event 1</em></strong><em>: Node A performs an action.</em></p><pre>Initial vector clock: V_A = (0,0,0)<br>After Event 1: V_A = (1,0,0)</pre><p><strong><em>Event 2</em></strong><em>:</em> <em>Node B performs an action after receiving a message from Node A</em></p><pre>Initial Vector clock: V_B = (0,0,0)<br>Node B receives a message from Node A, so it merges with Node A<br>Merged V_B = max(V_B, V_A) = max((0,0,0), (1,0,0)) = (1,0,0)<br>After Event 2: V_B = (1,1,0)</pre><p><strong><em>Event 3:</em></strong> <em>Node C performs an action independently</em></p><pre>No interaction with Nodes A or B.<br>Initial Vector clock: V_C = (0,0,0)<br>After Event 3: V_C = (0,0,1)</pre><p><strong><em>Casual Order Determination:</em></strong></p><p><em>To determine if Event 1 casually precedes Event 2:</em></p><pre>Vector Clock of Event 1: V_A = (1, 0, 0)<br>Vector Clock of Event 2: V_B = (1, 1, 0)</pre><p><em>We compare these clocks:</em></p><ul><li><em>For Event 1 to casually precede Event 2, V_A​ ≤ V_B, element-wise must hold: (1,0,0) ≤ (1,1,0)</em></li></ul><p><strong><em>Therefore, Event 1 casually precedes Event 2</em></strong><em>.</em></p><h4><strong>Concurrency Detection</strong></h4><p>It involves identifying if two events are independent and do not affect each other.</p><p>Two events <strong>A</strong> and <strong>B</strong> are concurrent if their vector clocks are incomparable. This means:</p><p><strong>not (V1​≤V2​) and not (V2​≤V1​) </strong>which is equivalent to <strong>VA​ ≰ VB​ and VB​ ≰ VA</strong></p><p><em>where</em> <strong>VA≰VB</strong>​<em> indicates that </em>VA <em>is not less than or equal to</em> VB <em>in any dimension.</em></p><p><strong><em>Example</em></strong><em>: Let’s check if Event 1 and Event 3 are concurrent</em></p><pre>Vector Clock of Event 1: V_A = (1, 0, 0)<br>Vector Clock of Event 3: V_C = (0, 0, 1)</pre><p><em>To determine if Event 1 and Event 3 are concurrent:</em></p><ol><li><em>Check if Event 1 causally precedes Event 3:</em></li></ol><pre>(1,0,0) ≤ (0,0,1) (false)</pre><p><em>2. Check if Event 3 causally precedes Event 1:</em></p><pre>(0,0,1) ≤ (1,0,0) (false)</pre><p><em>Since neither condition holds, </em><strong><em>Event 1 and Event 3 are concurrent</em></strong><em>.</em></p><p>In summary, <strong>Causal Order</strong> is determined by comparing vector clocks. If VA​ ≤VB​, then Event A casually precedes Event B. If neither precedes the other, they are <strong>Concurrent</strong>.</p><h4>Real-World Example</h4><p><em>Imagine a social media platform where users can like a post. User B and User C both like the same post of User A at nearly the same time, but their actions are processed by different servers. Since the system is distributed, these servers don’t immediately communicate, and each increments the like count separately.</em></p><p><em>When the servers eventually sync, they need to reconcile the like count. Without tracking event order, they might overwrite each other’s updates, leading to incorrect results. Vector clocks help here by keeping track of event history for each server. If two events are concurrent (like these likes), the system merges them instead of discarding or overwriting data. The final like count is correct, and both servers update their state accordingly.</em></p><p><em>In distributed systems, managing event order is critical but challenging due to the absence of a global clock. While Lamport Clocks ensure basic event ordering, they struggle with concurrency and causality. Vector Clocks extend this by capturing both event order and causal relationships, making them essential for more complex distributed operations.</em></p><p>Thanks for your time. Happy Learning!</p><h3>References</h3><p><a href="https://book.mixu.net/distsys/time.html">Distributed systems</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6788ba997479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Casual Ordering in Distributed Systems]]></title>
            <link>https://medium.com/@rangavamsi5/casual-ordering-84a9d1b4a2e8?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a9d1b4a2e8</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[computers]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 03:23:25 GMT</pubDate>
            <atom:updated>2024-11-06T11:57:29.778Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ordering Events</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*giNAg0lT_5Plv7bX" /><figcaption>Photo by <a href="https://unsplash.com/@timelordmp?utm_source=medium&amp;utm_medium=referral">T I M E L O R D</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In distributed computing, ordering events correctly is like ensuring the flow of electricity through a complex circuit — if one pulse comes too early or too late, it can disrupt the entire system. Whether it’s processing user requests, running financial transactions, or coordinating micro-services, maintaining event order is crucial to avoid data corruption and ensuring consistency.</p><p>But in systems where multiple nodes are scattered across different regions, each with its own local clocks and processing times, <strong>how do we establish a reliable order?</strong> How can we trust that one event didn’t sneak ahead of another when thousands of messages are flying through the network at any given moment?</p><h3>The Illusion of Time</h3><p>Time is our tool for organising the world around us. We use it to track when a message is sent, when data is updated, or when a process starts and finishes. Whether it’s waking up on time for work or tracking a package, we trust time to help us understand the <strong>sequence of events</strong>.</p><p><strong>In an ideal world</strong>, we (<em>except Christopher Nolan</em>) believe <strong>time is linear:</strong> Event A happens, then Event B, and finally Event C. We rely on time as a <strong>shared global truth</strong>. Clocks across the globe, from New York to Tokyo, are synchronised, leaving no ambiguity about when something occurs.</p><h3>The Reality of Time</h3><p>Unlike our everyday world, Distributed systems don’t follow the straightforward understanding of time. Here’s why:</p><h4>I. Events Happen Concurrently</h4><ul><li>There’s <strong>no global clock</strong>.</li><li>Each machine has it’s own clock, ticking in isolation. Events that happen on different machines can occur simultaneously, but <strong>without a single source </strong>of truth, it’s impossible to know <strong>which happened first</strong>.</li></ul><h4>II. Network Delays</h4><ul><li>A message sent from one node to another can arrive late, out-of-order, or even be lost in transit. The receiving node can’t always be sure when the message was sent, and the sending node can’t know when it was received.</li></ul><h4>III. Partial vs. Total Order</h4><ul><li><strong>On a single node</strong>, <strong>events are relatively easy to order</strong> (<strong>total order) </strong>— after all, the machine controls its own processes.</li><li>But across multiple nodes, events can only be <strong>partially ordered</strong>. This means that while each node knows order of its local events, it can’t always be certain how they fit with the events on another node.</li></ul><h3>Reframing Time</h3><blockquote>So, how do we determine the correct sequence of events when we can’t rely on time? This raises a bigger question: <strong>why do we care so much about time in the first place? </strong>Perhaps the question we should be asking is: <strong>do we need time at all?</strong></blockquote><p>Perhaps what truly matters isn’t the precise timestamp of each event but rather the “<strong>Order”</strong> in which they occur.</p><p>Take a step back and think about it — when we say, “Event A happened Event B”, we’re not saying this because we care about the exact time on the clock. What we <strong>actually care</strong> about is the <strong>relationship between the events</strong>. <em>Did Event A cause Event B? Did Event C happen after Event B?</em></p><p>These <strong>cause-and-effect</strong> relationships are more important than the specific timing. In distributed events, this means rethinking how we track events. Instead of focusing on aligning clocks and synchronising time, maybe we should focus on <strong>ordering events based on how they influence each other</strong>.</p><blockquote>It’s not time we care about — it’s the order of events that time represents.</blockquote><p>This reframing leads us to concept known as <strong>Casual Ordering.</strong></p><h3>Casual Ordering</h3><p>In distributed systems, casual ordering helps us track <strong>how events are related </strong>— who triggered whom — without needing to rely on exact timestamps.</p><h4>The Cause and Effect Principle</h4><p>At its core, casual ordering is about understanding the <strong>cause-and-effect</strong> relationships between events. Imagine you’re sending a series of messages between nodes in a distributed system. If Event A happens before Event B, we say Event A casually precedes Event B if:</p><ol><li><strong>Same Machine Rule: </strong>If two events occur on the same machine, and one happens before the other, then the first event causally precedes the second. <em>For instance, if a user clicks a button (Event A) before receiving a message (Event B) on the same machine, the button click causally precedes the message.</em></li><li><strong>Message Passing Rule:</strong> If a machine sends a message and another machine receives it, the sending event causally precedes the receiving event. <em>So, if Node X sends a message to Node Y, Node X’s send event casually precedes Node Y’s receive event.</em></li><li><strong>Transitive Rule: </strong>If Event A causes Event B, and Event B causes Event C, then Event A causally precedes Event C. This gives us a chain of causality where earlier events influence later ones.</li></ol><p>We can infer that events are ordered <strong>not by time</strong>, but by <strong>which events cause others</strong>. This way, even without synchronised clocks, we can infer a logical order of events.</p><blockquote>Causal ordering is about determining the order of events based on their relationships, not their timestamps.</blockquote><h4>Partial Order</h4><p>One key feature of Casual ordering in distributed systems is that it doesn’t try to enforce a <strong>total order</strong> across all events in a system. Instead, it allows for <strong>partial ordering</strong>.</p><p>In a <strong>total order,</strong> every event is comparable to every other event — either Event A happened before Event B or Event B happened before Event A. But in a distributed system, we can’t always determine this because different nodes might not have any shared knowledge of each other’s events.</p><p>With <strong>partial ordering</strong>, we only order events when we know they are casually related. If two events happen on different nodes with no interaction between them, they are <strong>concurrent — </strong>neither happens before the other. This is a key insight of casual ordering: we don’t need to impose a rigid global order. Instead, <strong>we only worry about the order when there is a causal relationship</strong>.</p><h4>Communication Defines Causality</h4><p>Two machines can only influence each other through communication, meaning if there’s no communication between them, there’s no casual relationship between their events.</p><p>This leads to a critical realisation:</p><blockquote>If not A-&gt;B, then A cannot have caused B.</blockquote><p>In other words, <strong>without a casual link, two events are considered independent or concurrent</strong>.</p><p><em>In essence, </em><strong><em>causal ordering</em></strong><em> shifts our thinking </em><strong><em>from tracking time to tracking influence</em></strong><em>. It’s not about when things happened, but about understanding why they happened in that particular order.</em></p><h3>The Building Block</h3><p>From tools like <strong>Vector Clocks</strong> that help track and approximate casual relationships between events to principles like <strong>Eventual Consistency</strong> that ensure all replicas converge to the same state despite temporary inconsistencies, causal ordering <strong>provides the foundation</strong> for understanding the intricacies of distributed systems. It also helps us navigate the <strong>CAP theorem’s </strong>trade-offs between consistency, availability and partition tolerance, while appreciating <strong>Consensus algorithms</strong> such as <strong>Paxos</strong> and <strong>Raft</strong> that maintain agreement among distributed nodes. Additionally, it introduces concepts such as <strong>Lamport Timestamps</strong>, which order events across different nodes, and CRDTs (Conflict-free Replicated Data Types), which support eventual consistency without complex conflict resolution.</p><p><em>In distributed systems, understanding event order through causal relationships rather than relying on synchronised time is crucial.</em></p><p>Thanks for your time, Happy Learning !</p><h3>References</h3><ul><li><a href="https://medium.com/baseds/ordering-distributed-events-29c1dd9d1eff">Ordering Distributed Events</a></li><li><a href="https://www.scattered-thoughts.net/writing/causal-ordering/">Causal ordering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a9d1b4a2e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronising Time in Distributed Systems]]></title>
            <link>https://medium.com/@rangavamsi5/time-in-chaos-b056b0d6e472?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/b056b0d6e472</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[computers]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 18:21:55 GMT</pubDate>
            <atom:updated>2024-12-15T12:41:26.717Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Time in Chaos</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xMRzq0cp6vXpETzm" /><figcaption>Photo by <a href="https://unsplash.com/@ahmadossayli?utm_source=medium&amp;utm_medium=referral">Ahmad Ossayli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We rarely think about how the systems we rely on actually work. Most of the time, that’s perfectly fine — we don’t need to understand the complexities behind every piece of technology we use. One such complexity is <strong>TIME</strong> — something we often take for granted.</p><p>Most modern devices have a built-in sense of time, from your smartphone to your smart fridge. In the realm of the internet, where billions of devices and servers interact daily, maintaining an accurate sense of time is a big challenge. What happens when a server in Tokyo thinks a transaction happened before the server in New York processed it? Or when two machines disagree on the exact sequence of events in a stock trade?</p><h3>How Computers Tick</h3><p>Imagine <strong>time</strong> as a <strong>universal rhythm</strong> that everyone follows. In the physical world, we use clocks to keep track of this rhythm, but how do computers know what time it is?</p><p>The answer is simpler than you might think: they also use <strong>clocks!</strong></p><h4>Real-Time Clock (RTC)</h4><p>Each computer has a small but crucial piece of hardware called a <strong>Real-Time Clock, </strong>or<strong> RTC </strong>for short. It’s a small integrated circuit embedded right onto the motherboard. I’s <strong>powered by battery</strong>, so it keeps ticking even when the computer is turned off.</p><p>The RTC keeps track of time by using a <strong>crystal oscillator</strong>, which vibrates at a constant rate. <em>Imagine a tiny quartz crystal vibrating 1000 times per second — this vibration is the heartbeat of the clock.</em> Every vibration, or oscillation, is counted by the RTC, and these ticks help keep track of time and this data is stored in a <strong>binary counter circuit</strong>.</p><p>When the computer is off, the <strong>RTC (Real-Time Clock)</strong> operates using its <strong>own battery</strong> and a <strong>crystal oscillator</strong>, keeping track of time independently from the computer’s main power. This allows the RTC to maintain the current time even when the computer is powered down. Upon booting up, the system clock is initialised using the time from the RTC.</p><p>The <strong>system clock</strong> is a software-based clock that operates only when the computer is on, relying on the <strong>main power supply</strong>. It retrieves the current time from the RTC at startup and runs independently during operation. Since the system clock can drift over time, it periodically synchronises with the RTC to correct any discrepancies. The machine’s operations follow the time provided by the system clock, regardless of external sources.</p><p><em>Basically, the RTC keeps accurate time when the system is off, while the system clock handles timekeeping while the computer is powered on. Both use oscillators but function separately.</em></p><h4>Time-Setting Knob</h4><p>An interesting quirk about <strong>system time</strong> is that it always <strong>begins counting from the moment the system clock starts</strong>. If we set the clock on a new computer to be twelve minutes slow or eighty days fast, that becomes the starting point. The system will then measure time relative to that inaccurate starting point — whether it’s behind or ahead.</p><blockquote>Essentially, the machine doesn’t know or care what the real time is; it simply counts from whatever point we’ve set.</blockquote><p>To prevent confusion, most systems follow a <a href="https://en.wikipedia.org/wiki/Epoch_(computing)">standardised approach</a> when determining this “starting point.” <em>For instance,</em> <strong><em>Unix-based </em></strong><em>systems use Unix time, where the clock starts ticking from the Unix </em><strong><em>epoch</em></strong><em> — January 1, 1970, at 00:00:00 UT (Universal Time). This is an agreed-upon baseline for time measurement.</em></p><p>When you first set up a new computer or spin up a new instance, the RTC provides the initial time. The RTC time is usually set to a default value when the computer is manufactured. However, this time might not be perfectly accurate right away. To ensure precise timekeeping, the system will synchronise with an external time source using <strong>Network Time Protocol</strong> (<strong>NTP</strong>). NTP servers provide reliable time information, and when your computer or server connects to an NTP server, it adjusts its internal clock to match the server’s time. This helps correct any discrepancies between the RTC and the actual current time, ensuring that the system remains synchronised with the real world.</p><h3>Consistency in Time</h3><p>We understand by now that each machine has its own notion of time. But if two different machines have two different ideas of time, how can we be sure which one is precise?</p><p>You might assume that because these clocks are digital, they must be flawlessly accurate. But even these highly engineered systems aren’t immune to slight inaccuracies. Take GPS satellites, for example. They rely on atomic clocks, which are incredibly precise. Yet, even these clocks can experience tiny deviations due to factors like Earth’s gravitational pull or even the speed at which the satellite is moving.</p><p>If even a sophisticated atomic clock can experience slight timing issues, it’s no surprise that your computer’s internal clock might fall out of sync. Unlike GPS satellites, your computer doesn’t have an atomic clock. Instead, it uses a crystal oscillator to keep time, but over days or weeks, this can still lead to tiny inaccuracies.</p><blockquote>Maybe it’s only a second or two, but these small errors gradually add up.</blockquote><p>So, why does this happen? A<strong> lot of factors can affect </strong>how accurately a clock ticks. Things like temperature changes, the clock’s location, its power source or even how well it was built can throw off its timing. This gradual shift in how a clock measure seconds, causing it to fall behind or race ahead, is know as <strong>Clock Drift</strong>.</p><p><strong>Clock Skew</strong> takes this one step further. While drift refers to the gradual change in a single clock’s accuracy over time, skew describes the difference between two clocks at any given moment. So, if your phone thinks it’s 3:02:15 PM and your laptop thinks it’s 3:02:20 PM, that’s <strong>clock skew</strong> in action.</p><blockquote>In short, d<strong>rift</strong> refers to one clock losing or gaining time over a period, skew is the immediate gap between two clocks that should be synced but aren’t.</blockquote><p>These small inconsistencies don’t usually affect our daily lives, but in the world of <strong>distributed systems</strong>, drift and skew can cause problems.</p><h3>The Impact</h3><p>Let’s take a step back and think about what a distributed system really is — “<strong>Multiple entities (or machines) communicating with one another, often spread across different locations, while also performing their own tasks”</strong>.</p><p>Each of these machines has its own internal clock, and they all keep track of time independently. So far, so good, right? Well, here’s where things gets tricky — <strong>these clocks are rarely in perfect sync</strong>.</p><p>Imagine two machines handling same set of tasks. One machine says an action is happened at 12:01:05, while the other thinks it happened at 12:01:02. If these machines need to work together to process events in the correct order, their conflicting sense of time can lead to confusion. <strong>Did Event A happen before Event B, or the other way around?</strong> The system might end up processing things out of order, causing issues like incorrect results, duplicate tasks, or worse.</p><p>In a distributed system, this seemingly small problem of clocks being out of sync can snowball into larger issues. When you have hundreds or thousands of machines working together, each with a slightly different view of time, ensuring consistency and accuracy becomes a real challenge.</p><blockquote>Whether it’s processing a transaction or simply coordinating data, timing matters.</blockquote><p>To solve this, distributed systems employ techniques to ensure that clocks are as synchronised as possible. But even then, perfect sync is almost impossible. That’s why systems use clever workaround — like tracking the order of events rather than relying solely on time — to ensure things run smoothly even when the clocks don’t line up perfectly.</p><p><em>In conclusion, time plays a critical role in distributed systems to ensure tasks are executed in the correct order and without error. While clock drift and skew may seem like small issues, they can lead to significant challenges when machines work together across different locations. Ultimately, it’s not just about keeping clocks in sync — it’s about ensuring the smooth coordination of the entire network.</em></p><p>Thanks for your time. Happy Learning !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b056b0d6e472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Data Security in SQL]]></title>
            <link>https://medium.com/@rangavamsi5/advanced-data-security-in-sql-5f530b96bf66?source=rss-58562903b723------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f530b96bf66</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[authorisation]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[mssql]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[ranga_vamsi]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 04:37:35 GMT</pubDate>
            <atom:updated>2024-08-11T04:37:35.538Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>In Data We Trust</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f19cdcUwjvoUXSU3" /><figcaption>Photo by <a href="https://unsplash.com/@arielbesagar?utm_source=medium&amp;utm_medium=referral">Ariel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we delve into advanced data security features in SQL, focusing on Row-Level Security (RLS) and Dynamic Data Masking (DDM). RLS allows fine-grained control over data access based on user roles, while DDM masks sensitive information dynamically based on user permissions.</p><h3>Row-Level Security (RLS)</h3><h4>Overview:</h4><p>Row-Level Security (RLS) is a database feature that <strong>controls access to rows in a table based on a user’s context</strong>, such as their role or specific attributes, <strong>by applying security policies</strong>. This allows different users to see different subsets of data from the same table according to their permissions, making it particularly useful in multi-tenant applications where data needs to be segmented by user or group.</p><p><strong>Lets delve into RLS using PostgreSQL:</strong></p><p><em>Steps to Install Postgres in Mac:</em></p><pre>#Install postgress<br>&gt; brew install postgresql<br>#Start PostgreSQL<br>&gt; brew services start postgresql<br>#Access PostgreSQL:<br>&gt; psql postgres<br><br># Stop &amp; Restart the postgres server<br>&gt; brew services stop postgresql<br>&gt; brew services restart postgresql</pre><h4>Policies:</h4><p>Security policies are used to define the rules for row-level access control in PostgreSQL. They are created using the <strong>CREATE POLICY</strong> command and applied to tables to control how different users interact with the data.</p><ul><li><strong>Policy Creation</strong>: : Define the policy and specify which operations (<strong>SELECT</strong> <strong>INSERT</strong> <strong>UPDATE</strong> <strong>DELETE)</strong> it should apply to. This determines how users can interact with the data.</li><li><strong>Policy Conditions</strong>: Each policy includes a condition expressed as a boolean expression. This condition dictates which rows are accessible or modifiable. If the condition evaluates to true, the operation is allowed; otherwise, it is blocked.</li></ul><p><strong>Syntax</strong></p><pre>CREATE POLICY policy_name<br>ON table_name<br>[ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]<br>[ TO { role_specification | PUBLIC | CURRENT_ROLE | CURRENT_USER } [, ...] ]<br>[ USING (expression) ]<br>[ WITH CHECK (expression) ];</pre><ul><li><strong>FOR</strong>: Specifies which operations the policy applies to, such as ALL operations or specific ones like SELECT, INSERT, UPDATE, or DELETE.</li><li><strong>TO</strong>: Specifies which roles the policy applies to. This can include specific roles, PUBLIC (all roles), CURRENT_ROLE, or CURRENT_USER.</li><li><strong>USING</strong>: Defines the condition that must be met for the operation to be allowed.</li><li><strong>WITH CHECK</strong>: Specifies conditions for INSERT and UPDATE operations to ensure that the new or updated data meets certain criteria. For example, it ensures that every entry in a `documents` table meets certain criteria before being accepted, much like a foreign key verifies relational integrity.</li></ul><p><strong>Let’s understand with an example:</strong></p><ul><li><em>Setup database &amp; tables</em></li></ul><pre>CREATE DATABASE bank_cms;<br>\c bank_cms<br><br>CREATE TABLE branches (<br>    branch_id SERIAL PRIMARY KEY,<br>    branch_name VARCHAR(100) NOT NULL<br>);<br><br>CREATE TABLE employees (<br>    employee_id SERIAL PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    username VARCHAR(50) NOT NULL,<br>    branch_id INT REFERENCES branches(branch_id),<br>    role VARCHAR(50) NOT NULL<br>);<br><br>CREATE TABLE customers (<br>    customer_id SERIAL PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    branch_id INT REFERENCES branches(branch_id)<br>);</pre><ul><li><em>Insert sample data</em></li></ul><pre>INSERT INTO branches (branch_name) VALUES<br>    (&#39;Los Pollos Hermanos&#39;),<br>    (&#39;Saul Goodman’s Office&#39;),<br>    (&#39;Gray Matter Technologies&#39;);<br><br>INSERT INTO employees (name, username, branch_id, role) VALUES<br>    (&#39;Gustavo Fring&#39;, &#39;gustavo&#39;, 1, &#39;Branch Manager&#39;),<br>    (&#39;Saul Goodman&#39;, &#39;saul&#39;, 2, &#39;Branch Manager&#39;),<br>    (&#39;Walter White&#39;, &#39;walter&#39;, 3, &#39;Regional Manager&#39;);<br><br>INSERT INTO customers (name, branch_id) VALUES<br>    (&#39;Jesse Pinkman&#39;, 1),<br>    (&#39;Hank Schrader&#39;, 1),<br>    (&#39;Skyler White&#39;, 2),<br>    (&#39;Gus Fring&#39;, 3);</pre><ul><li><em>Enable Row-Level Security</em> <em>for the </em><em>customers table:</em></li></ul><pre>ALTER TABLE customers ENABLE ROW LEVEL SECURITY;</pre><ul><li><em>Create Security Policies</em></li></ul><pre>-- Filter policy for Branch Manager<br>CREATE POLICY branch_manager_policy<br>ON customers<br>USING (branch_id = (<br>    SELECT branch_id<br>    FROM employees<br>    WHERE username = current_user<br>      AND role = &#39;Branch Manager&#39;<br>));<br><br>-- Policy with WITH CHECK Clause:<br>ON customers<br>FOR INSERT, UPDATE<br>USING (branch_id = (<br>    SELECT branch_id<br>    FROM employees<br>    WHERE username = current_user<br>      AND role = &#39;Branch Manager&#39;<br>))<br>WITH CHECK (branch_id = (<br>    SELECT branch_id<br>    FROM employees<br>    WHERE username = current_user<br>      AND role = &#39;Branch Manager&#39;<br>));</pre><ul><li><em>Create Roles &amp; Users</em></li></ul><pre>CREATE ROLE branch_manager_role;<br>GRANT CONNECT ON DATABASE bank_cms TO branch_manager_role;<br>GRANT SELECT, INSERT, UPDATE ON customers TO branch_manager_role;<br>GRANT SELECT ON employees TO branch_manager_role;<br><br>CREATE USER gustavo WITH PASSWORD &#39;9Iiau*i@$123&#39;;<br>GRANT branch_manager_role TO gustavo;</pre><ul><li><em>Verify the policy by logging as Branch manager</em></li></ul><p>The customer records visible to an employee are determined by their above set policies; for instance, the loggedin user Gustavo will only see and manage customers from his own branch.</p><pre>&gt; psql -U gustavo -d bank_cms<br>psql (14.12 (Homebrew))<br>Type &quot;help&quot; for help.<br><br>#bank_cms=&gt; SELECT * FROM customers;<br><br> customer_id |     name      | branch_id<br>-------------+---------------+-----------<br>           1 | Jesse Pinkman |         1<br>           2 | Hank Schrader |         1<br>(2 rows)</pre><h4>Note:</h4><p>Above demonstrates RLS in PostgreSQL. Different SQL databases implement similar security features in various ways. For instance, MySQL uses <a href="https://www.sqlmaestro.com/resources/all/row_level_security_mysql/"><strong>Views</strong></a> for row-level access, while SQL Server employs <a href="https://learn.microsoft.com/en-us/sql/relational-databases/security/row-level-security?view=sql-server-ver16"><strong>Filters and Security policies</strong></a>.</p><h3>Dynamic Data Masking (DDM)</h3><h4>Overview</h4><p>Dynamic Data Masking (DDM) is a security feature in <strong>SQL Server</strong> that <strong>obscures sensitive data or personally identifiable information (PII )in real-time</strong> based on user roles or permissions, ensuring that sensitive information remains concealed while allowing users to interact with non-sensitive portions of the data.</p><p>The <strong>masking is dynamic</strong>, meaning it happens in real-time as users query the database, with different users or roles viewing varying levels of detail based on their permissions.</p><h4>Masking Functions:</h4><p>SQL Server provides following <strong>in-built </strong>masking functions:</p><ol><li><strong>default()</strong>: Masks data by replacing it with a default placeholder value. (e.g., XXXX for strings, 0 for numbers).</li><li><strong>email()</strong>: Reveals the first letter and domain, masking the rest (e.g., <a href="/service/mailto:aXXX@XXXX.com">aXXX@XXXX.com</a>).</li><li><strong>random(begin, end)</strong>: Substitutes data with a random value within a range. (eg., A salary of 50000 might be masked as a random number between 30000 and 100000, such as 45000)</li><li><strong>partial(prefix, [padding],suffix):</strong> Reveals parts of the string with custom padding (e.g., 5XXXXXXX).</li><li><strong>datetime(unit):</strong> Allows masking of specific parts of a datetime value (e.g., datetime(“M”) masks the month of the value).</li></ol><h4>Permissions:</h4><ul><li>Users with <strong>SELECT</strong> permission can only see data in its masked form, protecting sensitive information from unauthorized access, while those with <strong>UNMASK</strong> permission <strong>can view the original</strong>, unmasked data, typically reserved for roles needing full information.</li><li><strong>Administrative roles</strong> like <strong>sysadmin</strong> or <strong>db_owner</strong> bypass all masking policies and have unrestricted access to all data.</li><li>Permissions to view unmasked data (UNMASK) can be granted or revoked at various levels, including the database, schema, table, or individual columns.</li></ul><p><strong>Let’s understand with an example:</strong></p><ul><li><em>Create Schema </em><strong>data</strong></li></ul><pre>CREATE SCHEMA data;</pre><ul><li><em>Create Table </em><strong>employees</strong><em> with Masking</em></li></ul><pre>CREATE TABLE data.employees (<br>    id INT IDENTITY(1,1) NOT NULL PRIMARY KEY,<br>    username VARCHAR(50) NOT NULL,<br>    name VARCHAR(100) NOT NULL,<br>    phone VARCHAR(12) MASKED WITH (FUNCTION = &#39;default()&#39;) NULL,<br>    email VARCHAR(100) MASKED WITH (FUNCTION = &#39;email()&#39;) NOT NULL,<br>    salary DECIMAL(10, 2) MASKED WITH (FUNCTION = &#39;random(30000, 100000)&#39;) NULL<br>);</pre><ul><li><em>Insert sample data</em></li></ul><pre>INSERT INTO data.employees (username, name, phone, email, salary)<br>VALUES<br>(&#39;walter&#39;, &#39;Walter White&#39;, &#39;555-1234&#39;, &#39;walter.white@example.com&#39;, 500000),<br>(&#39;jesse&#39;, &#39;Jesse Pinkman&#39;, &#39;555-5678&#39;, &#39;jesse.pinkman@example.com&#39;, 74000),<br>(&#39;saul&#39;, &#39;Saul Goodman&#39;, &#39;555-9012&#39;, &#39;saul.goodman@example.com&#39;, 123456),<br>(&#39;hank&#39;, &#39;Hank Schrader&#39;, &#39;555-3456&#39;, &#39;hank.schrader@example.com&#39;, 987234);</pre><ul><li><em>Grant </em><strong>UNMASK<em> </em></strong><em>permission to the user</em></li></ul><pre><br>-- database level<br>GRANT UNMASK TO hank;<br>-- schema level<br>GRANT UNMASK ON SCHEMA::data TO walter;<br>-- table level<br>GRANT UNMASK ON data.empoyees TO saul;<br>-- column level<br>GRANT UNMASK ON data.employees(phone) TO jesse;</pre><h4>Limitations:</h4><ul><li>Data masking does not apply to columns that are encrypted or computed. Encrypted columns require separate encryption mechanisms.</li><li>Granting <strong>UNMASK</strong> permissions at the column level applies unmasked access uniformly to all rows in that column, with no ability to customize access based on individual row data.</li><li>Masking is not supported for columns used in <strong>FULLTEXT</strong> indexes or PolyBase external tables, which can limit its application in certain scenarios.</li></ul><h4>Note:</h4><p>The DDM feature described above is supported in SQL Server but is not available in MySQL or PostgreSQL.</p><p>Thanks for your time.</p><h3>References:</h3><ul><li><a href="https://www.sqlmaestro.com/resources/all/row_level_security_mysql/">Implementing row level security in MySQL - SQL Maestro Group</a></li><li><a href="https://learn.microsoft.com/en-us/sql/relational-databases/security/row-level-security?view=sql-server-ver16">Row-level security - SQL Server</a></li><li><a href="https://learn.microsoft.com/en-us/sql/relational-databases/security/dynamic-data-masking?view=sql-server-ver16">Dynamic data masking - SQL Server</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f530b96bf66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>