<?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 Girish on Medium]]></title>
        <description><![CDATA[Stories by Girish on Medium]]></description>
        <link>https://medium.com/@girishkr?source=rss-c72c83160392------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YrjhyaOPUges6OIE8kk7lw.jpeg</url>
            <title>Stories by Girish on Medium</title>
            <link>https://medium.com/@girishkr?source=rss-c72c83160392------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:34:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@girishkr/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[Solidity data locations]]></title>
            <link>https://girishkr.medium.com/solidity-data-locations-0516d285ba5d?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/0516d285ba5d</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 10:42:08 GMT</pubDate>
            <atom:updated>2024-10-15T10:42:08.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solidity data locations explained</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_u8aTN0A5uV3FlqKqlaMzA.png" /></figure><p><strong>Detailed Explanation of Each Category:</strong></p><h3>1. calldata:</h3><p>• <strong>Persistence</strong>: Temporary, only exists during the execution of external functions.</p><p>• <strong>Modifiability</strong>: Read-only, cannot be modified during function execution.</p><p>• <strong>Gas Cost</strong>: Lower gas cost than memory when passing large arrays/structs to external functions.</p><p>• <strong>Use Case</strong>: Primarily used for external function parameters that are not modified, for example, large data structures passed to a function but not altered.</p><p>• <strong>Efficiency</strong>: It is gas-efficient because it avoids copying data to memory, which would increase gas usage.</p><h3>2. storage:</h3><p>• <strong>Persistence</strong>: Permanent, exists throughout the life of the contract and stores data on-chain.</p><p>• <strong>Modifiability</strong>: Modifiable, allows changes to contract state (e.g., balances, mappings). However, modifications are costly in terms of gas.</p><p>• <strong>Gas Cost</strong>: High for both reading and writing. Writing to storage is one of the most expensive operations in Solidity.</p><p>• <strong>Use Case</strong>: Stores persistent data that needs to remain between function calls and be part of the contract’s state, like balances, ownership records, or mappings.</p><h3>3. memory:</h3><p>• <strong>Persistence</strong>: Temporary, only exists during the function execution. It is cleared once the function call is completed.</p><p>• <strong>Modifiability</strong>: Modifiable, data can be changed within the function, but the changes are not saved once the function execution ends.</p><p>• <strong>Gas Cost</strong>: Moderate. More expensive than stack, but less costly than storage. Used for temporary data storage.</p><p>• <strong>Use Case</strong>: Used for temporary storage of variables such as arrays, strings, or structs that are needed only during a function’s execution.</p><h3>4. stack:</h3><p>• <strong>Persistence</strong>: Extremely temporary, valid only during the execution of a function.</p><p>• <strong>Modifiability</strong>: Modifiable, stores local primitive variables like uint, bool, etc.</p><p>• <strong>Gas Cost</strong>: Very low. Operations on the EVM stack are the cheapest in terms of gas.</p><p>• <strong>Use Case</strong>: Best for primitive local variables (e.g., counters, flags). However, the EVM stack is limited to 1024 slots, so it cannot hold large amounts of data.</p><h3>5. logs:</h3><p>• <strong>Persistence</strong>: Permanent, stored as part of blockchain logs and accessible through event listeners.</p><p>• <strong>Modifiability</strong>: Read-only, once an event is emitted, it cannot be modified. The data is logged and stored off-chain.</p><p>• <strong>Gas Cost</strong>: Event logging incurs gas costs based on the size of the data being logged.</p><p>• <strong>Use Case</strong>: Used for off-chain purposes, primarily for tracking events (such as transfers) and for dApps to listen to specific changes in the contract. Useful for indexing.</p><p>• <strong>Accessibility</strong>: Can be queried off-chain using the eth_getLogs RPC call.</p><h3>6. code:</h3><p>• <strong>Persistence</strong>: Permanent, represents the bytecode of the deployed contract on the blockchain.</p><p>• <strong>Modifiability</strong>: Immutable, cannot be modified once the contract is deployed.</p><p>• <strong>Gas Cost</strong>: The cost is incurred during the contract’s deployment, with no further gas cost during runtime.</p><p>• <strong>Use Case</strong>: Represents the contract’s business logic and behavior, which includes all functions, conditions, and rules of the contract. It cannot be modified post-deployment but can be executed by external calls.</p><p>• <strong>Limit</strong>: The maximum size for contract code is 24KB in Ethereum.</p><h3><strong>When to Use Each Data Location:</strong></h3><p>• calldata: When passing large read-only data structures like arrays to external functions. This reduces gas costs because calldata doesn’t copy data into memory.</p><p>• storage: For data that needs to persist across function calls and updates, such as balances, ownership records, mappings, or any contract state data.</p><p>• memory: For temporary data structures and variables within a function, which do not need to persist after the function’s execution. Examples include arrays, structs, or strings used for computation within a function.</p><p>• stack: For primitive data types like integers or booleans that need to be used temporarily during a function call. This is the most efficient storage mechanism in terms of gas cost but limited by size.</p><p>• logs: For emitting events that will be recorded in the transaction log but not stored as part of the contract state. These are typically used for off-chain processing, event indexing, and as signals to front-end dApps.</p><p>• code: Represents the contract’s logic. This data location cannot be changed after deployment, so it’s used for the business logic that runs within the EVM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0516d285ba5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity State Variables, Functions Visibility Modifiers]]></title>
            <link>https://girishkr.medium.com/solidity-state-variables-functions-visibility-28352470b433?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/28352470b433</guid>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 08:24:23 GMT</pubDate>
            <atom:updated>2024-10-15T10:07:36.311Z</atom:updated>
            <content:encoded><![CDATA[<p>A detailed summary table for all available modifiers for <strong>functions</strong> and <strong>state variables</strong> in Solidity, highlighting differences like external calls, internal calls, gas efficiency, and use cases.</p><p><strong>Function Visibility Modifiers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLXNh9JdTCiwsnISxst63w.png" /></figure><p><strong>State Variable Visibility Modifiers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLnrJOd1UzGRXwo9R-UgRg.png" /></figure><p><strong>Key Differences</strong></p><p><strong>1. External Calls</strong></p><p>• <strong>Functions</strong>: external and public functions can be called from outside the contract. internal and private functions cannot be accessed externally.</p><p>• <strong>State Variables</strong>: Only public state variables can be read externally, and Solidity generates an automatic getter for them.</p><p><strong>2. Internal Calls</strong></p><p>• <strong>Functions</strong>: public, internal, and private functions can be called internally without any special syntax. external functions require calling via this.functionName().</p><p>• <strong>State Variables</strong>: All state variables (public, internal, private) can be accessed internally by the contract.</p><p><strong>3. Gas Efficiency</strong></p><p>• <strong>Functions</strong>: external functions are more gas-efficient when handling large data (e.g., arrays) because they use calldata. public functions are less efficient as they copy the data into memory.</p><p>• <strong>State Variables</strong>: Gas costs are relevant when reading public variables via the auto-generated getter externally.</p><p><strong>4. Inheritance</strong></p><p>• <strong>Functions</strong>: public and internal functions can be inherited by child contracts, while private functions cannot.</p><p>• <strong>State Variables</strong>: Similarly, public and internal state variables can be inherited, but private cannot be accessed by derived contracts.</p><p><strong>Use Cases</strong></p><p>• external: Use for functions that are meant to be called from outside the contract, particularly when optimizing gas consumption with large dynamic data (like arrays). Avoid using them for internal calls unless necessary via this.functionName().</p><p>• public: Use for functions that require access both from inside and outside the contract. Also, use public for state variables when you want to allow external reading (with auto-generated getter) while controlling internal writes.</p><p>• internal: Use for functions and variables that should only be accessible within the contract and its derived contracts. Suitable for internal logic that does not need external exposure.</p><p>• private: Use for functions and variables that should only be accessible within the defining contract. This is ideal for sensitive internal logic and data that should not be exposed or inherited.</p><p>This table highlights the main differences across function and state variable modifiers in Solidity to help you choose the right visibility modifier for your use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28352470b433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[judge0 on Mac M3 macOS Sequoia]]></title>
            <link>https://girishkr.medium.com/judge0-on-mac-m3-macos-sequoia-26946b85d67c?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/26946b85d67c</guid>
            <category><![CDATA[judge0]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 18:54:55 GMT</pubDate>
            <atom:updated>2024-09-23T18:54:55.526Z</atom:updated>
            <content:encoded><![CDATA[<p>Update docker to latest.</p><p>go to docker settings and uncheck “Use Rosetta for x86_64/amd64 emulation on Apple Silicon”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLhbWvkCy4UCXrITyvgZxA.png" /></figure><p>After submission you may get error.</p><pre>No such file or directory @ rb_sysopen - /box/script.py</pre><p>Solution is available <a href="https://github.com/judge0/judge0/issues/325#issuecomment-1140230612">here</a></p><p>Go to</p><pre>vim ~/Library/Group\ Containers/group.com.docker/settings.json</pre><p>change the deprecatedCgroupv1 option from false to true</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26946b85d67c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consistent Hashing]]></title>
            <link>https://medium.com/prepster/consistent-hashing-80d3f9da474e?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/80d3f9da474e</guid>
            <category><![CDATA[consistent-hashing]]></category>
            <category><![CDATA[murmur3]]></category>
            <category><![CDATA[distributed-cache]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 06:40:16 GMT</pubDate>
            <atom:updated>2024-09-04T06:52:55.024Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Use Cases for Consistent Hashing</strong></h3><p>Consistent hashing is used in many distributed systems, particularly those that require horizontal scalability and need to minimize disruption when scaling. Some common use cases include:</p><ol><li><strong>Distributed Caches (e.g., Memcached, Redis Cluster)</strong>: Consistent hashing is used to distribute cached data across multiple nodes. When new cache nodes are added or removed, consistent hashing ensures that only a small subset of cached data is remapped, reducing cache misses.</li><li><strong>Distributed Databases (e.g., Cassandra, DynamoDB)</strong>: In systems like Cassandra and DynamoDB, consistent hashing is used to distribute database partitions across multiple nodes. This allows for seamless scaling as nodes are added or removed.</li><li><strong>Load Balancers</strong>: In load balancing, consistent hashing can be used to assign client requests to specific backend servers, ensuring that the same client is always directed to the same server (important for session persistence).</li><li><strong>Content Delivery Networks (CDNs)</strong>: CDNs can use consistent hashing to distribute content across multiple edge nodes. This ensures that content can be retrieved from the nearest node without disruption when nodes are added or removed.</li></ol><h3><strong>What is Consistent Hashing?</strong></h3><p><strong>Consistent hashing</strong> is a distributed hashing algorithm used to distribute data across a set of nodes (servers) in such a way that minimizes the redistribution of data when nodes are added or removed. It ensures that data is evenly distributed across nodes and reduces the number of objects that need to be moved when the system scales up or down.</p><p><strong>The Problem with Traditional Hashing</strong></p><p>In traditional hashing (e.g., using a modulo operation like hash(key) % N, where N is the number of servers), if you add or remove servers, it disrupts the mapping of nearly all keys to their respective servers. This causes large amounts of data to be reshuffled between nodes, which is inefficient.</p><p>For example:</p><p>• Initially, with 3 servers, a key K1 might be mapped to hash(K1) % 3 = Server 1.</p><p>• When a 4th server is added, all keys are rehashed, and K1 might now map to hash(K1) % 4 = Server 2, requiring a complete redistribution of the data.</p><h3><strong>How Consistent Hashing Works</strong></h3><p><strong>Consistent hashing</strong> solves the problem by mapping both keys (data) and nodes (servers) to a <strong>hash ring</strong>. Here’s the step-by-step process:</p><p><strong>1. The Hash Ring</strong></p><p>• Imagine a circle or “ring” that represents the entire range of hash values.</p><p>• Each server (or node) is assigned a position on this ring based on the hash of its identifier (e.g., server IP or ID).</p><p>• When a data item (key) is inserted, it is hashed, and the corresponding value is placed on the ring. The key is assigned to the <strong>next node clockwise</strong> on the ring from its hash value.</p><p><strong>2. Hashing Example</strong></p><p>Let’s say you have three nodes N1, N2, and N3:</p><p>• <strong>Step 1</strong>: Hash the server IDs to positions on the ring.</p><p>• hash(N1) = 100</p><p>• hash(N2) = 300</p><p>• hash(N3) = 600</p><p>• <strong>Step 2</strong>: Hash the data keys and place them on the ring.</p><p>• hash(K1) = 250 → assigned to N2 (next node clockwise).</p><p>• hash(K2) = 550 → assigned to N3.</p><p>• hash(K3) = 700 → wraps around the ring and is assigned to N1.</p><p><strong>3. Adding or Removing Nodes</strong></p><p>The key idea of consistent hashing is that when a node is added or removed, <strong>only a small portion of the keys are affected</strong>:</p><p>• <strong>Adding a Node</strong>: Suppose we add a node N4 at position 400. Now, keys between 300 and 400 that were previously assigned to N2 will move to N4, but all other keys remain unaffected.</p><p>• <strong>Removing a Node</strong>: If N2 is removed, the keys assigned to it will be reassigned to the next node clockwise (N4 or N3), but other keys remain untouched.</p><p>This property makes consistent hashing highly efficient in dynamic environments where nodes (servers) are frequently added or removed.</p><h3><strong>Virtual Nodes (VNodes)</strong></h3><p>A potential issue with basic consistent hashing is that nodes might not be evenly distributed around the ring, which can lead to an uneven load. To solve this, <strong>virtual nodes</strong> (or <strong>vnodes</strong>) are introduced.</p><p>• <strong>What are Virtual Nodes?</strong></p><p>• Instead of assigning one position on the ring to each physical node, you assign multiple positions (or virtual nodes) for each physical node.</p><p>• For example, N1 could be assigned positions 100, 400, and 700.</p><p>• <strong>Why Use Virtual Nodes?</strong></p><ul><li>Virtual nodes ensure that data is more evenly distributed across all physical nodes, preventing one node from becoming a bottleneck.</li></ul><h3><strong>Hash Functions Used in Consistent Hashing</strong></h3><p>For consistent hashing, the <strong>hash function</strong> is crucial because it needs to uniformly distribute data across the hash space. Some common hash functions used are:</p><p>1. <strong>MD5</strong>: A widely used cryptographic hash function, though considered insecure for cryptography, it is often used for hashing in distributed systems because of its uniform distribution properties.</p><p>2. <strong>SHA-1</strong>: Another cryptographic hash function used for its uniform distribution across the hash ring. It generates 160-bit hash values.</p><p>3. <strong>MurmurHash</strong>: A non-cryptographic, fast hash function that provides good distribution and performance. Often used in real-world systems like Cassandra.</p><p>4. <strong>FNV-1a</strong>: hash function that is faster than MD5 or SHA-1 but with weaker collision resistance, commonly used in cases where performance is more critical than security.</p><h3><strong>Handling Concurrency in Consistent Hashing</strong></h3><p>In distributed systems, multiple clients or nodes may try to update the cache or storage simultaneously, leading to potential race conditions and conflicts. Here’s how concurrency is handled:</p><p><strong>1. Atomic Operations</strong></p><p>• <strong>Locks and Synchronization</strong>:</p><p>• Consistent hashing systems often use distributed locks or coordination mechanisms like <strong>ZooKeeper</strong> or <strong>etcd</strong> to ensure that only one process updates the data at a time.</p><p>• <strong>Optimistic Locking</strong>:</p><p>• Instead of locking resources, some systems use optimistic concurrency control (e.g., version numbers). Clients check if the version of data they are updating is the most recent. If not, the update is rejected and retried.</p><p><strong>2. Quorum-Based Reads/Writes</strong></p><p>• <strong>Quorum Writes</strong>:</p><p>• In systems like Cassandra, data is replicated across multiple nodes. When writing data, a majority (quorum) of nodes must acknowledge the write for it to be considered successful.</p><p>• <strong>Quorum Reads</strong>:</p><p>• When reading data, a consistent hash system may read from a quorum of nodes to ensure the most up-to-date data is returned.</p><p><strong>3. Eventual Consistency</strong></p><p>• Many distributed systems using consistent hashing are <strong>eventually consistent</strong>, meaning that not all nodes are guaranteed to have the most up-to-date data at all times, but data will converge to the correct value over time.</p><p><strong>Real-World Concurrency Handling Example: Cassandra</strong></p><p>In <strong>Cassandra</strong>, which uses consistent hashing, concurrency is handled through:</p><p>• <strong>Tunable Consistency</strong>: Clients can specify the consistency level of reads and writes (e.g., write to 2 nodes out of 3, read from 2 out of 3).</p><p>• <strong>Vector Clocks</strong>: Used to detect conflicts between concurrent writes. If two writes happen at the same time, the system can resolve conflicts based on the vector clock history.</p><ul><li><strong>Gossip Protocol</strong>: Nodes periodically communicate with each other to share information about the data they store, ensuring eventual consistency across nodes.</li></ul><h3><strong>Implementing Consistent Hashing in a Distributed Cache</strong></h3><p><strong>1. Hash Function</strong></p><p>In consistent hashing, a hash function is used to map both the <strong>node IP addresses</strong> and the <strong>data (cache keys)</strong> to positions on the hash ring. The function needs to uniformly distribute the values across the entire range of possible hash values.</p><p>A common hash function used in distributed systems is <strong>MD5</strong> or <strong>SHA-1</strong>, but for non-cryptographic applications, <strong>MurmurHash</strong> is often used for its speed and uniform distribution properties.</p><p>Let’s use <strong>MurmurHash</strong> for this example.</p><pre>import mmh3  # MurmurHash3 hash function<br>import hashlib<br>import bisect</pre><p><strong>2. Hash Ranges and the Hash Ring</strong></p><p>The hash function outputs a large integer value. In the case of <strong>MurmurHash</strong>, the hash value is a 32-bit or 64-bit integer. We can visualize this range as a circular hash space (ring) where:</p><p>• The smallest hash value (0) is at one end of the ring.</p><p>• The largest hash value (2³² — 1 or 2⁶⁴ — 1 depending on the hash function) wraps around the ring to connect back to 0.</p><p>For example, if you use a <strong>32-bit hash function</strong>, the range of the hash ring will be:</p><pre>0 -----------------------------------&gt; 2^32 - 1</pre><p><strong>3. Assigning Nodes to the Ring</strong></p><p>Each cache node (server) is assigned one or more positions on the ring by hashing the node’s <strong>IP address</strong> (or another unique identifier, like the node’s ID) using the hash function.</p><p>For example, let’s say we have three nodes with IP addresses:</p><p>• 192.168.0.1</p><p>• 192.168.0.2</p><p>• 192.168.0.3</p><p>We hash these IP addresses and map them to positions on the hash ring.</p><pre># Example to hash node IPs using MurmurHash3<br>nodes = [&#39;192.168.0.1&#39;, &#39;192.168.0.2&#39;, &#39;192.168.0.3&#39;]<br>hash_ring = {}<br><br>for node in nodes:<br>    hash_value = mmh3.hash(node)<br>    hash_ring[hash_value] = node<br><br># Print the node-to-hash mapping<br>print(hash_ring)</pre><p>Let’s assume the hash values for the nodes are:</p><p>• 192.168.0.1 → 153</p><p>• 192.168.0.2 → 450000000</p><p>• 192.168.0.3 → 850000000</p><p>This places each node at a specific location on the ring.</p><p><strong>4. Data Mapping (Hashing the Data Keys)</strong></p><p>Next, each data item (cache key) is also hashed using the same hash function to determine its position on the ring. The data will be stored on the first node encountered moving <strong>clockwise</strong> on the ring from the data key’s hash.</p><p>For example, let’s say we have a data key “user123”, and we hash it:</p><pre># Hash the data key using MurmurHash<br>key = &quot;user123&quot;<br>key_hash = mmh3.hash(key)<br><br># Find the node responsible for this key (first node clockwise)<br>sorted_nodes = sorted(hash_ring.keys())<br>node_index = bisect.bisect(sorted_nodes, key_hash) % len(sorted_nodes)<br>assigned_node = hash_ring[sorted_nodes[node_index]]<br><br>print(f&quot;Data key &#39;{key}&#39; with hash {key_hash} is assigned to node {assigned_node}&quot;)</pre><p>Let’s say key_hash for “user123” is 700000000. The first node encountered clockwise from this position would be 192.168.0.3 (since its hash value is 850000000), so the data will be assigned to 192.168.0.3.</p><p><strong>5. Handling Node Addition and Removal</strong></p><p>• <strong>Adding a Node</strong>:</p><p>• Let’s say we add a new node 192.168.0.4. The new node’s hash value will be placed on the ring (let’s assume it’s 650000000).</p><p>• Now, any keys whose hash falls between 450000000 (the hash of 192.168.0.2) and 650000000 will be moved to the new node, while other data stays unaffected.</p><p>• <strong>Removing a Node</strong>:</p><p>• If a node, say 192.168.0.3, is removed, the data previously assigned to that node will be reassigned to the next node clockwise on the ring, which is 192.168.0.1.</p><p>This process ensures that only a small portion of the data is remapped when nodes are added or removed.</p><p><strong>6. Virtual Nodes (VNodes)</strong></p><p>One potential issue with basic consistent hashing is that some nodes may handle much more data than others due to uneven distribution on the hash ring. This can lead to <strong>load imbalance</strong>.</p><p>To solve this, we introduce <strong>virtual nodes</strong>. Each physical node is represented by multiple positions on the hash ring by hashing the node with different “tokens” (e.g., the IP concatenated with different numbers).</p><p>For example:</p><pre>virtual_nodes = {}<br>replicas = 3  # Each physical node has 3 virtual nodes<br><br>for node in nodes:<br>    for i in range(replicas):<br>        virtual_node_hash = mmh3.hash(f&quot;{node}-{i}&quot;)<br>        virtual_nodes[virtual_node_hash] = node<br><br># Print the virtual nodes<br>print(virtual_nodes)</pre><p>In this example:</p><p>• For 192.168.0.1, we might create virtual nodes at hash values 153, 200000, and 500000.</p><p>• For 192.168.0.2, virtual nodes might be at 450000000, 460000000, and 470000000.</p><p>This <strong>spreads the load</strong> more evenly across the ring, preventing hotspots where a single node might be overwhelmed.</p><h3><strong>Distributed cache system using consistent hashing</strong></h3><p>Let’s go step by step to explain how the distributed cache works when handling incoming requests:</p><p><strong>1. Nodes and Data Distribution Using Consistent Hashing</strong></p><p>In a distributed cache system:</p><ul><li><strong>Nodes</strong>: These are the cache servers that store portions of the data (e.g., Redis or Memcached instances).</li><li><strong>Consistent Hashing</strong>: Both the nodes (cache servers) and data keys (cache keys) are placed on a circular hash ring using a hash function. Each node is responsible for a portion of the hash space, and a data key is assigned to the first node encountered clockwise on the ring.</li></ul><p><strong>2. Incoming Request to Store Data (Cache Write)</strong></p><p>When an incoming request to store data arrives (a <strong>write request</strong>), the distributed cache system follows these steps:</p><p><strong>Step-by-Step Process:</strong></p><ol><li><strong>Hash the Data Key</strong>:</li></ol><p>The data key (e.g., “user123”) is hashed using a consistent hash function (like <strong>MurmurHash</strong>, <strong>MD5</strong>, etc.) to produce a hash value that maps to a position on the hash ring.</p><p>Example:</p><ul><li>Data key: “user123”</li><li>Hash value: 700000000</li></ul><p><strong>2. Find the Responsible Node</strong>:</p><ul><li>The hash value of the data key is used to find the first node clockwise from the data key’s hash position on the ring.</li><li>The data is stored in this node.</li></ul><p>Example:</p><ul><li>Let’s say node N3 is positioned at 850000000 on the ring. Since 700000000 is closest to 850000000 in a clockwise direction, <strong>node N3</strong> will be responsible for storing the data associated with “user123”.</li></ul><p><strong>3. Store the Data in the Selected Node</strong>:</p><ul><li>The cache value associated with the key “user123” is stored on <strong>node N3</strong>.</li><li>The client does not need to know which node is used because the consistent hashing algorithm takes care of this.</li></ul><p>Example:</p><pre>{<br>&quot;key&quot;: &quot;user123&quot;,<br>&quot;value&quot;: &quot;user data for user123&quot;,<br>&quot;stored_in&quot;: &quot;node N3&quot;<br>}</pre><p><strong>Summary:</strong></p><ol><li><strong>Client request</strong>: Store “user123” and its value.</li><li><strong>Hash calculation</strong>: Hash value 700000000.</li><li><strong>Node selection</strong>: Data is mapped to node N3.</li><li><strong>Data storage</strong>: “user123” and its associated data are stored in node N3.</li></ol><p><strong>3. Incoming Request to Retrieve Data (Cache Read)</strong></p><p>When a <strong>read request</strong> arrives, the distributed cache system needs to retrieve the cached value associated with a key. The process is similar to storing data:</p><p><strong>Step-by-Step Process:</strong></p><ul><li><strong>Hash the Data Key</strong>:</li><li>The data key (e.g., “user123”) is hashed again using the same consistent hash function.</li></ul><p>Example:</p><ul><li>Data key: “user123”</li><li>Hash value: 700000000</li><li><strong>Find the Responsible Node</strong>:</li><li>The hash value of the data key is used to find the first node clockwise on the hash ring.</li><li>The system determines that the data for “user123” is stored in <strong>node N3</strong> (from the previous write).</li><li><strong>Retrieve the Data</strong>:</li><li>The cache system queries <strong>node N3</strong> for the data associated with the key “user123”.</li><li>Node N3 responds with the cached value, and the data is returned to the client.</li></ul><p>Example:</p><pre>{<br>  &quot;key&quot;: &quot;user123&quot;,<br>  &quot;value&quot;: &quot;user data for user123&quot;,<br>  &quot;retrieved_from&quot;: &quot;node N3&quot;<br>}</pre><p><strong>Summary:</strong></p><ol><li><strong>Client request</strong>: Retrieve data for “user123”.</li><li><strong>Hash calculation</strong>: Hash value 700000000.</li><li><strong>Node selection</strong>: Data is mapped to node N3.</li><li><strong>Data retrieval</strong>: The value for “user123” is retrieved from node N3.</li></ol><p><strong>4. Handling Cache Misses (When Data is Not in Cache)</strong></p><ul><li><strong>Cache Miss</strong>: If the requested key is not present in the cache (cache miss), the cache system retrieves the data from the <strong>underlying data store</strong> (e.g., database), stores it in the selected cache node, and returns it to the client.</li></ul><p><strong>Process for a Cache Miss:</strong></p><ol><li><strong>Client Request</strong>: Retrieve data for a key.</li><li><strong>Hash and Node Lookup</strong>: Hash the key, find the responsible node.</li><li><strong>Data Not Found in Cache</strong>: If the key is not found on the node (cache miss), fetch the data from the underlying data store (database).</li><li><strong>Store in Cache</strong>: Once the data is fetched from the database, store it in the cache for future use.</li><li><strong>Return to Client</strong>: Send the retrieved data back to the client.</li></ol><p><strong>5. Adding or Removing Cache Nodes (Dynamic Scaling)</strong></p><p>When the system needs to <strong>scale</strong> (e.g., add more nodes to handle higher traffic):</p><p><strong>Adding a Node:</strong></p><ul><li>When a new node is added to the ring, it takes over a portion of the hash space from its neighboring node(s). Only the data between the new node and its clockwise neighbor needs to be redistributed.</li><li>For example, if a new node N4 is added at position 750000000, it will take over some data previously handled by node N3.</li></ul><p><strong>Removing a Node:</strong></p><ul><li>When a node is removed, the data it was responsible for is reassigned to the next node clockwise.</li><li>For example, if node N2 is removed, its data will be distributed to node N3 or N1 (depending on the node positions).</li></ul><p><strong>6. Virtual Nodes (VNodes) for Load Balancing</strong></p><p>In distributed cache systems, some nodes may be overloaded due to uneven data distribution. <strong>Virtual nodes (VNodes)</strong> help ensure even load distribution by allowing each physical node to be represented by multiple virtual nodes on the ring.</p><p><strong>How VNodes Work:</strong></p><ul><li>Each physical node has multiple positions on the hash ring, so the data is spread across multiple “virtual” instances of the node.</li><li>When a new node is added, some of the virtual nodes are redistributed across the new node, leading to better load balancing.</li></ul><p>Example:</p><ul><li>Node N1 is represented by virtual nodes at hash positions 100, 400000, and 700000.</li><li>Node N2 is represented by virtual nodes at positions 300000, 500000, and 900000.</li><li>This ensures that the data load is distributed evenly, even if the physical nodes differ in their capacity.</li></ul><p><strong>Conclusion: How Distributed Cache Works with Consistent Hashing</strong></p><p>In a distributed cache system using consistent hashing:</p><ol><li><strong>Write Operations</strong>: Hash the key, find the responsible node, and store the data there.</li><li><strong>Read Operations</strong>: Hash the key, find the responsible node, and retrieve the data from that node.</li><li><strong>Cache Misses</strong>: If the data is not found, fetch it from the underlying data store and store it in the cache.</li><li><strong>Node Addition/Removal</strong>: Consistent hashing ensures minimal data reorganization when nodes are added or removed.</li><li><strong>Virtual Nodes</strong>: Virtual nodes ensure that the load is evenly distributed across all physical nodes, improving scalability and fault tolerance.</li></ol><p>This design provides scalability, fault tolerance, and efficient cache lookups with minimal disruption when nodes are added or removed from the system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80d3f9da474e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prepster/consistent-hashing-80d3f9da474e">Consistent Hashing</a> was originally published in <a href="https://medium.com/prepster">Prepster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unique ID Generators]]></title>
            <link>https://medium.com/prepster/unique-id-generators-4e3f898d0999?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e3f898d0999</guid>
            <category><![CDATA[unique-id-generator]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 07:54:52 GMT</pubDate>
            <atom:updated>2024-08-31T07:58:28.330Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>Snowflake ID Generator</strong> is a unique identifier generator developed by Twitter and is widely used in distributed systems to create unique, time-ordered IDs. It was designed to overcome the limitations of traditional incrementing IDs in distributed environments, where ensuring uniqueness across multiple nodes can be challenging. The Snowflake algorithm generates 64-bit IDs that are unique across distributed systems and sortable by time.</p><p><strong>How the Snowflake ID Generator Works</strong></p><p>The Snowflake ID Generator produces a 64-bit long ID by combining several components into a single number. The ID is structured as follows:</p><pre>| 1 bit | 41 bits           | 10 bits      | 12 bits      |<br>|-------|-------------------|--------------|--------------|<br>| Sign  | Timestamp         | Node ID      | Sequence ID  |</pre><p><strong>Breakdown of the 64-bit ID:</strong></p><ol><li><strong>1 bit (Unused Sign Bit)</strong>:</li></ol><ul><li>The first bit is a sign bit, and since IDs are positive, it is always set to 0.</li></ul><p><strong>2. 41 bits (Timestamp in milliseconds)</strong>:</p><ul><li>This portion of the ID represents the timestamp, in milliseconds, relative to a custom epoch. This ensures that IDs are time-ordered, which can be useful for certain types of queries and sorting operations.</li><li>With 41 bits, this allows for approximately 69 years of unique timestamps (2⁴¹ / (1000 * 60 * 60 * 24 * 365)).</li></ul><p><strong>3. 10 bits (Node ID or Datacenter and Machine ID)</strong>:</p><ul><li>The next 10 bits are used to identify the node or machine that generated the ID. This allows for 1024 (2¹⁰) unique nodes, which is typically enough for most distributed systems.</li><li>In some implementations, these 10 bits might be split into 5 bits for a datacenter ID and 5 bits for a machine ID within that datacenter.</li></ul><p><strong>4. 12 bits (Sequence Number)</strong>:</p><ul><li>The final 12 bits are a sequence number, which is incremented for each ID generated within the same millisecond by the same node. This allows for 4096 (2¹²) unique IDs to be generated per millisecond, per node.</li><li>If more than 4096 IDs are needed in a single millisecond on a node, the generator will wait for the next millisecond to generate more IDs.</li></ul><p><strong>Characteristics of Snowflake IDs</strong></p><ol><li><strong>Uniqueness</strong>:</li></ol><ul><li>The combination of the timestamp, node ID, and sequence number ensures that each ID is unique, even when generated across multiple nodes or machines.</li></ul><p><strong>2. Time-Ordered</strong>:</p><ul><li>Since the timestamp is the most significant part of the ID, the IDs are roughly ordered by the time of generation, which can be useful for sorting and querying by time.</li></ul><p><strong>3. Scalability</strong>:</p><ul><li>Snowflake IDs are highly scalable, allowing multiple nodes to generate IDs concurrently without the risk of collisions.</li></ul><p><strong>4. Decentralization</strong>:</p><ul><li>The Snowflake ID Generator allows IDs to be generated in a decentralized manner without relying on a central authority or database, which eliminates single points of failure and bottlenecks.</li></ul><p><strong>Example of a Snowflake ID</strong></p><p>Suppose the Snowflake ID generator creates an ID with the following components:</p><ul><li><strong>Timestamp</strong>: 41 bits representing a timestamp in milliseconds (e.g., 1617123456789)</li><li><strong>Node ID</strong>: 10 bits representing a machine or node ID (e.g., 512)</li><li><strong>Sequence</strong>: 12 bits representing a sequence number within the same millisecond (e.g., 123)</li></ul><p>The generated Snowflake ID might look like this (in binary):</p><pre>0 000000000000000000000000000000000000000000 1000000000 0000000001111011</pre><p>In decimal, this binary value corresponds to a large 64-bit number, which is the unique Snowflake ID.</p><p><strong>Advantages of Using Snowflake IDs</strong></p><ul><li><strong>Decentralized Generation</strong>: Snowflake IDs can be generated independently on multiple nodes without the need for synchronization or coordination, making it ideal for distributed systems.</li><li><strong>Scalability</strong>: The structure of the ID allows for massive scalability, both in terms of the number of nodes generating IDs and the number of IDs generated per millisecond.</li><li><strong>Efficiency</strong>: The ID generation process is computationally efficient, requiring only bitwise operations and no database access.</li></ul><p><strong>Use Cases for Snowflake IDs</strong></p><ul><li><strong>Distributed Databases</strong>:</li><li>Snowflake IDs are commonly used in distributed databases and key-value stores, where it is essential to generate unique identifiers without relying on a central authority.</li><li><strong>Message Queues</strong>:</li><li>Systems like Kafka or other message queues can use Snowflake IDs to uniquely identify messages across distributed brokers.</li><li><strong>Social Media Platforms</strong>:</li><li>Social media platforms, such as Twitter, use Snowflake IDs to uniquely identify posts, tweets, and other user-generated content.</li><li><strong>Log Aggregation</strong>:</li><li>For log aggregation systems, Snowflake IDs can be used to uniquely identify log entries across multiple services and machines, while preserving the order of events.</li></ul><h3>Implementing a Snowflake ID Generator</h3><p>Below is an implementation of a basic Snowflake ID Generator in Python.</p><pre>import time<br>import threading<br><br>class SnowflakeIDGenerator:<br>    def __init__(self, node_id, epoch=1609459200000):<br>        &quot;&quot;&quot;<br>        Snowflake ID Generator<br><br>        :param node_id: A unique identifier for the node (usually between 0 and 1023).<br>        :param epoch: A custom epoch to start counting from (in milliseconds).<br>        &quot;&quot;&quot;<br>        self.node_id = node_id<br>        self.epoch = epoch<br>        self.sequence = 0<br>        self.last_timestamp = -1<br><br>        # Constants<br>        self.node_id_bits = 10<br>        self.sequence_bits = 12<br><br>        self.max_node_id = -1 ^ (-1 &lt;&lt; self.node_id_bits)<br>        self.max_sequence = -1 ^ (-1 &lt;&lt; self.sequence_bits)<br><br>        self.node_id_shift = self.sequence_bits<br>        self.timestamp_shift = self.node_id_bits + self.sequence_bits<br><br>        self.lock = threading.Lock()<br><br>        if self.node_id &lt; 0 or self.node_id &gt; self.max_node_id:<br>            raise ValueError(f&quot;Node ID must be between 0 and {self.max_node_id}&quot;)<br><br>    def _current_timestamp(self):<br>        return int(time.time() * 1000)<br><br>    def _wait_for_next_millis(self, last_timestamp):<br>        timestamp = self._current_timestamp()<br>        while timestamp &lt;= last_timestamp:<br>            timestamp = self._current_timestamp()<br>        return timestamp<br><br>    def generate_id(self):<br>        &quot;&quot;&quot;<br>        Generate a new Snowflake ID.<br><br>        :return: A unique 64-bit ID.<br>        &quot;&quot;&quot;<br>        with self.lock:<br>            timestamp = self._current_timestamp()<br><br>            if timestamp &lt; self.last_timestamp:<br>                raise Exception(&quot;Clock moved backwards. Refusing to generate ID.&quot;)<br><br>            if timestamp == self.last_timestamp:<br>                self.sequence = (self.sequence + 1) &amp; self.max_sequence<br>                if self.sequence == 0:<br>                    timestamp = self._wait_for_next_millis(self.last_timestamp)<br>            else:<br>                self.sequence = 0<br><br>            self.last_timestamp = timestamp<br><br>            id_ = ((timestamp - self.epoch) &lt;&lt; self.timestamp_shift) | \<br>                  (self.node_id &lt;&lt; self.node_id_shift) | \<br>                  self.sequence<br><br>            return id_<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    generator = SnowflakeIDGenerator(node_id=1)<br><br>    # Generate 10 IDs<br>    for _ in range(10):<br>        print(generator.generate_id())</pre><p>Output</p><pre>484995212897161216<br>484995212897161217<br>484995212897161218<br>484995212897161219<br>484995212897161220<br>484995212897161221<br>484995212897161222<br>484995212897161223<br>484995212897161224<br>484995212897161225</pre><p><strong>Explanation of the Implementation</strong></p><p>1. <strong>Initialization</strong>:</p><p>• The SnowflakeIDGenerator class is initialized with a node_id (unique to each machine or process generating IDs) and an optional epoch (a custom timestamp in milliseconds). The epoch represents the start of the time period for ID generation, allowing IDs to be smaller numbers relative to this point in time.</p><p>2. <strong>Constants</strong>:</p><p>• <strong>Node ID Bits</strong>: 10 bits are reserved for the node ID, allowing up to 1024 unique node IDs.</p><p>• <strong>Sequence Bits</strong>: 12 bits are reserved for the sequence number, allowing for up to 4096 IDs to be generated per node, per millisecond.</p><p>• <strong>Shifts</strong>: The bit shifts required to place the timestamp, node ID, and sequence number in their respective positions within the 64-bit ID.</p><p>3. <strong>Methods</strong>:</p><p>• _current_timestamp: Returns the current timestamp in milliseconds.</p><p>• _wait_for_next_millis: Ensures that the generator waits until the next millisecond if the current sequence number exceeds its limit within the same millisecond.</p><p>• generate_id: Generates a unique Snowflake ID by combining the timestamp, node ID, and sequence number.</p><p>4. <strong>Thread Safety</strong>:</p><p>• The ID generation is thread-safe, using a lock to prevent race conditions when multiple threads attempt to generate IDs concurrently.</p><p><strong>How the ID is Generated</strong></p><p>• <strong>Timestamp</strong>: The timestamp is calculated as the difference between the current time and the epoch, ensuring that IDs are time-ordered.</p><p>• <strong>Node ID</strong>: The node ID is shifted into its position within the 64-bit ID.</p><p>• <strong>Sequence Number</strong>: The sequence number is incremented for each ID generated within the same millisecond. If the sequence number exceeds its maximum (4095), the generator waits for the next millisecond.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e3f898d0999" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prepster/unique-id-generators-4e3f898d0999">Unique ID Generators</a> was originally published in <a href="https://medium.com/prepster">Prepster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to choose Apache Spark Vs Apache Flink]]></title>
            <link>https://medium.com/prepster/when-to-choose-apache-spark-vs-apache-flink-643223b74f2d?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/643223b74f2d</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[apache-flink]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 12:20:37 GMT</pubDate>
            <atom:updated>2024-08-30T12:20:37.083Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Spark and Apache Flink are two of the most popular open-source frameworks for big data processing. Both are designed to handle large-scale data processing tasks, but they have different design philosophies, strengths, and use cases. Here’s a detailed comparison between the two:</p><p><strong>1. Processing Model</strong></p><p><strong>Apache Spark</strong>:</p><ul><li><strong>Batch Processing</strong>: Spark was originally designed as a batch processing engine and excels in processing large datasets in a distributed manner. It uses Resilient Distributed Datasets (RDDs) as the core abstraction for processing data.</li><li><strong>Micro-Batch Streaming</strong>: Spark Streaming extends Spark’s batch processing model to handle real-time streaming data. It processes data streams as a series of small, deterministic micro-batches.</li></ul><p><strong>Apache Flink</strong>:</p><ul><li><strong>Stream Processing</strong>: Flink was designed from the ground up as a streaming-first engine, and it treats batch processing as a special case of stream processing. It can process data streams in real-time with low latency.</li><li><strong>Batch Processing</strong>: While Flink is optimized for stream processing, it can also perform batch processing. Flink’s DataSet API is used for batch processing, whereas the DataStream API is used for stream processing.</li></ul><p><strong>2. Latency and Throughput</strong></p><p><strong>Apache Spark</strong>:</p><ul><li><strong>Latency</strong>: Spark’s micro-batch processing model introduces some latency since it processes data in small batches rather than immediately as it arrives. This is suitable for use cases where slight delays are acceptable.</li><li><strong>Throughput</strong>: Spark is known for its high throughput in batch processing and is highly efficient when dealing with large volumes of data.</li></ul><p><strong>Apache Flink</strong>:</p><ul><li><strong>Latency</strong>: Flink is designed for low-latency stream processing. It processes data as soon as it arrives, making it suitable for real-time applications where immediate processing is required.</li><li><strong>Throughput</strong>: Flink provides both high throughput and low latency, making it suitable for a wide range of streaming use cases.</li></ul><p><strong>3. Fault Tolerance</strong></p><p><strong>Apache Spark</strong>:</p><ul><li><strong>Fault Tolerance</strong>: Spark uses lineage information to recompute lost data in case of failures, which is effective in both batch and micro-batch streaming. In Spark Streaming, the micro-batch processing can be recomputed from the logs in case of a failure.</li><li><strong>Checkpointing</strong>: Spark Streaming supports checkpointing, which periodically saves the state of the RDDs to allow recovery after a failure.</li></ul><p><strong>Apache Flink</strong>:</p><ul><li><strong>Fault Tolerance</strong>: Flink provides exactly-once processing guarantees through distributed snapshots and stateful stream processing. Flink’s fault tolerance mechanism is built around lightweight distributed snapshots, which allows it to recover quickly from failures.</li><li><strong>Checkpointing</strong>: Flink’s stateful stream processing is highly advanced, with efficient and consistent checkpointing that ensures exactly-once semantics.</li></ul><p><strong>4. Ease of Use and APIs</strong></p><p><strong>Apache Spark</strong>:</p><ul><li><strong>APIs</strong>: Spark provides high-level APIs in Java, Scala, Python, and R, which makes it accessible to a wide range of developers. The DataFrame and Dataset APIs are particularly user-friendly and allow for SQL-like operations.</li><li><strong>Ease of Use</strong>: Spark’s APIs are generally easier to use for batch processing and machine learning tasks, and its integration with the wider Hadoop ecosystem makes it a popular choice for data engineering tasks.</li></ul><p><strong>Apache Flink</strong>:</p><ul><li><strong>APIs</strong>: Flink also provides APIs in Java and Scala. Its APIs are more focused on stream processing and can be more complex due to the need to manage state and time-based operations. However, Flink’s Table API and SQL support make it easier to use for structured data processing.</li><li><strong>Ease of Use</strong>: Flink’s APIs are more advanced for stream processing, offering detailed control over time and state management. This makes Flink more powerful for real-time applications but also potentially more complex to use.</li></ul><p><strong>5. Deployment and Integration</strong></p><p><strong>Apache Spark</strong>:</p><ul><li><strong>Deployment</strong>: Spark can be deployed on a variety of cluster managers, including Hadoop YARN, Apache Mesos, and Kubernetes. It’s also available as a standalone cluster.</li><li><strong>Integration</strong>: Spark integrates well with the Hadoop ecosystem, including HDFS, Hive, and HBase. It also has strong support for working with distributed data stores like Cassandra, MongoDB, and Kafka.</li></ul><p><strong>Apache Flink</strong>:</p><ul><li><strong>Deployment</strong>: Flink can be deployed on standalone clusters, Hadoop YARN, Kubernetes, and Mesos. It also offers a native deployment option on Apache Kafka for stream processing.</li><li><strong>Integration</strong>: Flink integrates with various data sources and sinks, including Kafka, HDFS, and relational databases. Flink’s connectors are optimized for low-latency data ingestion and processing.</li></ul><p><strong>6. Community and Ecosystem</strong></p><p><strong>Apache Spark</strong>:</p><ul><li><strong>Community</strong>: Spark has a large and active community, with extensive documentation, tutorials, and third-party libraries. It has become a de facto standard for big data processing in many organizations.</li><li><strong>Ecosystem</strong>: Spark has a broad ecosystem, including libraries for SQL (Spark SQL), machine learning (MLlib), graph processing (GraphX), and stream processing (Spark Streaming).</li></ul><p><strong>Apache Flink</strong>:</p><ul><li><strong>Community</strong>: Flink has a growing community, particularly in the stream processing space. The Flink community is active in developing new features, particularly around real-time processing and stateful computations.</li><li><strong>Ecosystem</strong>: Flink’s ecosystem is more focused on stream processing and real-time analytics. It includes libraries for complex event processing (CEP), machine learning, and graph processing, but the ecosystem is not as extensive as Spark’s.</li></ul><p><strong>7. Use Cases</strong></p><p><strong>Apache Spark</strong>:</p><ul><li><strong>Batch Processing</strong>: ETL processes, batch data processing, data warehousing, machine learning pipelines.</li><li><strong>Streaming</strong>: Near real-time processing where slight delays are acceptable, such as log processing, and data integration tasks.</li></ul><p><strong>Apache Flink</strong>:</p><ul><li><strong>Stream Processing</strong>: Real-time analytics, event-driven applications, real-time fraud detection, complex event processing.</li><li><strong>Batch Processing</strong>: Large-scale data processing, though Flink is more commonly used for stream processing.</li></ul><p><strong>Summary</strong></p><ul><li><strong>Apache Spark</strong> is the go-to choice for batch processing and machine learning tasks due to its ease of use, rich APIs, and strong integration with the Hadoop ecosystem. It’s also suitable for near real-time stream processing through its micro-batch model.</li><li><strong>Apache Flink</strong> excels in real-time, low-latency stream processing with exactly-once semantics and advanced stateful stream processing capabilities. It’s ideal for use cases where real-time data processing and low latency are critical.</li></ul><p>Choosing between Spark and Flink depends on your specific use case:</p><ul><li>If you need to process large volumes of historical data in batches or run machine learning algorithms on large datasets, <strong>Apache Spark</strong> is likely the better choice.</li><li>If you require real-time processing with low latency and exactly-once guarantees, especially for complex event processing, <strong>Apache Flink</strong> would be the preferred option.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=643223b74f2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prepster/when-to-choose-apache-spark-vs-apache-flink-643223b74f2d">When to choose Apache Spark Vs Apache Flink</a> was originally published in <a href="https://medium.com/prepster">Prepster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Geohash Works in Proximity Search]]></title>
            <link>https://medium.com/prepster/how-geohash-works-in-proximity-search-c56b8fc23a93?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/c56b8fc23a93</guid>
            <category><![CDATA[geohash]]></category>
            <category><![CDATA[base32]]></category>
            <category><![CDATA[proximity-searches]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 07:09:19 GMT</pubDate>
            <atom:updated>2024-08-30T07:09:19.752Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Base32 Encoding: An Overview</strong></p><p><strong>Base32 encoding</strong> is a method for encoding binary data using a set of 32 different ASCII characters. It is often used in applications where human readability is important, or in cases where the data needs to be transferred over mediums that are not binary-safe (e.g., email, URLs). Base32 is particularly useful for encoding data like secret keys, unique identifiers, or binary files in a format that can be easily handled by text-processing systems.</p><p><strong>How Base32 Encoding Works</strong></p><ul><li><strong>Character Set</strong>:</li><li>Base32 encoding uses a set of 32 characters. The standard character set is:</li></ul><pre>A-Z (26 letters)<br>2–7 (6 digits)</pre><ul><li>The characters 0, 1, 8, and 9 are typically excluded to avoid confusion with the letters O and I and to improve human readability.</li><li><strong>Encoding Process</strong>:</li><li><strong>Step 1</strong>: Convert the binary data into a series of 5-bit groups. Since Base32 uses 32 characters, each character can represent 5 bits of data (because log2(32) = 5).</li><li><strong>Step 2</strong>: Each 5-bit group is mapped to a character in the Base32 character set.</li><li><strong>Step 3</strong>: If the total number of bits is not a multiple of 5, padding is added to make it so. The padding character used is typically = to fill in the remaining space.</li><li><strong>Padding</strong>:</li><li>Padding is used when the length of the binary data is not a multiple of 5 bits. The padding character = is appended to the encoded output to make sure the final string length is a multiple of 8 characters.</li><li>The padding allows the Base32 decoder to know how many bits of the final encoded block were part of the actual data.</li><li><strong>Example</strong>:</li><li>Suppose you have the binary data 101010110110. To encode this in Base32:</li><li><strong>Binary Data</strong>: 101010110110</li><li><strong>5-bit Groups</strong>: 10101 01101 10000 (note: the last group is padded with zeros)</li><li><strong>Base32 Characters</strong>: The corresponding Base32 characters might be V, M, Q.</li><li><strong>Final Encoded String</strong>: The result would be VMQ= (with padding).</li></ul><p><strong>Use Cases of Base32 Encoding</strong></p><ul><li><strong>Human-Readable Identifiers</strong>:</li><li>Base32 encoding is often used to create human-readable identifiers that are case-insensitive, avoiding confusion between similar-looking characters.</li><li><strong>Secret Key Encoding</strong>:</li><li>When encoding binary keys (e.g., for TOTP/HOTP in 2FA systems), Base32 is commonly used because it generates a string that can be easily copied or manually input by users.</li><li><strong>Data Transmission in Text-Based Systems</strong>:</li><li>Base32 is used to encode binary data that needs to be safely transmitted over text-based protocols like email or URLs, where binary data might get corrupted.</li><li><strong>QR Codes</strong>:</li><li>Base32 is sometimes used to encode data for QR codes, ensuring that the encoded data is compact and can be accurately represented.</li></ul><p><strong>Advantages of Base32 Encoding</strong></p><ul><li><strong>Human Readability</strong>: The character set is designed to be easily read and written by humans, with a lower risk of confusion compared to other encoding schemes.</li><li><strong>Case Insensitivity</strong>: The use of only uppercase letters (or lowercase, depending on implementation) makes the encoded data case-insensitive, which is beneficial for certain applications like serial numbers or activation codes.</li><li><strong>Compatibility</strong>: Base32 encoded strings are URL-safe and email-safe, making them compatible with a wide range of applications and transmission protocols.</li></ul><p><strong>Disadvantages of Base32 Encoding</strong></p><ul><li><strong>Inefficiency</strong>: Base32 encoding is less space-efficient compared to Base64 because it uses 8 bits to store 5 bits of data, resulting in a 60% increase in the data size. This is more pronounced with larger datasets.</li><li><strong>Less Common</strong>: While Base64 is widely used and supported, Base32 is less common, meaning some tools or systems might not natively support it.</li></ul><p><strong>Comparison with Base64 Encoding</strong></p><ul><li><strong>Base64</strong>: Encodes data in 64-character sets, making it more compact than Base32. It uses A-Z, a-z, 0–9, +, and / as its character set.</li><li><strong>Base32</strong>: Encodes data in 32-character sets, which is less compact but more human-readable, and avoids characters that can be easily confused (like 0 and O).</li></ul><p><strong>Summary</strong></p><p>Base32 encoding is a method of encoding binary data using a 32-character set. It is particularly useful for generating human-readable strings, encoding secret keys, and ensuring safe transmission of data over text-based protocols. While it is less efficient than Base64, its simplicity and readability make it ideal for certain use cases, especially where case insensitivity and ease of manual input are important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vq4RfomkdMD4jI-G.png" /></figure><p><strong>Geohash</strong> is a geocoding method that converts latitude and longitude coordinates into a short string of letters and digits. It represents a specific location on the Earth in a way that preserves spatial proximity; points that are close together geographically will often have similar prefixes in their geohash representations.</p><p><strong>How Geohash Works</strong></p><ul><li><strong>Dividing the World into Grids</strong>:</li><li>The Earth is divided into a grid of rectangular cells. Each cell represents a specific area on the Earth’s surface.</li><li>The Geohash algorithm continuously subdivides these cells into smaller cells, assigning a unique identifier (a geohash) to each cell.</li><li><strong>Encoding Latitude and Longitude</strong>:</li><li>Latitude and longitude values are interleaved into a binary string, which is then converted into a base32 encoded string (using 32 possible characters: 0–9 and a-z excluding some letters).</li><li><strong>Precision</strong>:</li><li>The length of the Geohash string determines the precision of the location:</li><li>A longer Geohash string represents a smaller and more precise area.</li><li>A shorter Geohash string represents a larger area.</li></ul><p><strong>Example: Encoding a Location with Geohash</strong></p><p>Let’s go through an example of encoding a specific latitude and longitude into a Geohash.</p><p><strong>Location:</strong></p><ul><li><strong>Latitude</strong>: 37.7749 (San Francisco, CA)</li><li><strong>Longitude</strong>: -122.4194</li></ul><p><strong>Step 1: Divide the World into Two Halves</strong></p><ul><li><strong>Latitude</strong>: The latitude of the Earth is divided into two halves: Northern Hemisphere (0 to +90) and Southern Hemisphere (0 to -90).</li><li><strong>Longitude</strong>: Similarly, the longitude is divided into two halves: Eastern Hemisphere (0 to +180) and Western Hemisphere (0 to -180).</li></ul><p><strong>Step 2: Encode the Latitude and Longitude Separately</strong></p><ul><li><strong>Latitude (37.7749)</strong>:</li><li>Start by deciding whether 37.7749 is in the Northern Hemisphere (&gt; 0) or Southern Hemisphere (&lt;= 0).</li><li>Keep dividing the current interval (0 to 90) in half and check where the actual latitude lies:</li><li>First interval: [0, 90] → 37.7749 is in the lower half (so 0)</li><li>Second interval: [0, 45] → 37.7749 is in the upper half (so 1)</li><li>Continue this process…</li><li><strong>Longitude (-122.4194)</strong>:</li><li>Similarly, start with the interval (-180 to 0) and subdivide it:</li><li>First interval: [-180, 0] → -122.4194 is in the upper half (so 1)</li><li>Second interval: [-180, -90] → -122.4194 is in the lower half (so 0)</li><li>Continue this process…</li></ul><p><strong>Step 3: Interleave the Bits</strong></p><p>The binary bits from the latitude and longitude are then interleaved to form a single binary sequence.</p><p><strong>Step 4: Convert Binary Sequence to Base32</strong></p><p>This binary sequence is then converted into a base32 encoded string using a predefined character set (0123456789bcdefghjkmnpqrstuvwxyz).</p><p><strong>Example Geohash</strong></p><p>Let’s compute the Geohash for the example coordinates.</p><ul><li><strong>Latitude (37.7749)</strong> and <strong>Longitude (-122.4194)</strong> are encoded as:</li><li>Latitude bits: 0101101101010…</li><li>Longitude bits: 1100101100100…</li><li><strong>Interleaving Bits</strong>:</li><li>Interleave latitude and longitude bits into a single binary string.</li><li><strong>Convert to Base32</strong>:</li><li>The resulting binary string is then divided into groups of 5 bits, each of which is mapped to a character in the Base32 alphabet.</li></ul><p>For Latitude 37.7749 and Longitude -122.4194, the Geohash might be something like:</p><p><strong>Geohash</strong>: 9q8yy</p><p><strong>Interpretation</strong></p><ul><li><strong>Precision</strong>:</li><li>The Geohash 9q8yy represents a specific area in San Francisco with moderate precision. The more characters you add, the more precise the location.</li><li>Shortening the Geohash, such as 9q8y, represents a broader area. Adding more characters, such as 9q8yyf, pinpoints a smaller area.</li></ul><p><strong>Example Use Cases of Geohash</strong></p><ul><li><strong>Proximity Searches</strong>:</li><li>Geohash is useful for proximity searches because locations that are close to each other have similar Geohash prefixes.</li><li>For example, searching for nearby restaurants can be done by searching for locations that share the same Geohash prefix.</li><li><strong>Spatial Indexing</strong>:</li><li>In databases, Geohash can be used to index geographic locations efficiently, allowing for fast retrieval of spatial data.</li><li><strong>Map Display</strong>:</li><li>Geohashes can be used to quickly generate grids of a map display, where each grid cell corresponds to a Geohash region.</li></ul><p><strong>Summary</strong></p><p>Geohash is a powerful method for encoding geographic coordinates into a compact, alphanumeric string. It preserves spatial locality, making it useful for proximity searches, spatial indexing, and other geospatial applications. The length of the Geohash determines the precision, with longer hashes providing more precise locations.</p><h3>Proximity Search with Geohash</h3><p><strong>Example of a Proximity Search</strong></p><p>Let’s say you want to find all restaurants within a 5-mile radius of a given location in San Francisco.</p><p><strong>Step 1: Encode the Location as a Geohash</strong></p><ul><li>Suppose the latitude and longitude of your starting location are 37.7749, -122.4194.</li><li>Convert these coordinates into a Geohash. For simplicity, let’s assume the Geohash is 9q8yy.</li></ul><p><strong>Step 2: Identify Neighboring Geohashes</strong></p><ul><li>To perform a proximity search, you need to consider not just the Geohash of the starting location but also the neighboring Geohashes. This is because the area you’re searching might span multiple Geohashes.</li><li>Geohash has 8 possible neighboring cells for any given Geohash, plus the central cell itself. These neighbors are:</li><li>North, South, East, West, Northeast, Northwest, Southeast, Southwest.</li></ul><pre>+-----------+-----------+-----------+<br>| Northwest |   North   | Northeast |<br>|           |           |           |<br>+-----------+-----------+-----------+<br>|    West   |  Central  |    East   |<br>|           |   Cell    |           |<br>+-----------+-----------+-----------+<br>| Southwest |   South   | Southeast |<br>|           |           |           |<br>+-----------+-----------+-----------+</pre><p><strong>Step 3: Search in the Geohash and Its Neighbors</strong></p><ul><li>For the Geohash 9q8yy, you would calculate the Geohashes for the neighboring cells.</li><li>For instance:</li><li>North: 9q8yz</li><li>South: 9q8yw</li><li>East: 9q8yx</li><li>West: 9q8yv</li><li>Northeast: 9q8yyz</li><li>Northwest: 9q8yyv</li><li>Southeast: 9q8ywx</li><li>Southwest: 9q8ywv</li><li>You would then search for all restaurants (or any POIs) within these Geohashes.</li><li><strong>Calculate Neighbors</strong></li><li><strong>Determine the Neighboring Directions:</strong></li><li>Split the given Geohash (9q8yy) into latitude and longitude bits.</li><li>Identify the direction in which you want to move (North, South, East, West).</li><li>Adjust the relevant bits to move in that direction.</li><li><strong>Adjust the Last Character Based on Direction:</strong></li><li>Depending on whether you’re moving north, south, east, or west, you’ll adjust the last character of the Geohash.</li><li>For example:</li><li><strong>North</strong>: Increase the latitude bit.</li><li><strong>South</strong>: Decrease the latitude bit.</li><li><strong>East</strong>: Increase the longitude bit.</li><li><strong>West</strong>: Decrease the longitude bit.</li></ul><p>Calculate Specific Neighbors</p><p>Here’s how you would manually calculate the neighboring Geohashes:</p><ul><li><strong>North (9q8yy → 9q8yz)</strong>:</li><li>Increment the latitude by adjusting the last character to the next character in the base32 sequence.</li><li><strong>South (9q8yy → 9q8yw)</strong>:</li><li>Decrement the latitude by adjusting the last character to the previous character in the base32 sequence.</li><li><strong>East (9q8yy → 9q8yx)</strong>:</li><li>Increment the longitude by adjusting the last character.</li><li><strong>West (9q8yy → 9q8yv)</strong>:</li><li>Decrement the longitude by adjusting the last character.</li><li><strong>Northeast (9q8yy → 9q8yyz)</strong>:</li><li>Increment both latitude and longitude.</li><li><strong>Northwest (9q8yy → 9q8yyv)</strong>:</li><li>Increment latitude and decrement longitude.</li><li><strong>Southeast (9q8yy → 9q8ywx)</strong>:</li><li>Decrement latitude and increment longitude.</li><li><strong>Southwest (9q8yy → 9q8ywv)</strong>:</li><li>Decrement both latitude and longitude.</li></ul><p><strong>Summary of Calculations</strong></p><ul><li><strong>Central</strong>: 9q8yy</li><li><strong>North</strong>: 9q8yz</li><li><strong>South</strong>: 9q8yw</li><li><strong>East</strong>: 9q8yx</li><li><strong>West</strong>: 9q8yv</li><li><strong>Northeast</strong>: 9q8yyz</li><li><strong>Northwest</strong>: 9q8yyv</li><li><strong>Southeast</strong>: 9q8ywx</li><li><strong>Southwest</strong>: 9q8ywv</li></ul><p><strong>Automated Calculation</strong></p><p>While manual calculation is possible, in practice, it is more common to use libraries or tools that handle the Geohash calculation for you. Libraries like geohash in Python or similar in other languages can calculate these neighbors programmatically.</p><p>For example, in Python:</p><pre>import geohash<br>geohash_neighbors = geohash.neighbors(&#39;9q8yy&#39;)<br>print(geohash_neighbors)</pre><p>This will return a list of all neighboring Geohashes.</p><p><strong>Step 4: Filter Results by Exact Distance</strong></p><ul><li>Although Geohash is useful for narrowing down the search area, the cells themselves are rectangular and can extend beyond the desired radius.</li><li>Once you’ve retrieved all possible matches within the relevant Geohashes, apply a more precise distance calculation (e.g., using the Haversine formula) to filter the results and ensure they fall within the exact 5-mile radius.</li></ul><p><strong>Advantages of Using Geohash for Proximity Search</strong></p><ul><li><strong>Efficiency</strong>:</li><li>Geohash allows you to quickly narrow down the search area by considering only the relevant Geohashes. This reduces the number of points you need to evaluate compared to searching all data points in a database.</li><li><strong>Indexing</strong>:</li><li>Databases can index locations by their Geohash. When performing a proximity search, you can quickly query all points that fall within a specific set of Geohashes, making the search operation fast.</li><li><strong>Scalability</strong>:</li><li>Geohash-based proximity search scales well as the dataset grows, especially in distributed systems where data is partitioned based on Geohash.</li></ul><p><strong>Example: Searching for Restaurants</strong></p><ol><li><strong>User Location</strong>: San Francisco, Geohash 9q8yy.</li><li><strong>Neighboring Geohashes</strong>:</li></ol><ul><li>You would look up all restaurants within the Geohashes 9q8yy, 9q8yz, 9q8yw, 9q8yx, 9q8yv, 9q8yyz, 9q8yyv, 9q8ywx, and 9q8ywv.</li></ul><ol><li><strong>Query Execution</strong>:</li></ol><ul><li>Your database query might look for records in these Geohashes.</li></ul><ol><li><strong>Filtering</strong>:</li></ol><ul><li>Apply a final filter to ensure each result is within the 5-mile radius of the original location.</li></ul><p><strong>Challenges and Considerations</strong></p><ul><li><strong>Edge Cases</strong>:</li><li>When the search area is near the edge of a Geohash cell, you must ensure that neighboring cells are included to avoid missing results.</li><li><strong>Variable Cell Size</strong>:</li><li>Geohash cells are not uniform in size; they vary depending on the latitude. The closer you get to the poles, the smaller the cells. This variation must be considered in proximity searches.</li><li><strong>Accuracy</strong>:</li><li>Geohash alone may not be precise enough for very small distances, so it’s important to combine it with more accurate distance calculations.</li></ul><p>Play around<br><a href="https://geohash.softeng.co/9q8yy">https://geohash.softeng.co/9q8yy</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c56b8fc23a93" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prepster/how-geohash-works-in-proximity-search-c56b8fc23a93">How Geohash Works in Proximity Search</a> was originally published in <a href="https://medium.com/prepster">Prepster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Saga Pattern in Microservices Architecture]]></title>
            <link>https://medium.com/prepster/understanding-the-saga-pattern-in-microservices-architecture-4ca4392d97d0?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ca4392d97d0</guid>
            <category><![CDATA[saga-pattern]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 07:05:21 GMT</pubDate>
            <atom:updated>2024-09-17T07:43:59.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7ypz28zDrrj6H_sLqoCLA.png" /><figcaption>credit: microservices.io</figcaption></figure><p>The <strong>Saga pattern</strong> is a design pattern used to manage distributed transactions in microservices architectures. Unlike traditional monolithic architectures where a single database transaction can ensure ACID (Atomicity, Consistency, Isolation, Durability) properties, microservices often involve multiple services with their own databases. This makes it challenging to maintain consistency across services, especially when a transaction spans multiple microservices. The Saga pattern addresses this challenge by breaking down a transaction into a series of smaller, independent steps, each of which can be rolled back or compensated if something goes wrong.</p><p><strong>What is the Saga Pattern?</strong></p><p>In the Saga pattern, a long-running transaction is split into multiple smaller, isolated transactions that are managed by individual microservices. Each of these smaller transactions is known as a <strong>saga step</strong>. If all the saga steps complete successfully, the entire transaction is considered successful. However, if any step fails, the system must undo or “compensate” for the steps that have already been completed, ensuring that the system remains consistent.</p><p><strong>Types of Sagas</strong></p><p>There are two primary types of Sagas:</p><p><strong>Choreography-Based Saga</strong>:</p><ul><li>In this approach, each microservice involved in the saga publishes events when a transaction is completed.</li><li>Other services listen to these events and decide whether to continue the saga or to trigger compensating transactions.</li><li>There is no central coordinator; the services coordinate with each other through events.</li></ul><p><strong>Orchestration-Based Saga</strong>:</p><ul><li>In this approach, a central saga orchestrator or coordinator manages the saga.</li><li>The orchestrator sends commands to each service to execute a transaction step and awaits a response.</li><li>If a step fails, the orchestrator instructs the relevant services to execute compensating transactions to roll back the saga.</li></ul><p><strong>Compensating Transactions</strong></p><p><strong>Compensating transactions</strong> are an essential part of the Saga pattern. They are the equivalent of a rollback in traditional database transactions, but they are more complex because they must be explicitly defined and implemented for each saga step.</p><ul><li><strong>Definition</strong>: A compensating transaction is an operation that undoes the effects of a previous transaction step in case of a failure. It’s like reversing a previous transaction to bring the system back to a consistent state.</li><li><strong>Example</strong>: If a step in a saga deducts money from a user’s account, the compensating transaction would be to credit that money back if the saga fails at a later step.</li></ul><h3><strong>Example of a Saga Pattern with Compensating Transactions</strong></h3><p>Consider an e-commerce application where a user places an order. The order process involves multiple microservices:</p><ol><li><strong>Order Service</strong>: Creates the order.</li><li><strong>Payment Service</strong>: Charges the user’s credit card.</li><li><strong>Inventory Service</strong>: Reserves the items in the inventory.</li><li><strong>Shipping Service</strong>: Schedules the shipment of the items.</li></ol><p><strong>Choreography-Based Saga Example</strong></p><ul><li><strong>Step 1</strong>: The Order Service creates the order and publishes an “Order Created” event.</li><li><strong>Step 2</strong>: The Payment Service listens to the “Order Created” event, charges the credit card, and publishes a “Payment Completed” event.</li><li><strong>Step 3</strong>: The Inventory Service listens to the “Payment Completed” event, reserves the items, and publishes an “Inventory Reserved” event.</li><li><strong>Step 4</strong>: The Shipping Service listens to the “Inventory Reserved” event, schedules the shipment, and publishes a “Shipment Scheduled” event.</li></ul><p>If any of these steps fail, the respective service must trigger compensating transactions:</p><ul><li><strong>If the Payment Service fails</strong>: The Order Service might cancel the order.</li><li><strong>If the Inventory Service fails</strong>: The Payment Service might refund the payment, and the Order Service might cancel the order.</li><li><strong>If the Shipping Service fails</strong>: The Inventory Service might release the reserved items, the Payment Service might refund the payment, and the Order Service might cancel the order.</li></ul><p><strong>Orchestration-Based Saga Example</strong></p><ul><li><strong>Step 1</strong>: The saga orchestrator sends a command to the Order Service to create the order.</li><li><strong>Step 2</strong>: Upon successful completion, the orchestrator sends a command to the Payment Service to charge the credit card.</li><li><strong>Step 3</strong>: If the Payment Service confirms the payment, the orchestrator sends a command to the Inventory Service to reserve the items.</li><li><strong>Step 4</strong>: If the Inventory Service confirms the reservation, the orchestrator sends a command to the Shipping Service to schedule the shipment.</li></ul><p>If a step fails:</p><ul><li><strong>Compensation</strong>: The orchestrator will send compensating commands to undo the effects of the previous successful steps.</li><li><strong>If the Inventory Service fails</strong>: The orchestrator might first instruct the Payment Service to refund the payment and then instruct the Order Service to cancel the order.</li></ul><h3><strong>Advantages of the Saga Pattern</strong></h3><p><strong>Resilience and Consistency</strong>:</p><ul><li>The Saga pattern helps maintain consistency in distributed systems by ensuring that even if a failure occurs, compensating transactions can roll back the system to a consistent state.</li></ul><p><strong>Scalability</strong>:</p><ul><li>Since each microservice manages its own transaction, the system can scale more easily, with each service handling its part of the overall transaction independently.</li></ul><p><strong>Flexibility</strong>:</p><ul><li>Different services can be implemented in different technologies and programming languages since each transaction step is independent.</li></ul><h3><strong>Challenges of the Saga Pattern</strong></h3><p><strong>Complexity</strong>:</p><ul><li>Implementing compensating transactions and ensuring they correctly reverse the effects of previous steps can be complex and error-prone.</li></ul><p><strong>Idempotency</strong>:</p><ul><li>Each step in a saga should be idempotent, meaning that if the same operation is executed multiple times, the result should be the same. This ensures that retries (in case of failure) do not lead to inconsistent states.</li></ul><p><strong>Data Consistency</strong>:</p><ul><li>Achieving eventual consistency can be challenging, especially in systems with high write concurrency and frequent failures.</li></ul><p><strong>Monitoring and Debugging</strong>:</p><ul><li>Tracking the progress of a saga and diagnosing issues can be difficult, especially in choreography-based sagas where there is no central coordinator.</li></ul><p><strong>Best Practices</strong></p><ul><li><strong>Design Clear Compensating Transactions</strong>:</li><li>Ensure that every transactional step has a well-defined compensating transaction. This requires careful planning and understanding of how each service interacts with others.</li><li><strong>Use Orchestration for Complex Workflows</strong>:</li><li>In complex workflows with multiple dependencies, using an orchestration-based saga can simplify the control flow and make the system easier to manage.</li><li><strong>Implement Idempotency</strong>:</li><li>Ensure that all operations, including compensating transactions, are idempotent to handle retries safely.</li><li><strong>Monitor and Log Sagas</strong>:</li><li>Implement robust monitoring and logging to track the progress of sagas and identify where failures occur. This can help in quickly diagnosing and resolving issues.</li></ul><p><strong>Conclusion</strong></p><p>The Saga pattern is a powerful tool for managing distributed transactions in a microservices architecture. By breaking down large transactions into smaller, independent steps and implementing compensating transactions, the Saga pattern ensures that systems can maintain consistency even in the face of failures. However, this approach requires careful design, particularly around compensating transactions and idempotency, to ensure that the system remains robust and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ca4392d97d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prepster/understanding-the-saga-pattern-in-microservices-architecture-4ca4392d97d0">Understanding the Saga Pattern in Microservices Architecture</a> was originally published in <a href="https://medium.com/prepster">Prepster</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Export Solana Phantom wallet key as Json]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">solana-keygen recover &#x2018;prompt:?key=0/0&#x2019; -o phantom_wallet.json</p><p class="medium-feed-link"><a href="https://girishkr.medium.com/export-solana-phantom-wallet-key-as-json-fadceece649d?source=rss-c72c83160392------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://girishkr.medium.com/export-solana-phantom-wallet-key-as-json-fadceece649d?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/fadceece649d</guid>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[phantom]]></category>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 10:35:16 GMT</pubDate>
            <atom:updated>2024-08-30T11:15:29.631Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Test npm package locally]]></title>
            <link>https://girishkr.medium.com/test-npm-package-locally-9f4ec436d01d?source=rss-c72c83160392------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4ec436d01d</guid>
            <dc:creator><![CDATA[Girish]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 14:01:18 GMT</pubDate>
            <atom:updated>2024-01-21T04:56:54.738Z</atom:updated>
            <content:encoded><![CDATA[<h3>npm pack</h3><p><a href="https://docs.npmjs.com/cli/pack">The </a><a href="https://docs.npmjs.com/cli/pack">pack command</a> creates a .tgz file exactly the way it would if you were going to publish the package to npm. It pulls the name and version from package.json, resulting in a file like package-name-0.0.0.tgz. This can be copied, uploaded, or sent to a coworker. It&#39;s exactly the file that would be uploaded to npm if you published it.</p><pre>npm pack</pre><p>Once you have the file, you can install it. npm install</p><pre>$ npm pack<br>$ cp package-name-0.0.0.tgz ~<br>$ npm install ~/package-name-0.0.0.tgz</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4ec436d01d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>