<?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 Kedar kanase on Medium]]></title>
        <description><![CDATA[Stories by Kedar kanase on Medium]]></description>
        <link>https://medium.com/@kedarkanase12?source=rss-17272427ba0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cHMdlNireAtAf3A1BZdjWA.jpeg</url>
            <title>Stories by Kedar kanase on Medium</title>
            <link>https://medium.com/@kedarkanase12?source=rss-17272427ba0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:34:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kedarkanase12/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[Redis Internals & CE-Cluster Setup]]></title>
            <link>https://medium.com/@kedarkanase12/redis-internals-ce-cluster-setup-32007d0addab?source=rss-17272427ba0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/32007d0addab</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Kedar kanase]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 10:57:06 GMT</pubDate>
            <atom:updated>2026-06-01T10:57:06.863Z</atom:updated>
            <content:encoded><![CDATA[<p>Redis (Remote Dictionary Server) is an in-memory data structure store known for its high performance and low latency. In this article, we will explore Redis internals, including its event-driven architecture, I/O multiplexing, command processing, memory management, persistence, and replication mechanisms. Additionally, we will walk through the deployment and configuration of a Redis Community Edition (CE) cluster on RHEL servers.</p><blockquote><strong>Understanding Redis Internal Architecture: How Redis Processes a Command</strong></blockquote><p>High-Level Design(HLD):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTjkuz7ABWAxGh1Jwn1mZw.png" /></figure><h3>Step 1: Client Sends a Request</h3><p>Applications do not directly communicate with Redis. Instead, they use Redis client libraries such as:</p><ul><li>redis-py (Python)</li><li>Jedis (Java)</li><li>ioredis (Node.js)</li><li>StackExchange.Redis (.NET)</li></ul><p>Most Redis clients maintain a connection pool to avoid creating a new TCP connection for every request.</p><p>For example:</p><pre>SET name kedar</pre><p>The client converts this command into Redis Serialization Protocol (RESP) format and sends it through an existing TCP connection.</p><h3>Step 2: Request Reaches Redis Server</h3><p>Redis listens on TCP port 6379 by default.</p><p>When the request arrives:</p><ol><li>The network interface card (NIC) receives the packet.</li><li>The Linux kernel processes the packet.</li><li>The packet is placed into the socket receive buffer.</li><li>Redis is notified that data is available to read.</li></ol><p>At this point, Redis has not yet processed the command.</p><h3>Step 3: I/O Multiplexing</h3><p>One of Redis’s most important optimizations is I/O Multiplexing.</p><p>A Redis server may have thousands of connected clients simultaneously. Creating one thread per connection would consume excessive memory and CPU resources.</p><p>Instead, Redis uses:</p><ul><li>epoll on Linux</li><li>kqueue on BSD/macOS</li><li>select/poll on older systems</li></ul><p>Redis registers all client sockets with epoll and waits for activity.</p><p>Internally:</p><pre>epoll_wait()</pre><p>When a packet arrives, the kernel wakes Redis and informs it which socket has data available.</p><p>This allows a single Redis thread to efficiently handle thousands of client connections.</p><h3>Step 4: Event Loop Processing</h3><p>Redis uses an event-driven architecture.</p><p>The main event loop continuously performs the following operations:</p><ol><li>Wait for network events.</li><li>Identify sockets that are ready.</li><li>Read incoming data.</li><li>Process commands.</li><li>Send responses.</li></ol><p>This design eliminates unnecessary context switching and lock contention.</p><h3>Step 5: Command Parsing</h3><p>Redis uses RESP (Redis Serialization Protocol).</p><p>A command such as:</p><pre>SET name kedar</pre><p>is received in a structured format and parsed into:</p><pre>Command = SET<br>Argument1 = name<br>Argument2 = kedar</pre><p>Redis now understands what operation must be performed.</p><h3>Step 6: Command Lookup Table</h3><p>Redis maintains an internal command table containing all supported commands.</p><p>Simplified example:</p><pre>SET   → setCommand()<br>GET   → getCommand()<br>HSET  → hsetCommand()<br>DEL   → delCommand()</pre><p>When Redis receives a command, it performs a lookup and calls the appropriate handler function.</p><p>For our example:</p><pre>SET → setCommand()</pre><h3>Step 7: Redis Database Structure</h3><p>Internally, Redis stores data in a hash table called a dictionary.</p><p>The structure can be visualized as:</p><pre>RedisDB<br>   ↓<br>Dictionary (Hash Table)<br>   ↓<br>Key → Value</pre><p>For example:</p><pre>&quot;name&quot; → Redis Object<br>&quot;user:1&quot; → Redis Object<br>&quot;session:10&quot; → Redis Object</pre><p>Every key in Redis is stored inside this main dictionary.</p><h3>Step 8: Hashing the Key</h3><p>When Redis receives:</p><pre>SET name kedar</pre><p>it calculates a hash value for the key:</p><pre>name</pre><p>The hash determines which bucket in the hash table should contain the key.</p><p>Example:</p><pre>Hash(name)<br>    ↓<br>Bucket 12</pre><p>Redis then inserts the entry into that bucket.</p><p>This is the reason most Redis operations have O(1) average lookup time.</p><h3>Step 9: Creating a Redis Object</h3><p>Redis does not directly store raw strings.</p><p>Instead, every value is wrapped inside a Redis Object.</p><p>Example:</p><pre>Redis Object<br>    Type = STRING<br>    Encoding = RAW<br>    Pointer = Actual Data</pre><p>For:</p><pre>SET name kedar</pre><p>Redis creates a String Object representing the value “kedar”.</p><h3>Step 10: Storing the Data</h3><p>Internally the memory layout becomes:</p><pre>RedisDB<br>    ↓<br>Dictionary<br>    ↓<br>dictEntry<br>    ├── key = &quot;name&quot;<br>    └── value = Redis Object<br>                     ↓<br>                  &quot;kedar&quot;</pre><p>This object-oriented design allows Redis to support different data types using a common framework.</p><h3>Step 11: Internal Data Structures</h3><p>Redis supports several data types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*G5pkp0iZ3Q22p_mLUXXAHw.png" /></figure><p>Redis automatically chooses the most memory-efficient internal representation.</p><h3>Step 12: Persistence and Replication</h3><p>After storing the data in memory, Redis may perform additional operations:</p><h3>Persistence</h3><p>If AOF is enabled:</p><pre>SET name kedar</pre><p>is appended to the Append Only File.</p><p>If RDB snapshots are enabled, Redis periodically creates a point-in-time snapshot of the dataset.</p><h3>Replication</h3><p>If replicas exist:</p><pre>Primary<br>    ↓<br>Replica 1<br>Replica 2<br>Replica 3</pre><p>the command is propagated to all replicas.</p><h3>Step 13: Sending Response Back</h3><p>Once the operation completes successfully, Redis sends:</p><pre>OK</pre><p>back to the client through the same TCP connection.</p><p>The client receives the response and the command lifecycle is complete.</p><h3>Why Redis Is So Fast</h3><p>Redis achieves high performance because of several architectural decisions:</p><ul><li>Data stored in memory</li><li>Single-threaded command execution</li><li>I/O Multiplexing using epoll/kqueue</li><li>Highly optimized data structures</li><li>O(1) average lookup using hash tables</li><li>Minimal locking overhead</li><li>Efficient network event handling</li></ul><p>These optimizations allow Redis to process millions of operations per second with very low latency.</p><h3><strong>Understanding and Deploying Redis CE Cluster Setup:</strong></h3><blockquote><strong>Prerequisites</strong>:</blockquote><p>On Linux:</p><ol><li>Basic understanding of Linux.</li><li>Local Repo should be configured.</li><li>Install essential development tools.</li><li>Firewall Configuration.</li></ol><p>High-Level Design(HLD):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*bSzZL5i9uOqnf50fgSXpHw.png" /></figure><blockquote>Setuping the Redis OSS Cluster:</blockquote><p><strong>Installing Redis on All Nodes</strong></p><p>Step 1: install redis on all the nodes:</p><p>1. Log into all the instances via SSH, then run the following command to install the Redis module using the DNF package manager as shown.</p><pre>[root@redismaster ~]# dnf module install redis</pre><p>2.<a href="http://2.next/"> Next</a>, start the <strong>Redis</strong> service, enable it to automatically start at system boot and check its status to verify that it is running (verify the service on all the 6 instances):</p><pre>[root@redismaster ~]# systemctl start redis<br>[root@redismaster ~]# systemctl enable redis<br>[root@redismaster ~]# systemctl status redis</pre><p>Step 2: Configuring Redis Instances on all Nodes</p><p>1. This section describes how to configure the Redis cluster nodes. Remember to perform the configurations here on all the nodes.</p><p>Use the /etc/redis.conf configuration file to configure the Redis server. As a recommended practice, create a backup of the original file before editing it using a command-line text editor of your choice.</p><pre>[root@redismaster ~]#  vim /etc/redis/redis.conf</pre><p>2.<a href="http://2.next/"> Next</a>, find the following configuration parameters and edit their values as shown. The <strong>bind</strong> parameter sets the interface of the Redis server will listen on, set its value to the instance LAN IP. Remove the <strong>127.0.0.1</strong> because we realized leaving it there slows down the process of cluster creation, particularly the stage of joining the cluster.</p><pre>bind 172.16.40.65</pre><p>3. Then set the <strong>protected-mode</strong> to no to allow connections from the other instances on the cluster.</p><pre>protected-mode no</pre><p>4. The port parameter defines the port the Redis server will listen on for connections, the default is 6379. This is the data port for communicating with clients.</p><pre>port 6379</pre><p>5. The next set of parameters will enable the cluster mode and set some of its useful features. The cluster-enabled parameter, when set to <strong>yes</strong>, activates the cluster mode.</p><pre>cluster-enabled yes</pre><p>6. Next, the cluster-config-file parameter sets the name of a cluster node’s cluster configuration file (e.g nodes-6379.conf). The file is created in the working directory (default is /var/lib/redis defined using the dir parameter) and is not user editable.</p><pre>cluster-config-file nodes-6379.conf</pre><p>7. The next useful cluster option is cluster-node-timeout, it is used to set the maximum amount of time in milliseconds an instance can be unavailable for it to be considered in a failure state. A value of 15000 is equivalent to 15 seconds.</p><pre>cluster-node-timeout 15000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yXBOHGvtRh3_Y-O3.png" /></figure><p>8. We also need to enable Redis persistence on disk. We can use one of the persistence modes, that is the Append Only File (AOF): it logs (in the file appendonly.aof created under the working directory) every write operation successfully received by the server. The data will be played during the server startup to reconstruct the original dataset.</p><pre>appendonly yes</pre><p>After making all the changes, restart the Redis service on all the nodes to apply the recent changes.</p><pre>[root@redismaster ~]# systemctl restart redis</pre><p>9. At this point, every cluster node should now have an ID. You can check this in the logfile located at /var/log/redis/redis.log.</p><pre>[root@redismaster ~]# cat /var/log/redis/redis.log</pre><p>10. Next, open port <strong>6397</strong> and <strong>16379</strong> on all the instances. The later <strong>port</strong> is used for the cluster bus (a <strong>node-to-node</strong> communication channel using a binary protocol). This is a basic requirement for the Redis cluster TCP connections.</p><pre>[root@redismaster ~]# firewall-cmd --zone=public --permanent --add-port=6379/tcp<br>[root@redismaster ~]# firewall-cmd --zone=public --permanent --add-port=16379/tcp<br>[root@redismaster ~]# firewall-cmd --reload</pre><p>Step 3: Creating the Redis Cluster</p><p>To create the cluster, use the redis-cli command-line client as follows. The — cluster create enables cluster creation and — cluster-replicas 1 means create one replica per master.</p><p>For our setup which has 6 nodes, we will have 3 masters and 3 slaves.</p><p><strong>Note: </strong>The first 6 nodes will be considered masters (M) and the next three will be considered slaves (S). The first slave</p><pre>[root@redismaster ~]# redis-cli --cluster create 172.168.1.67:6379 172.166.1.66:6379 172.166.1.74:6379 172.168.1.40:6379 172.16.1.44:6379 172.168.1.45:6379 --cluster-replicas 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7YDp_RYIAw19_gFh.png" /></figure><p>Finally, your Redis Cluster is successfully created!!</p><p>Step 4: Verification</p><p>Login to cluster by using:</p><pre>[root@redismaster ~]# redis-cli -h &lt;master_ip&gt; -p 6379</pre><p>Authenticate with Cluster, if configured:</p><pre>[root@redismaster ~]# AUTH redis123</pre><p>Useful first commands after connecting:</p><pre>CLUSTER INFO</pre><pre>CLUSTER NODES</pre><pre>CLUSTER SHARDS</pre><p>Redis is much more than just an in-memory database. Its event-driven architecture, I/O multiplexing, optimized data structures, and efficient memory management enable it to deliver exceptional performance and scalability. By understanding how Redis processes requests internally and how to deploy a Redis CE cluster, engineers can better design, troubleshoot, and optimize Redis-based solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32007d0addab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High Availability-PCS Cluster Setup & Configuration]]></title>
            <link>https://medium.com/@kedarkanase12/high-availability-pcs-cluster-setup-configuration-03bdd65db254?source=rss-17272427ba0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/03bdd65db254</guid>
            <category><![CDATA[high-availability]]></category>
            <category><![CDATA[iscsi]]></category>
            <category><![CDATA[lvm]]></category>
            <category><![CDATA[virtual-ip-address]]></category>
            <dc:creator><![CDATA[Kedar kanase]]></dc:creator>
            <pubDate>Mon, 25 May 2026 11:46:33 GMT</pubDate>
            <atom:updated>2026-05-25T11:46:33.651Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will configure a high availability (HA) cluster using iSCSI service and targetcli for an e-commerce website. The setup involves two nodes and one shared storage. The goal is to ensure that if one node fails, the services continue to run seamlessly on the other node.</p><blockquote>High Level Design(HLD):</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_mekhPQq0ihI4eXR.png" /></figure><blockquote>Prerequisites:</blockquote><ul><li>Three RHEL virtual machines: Node1, Node2, and Storage.</li><li>Need high availability RHEL machines.</li><li>Basic understanding of Linux command line.</li><li>Administrative privileges on all machines.</li></ul><p><strong>Step 1: Set Static hostnames for all virtual machines</strong></p><p>For node1:</p><pre>hostnamectl set-hostname node1.localhost.com</pre><p>For node2:</p><pre>hostnamectl set-hostname node2.localhost.com</pre><p>For Storage:</p><pre>hostnamectl set-hostname storage.localhost.com</pre><p>Make entries in /etc/hosts file in all virtual machines.</p><pre>vim /etc/hosts</pre><pre>192.168.1.26 node1.localhost.com node1<br>192.168.1.27 node2.localhost.com node2<br>192.168.1.28 storage.localhost.com storage</pre><p>Note: Make sure that all machines can ping each other.</p><p><strong>Step 2: Configuring iSCSI Initiator on Node1 and Node2</strong></p><p>An iSCSI initiator is the client that connects to an iSCSI target (the storage server) over the network.</p><pre>sudo yum install iscsi-initiator-utils -y</pre><p>Check the status of iscsi:</p><pre>sudo systemctl status iscsid</pre><p>If Service is not running, then start and enable the service:</p><pre>sudo systemctl start iscsid<br>sudo systemctl enable --now iscsid</pre><p>Note: Make sure you need to configure these steps on both nodes(node1 &amp; node2)</p><p><strong>Step 3: Configure iSCSI Target</strong></p><p>targetcli is a command-line interface tool used to configure and manage storage targets on a Linux system</p><pre>sudo yum install targetcli -y</pre><p>Check the status of target service:</p><pre>systemctl status target</pre><p>Start the target service:</p><pre>systemctl start target</pre><p>Enable the target service:</p><pre>systemctl enable --now target</pre><p>Now, do:</p><pre>lsblk</pre><p>In my case i have and extra storage of 20G (sdb) which i used as an shared storage:</p><ul><li>Now, create physical volume of the sdb:</li></ul><pre>pvcreate /dev/sdb</pre><ul><li>Create volume group:</li></ul><pre>vgcreate vggroup /dev/sdb</pre><ul><li>Create logical volume</li></ul><pre>lvcreate -l 100%FREE -n lvgroup vggroup</pre><p>Verify the <strong>lv</strong> by using command:</p><pre>lvs</pre><p>or,</p><pre>lvdisplay</pre><p><strong>Step 4: Check the iqn number in both node1 &amp; node2</strong></p><p>The iSCSI Qualified Name (IQN) is a globally unique identifier used to identify iSCSI targets and initiators.</p><pre>cat /etc/iscsi/initiatorname.iscsi</pre><p>Note: We need iqn number of both the nodes to map with shared storage.</p><p><strong>Step 5: Configure iSCSI Target</strong></p><p>Run the following commands:</p><pre>sudo targetcli</pre><pre>cd /backstores/block</pre><pre>create shared_storage /dev/vggroup/lvgroup</pre><pre>cd /iscsi</pre><pre>create</pre><pre>cd /iscsi/iqn.2024-06.com.example:storage.target01/tpg1/acls</pre><p>Note: In your case the iqn number is different so just use tab.</p><pre>create &lt;node1 iqn number&gt;</pre><pre>create &lt;node2 iqn number&gt;</pre><pre>cd ..</pre><pre>cd luns</pre><pre>create /backstores/block/shared_storage</pre><pre>cd /</pre><pre>ls</pre><pre>saveconfig</pre><pre>exit</pre><p>Additionally, on storage node add port in firewall:</p><pre>firewall-cmd --permanent --add-port=3260/tcp</pre><p>Reload the firewall service:</p><pre>firewall-cmd --reload</pre><p><strong>Step 6: Discover and Log Into the iSCSI Target on Node1 and Node2</strong></p><p>Run this commands on both node1 &amp; node2 just cross check your iqn and ip of storage vm.</p><pre>sudo iscsiadm -m discovery -t st -p &lt;IP-of-SharedStorage&gt;</pre><pre>sudo iscsiadm -m node -T iqn.2024-06.com.example:storage.target01 -p &lt;IP-of-SharedStorage&gt; --login</pre><p>Restart the iscsi service</p><pre>systemctl restart iscsid</pre><p>Verify the Connection:</p><pre>lsblk</pre><p><strong>Step 7: Create Physical volume, volume group, logical volume in any one of the node</strong></p><p>I am creating in node1</p><ul><li>Creating physical volume</li></ul><pre>pvcreate /dev/sda</pre><ul><li>Creating volume group:</li></ul><pre>vgcreate vgapache /dev/sda</pre><ul><li>Creating logical volume:</li></ul><pre>lvcreate -l 100%FREE -N lvapache vgapache</pre><ul><li>Attach ext4 filesystem to logical volume:</li></ul><pre>mkfs.ext4 /dev/vgapache/lvapache</pre><p>Now, must need to show this logical volume in Node2 so, go in node2 and run the following commads:</p><pre>pvscan</pre><pre>vgscan</pre><pre>lvscan</pre><p>Note: Default logical volume is inactive, to active run the command:</p><pre>vgchange -ay vgapache</pre><p>Make sure the lv is in active state.</p><pre>lvscan</pre><p><strong>Step 8: Installing the required of High Availability in both Nodes</strong></p><pre>sudo dnf install pcs fence-agents-all pcp-zeroconf</pre><p>This command will install all required packages.</p><p>Note:</p><p>By default high-availability repo is disable, you need to enable this repo use this package (this command is for redhat 9):</p><pre>sudo subscription-manager repos --enable=rhel-9-for-x86_64-highavailability-rpms</pre><p>Add high-availability service in firewall service:</p><pre>firewall-cmd --permanent --add-service=high-availability</pre><p>Reload the firewall service:</p><pre>firewall-cmd --reload</pre><p>Start and Enable PCS Service</p><pre>sudo systemctl start pcsd<br>sudo systemctl enable --now pcsd<br>sudo systemctl status pcsd</pre><p><strong>Step 9: Create and configure cluster</strong></p><ul><li>Set a Password for the PCS User on both the nodes( node 1 &amp; node 2 )</li></ul><pre>sudo passwd hacluster</pre><ul><li>Authenticate the Nodes ( any one node )</li></ul><pre>sudo pcs cluster auth node1.localhost.com node2.loacalhost.com</pre><ul><li>Create and Start the Cluster</li></ul><pre>sudo pcs cluster setup kedar --start node1.localhost.com node2.loacalhost.com</pre><ul><li>Enable the Cluster Services</li></ul><pre>sudo pcs cluster enable --all</pre><ul><li>Verify Cluster Status</li></ul><pre>sudo pcs cluster status</pre><ul><li>Vertify pcs status</li></ul><pre>sudo pcs status</pre><p>Note: There will be showing an warning of &quot;no stonith-device and stonith-enabled is not fasle&quot;, to solve this issue in <strong>vm </strong>run following command:</p><pre>pcs property set stoning-enabled=false</pre><p>To these step your cluster configured successfully, if any errors, feel free to reach out in comment section!!</p><p><strong>Step 10: Creating resource for website:</strong></p><p>Initially, create folder to store the website content on both nodes</p><pre>mkdir /mnt/shared</pre><p>Mount this file to logical volume</p><pre>mount /dev/vgapache/lvapache /mnt/shared</pre><p>Move the website content in the shared storage.</p><pre>sudo mv kedar.html /mnt/shared/</pre><p>Add the below content in /etc/httpd/conf/httpd.conf in both the nodes</p><pre>DocumentRoot &quot;/mnt/shared&quot;<br>&lt;Directory &quot;/mnt/shared&quot;&gt;<br>    Options FollowSymLinks<br>    AllowOverride None<br>    Require all granted<br>&lt;/Directory&gt;</pre><p>Save the configuration file and restart Apache:</p><pre>sudo systemctl restart httpd</pre><p>Try Access Content:</p><p>Once Apache is configured, you can access the content of &quot;kedar.html&quot; by entering the IP address or hostname of Node 1 or Node 2 in a web browser:</p><pre>http://node1_ip_or_hostname/kedar.html<br>http://node2_ip_or_hostname/kedar.html</pre><p>Note: If the content is not accessible for any one of the node check the selinux type it should be (httpd_sys_content_t), permission (755), ownership should be (apache:apache) of /mnt/shared or restart the httpd service.</p><p>Create a PCS resource for the virtual IP (192.198.1.29) and associate it with the Apache service. You can use the following commands:</p><pre>sudo pcs resource create virtual_ip ocf:heartbeat:IPaddr2 ip=192.198.1.29 cidr_netmask=24 op monitor interval=30s</pre><pre>sudo pcs resource create apache systemd:httpd op monitor interval=30s</pre><pre>sudo pcs resource group add apache-group apache virtual_ip</pre><pre>sudo pcs resource enable apache-group</pre><p><strong>Step 11: </strong>Access Content via Virtual IP<strong>:</strong></p><p>Once the resources are active, you can access the content of /mnt/shared/kedar.html using the virtual IP address in a web browser. Open a web browser and enter the following URL:</p><pre>http://192.188.1.29/kedar.html</pre><p>Now, PCS cluster (Pacemaker/Corosync) will manage failover between nodes. If one node fails, the other node will take over and continue serving the content through the virtual IP. Users accessing <a href="http://192.168.67.200/kedar.html">http://192.198.1.29/kedar.html</a> will still see the content without interruption.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03bdd65db254" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UNIQUE ID GENERATOR IN DISTRIBUTED SYSTEMS]]></title>
            <link>https://medium.com/@kedarkanase12/unique-id-generator-in-distributed-systems-3b36d9f6d990?source=rss-17272427ba0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b36d9f6d990</guid>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[id-generator]]></category>
            <category><![CDATA[unique-id-generator]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Kedar kanase]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 11:54:03 GMT</pubDate>
            <atom:updated>2025-02-14T11:55:52.741Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>SYSTEM DESIGN</strong></p><p>In distributed systems, generating unique identifiers (IDs) efficiently and reliably is crucial for tasks such as tracking orders, managing sessions, and referencing data entities. Several strategies have been developed to achieve this, each with its own advantages and trade-offs.</p><p>Your first thought might be to use a primary key with the <em>auto_increment </em>attribute in a traditional database. However, <em>auto_increment </em>does not work in a distributed environment because a single database server is not large enough and generating unique IDs across multiple databases with minimal delay is challenging.</p><p>Lets explore the different approaches used for generating the Unique ID’s</p><p><strong>Various Approaches &amp; Deep Dive</strong></p><ul><li>Multi-Master Replication</li><li>UUID (Universally Unique Identifier)</li><li>MongoDB ObjectID</li><li>Ticket Server Approach (Flickr)</li><li>Twitter Snowflake</li></ul><blockquote><strong>Multi-Master Replication</strong></blockquote><p>Traditional relational databases offer auto-incrementing primary keys, which ensure unique IDs by incrementing a counter for each new record. In distributed systems, a multi-master replication approach can be used, where each database server is configured to increment IDs by a step size equal to the number of servers. i.e. Instead of increasing the next ID by 1, we increase it by <em>k, </em>where <em>k </em>is the number of database servers in use.</p><p>As shown in below figure, the first approach is multi-master replication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*oUHU3t1KftMqbuVQemClsA.png" /><figcaption>no. of servers = 3</figcaption></figure><p><em>Pros:</em></p><ul><li>Easy to implement using existing database features.</li><li>Generated IDs are sequential within each server.</li></ul><p><em>Cons:</em></p><ul><li>Managing unique IDs across multiple servers can be challenging.</li><li>IDs may not be globally ordered by time across all servers.</li><li>Adding or removing servers complicates ID generation.</li></ul><p>This approach is suitable for systems with a limited number of nodes and lower scalability requirements</p><blockquote><strong>UUID (Universally Unique Identifier)</strong></blockquote><p>A <strong>Universally Unique Identifier (UUID)</strong> is a <strong>128-bit identifier</strong> designed to be globally unique across systems and time. UUIDs are <strong>standardized by RFC 4122</strong> and widely used in databases (PostgreSQL, MySQL), cloud services, and micro-services.</p><p>UUID Structure (128-bit / 16 bytes)</p><pre>xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx</pre><p>Where:</p><ul><li>M = Version (1, 2, 3, 4, or 5)</li><li>N = Variant (indicates encoding type)</li><li>1 hexadecimal digit (0–9, A-F) = 4 bits (half a byte)</li><li>2 hexadecimal digits = 1 byte (8 bits)</li></ul><p>Example UUID:</p><pre>550e8400-e29b-41d4-a716–446655440000</pre><p>Each section has a specific role:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41X7_vW55WIRukKeq9bnGw.png" /></figure><p>UUIDs can be generated using different methods based on <strong>versions</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFITWYiHTqvFmcVXs5wjjg.png" /></figure><p>UUIDs have <strong>four possible variants</strong>, but <strong>only two are commonly used</strong> today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2MYvNSLbaiq4JgrIn0LlQ.png" /></figure><p>RFC 4122 UUIDs (Variant 1) are the industry standard and the most commonly used.<br>Microsoft GUIDs (Variant 2) are used mainly in Windows applications.</p><p>UUIDs can be generated independently without coordination between servers. In this design, each web server contains an ID generator, and a web server is responsible for generating IDs independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*k0oPAjH9qTmrOU_6HqEL2w.png" /></figure><p>Lets discuss about Pros &amp; Cons of UUID</p><p><em>Pros:</em></p><ul><li>Each node can generate IDs independently, eliminating the need for coordination.</li><li>The vast address space makes collisions highly unlikely.</li><li>Most programming languages offer built-in libraries for UUID generation.</li><li>The system is easy to scale because each web server is responsible for generating IDs they consume. ID generator can easily scale with web servers.</li></ul><p><em>Cons:</em></p><ul><li>At 128 bits, UUIDs can be storage-intensive.</li><li>UUIDs are not sequential, which can lead to inefficiencies in database indexing and retrieval.</li><li>IDs could be non-numeric.</li></ul><p>UUIDs are ideal when you need globally unique IDs without central coordination and when the order of IDs is not important.</p><blockquote><strong>MongoDB ObjectID</strong></blockquote><p>MongoDB uses <strong>ObjectID</strong> as the default primary key (_id) for documents in a collection. It’s a <strong>12-byte unique identifier </strong>designed for efficiency, uniqueness, and scalability in a distributed environment.</p><p>ObjectID is a <strong>12-byte (96-bit) hexadecimal number</strong>, structured as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SwjrzEPjMl4xU3cbvrpxg.png" /></figure><p>Example ObjectID:</p><pre>ObjectID(&quot;6518aafbb6234c91b2e8a3f7&quot;)</pre><p>MongoDB generates ObjectIDs using a combination of <strong>time, machine details, process ID, and counter</strong>, ensuring:</p><ol><li><strong>Globally unique</strong> across distributed nodes.</li><li><strong>Monotonic</strong> within a single instance (helps with sorting).</li><li><strong>Efficient</strong> (only 12 bytes, smaller than UUIDs).</li></ol><p>Since the timestamp is <strong>first</strong>, sorting by ObjectID <strong>preserves insertion order</strong> (newer documents have higher IDs).</p><p><strong>Breakdown of Each Component</strong></p><p>4-Byte Timestamp</p><ul><li>Stores <strong>seconds</strong> since Unix epoch (time_t in C).</li><li>Ensures IDs are <em>roughly ordered chronologically</em> in distributed environments.</li><li>Limited to 136 years (~1901 to 2038), but adequate for most applications.</li></ul><p>5-Byte Machine Identifier</p><ul><li>Derived from the <strong>MAC address</strong> of the host.</li><li>Prevents ID collisions between multiple nodes in a cluster.</li><li>If the MAC address isn’t available, MongoDB uses a <strong>random hash</strong>.</li></ul><p>2-Byte Process Identifier</p><ul><li>Stores the <strong>PID</strong> of the MongoDB instance generating the ID.</li><li>Ensures that different processes on the same machine don’t generate duplicate ObjectIDs.</li></ul><p>3-Byte Counter</p><ul><li>A simple <strong>monotonic counter</strong> that starts from a random value and increments.</li><li>Resets when the process restarts.</li><li>Ensures multiple ObjectIDs generated in the <strong>same second</strong> are unique</li></ul><p><em>Pros:</em></p><ul><li>ObjectIDs are <strong>smaller than UUIDs (16 bytes)</strong>, reducing <strong>index size and storage overhead</strong>.</li><li>Faster <strong>sorting &amp; indexing</strong> due to <strong>timestamp-based ordering</strong>.</li><li>No need for a central authority (unlike ticket-server-based ID generation).</li><li>Each MongoDB instance can independently generate unique ObjectIDs.</li><li>The timestamp makes IDs <strong>insertion-ordered</strong>, improving <strong>range queries</strong> and <strong>index locality</strong>.</li></ul><p><em>Cons:</em></p><ul><li>ObjectIDs are roughly ordered <strong>within the same second</strong>, but <strong>not strictly sequential</strong>.</li><li>If multiple nodes generate IDs simultaneously, ordering may <strong>not be perfectly preserved</strong>.</li><li>Since the first 4 bytes store a timestamp, it’s possible to <strong>extract the document’s creation time</strong>, which might expose metadata in some use cases.</li><li>The 4-byte timestamp may cause issues <strong>post-2038</strong> (similar to the Year 2038 problem in C’s time_t).</li></ul><p>MongoDB ObjectID is a <strong>compact, globally unique, time-ordered identifier</strong> ideal for distributed databases. While it offers efficiency and sorting benefits, it <strong>isn’t perfectly sequential</strong> and can be <strong>reverse-engineered for timestamps</strong>.</p><blockquote><strong>Ticket Server Approach (Flickr)</strong></blockquote><p>Ticket servers are another interesting way to generate unique IDs. Flicker developed ticket servers to generate distributed primary keys. It is worth mentioning how the system works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkNsf3h4jhfCAEGukgwaAw.png" /></figure><p>A Flickr ticket server is a dedicated database server, with a single database on it, and in that database there are tables like Tickets32 for 32-bit IDs, and Tickets64 for 64-bit IDs.</p><p>The Tickets64 schema looks like:</p><pre>CREATE TABLE `Tickets64` (<br>  `id` bigint(20) unsigned NOT NULL auto_increment,<br>  `stub` char(1) NOT NULL default &#39;&#39;,<br>  PRIMARY KEY  (`id`),<br>  UNIQUE KEY `stub` (`stub`)<br>) ENGINE=InnoDB</pre><p>SELECT * from Tickets64 returns a single row that looks something like:</p><pre>+-------------------+------+<br>| id                | stub |<br>+-------------------+------+<br>| 72157623227190423 |    a |<br>+-------------------+------+</pre><p>When I need a new globally unique 64-bit ID I issue the following SQL:</p><pre>REPLACE INTO Tickets64 (stub) VALUES (&#39;a&#39;);<br>SELECT LAST_INSERT_ID();</pre><p>Pros:</p><p>• Numeric IDs.<br>• It is easy to implement, and it works for small to medium-scale applications.</p><p>Cons:</p><p>• Single point of failure. Single ticket server means if the ticket server goes down, all systems that depend on it will face issues. To avoid a single point of failure, we can set up multiple ticket servers. However, this will introduce new challenges such as data synchronization.</p><blockquote><strong>Twitter Snowflake</strong></blockquote><p>The approaches we discussed give us insights into different ID generation methods, but none fully meet our needs. That’s why we need a different approach. Twitter’s <strong>Snowflake</strong> ID system is a great example that fits our requirements.</p><p>Instead of creating an ID in one step, we <strong>break it into smaller parts</strong>. This makes the process more efficient and scalable. Below Figure illustrates how a <strong>64-bit ID</strong> is structured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F844vBItEgZPA8OcTatYjA.png" /></figure><p>Each section is explained below.</p><p>• Sign bit: <strong>1 bit</strong>. It will always be 0. This is reserved for future uses. It can potentially be used to distinguish between signed and unsigned numbers.</p><p>• Timestamp: <strong>41 bits</strong>. Milliseconds since the epoch or custom epoch. We use Twitter snowflake default epoch 1288834974657, equivalent to Nov 04, 2010, 01:42:54 UTC.</p><p>• Datacenter ID: <strong>5 bits</strong>, which gives us <em>2 ^ 5 = 32 </em>datacenters.<br>• Machine ID: 5 bits, which gives us <em>2 ^ 5 = 32 </em>machines per datacenter.</p><p>• Sequence number: <strong>12 bits</strong>. For every ID generated on that machine/process, the sequence number is incremented by 1. The number is reset to 0 every millisecond.</p><p><strong>Note: </strong>Datacenter and machine IDs are assigned when the system starts and typically remain unchanged while it is running. Any modifications to these IDs require careful consideration, as unintended changes can result in ID conflicts. Meanwhile, timestamps and sequence numbers are generated dynamically while the ID generator is in operation.</p><p><strong>Timestamp</strong></p><p>The most important 41 bits make up the timestamp section. As timestamps grow with time, IDs are sortable by time. Below Figure shows an example of how binary representation is converted to UTC. You can also convert UTC back to binary representation using a similar method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUk8JFTgeQySufqsHR0VuQ.png" /></figure><p>The maximum timestamp that can be represented in 41 bits is<br><em>2 ^ 41–1 = 2199023255551 </em>milliseconds (ms), which gives us: ~ 69 years =</p><p><em>2199023255551 ms / 1000 seconds / 365 days / 24 hours/ 3600 seconds</em>. This means the ID generator will work for 69 years and having a custom epoch time close to today’s date delays the overflow time. After 69 years, we will need a new epoch time or adopt other techniques to migrate IDs.</p><p><strong>Sequence number</strong></p><p>Sequence number is 12 bits, which give us 2 ^ 12 = 4096 combinations. This field is 0 unless more than one ID is generated in a millisecond on the same server. In theory, a machine can support a maximum of 4096 new IDs per millisecond.</p><p><strong>References:</strong></p><ul><li><a href="https://www.uuidtools.com/decode#">UUID Decoder</a></li><li><a href="https://code.flickr.net/2010/02/08/ticket-servers-distributed-unique-primary-keys-on-the-cheap/">Ticket Servers: Distributed Unique Primary Keys on the Cheap</a></li><li><a href="https://www.mongodb.com/docs/manual/reference/method/ObjectId/">ObjectId()</a></li><li><a href="https://en.wikipedia.org/wiki/Snowflake_ID">Snowflake ID - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b36d9f6d990" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>