<?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 Jitender Kumar on Medium]]></title>
        <description><![CDATA[Stories by Jitender Kumar on Medium]]></description>
        <link>https://medium.com/@jitenderkmr?source=rss-8baee8074916------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eaKrJxuEhkiw05UdVjBF2A.jpeg</url>
            <title>Stories by Jitender Kumar on Medium</title>
            <link>https://medium.com/@jitenderkmr?source=rss-8baee8074916------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:37:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jitenderkmr/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[Understanding the ZAB Protocol: The Foundation of Apache Zookeeper]]></title>
            <link>https://medium.com/@jitenderkmr/understanding-the-zab-protocol-the-foundation-of-apache-zookeeper-d335dbae3ec9?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/d335dbae3ec9</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 10:07:17 GMT</pubDate>
            <atom:updated>2024-12-15T10:07:17.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*NJSSTMtV_c5-3FPCDESuhA.jpeg" /></figure><p>The Zookeeper Atomic Broadcast (ZAB) protocol is a cornerstone of distributed systems, powering the consistency and fault tolerance of Apache Zookeeper. Developed to support highly reliable distributed coordination, ZAB ensures ordered delivery of messages and state synchronization across servers. This blog dives into the essence of ZAB, its two phases, and how it achieves consistency and high availability in dynamic distributed environments.</p><h3>What is the ZAB Protocol?</h3><p>ZAB is a totally ordered broadcast protocol designed for systems where maintaining a consistent state across distributed nodes is critical. While similar to Paxos in many ways, ZAB is uniquely optimized for Zookeeper, emphasizing sequential consistency and high throughput for read-dominant workloads.</p><p>Key Goals:</p><ol><li><strong>Total Order Broadcast</strong>: Ensures all nodes process transactions in the same order.</li><li><strong>Fault Tolerance</strong>: Maintains operation despite node failures.</li><li><strong>High Availability</strong>: Quickly elects a new leader during failures to minimize downtime.</li><li><strong>State Synchronization</strong>: Guarantees all servers converge on the same state during recovery.</li></ol><h3>How ZAB Works</h3><p>ZAB operates in two key phases: <strong>leader election and synchronization</strong> (Phase 1) and <strong>atomic broadcast</strong> (Phase 2).</p><h4>Phase 1: Leader Election and Synchronization</h4><p>The system requires one leader at any given time to coordinate state updates. If the current leader fails, ZAB triggers a leader election process.</p><ol><li><strong>Leader Election</strong>:</li></ol><ul><li>Nodes propose themselves as candidates, including their current state (epoch and log).</li><li>The node with the most up-to-date state (highest epoch) becomes the leader.</li></ul><p><strong>2. Synchronization</strong>:</p><ul><li>The leader synchronizes followers by ensuring they apply any missing transactions from its log.</li><li>Only after synchronization do followers start processing new transactions, ensuring all nodes are aligned.</li></ul><h4>Phase 2: Atomic Broadcast</h4><p>Once synchronized, the system enters the broadcast phase to handle client requests.</p><ol><li><strong>Proposal</strong>:</li></ol><ul><li>The leader proposes a transaction and assigns it a globally unique ID (ZXID).</li><li>It sends the proposal to all followers.</li></ul><p><strong>2. Acknowledgment</strong>:</p><ul><li>Followers persist the proposal and send an acknowledgment (ACK) back to the leader.</li></ul><p><strong>3. Commit</strong>:</p><ul><li>Upon receiving ACKs from a quorum of followers, the leader broadcasts a commit message.</li><li>Transactions are applied to the state machine in the same order across all nodes, ensuring consistency.</li></ul><h3>Key Features of ZAB</h3><ol><li><strong>Total Order of Transactions</strong>: ZAB enforces a strict global ordering of transactions using ZXIDs, ensuring consistency even during leader transitions.</li><li><strong>High Availability Through Quorums</strong>: ZAB requires a majority quorum for operation. This overlap guarantees continuity even during failures, preventing split-brain scenarios.</li><li><strong>Durability</strong>: Transactions are written to persistent logs, ensuring recovery after crashes.</li><li><strong>Fast Recovery</strong>: ZAB prioritizes quick leader election and synchronization to minimize downtime.</li><li><strong>Support for Observers</strong>: Observers are non-voting nodes that can read the state without participating in quorum, enhancing scalability for read-heavy workloads.</li></ol><h3>Why ZAB is Perfect for Zookeeper</h3><p>Zookeeper uses ZAB to achieve strong consistency and reliability in its distributed coordination tasks. Some specific benefits include:</p><ul><li><strong>Sequential Consistency</strong>: All clients see the same view of the system, even during failures.</li><li><strong>Leader-Driven Architecture</strong>: A single leader ensures simpler coordination and faster write operations.</li><li><strong>Efficient Reads</strong>: Followers and observers handle read operations, reducing the load on the leader.</li></ul><h3>ZAB in Action: Handling Failures</h3><p>Let’s look at how ZAB manages node failures:</p><ol><li><strong>Leader Crash</strong>:</li></ol><ul><li>The system halts new transactions.</li><li>A new leader is elected, and followers synchronize their state.</li><li>Once aligned, the system resumes normal operations.</li></ul><p><strong>2. Follower Crash</strong>:</p><ul><li>The quorum continues to function as long as a majority is available.</li><li>The crashed follower can rejoin after synchronization with the leader.</li></ul><h3>Challenges and Limitations</h3><ol><li><strong>Dependency on Quorum</strong>:</li></ol><ul><li>A majority of nodes must be operational, limiting ZAB’s tolerance for large-scale failures.</li></ul><p><strong>2. Write Bottlenecks</strong>:</p><ul><li>The leader handles all writes, which can become a bottleneck in write-heavy workloads.</li></ul><p><strong>3. Complex Failure Scenarios</strong>:</p><ul><li>Simultaneous crashes and network partitions can challenge the recovery process.</li></ul><h3>Go-Based Implementation of the ZAB</h3><p>The nodes in this system can have roles: Leader, Follower, or Observer. Additionally, message types such as Transaction, Sync, and Ack are used for communication.</p><pre>type NodeRole string<br>type MessageType string<br><br>const (<br>    Leader   NodeRole = &quot;LEADER&quot;<br>    Follower NodeRole = &quot;FOLLOWER&quot;<br>    Observer NodeRole = &quot;OBSERVER&quot;<br>    Transaction MessageType = &quot;TRANSACTION&quot;<br>    Sync        MessageType = &quot;SYNC&quot;<br>    Ack         MessageType = &quot;ACK&quot;<br>)</pre><h4>2. Proposal and Message Definitions</h4><ul><li><strong>Proposal</strong>: Represents a transaction with an epoch, Zxid (ZooKeeper Transaction ID), and a payload (Tx).</li><li><strong>Message</strong>: Encapsulates communication details between nodes, including the sender, message type, and payload.</li></ul><pre>type Proposal struct {<br>    Epoch int64<br>    Zxid  int64<br>    Tx    string<br>}<br><br>type Message struct {<br>    FromNodeID       int<br>    Type             MessageType<br>    Payload          string<br>    PayloadZxid      int64<br>    PayloadCommitted int64<br>}</pre><h4>3. Node State and Behavior</h4><p>Each node maintains:</p><ul><li><strong>State</strong>: Tracks the latest transaction (Zxid), committed transaction, and a log of entries.</li><li><strong>IdempotentTracker</strong>: Prevents duplicate processing of the same transaction.</li><li><strong>Role-based Actions</strong>: Handles messages differently depending on the node’s role.</li></ul><p><strong>Message Processing</strong>:</p><ul><li>Transaction: Logs the transaction if valid.</li><li>Sync: Updates the node&#39;s state to match the leader&#39;s.</li><li>Ack: Confirms receipt of a message.</li></ul><pre>func (n *Node) ReceiveMessage(msg Message) {<br>    n.mu.Lock()<br>    defer n.mu.Unlock()<br>    switch msg.Type {<br>      case Transaction:<br>        proposal := ParseProposal(msg.Payload)<br>        if proposal.Zxid &lt;= n.State.Committed {<br>            log.Printf(&quot;Node %d: Ignoring duplicate or outdated proposal %s&quot;, n.ID, msg.Payload)<br>            return<br>        }<br>        n.State.LogEntries = append(n.State.LogEntries, msg.Payload)<br>        n.State.Zxid = proposal.Zxid<br>        log.Printf(&quot;Node %d received transaction: %s&quot;, n.ID, proposal.Tx)<br>      case Sync:<br>        n.State.Zxid = msg.PayloadZxid<br>        n.State.Committed = msg.PayloadCommitted<br>        log.Printf(&quot;Node %d synchronized with leader&quot;, n.ID)<br>      case Ack:<br>        log.Printf(&quot;Node %d acknowledged message&quot;, n.ID)<br>    }<br>}</pre><h4>4. Leader Election</h4><p>The leader is chosen based on the highest epoch among healthy nodes. If no leader is found, the election process retries.</p><pre>func ElectLeader(nodes []*Node, net *Network) *Node {<br>    var leader *Node<br>    highestEpoch := int64(0)<br>    for _, node := range nodes {<br>        if node.CheckHealth() &amp;&amp; node.CurrentEpoch &gt; highestEpoch {<br>            highestEpoch = node.CurrentEpoch<br>            leader = node<br>        }<br>    }<br>    if leader == nil {<br>        log.Println(&quot;No healthy leader found, retrying...&quot;)<br>        time.Sleep(time.Second)<br>        return ElectLeader(nodes, net)<br>    }<br>    leader.mu.Lock()<br>    leader.Role = Leader<br>    leader.CurrentEpoch++<br>    leader.mu.Unlock()<br>    for _, node := range nodes {<br>        if node.ID != leader.ID {<br>            node.Role = Follower<br>            node.LeaderID = leader.ID<br>        }<br>    }<br>    log.Printf(&quot;Leader elected: Node %d (Epoch: %d)&quot;, leader.ID, highestEpoch)<br>    leader.Synchronize(nodes)<br>    return leader<br>}</pre><h4>5. Synchronization</h4><p>The leader synchronizes followers to ensure they have the same committed state and log entries.</p><pre>func (n *Node) Synchronize(followers []*Node) {<br>    if n.Role != Leader {<br>        log.Println(&quot;Only the leader can initiate synchronization&quot;)<br>        return<br>    }<br>    for _, follower := range followers {<br>        follower.mu.Lock()<br>        missingEntries := n.State.LogEntries[follower.State.Committed:]<br>        follower.State.LogEntries = append(follower.State.LogEntries, missingEntries...)<br>        follower.State.Zxid = n.State.Zxid<br>        follower.State.Committed = n.State.Committed<br>        follower.mu.Unlock()<br>        log.Printf(&quot;Synchronized Node %d with Leader (Committed: %d)&quot;, follower.ID, n.State.Committed)<br>    }<br>}</pre><h4>6. Broadcasting Transactions</h4><p>The leader broadcasts transactions to followers. Once a quorum acknowledges the transaction, it is marked as committed.</p><pre>func (n *Node) BroadcastTransaction(tx string, followers []*Node, net *Network) {<br>    if n.Role != Leader {<br>        log.Println(&quot;Only the leader can broadcast transactions&quot;)<br>        return<br>    }<br>    proposal := Proposal{<br>        Epoch: n.CurrentEpoch,<br>        Zxid:  n.State.Zxid + 1,<br>        Tx:    tx,<br>    }<br>    n.mu.Lock()<br>    n.State.Zxid = proposal.Zxid<br>    n.State.LogEntries = append(n.State.LogEntries, proposal.String())<br>    n.mu.Unlock()<br>    acks := 0<br>    for _, follower := range followers {<br>        success := net.SendReliableMessage(follower.ID, Message{<br>            FromNodeID: n.ID,<br>            Type:       Transaction,<br>            Payload:    proposal.String(),<br>        })<br>        if success {<br>            acks++<br>            log.Printf(&quot;Transaction %s sent to Node %d&quot;, tx, follower.ID)<br>        }<br>    }<br>    if acks &gt;= (len(followers)/2)+1 {<br>        n.mu.Lock()<br>        n.State.Committed = proposal.Zxid<br>        n.mu.Unlock()<br>        log.Printf(&quot;Transaction %s committed by Leader&quot;, tx)<br>    } else {<br>        log.Println(&quot;Quorum not reached. Transaction aborted&quot;)<br>    }<br>}</pre><h4>7. Network Simulation</h4><p>The Network class simulates communication between nodes. Messages are reliably sent to reachable nodes.</p><pre>type Network struct {<br>    mu        sync.Mutex<br>    connected map[int]*Node<br>}<br><br>func (net *Network) SendReliableMessage(toNodeID int, msg Message) bool {<br>    net.mu.Lock()<br>    defer net.mu.Unlock()<br>    if node, ok := net.connected[toNodeID]; ok {<br>        node.ReceiveMessage(msg)<br>        return true<br>    }<br>    log.Printf(&quot;Node %d not reachable&quot;, toNodeID)<br>    return false<br>}</pre><h4>8. Main Function</h4><p>The main function sets up the network, initializes nodes, elects a leader, and tests the protocol with:</p><ul><li>Leader election</li><li>Synchronization</li><li>Transaction broadcasting</li><li>Simulated node failures.</li></ul><pre>func main() {<br> rand.Seed(time.Now().UnixNano())<br> net := NewNetwork()<br><br> // Initialize nodes and observers<br> nodes := []*Node{<br>  {ID: 1, CurrentEpoch: 1, State: &amp;NodeState{LogEntries: []string{}}},<br>  {ID: 2, CurrentEpoch: 2, State: &amp;NodeState{LogEntries: []string{}}},<br>  {ID: 3, CurrentEpoch: 1, State: &amp;NodeState{LogEntries: []string{}}},<br> }<br> observers := []*Node{<br>  {ID: 6, Role: Observer, State: &amp;NodeState{}},<br> }<br><br> // Register nodes and observers<br> for _, node := range nodes {<br>  net.RegisterNode(node)<br> }<br> for _, observer := range observers {<br>  net.RegisterNode(observer)<br> }<br><br> // Leader election<br> leader := ElectLeader(nodes, net)<br> var followers []*Node<br> for _, node := range nodes {<br>  if node.Role == Follower {<br>   followers = append(followers, node)<br>  }<br> }<br><br> // Synchronize followers and validate<br> leader.Synchronize(followers)<br> leader.BroadcastTransaction(&quot;TX1&quot;, followers, net)<br> leader.BroadcastTransaction(&quot;TX2&quot;, followers, net)<br><br> // Simulate leader failure<br> log.Println(&quot;Simulating leader failure...&quot;)<br> leader.Role = Follower<br> log.Println(&quot;Checking debug logs during re-election...&quot;)<br> leader = ElectLeader(nodes, net)<br> log.Printf(&quot;Debug: New leader elected with ID %d&quot;, leader.ID)<br> // Add transactions and test log truncation<br> for i := 1; i &lt;= 10; i++ {<br>  leader.BroadcastTransaction(fmt.Sprintf(&quot;TX%d&quot;, i), followers, net)<br> }<br> leader.mu.Lock()<br> if len(leader.State.LogEntries) &gt; 5 {<br>  leader.State.LogEntries = leader.State.LogEntries[len(leader.State.LogEntries)-5:]<br> }<br> leader.mu.Unlock()<br> log.Printf(&quot;Logs after truncation: %v&quot;, leader.State.LogEntries)<br><br> // Simulate follower failure<br> log.Println(&quot;Simulating follower failure...&quot;)<br> failedFollower := followers[0]<br> net.mu.Lock()<br> delete(net.connected, failedFollower.ID)<br> net.mu.Unlock()<br><br> for _, follower := range followers {<br>  if _, ok := net.connected[follower.ID]; ok {<br>   log.Printf(&quot;Follower %d is still active&quot;, follower.ID)<br>  } else {<br>   log.Printf(&quot;Follower %d is down&quot;, follower.ID)<br>  }<br> }<br><br> leader.Synchronize(followers)<br> leader.mu.Lock()<br> log.Printf(&quot;Debug: Leader committed Zxid: %d&quot;, leader.State.Committed)<br> leader.mu.Unlock()<br><br> log.Println(&quot;Test scenarios completed&quot;)<br> <br>}</pre><h3>Output</h3><pre>2024/12/15 12:39:03 Node 1 registered in the network<br>2024/12/15 12:39:03 Node 2 registered in the network<br>2024/12/15 12:39:03 Node 3 registered in the network<br>2024/12/15 12:39:03 Node 6 registered in the network<br>2024/12/15 12:39:03 Leader elected: Node 2 (Epoch: 2)<br>2024/12/15 12:39:03 Leader has no log entries to synchronize<br>2024/12/15 12:39:03 Leader has no log entries to synchronize<br>2024/12/15 12:39:03 Node 1 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX1 committed by Leader<br>2024/12/15 12:39:03 Node 1 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX2 committed by Leader<br>2024/12/15 12:39:03 Simulating leader failure...<br>2024/12/15 12:39:03 Checking debug logs during re-election...<br>2024/12/15 12:39:03 Leader elected: Node 1 (Epoch: 1)<br>2024/12/15 12:39:03 Synchronized Node 1 with Leader (Committed: 0)<br>2024/12/15 12:39:03 Synchronized Node 2 with Leader (Committed: 0)<br>2024/12/15 12:39:03 Synchronized Node 3 with Leader (Committed: 0)<br>2024/12/15 12:39:03 Debug: New leader elected with ID 1<br>2024/12/15 12:39:03 Node 1 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX1 committed by Leader<br>2024/12/15 12:39:03 Node 1 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX2 committed by Leader</pre><h4>1. Node Registration</h4><pre>2024/12/15 12:39:03 Node 1 registered in the network<br>2024/12/15 12:39:03 Node 2 registered in the network<br>2024/12/15 12:39:03 Node 3 registered in the network<br>2024/12/15 12:39:03 Node 6 registered in the network</pre><ul><li>Nodes <strong>1, 2, 3</strong> are registered as participants in the distributed system.</li><li>Node <strong>6</strong> is an <strong>observer</strong> node (role is Observer), which does not participate in leader election or transaction processing.</li></ul><h4>2. Leader Election</h4><pre>2024/12/15 12:39:03 Leader elected: Node 2 (Epoch: 2)</pre><ul><li>A leader election is conducted among nodes <strong>1, 2, and 3</strong>.</li><li><strong>Node 2</strong> is elected as the leader because it has the highest CurrentEpoch value (<strong>2</strong>).</li></ul><h4>3. Synchronization (Leader-to-Follower)</h4><pre>2024/12/15 12:39:03 Leader has no log entries to synchronize<br>2024/12/15 12:39:03 Leader has no log entries to synchronize</pre><ul><li>The leader (<strong>Node 2</strong>) attempts to synchronize its state with the followers (<strong>Nodes 1 and 3</strong>).</li><li>Since the leader has no log entries yet (LogEntries is empty), no synchronization occurs.</li></ul><h4>4. Broadcasting Transactions</h4><p><strong>Transaction TX1</strong></p><pre>2024/12/15 12:39:03 Node 1 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX1 committed by Leader</pre><ul><li>The leader (<strong>Node 2</strong>) broadcasts <strong>Transaction TX1</strong> to the followers (<strong>Nodes 1 and 3</strong>).</li><li>Each follower receives the transaction and appends it to its local log (LogEntries).</li><li>Since a quorum (majority) of followers acknowledges the transaction, it is <strong>committed by the leader</strong>.</li></ul><p><strong>Transaction TX2</strong></p><pre>2024/12/15 12:39:03 Node 1 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX2 committed by Leader</pre><ul><li>The process repeats for <strong>Transaction TX2</strong>, with similar steps as for <strong>TX1</strong>.</li></ul><h4>5. Leader Failure Simulation</h4><pre>2024/12/15 12:39:03 Simulating leader failure...<br>2024/12/15 12:39:03 Checking debug logs during re-election...</pre><ul><li>A <strong>leader failure</strong> is simulated by changing the role of <strong>Node 2</strong> (previous leader) to Follower.</li><li>The system initiates a new <strong>leader election</strong>.</li></ul><h4>6. New Leader Election</h4><pre>2024/12/15 12:39:03 Leader elected: Node 1 (Epoch: 1)</pre><ul><li><strong>Node 1</strong> is elected as the new leader, based on its health and epoch.</li><li>The debug logs confirm the election of <strong>Node 1</strong> as the new leader.</li></ul><h4>7. Synchronization (New Leader)</h4><pre>2024/12/15 12:39:03 Synchronized Node 1 with Leader (Committed: 0)<br>2024/12/15 12:39:03 Synchronized Node 2 with Leader (Committed: 0)<br>2024/12/15 12:39:03 Synchronized Node 3 with Leader (Committed: 0)</pre><ul><li>The new leader (<strong>Node 1</strong>) synchronizes its state with the other nodes (<strong>2 and 3</strong>).</li><li>Synchronization ensures that all nodes are up-to-date with the committed transactions.</li></ul><h4>8. Broadcasting Transactions (New Leader)</h4><p><strong>Transaction TX1</strong></p><pre>2024/12/15 12:39:03 Node 1 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX1<br>2024/12/15 12:39:03 Transaction TX1 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX1 committed by Leader</pre><ul><li><strong>Node 1</strong> (new leader) broadcasts <strong>Transaction TX1</strong> to the followers.</li><li>As before, the transaction is committed after acknowledgment from a majority of followers.</li></ul><p><strong>Transaction TX2</strong></p><pre>2024/12/15 12:39:03 Node 1 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 1<br>2024/12/15 12:39:03 Node 3 received transaction: TX2<br>2024/12/15 12:39:03 Transaction TX2 sent to Node 3<br>2024/12/15 12:39:03 Transaction TX2 committed by Leader</pre><ul><li>The process repeats for <strong>Transaction TX2</strong>.</li></ul><h3>Conclusion</h3><p>The ZAB protocol exemplifies the elegance of distributed systems design, balancing consistency, fault tolerance, and high availability. By guaranteeing total order broadcast and efficient recovery, ZAB empowers Apache Zookeeper to be the robust coordination service trusted by countless distributed applications.</p><p>Whether you’re building distributed databases, microservices orchestration platforms, or any system demanding consistent state, understanding ZAB provides invaluable insights into achieving reliability at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*-IaXpFzIGHoHOEs0HuqENw.gif" /></figure><p><strong>Github Link: </strong><a href="https://github.com/Jitender271/go-zab/">https://github.com/Jitender271/go-zab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d335dbae3ec9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reliable Systems: Understanding Paxos and Multi-Paxos with Go]]></title>
            <link>https://medium.com/@jitenderkmr/building-reliable-systems-understanding-paxos-and-multi-paxos-with-go-5cfcef6b06bb?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cfcef6b06bb</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 16:12:03 GMT</pubDate>
            <atom:updated>2024-12-11T16:12:03.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFaeNO48gYlRMQii977cQg.jpeg" /></figure><p>Distributed systems often face challenges in achieving consensus among nodes, especially when failures occur. The <strong>Paxos algorithm</strong>, designed by Leslie Lamport, addresses these challenges by ensuring fault-tolerant consensus in distributed environments. Multi-Paxos extends Paxos to optimize performance when multiple proposals need to be agreed upon sequentially.</p><p>This blog explains Paxos and Multi-Paxos in-depth, illustrated with a Go implementation, while also addressing the algorithm’s strengths and areas for improvement.</p><h3>Paxos Algorithm Overview</h3><p>Paxos ensures <strong>consensus</strong> through three roles:</p><ol><li><strong>Proposers</strong>: Suggest values.</li><li><strong>Acceptors</strong>: Agree or reject proposals.</li><li><strong>Learners</strong>: Apply accepted values to the system state.</li></ol><h4>Phases of Paxos</h4><p><strong>Phase 1: Prepare/Promise</strong></p><ul><li>A proposer sends a prepare message with a unique proposal number to a majority (quorum) of acceptors.</li><li>If the proposal number is higher than any previously promised number, acceptors respond with a promise and their last accepted proposal (if any).</li></ul><p><strong>Phase 2: Accept/Accepted</strong></p><ul><li>Upon receiving a quorum of promises, the proposer sends an accept request with its value.</li><li>Acceptors accept the proposal if the proposal number matches or exceeds their promised number.</li></ul><ol><li><strong>Learning</strong></li></ol><ul><li>Once a quorum of acceptors agrees, the value is committed and learned.</li></ul><h4>Key Properties of Paxos</h4><ul><li><strong>Safety</strong>: No two proposals conflict.</li><li><strong>Liveness</strong>: Progress is guaranteed when a majority is available.</li></ul><h3>Multi-Paxos</h3><p>In systems requiring multiple consensus decisions, <strong>Multi-Paxos</strong> avoids re-running leader elections for every value:</p><ol><li>A single leader is elected to handle multiple proposals.</li><li>The leader proposes values directly in Phase 2 for subsequent proposals.</li></ol><p><strong>Key Advantages:</strong></p><ul><li>Reduces overhead of repeated leader elections.</li><li>Maintains log consistency across nodes.</li></ul><h4>Challenges Addressed by Paxos</h4><p>Paxos was designed to solve the fundamental problem of consensus in a distributed system, where nodes must agree on a single value despite network delays, node failures, and the possibility of partitions. The algorithm guarantees safety (no conflicting proposals) and liveness (progress as long as a majority of nodes are functioning).</p><p>However, Paxos faces performance challenges due to frequent leader elections, especially when multiple values need to be agreed upon. This is where <strong>Multi-Paxos</strong> comes in, enhancing Paxos to handle such scenarios efficiently.</p><h4>Paxos vs. Multi-Paxos</h4><ul><li><strong>Paxos</strong>: Primarily designed to ensure a single decision can be made in a distributed system by reaching consensus on a single proposal.</li><li><strong>Multi-Paxos</strong>: Optimized version of Paxos for handling <strong>multiple consensus decisions</strong> over time, avoiding the overhead of re-running the leader election for each new proposal.</li></ul><p>In Multi-Paxos, once a leader is elected, it can continue to propose values without the need to re-elect after every decision, which minimizes network overhead and improves the system’s throughput and fault tolerance.</p><h4>Leader Election in Multi-Paxos</h4><p>Multi-Paxos introduces the concept of a <strong>persistent leader</strong>. After the leader is elected, it is allowed to propose a series of values without repeated leader elections. If the leader fails, a new leader is elected to continue the consensus process. This approach significantly reduces the latency and overhead that comes with the constant election process in Paxos.</p><h4>Log Replication</h4><p>Both Paxos and Multi-Paxos rely on <strong>log replication</strong> to maintain consistency across the system. The state of the system is replicated across multiple nodes, and decisions are recorded in the logs of each node. Once a consensus is reached for a value, it is applied to the log of each node, ensuring consistency.</p><p>In Multi-Paxos, after the leader is elected, it is responsible for proposing values sequentially, and the logs are synchronized across all nodes to prevent conflicts.</p><h4>Applications of Paxos and Multi-Paxos</h4><ul><li><strong>Distributed Databases</strong>: Paxos ensures consistency in distributed databases, especially in scenarios where write and read operations are spread across multiple nodes.</li><li><strong>File Systems</strong>: Distributed file systems use Paxos to ensure all nodes have a consistent view of the file system state, especially when metadata changes need to be propagated across nodes.</li><li><strong>Blockchain and Consensus Protocols</strong>: Paxos-like consensus algorithms are widely used in blockchain technologies for ensuring that all participants agree on the order of transactions.</li><li><strong>Distributed Coordination</strong>: Services such as configuration management and leader election systems use Paxos to coordinate actions across distributed systems.</li></ul><h3>1. The State Machine</h3><p>The <strong>StateMachine</strong> represents the system’s applied state. It ensures values are applied in order and prevents inconsistencies.</p><h3>Code Explanation:</h3><pre>type StateMachine struct {<br>	state      map[int]string<br>	applyIndex int<br>	mu         sync.Mutex<br>}</pre><ul><li><strong>state</strong>: A map storing applied values keyed by their log index.</li><li><strong>applyIndex</strong>: Tracks the highest index applied to the state machine.</li><li><strong>mu</strong>: A mutex ensures thread-safe operations.</li></ul><h4>Constructor:</h4><pre>func NewStateMachine() *StateMachine {<br>	return &amp;StateMachine{<br>		state:      make(map[int]string),<br>		applyIndex: 0,<br>	}<br>}</pre><ul><li>Creates a new StateMachine instance with an empty state and initial index.</li></ul><h4>Applying Values:</h4><pre>func (sm *StateMachine) ApplyValue(index int, value string) {<br>	sm.mu.Lock()<br>	defer sm.mu.Unlock()<br>	if index == sm.applyIndex+1 {<br>		sm.state[index] = value<br>		sm.applyIndex = index<br>		fmt.Printf(&quot;StateMachine applied: [%d] -&gt; %s\n&quot;, index, value)<br>	} else {<br>		fmt.Printf(&quot;Out of order log: [%d], expected: [%d]\n&quot;, index, sm.applyIndex+1)<br>	}<br>}</pre><ul><li>Applies a value if its index matches applyIndex + 1.</li><li>Out-of-order logs are ignored.</li></ul><h4>Displaying State:</h4><pre>func (sm *StateMachine) DisplayState() {<br>	sm.mu.Lock()<br>	defer sm.mu.Unlock()<br>	fmt.Println(&quot;State Machine Current State:&quot;)<br>	for i := 1; i &lt;= sm.applyIndex; i++ {<br>		fmt.Printf(&quot;[%d]: %s\n&quot;, i, sm.state[i])<br>	}<br>}</pre><ul><li>Iterates through state to display the current applied values.</li></ul><h3>2. Paxos Components</h3><p>Paxos comprises <strong>Proposers</strong>, <strong>Acceptors</strong>, and a shared state.</p><h4>Proposer</h4><p>A proposer attempts to lead the system by proposing values.</p><h4>Attributes:</h4><pre>type Proposer struct {<br>	id           int<br>	proposalNum  int<br>	leader       bool<br>	acceptedLogs map[int]string<br>	mu           sync.Mutex<br>}</pre><ul><li><strong>id</strong>: Unique identifier for the proposer.</li><li><strong>proposalNum</strong>: Number used during leader election.</li><li><strong>leader</strong>: Indicates if the proposer is the current leader.</li><li><strong>acceptedLogs</strong>: Stores values accepted during consensus.</li></ul><h4>Leader Election:</h4><pre>func (p *Proposer) RunPhase1(acceptors []*Acceptor, quorum int) bool {<br> p.mu.Lock()<br> defer p.mu.Unlock()<br><br> p.proposalNum += 10 + p.id<br> prepareNum := p.proposalNum<br> promises := 0<br> highestAcceptedNum := 0<br> highestAcceptedVal := &quot;&quot;<br><br> fmt.Printf(&quot;Proposer %d starts Phase 1 (Prepare Num: %d)\n&quot;, p.id, prepareNum)<br><br> for _, acc := range acceptors {<br>  acc.mu.Lock()<br>  if prepareNum &gt; acc.promisedNum {<br>   acc.promisedNum = prepareNum<br>   if acc.acceptedNum &gt; highestAcceptedNum {<br>    highestAcceptedNum = acc.acceptedNum<br>    highestAcceptedVal = acc.acceptedVal<br>   }<br>   promises++<br>  }<br>  acc.mu.Unlock()<br> }<br><br> if promises &gt;= quorum {<br>  p.leader = true<br>  if highestAcceptedNum &gt; 0 {<br>   p.acceptedLogs[highestAcceptedNum] = highestAcceptedVal<br>  }<br>  fmt.Printf(&quot;Proposer %d becomes leader\n&quot;, p.id)<br>  return true<br> }<br><br> fmt.Printf(&quot;Proposer %d failed to become leader\n&quot;, p.id)<br> return false<br>}</pre><ul><li><strong>Phase 1 (Prepare)</strong>: Proposers request promises from acceptors.</li><li>Becomes a leader if a majority (quorum) of acceptors promise support.</li></ul><h4>Proposing Values:</h4><pre>func (p *Proposer) ProposeValue(index int, value string, acceptors []*Acceptor, quorum int) bool {<br> if !p.leader {<br>  fmt.Printf(&quot;Proposer %d is not the leader. Cannot propose value.\n&quot;, p.id)<br>  return false<br> }<br><br> acceptCount := 0<br> for _, acc := range acceptors {<br>  acc.mu.Lock()<br>  if p.proposalNum &gt;= acc.promisedNum {<br>   acc.acceptedNum = p.proposalNum<br>   acc.acceptedLogs[index] = value<br>   acc.acceptedVal = value<br>   acceptCount++<br>  }<br>  acc.mu.Unlock()<br> }<br><br> if acceptCount &gt;= quorum {<br>  p.acceptedLogs[index] = value<br>  fmt.Printf(&quot;Proposer %d successfully proposed value &#39;%s&#39; at index %d\n&quot;, p.id, value, index)<br>  return true<br> }<br><br> fmt.Printf(&quot;Proposer %d failed to propose value &#39;%s&#39; at index %d\n&quot;, p.id, value, index)<br> return false<br>}<br></pre><ul><li>Proposes a value to acceptors if the proposer is the leader.</li><li>Majority acceptance leads to consensus.</li></ul><h4>Simulating Failure:</h4><pre>func (p *Proposer) SimulateLeaderFailure() {<br>	p.mu.Lock()<br>	defer p.mu.Unlock()<br>	p.leader = false<br>	fmt.Printf(&quot;Leader Proposer %d has failed!\n&quot;, p.id)<br>}</pre><ul><li>Simulates leader failure, marking the proposer as inactive.</li></ul><h4>Log Synchronization:</h4><pre>func (p *Proposer) SynchronizeLogs(acceptors []*Acceptor) {<br>	for _, acc := range acceptors {<br>		acc.mu.Lock()<br>		for idx, val := range acc.acceptedLogs {<br>			if _, exists := p.acceptedLogs[idx]; !exists {<br>				p.acceptedLogs[idx] = val<br>			}<br>		}<br>		acc.mu.Unlock()<br>	}<br>	fmt.Printf(&quot;Proposer %d synchronized logs with acceptors.\n&quot;, p.id)<br>}</pre><ul><li>Ensures a new leader synchronizes logs with acceptors.</li></ul><h3>Acceptor</h3><p>An acceptor promises or accepts values during consensus.</p><h4>Attributes:</h4><pre>type Acceptor struct {<br>	id           int<br>	promisedNum  int<br>	acceptedNum  int<br>	acceptedVal  string<br>	acceptedLogs map[int]string<br>	mu           sync.Mutex<br>}</pre><ul><li><strong>promisedNum</strong>: Highest proposal number promised.</li><li><strong>acceptedNum</strong>: Last accepted proposal number.</li><li><strong>acceptedVal</strong>: Last accepted value.</li><li><strong>acceptedLogs</strong>: Log of accepted values.</li></ul><h3>3. Paxos State</h3><pre>type PaxosState struct {<br>	proposers []*Proposer<br>	acceptors []*Acceptor<br>	quorum    int<br>}</pre><ul><li>Contains proposers, acceptors, and the quorum size.</li></ul><h4>Initializing the Paxos System:</h4><pre>func newPaxosSystem(proposerCount, acceptorCount int) *PaxosState {<br>	ps := &amp;PaxosState{<br>		proposers: []*Proposer{},<br>		acceptors: []*Acceptor{},<br>		quorum:    (acceptorCount / 2) + 1,<br>	}<br>	for i := 1; i &lt;= proposerCount; i++ {<br>		ps.proposers = append(ps.proposers, &amp;Proposer{<br>			id:           i,<br>			proposalNum:  0,<br>			leader:       false,<br>			acceptedLogs: make(map[int]string),<br>		})<br>	}<br>	for i := 1; i &lt;= acceptorCount; i++ {<br>		ps.acceptors = append(ps.acceptors, &amp;Acceptor{<br>			id:           i,<br>			acceptedLogs: make(map[int]string),<br>		})<br>	}<br>	return ps<br>}</pre><ul><li>Creates a new Paxos state with proposers and acceptors.</li></ul><h3>4. Main Function</h3><p>The main function demonstrates the Paxos workflow.</p><ul><li><strong>Leader Election</strong>: Proposers compete to become the leader.</li><li><strong>Proposing Values</strong>: The leader proposes values.</li><li><strong>Leader Failure</strong>: Simulates leader failure and elects a new leader.</li><li><strong>State Machine Application</strong>: Applies accepted values to the state machine.</li></ul><h3>Output</h3><pre>Proposer 1 starts Phase 1 (Prepare Num: 11)<br>Proposer 1 becomes leader<br>Proposer 1 successfully proposed value &#39;value1&#39; at index 1<br>Proposer 1 successfully proposed value &#39;value2&#39; at index 2<br>Proposer 1 successfully proposed value &#39;value3&#39; at index 3<br>Leader Proposer 1 has failed!<br>Proposer 2 starts Phase 1 (Prepare Num: 12)<br>Proposer 2 becomes leader<br>New leader elected: Proposer 2<br>Proposer 2 synchronized logs with acceptors.<br>Proposer 2 successfully proposed value &#39;value1&#39; at index 1<br>StateMachine applied: [1] -&gt; value1<br>Proposer 2 successfully proposed value &#39;value2&#39; at index 2<br>StateMachine applied: [2] -&gt; value2<br>Proposer 2 successfully proposed value &#39;value3&#39; at index 3<br>StateMachine applied: [3] -&gt; value3<br>State Machine Current State:<br>[1]: value1<br>[2]: value2<br>[3]: value3</pre><p>The output of the program demonstrates the following sequence of operations and events in the Paxos system:</p><ol><li><strong>Initial Leader Election</strong>:</li></ol><ul><li>Proposer 1 begins Phase 1 with a Prepare Num of 11.</li><li>It gathers sufficient promises from acceptors and becomes the leader.</li></ul><p><strong>2. Proposing Values</strong>:</p><ul><li>As the leader, Proposer 1 successfully proposes three values (value1, value2, and value3) at indices 1, 2, and 3 respectively.</li></ul><p><strong>3. Leader Failure</strong>:</p><ul><li>Proposer 1 simulates a failure, marking itself as no longer the leader.</li></ul><p><strong>4. New Leader Election</strong>:</p><ul><li>Proposer 2 starts Phase 1 with a Prepare Num of 12.</li><li>Proposer 2 receives sufficient promises from acceptors and is elected as the new leader.</li></ul><p><strong>5. Log Synchronization</strong>:</p><ul><li>Proposer 2 synchronizes its logs with those of the acceptors to ensure consistency.</li></ul><p><strong>6. Re-Proposing Values to the State Machine</strong>:</p><ul><li>Proposer 2 re-proposes the values (value1, value2, and value3) at their respective indices.</li><li>The state machine successfully applies these values in order.</li></ul><p><strong>7. Final State Display</strong>:</p><ul><li>The state machine displays its current state, showing all the applied values:</li></ul><pre>[1]: value1<br>[2]: value2<br>[3]: value3</pre><p>This output highlights the Paxos system’s robustness and ability to maintain consistency, even after leader failure. It ensures that all proposed values are eventually applied in the correct order. The synchronized logs and the state machine validate the reliability of the Paxos protocol in distributed systems.</p><h3>Conclusion</h3><p>Distributed systems demand reliable and fault-tolerant mechanisms for achieving consensus. Paxos is one of the foundational algorithms that ensures consistency even in the presence of failures. By breaking down the implementation step-by-step, this article has demonstrated:</p><ol><li><strong>Core Paxos Components</strong>: How Proposers, Acceptors, and a State Machine interact to ensure system-wide agreement.</li><li><strong>Leader Election and Consensus</strong>: The importance of achieving quorum to drive decision-making.</li><li><strong>Handling Failures</strong>: How Paxos maintains consistency by electing new leaders and synchronizing logs after failures.</li></ol><p>The implementation showcases how Paxos can handle typical challenges in distributed systems, such as leader failures and concurrent proposals, while maintaining correctness.</p><p>This example is not only a practical introduction to Paxos but also a foundation to explore other consensus protocols like Raft or Multi-Paxos, which build upon Paxos to offer greater efficiency and usability.</p><p>By experimenting with the provided code, you can enhance your understanding of distributed systems and consensus algorithms, paving the way to designing robust and scalable systems for real-world applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*FdKiOfsVyRt7yn5hi38OcA.gif" /></figure><p><strong>Github Link: </strong><a href="https://github.com/Jitender271/go-paxos">https://github.com/Jitender271/go-paxos</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cfcef6b06bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Discovery with Zookeeper and Go: A Comprehensive Guide]]></title>
            <link>https://medium.com/@jitenderkmr/service-discovery-with-zookeeper-and-go-a-comprehensive-guide-c3ec16bf072d?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3ec16bf072d</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 18:26:44 GMT</pubDate>
            <atom:updated>2024-10-13T13:33:32.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkugr_FL-4WAXLlDDnb8BQ.png" /></figure><p>In the dynamic landscape of microservices architecture, <strong>Service Discovery</strong> plays a pivotal role in enabling seamless communication between services. This article delves into implementing Service Discovery using <strong>Apache Zookeeper</strong> with a <strong>Golang</strong> backend. We’ll walk through setting up Zookeeper, building a Go-based API for service registration and discovery, and ensuring robust and dynamic interactions between services.</p><h3>Table of Contents</h3><ol><li>Introduction to Service Discovery</li><li>Why Choose Zookeeper for Service Discovery?</li><li>Key Concepts in Zookeeper</li></ol><ul><li>Znodes</li><li>Watchers</li><li>Sessions</li></ul><p>4. Setting Up Zookeeper</p><ul><li>Verify Zookeeper Setup</li></ul><p>5. Building the Go API for Service Discovery</p><ul><li>service.go</li><li>server.go</li><li>handlers.go</li><li>discovery.go</li><li>main.go</li></ul><p>6. Running and Testing the API</p><ul><li>Start the Go Server</li><li>Register a Service</li><li>Discover Services</li><li>Testing Watchers with Dynamic Updates</li><li>Verifying Ephemeral Nodes</li></ul><p>7. Conclusion</p><h3>Introduction to Service Discovery</h3><p>In a microservices architecture, applications are composed of multiple loosely coupled services that communicate over a network. <strong>Service Discovery</strong> is the mechanism through which services locate and communicate with each other. Instead of hardcoding service locations (like IP addresses and ports), Service Discovery allows services to dynamically find each other, enhancing scalability and resilience.</p><h3>Why Choose Zookeeper for Service Discovery?</h3><p><strong>Apache Zookeeper</strong> is a robust, open-source distributed coordination service that provides configuration management, synchronization, and naming registry for large distributed systems. Its features make it a strong candidate for implementing Service Discovery:</p><ul><li><strong>Hierarchical Namespace:</strong> Organizes data in a tree-like structure, making it intuitive to manage service registrations.</li><li><strong>Watchers:</strong> Enable clients to get notified about changes, facilitating dynamic updates.</li><li><strong>Sessions:</strong> Maintain stateful connections, ensuring only active services are discoverable.</li></ul><h3>Key Concepts in Zookeeper</h3><h3>Znodes</h3><p><strong>Znodes</strong> are the fundamental data nodes in Zookeeper’s hierarchical namespace, analogous to files in a filesystem. Each znode can store data and have child znodes.</p><ul><li><strong>Ephemeral Znodes:</strong> These nodes are tied to the session that created them. If the session ends (e.g., service crashes), the znode is automatically removed.</li><li><strong>Sequential Znodes:</strong> Automatically appended with a monotonically increasing number, ensuring unique identifiers.</li></ul><h3>Watchers</h3><p><strong>Watchers</strong> allow clients to subscribe to changes on znodes. When a znode changes (creation, deletion, data modification), all clients with watchers on that znode are notified. This feature is crucial for dynamic Service Discovery, enabling clients to react to service availability changes without polling.</p><h3>Sessions</h3><p>A <strong>Session</strong> represents a connection between a client and the Zookeeper ensemble. Sessions ensure that znodes created with ephemeral flags are tied to the client’s lifecycle. If a client fails to communicate within the session timeout, Zookeeper automatically cleans up the ephemeral znodes, maintaining an up-to-date service registry.</p><h3>Setting Up Zookeeper</h3><p>Before diving into code, let’s set up Zookeeper to facilitate our Service Discovery implementation.</p><h3>Verify Zookeeper Setup</h3><h4>Ensure Zookeeper is Running</h4><ol><li><strong>Install Zookeeper via Homebrew (macOS):</strong></li></ol><p>brew install zookeeper</p><p><strong>2. Start Zookeeper:</strong></p><p>brew services start zookeeper</p><h4>Check and Create the Base Path /services</h4><ol><li><strong>Open the Zookeeper CLI:</strong></li><li>Access the Zookeeper command-line interface (CLI):</li></ol><p>zkCli.sh</p><pre>jitender@Jitenders-MacBook-Pro go-service-discovery % cd /opt/homebrew/bin/<br>jitender@Jitenders-MacBook-Pro bin % ./zkCli -server 127.0.0.1:2181<br><br>Connecting to 127.0.0.1:2181<br>Welcome to ZooKeeper!<br>JLine support is enabled<br>[zk: 127.0.0.1:2181(CONNECTING) 0]<br>WATCHER::<br><br>WatchedEvent state:SyncConnected type:None path:null zxid: -1<br></pre><p><strong>Note:</strong> If zkCli.sh isn&#39;t in your PATH, navigate to the Zookeeper installation directory or specify the full path.</p><ol><li><strong>List Root Nodes to Verify </strong><strong>/services Exists:</strong></li></ol><p>Once inside the CLI, list the znodes at the root:</p><p>ls /</p><p><strong>Output (if </strong><strong>/services exists):</strong></p><p>[services]</p><p><strong>3. Create </strong><strong>/services if It Doesn&#39;t Exist:</strong></p><p>create /services &quot;&quot;</p><p><strong>Output:</strong></p><p>Created /services</p><p><strong>4. Verify Creation:</strong></p><p>ls /</p><p><strong>Output:</strong></p><p>[services]</p><h3>Building the Go API for Service Discovery</h3><p>With Zookeeper set up, let’s proceed to build a Go-based API that allows services to register themselves and discover other services dynamically.</p><h3>Repository Structure</h3><p>Organize your project directory as follows:</p><pre>go-service-discovery/<br>└── go/<br>    ├── go.mod<br>    ├── main.go<br>    ├── server.go<br>    ├── handlers.go<br>    ├── service.go<br>    └── discovery.go</pre><h3>Install Dependencies</h3><ol><li><strong>Install Necessary Dependencies:</strong></li></ol><p>We’ll use <strong>Gorilla Mux</strong> for routing and <strong>go-zookeeper</strong> as the Zookeeper client.</p><p>go get -u github.com/gorilla/mux</p><p>go get -u github.com/go-zookeeper/zk</p><h3>Step 2: Implementing the Go Code</h3><p>We’ll create several Go files to modularize our application:</p><ul><li>service.go: Handles service registration logic.</li><li>server.go: Manages the Zookeeper connection.</li><li>handlers.go: Defines HTTP handlers for registration and discovery.</li><li>discovery.go: Implements service discovery and watchers.</li><li>main.go: Initializes the server and routes.</li></ul><h4>service.go</h4><p>This file ensures that the necessary Zookeeper paths exist and handles service registration.</p><pre>import (<br>	&quot;log&quot;<br>	&quot;strconv&quot;<br>	&quot;strings&quot;</pre><pre>	&quot;github.com/go-zookeeper/zk&quot;<br>)</pre><pre>// Service represents a service to be registered<br>type Service struct {<br>	Name    string `json:&quot;name&quot; validate:&quot;required&quot;`<br>	Address string `json:&quot;address&quot; validate:&quot;required&quot;`<br>	Port    int    `json:&quot;port&quot; validate:&quot;required&quot;`<br>}</pre><pre>// createPath ensures that the given path exists by creating any missing znodes<br>func createPath(conn *zk.Conn, path string) error {<br>	parts := strings.Split(path, &quot;/&quot;)<br>	currentPath := &quot;&quot;<br>	for _, part := range parts {<br>		if part == &quot;&quot; {<br>			continue<br>		}<br>		currentPath += &quot;/&quot; + part<br>		exists, _, err := conn.Exists(currentPath)<br>		if err != nil {<br>			return err<br>		}<br>		if !exists {<br>			_, err := conn.Create(currentPath, []byte(&quot;&quot;), 0, zk.WorldACL(zk.PermAll))<br>			if err != nil &amp;&amp; err != zk.ErrNodeExists {<br>				return err<br>			}<br>			log.Printf(&quot;Created path: %s&quot;, currentPath)<br>		}<br>	}<br>	return nil<br>}</pre><pre>// registerService registers a new service in Zookeeper<br>func registerService(conn *zk.Conn, service Service) error {<br>	servicePath := &quot;/services/&quot; + service.Name</pre><pre>	// Ensure the service type path exists<br>	if err := createPath(conn, servicePath); err != nil {<br>		return err<br>	}</pre><pre>	// Create a unique node for the service instance using sequential ephemeral nodes<br>	nodePath := servicePath + &quot;/service-&quot;<br>	data := []byte(service.Address + &quot;:&quot; + strconv.Itoa(service.Port))<br>	createdPath, err := conn.CreateProtectedEphemeralSequential(nodePath, data, zk.WorldACL(zk.PermAll))<br>	if err != nil {<br>		return err<br>	}</pre><pre>	log.Printf(&quot;Service registered: %s at %s&quot;, createdPath, data)<br>	return nil<br>}</pre><ul><li><strong>createPath Function:</strong> Ensures all intermediate znodes exist, preventing &quot;node does not exist&quot; errors.</li><li><strong>Ephemeral Sequential Nodes:</strong> Guarantees unique and temporary service registrations tied to the session.</li></ul><h4>server.go</h4><p>This file initializes the Zookeeper connection and ensures the base /services path exists.</p><pre>import (<br>	&quot;log&quot;<br>	&quot;time&quot;</pre><pre>	&quot;github.com/go-zookeeper/zk&quot;<br>)</pre><pre>// Server holds the dependencies for the HTTP handlers<br>type Server struct {<br>	zkConn *zk.Conn<br>}</pre><pre>// NewServer initializes the Zookeeper connection and returns a Server instance<br>func NewServer() (*Server, error) {<br>	zkAddress := &quot;localhost:2181&quot; // Configurable as needed<br>	conn, _, err := zk.Connect([]string{zkAddress}, time.Second*5)<br>	if err != nil {<br>		return nil, err<br>	}</pre><pre>	// Ensure the base path exists<br>	basePath := &quot;/services&quot;<br>	exists, _, err := conn.Exists(basePath)<br>	if err != nil {<br>		return nil, err<br>	}<br>	if !exists {<br>		_, err = conn.Create(basePath, []byte(&quot;&quot;), 0, zk.WorldACL(zk.PermAll))<br>		if err != nil &amp;&amp; err != zk.ErrNodeExists {<br>			return nil, err<br>		}<br>		log.Printf(&quot;Created base path: %s&quot;, basePath)<br>	}</pre><pre>	return &amp;Server{zkConn: conn}, nil<br>}</pre><ul><li><strong>Server Struct:</strong> Encapsulates the Zookeeper connection, making it accessible to handlers.</li><li><strong>Base Path Verification:</strong> Ensures /services exists to prevent runtime errors during service registration.</li></ul><h4>handlers.go</h4><p>Defines HTTP handlers for registering services and discovering them.</p><pre>import (<br>	&quot;encoding/json&quot;<br>	&quot;log&quot;<br>	&quot;net/http&quot;</pre><pre>	&quot;github.com/gorilla/mux&quot;<br>	&quot;github.com/go-zookeeper/zk&quot;<br>)</pre><pre>// handleRegister handles the /register POST endpoint<br>func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {<br>	var service Service<br>	if err := json.NewDecoder(r.Body).Decode(&amp;service); err != nil {<br>		http.Error(w, &quot;Invalid request payload&quot;, http.StatusBadRequest)<br>		return<br>	}<br>	defer r.Body.Close()</pre><pre>	// Validate service fields (optional but recommended)<br>	if service.Name == &quot;&quot; || service.Address == &quot;&quot; || service.Port == 0 {<br>		http.Error(w, &quot;Missing required fields&quot;, http.StatusBadRequest)<br>		return<br>	}</pre><pre>	// Register the service<br>	err := registerService(s.zkConn, service)<br>	if err != nil {<br>		log.Printf(&quot;Failed to register service: %v&quot;, err)<br>		http.Error(w, &quot;Failed to register service&quot;, http.StatusInternalServerError)<br>		return<br>	}</pre><pre>	w.WriteHeader(http.StatusOK)<br>	w.Write([]byte(&quot;Service registered successfully&quot;))<br>}</pre><pre>// handleDiscover handles the /discover/{serviceType} GET endpoint<br>func (s *Server) handleDiscover(w http.ResponseWriter, r *http.Request) {<br>	vars := mux.Vars(r)<br>	serviceType := vars[&quot;serviceType&quot;]</pre><pre>	services, err := discoverServices(s.zkConn, serviceType)<br>	if err != nil {<br>		log.Printf(&quot;Failed to discover services: %v&quot;, err)<br>		http.Error(w, &quot;Failed to discover services&quot;, http.StatusInternalServerError)<br>		return<br>	}</pre><pre>	respondJSON(w, http.StatusOK, map[string]interface{}{&quot;services&quot;: services})<br>}</pre><pre>// respondJSON sends a JSON response<br>func respondJSON(w http.ResponseWriter, status int, payload interface{}) {<br>	response, err := json.Marshal(payload)<br>	if err != nil {<br>		http.Error(w, &quot;Error processing response&quot;, http.StatusInternalServerError)<br>		return<br>	}<br>	w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>	w.WriteHeader(status)<br>	w.Write(response)<br>}</pre><ul><li><strong>handleRegister:</strong> Decodes incoming JSON payloads and registers services.</li><li><strong>handleDiscover:</strong> Retrieves a list of services of a specific type.</li><li><strong>Error Handling:</strong> Provides meaningful HTTP responses based on operation outcomes.</li></ul><h4>discovery.go</h4><p>Implements service discovery and sets up watchers to monitor service changes.</p><pre>import (<br>	&quot;log&quot;</pre><pre>	&quot;github.com/go-zookeeper/zk&quot;<br>)</pre><pre>// discoverServices retrieves the list of services from Zookeeper and sets up watchers<br>func discoverServices(conn *zk.Conn, serviceType string) ([]string, error) {<br>	servicePath := &quot;/services/&quot; + serviceType</pre><pre>	// Check if the service type exists<br>	exists, _, err := conn.Exists(servicePath)<br>	if err != nil {<br>		return nil, err<br>	}<br>	if !exists {<br>		return []string{}, nil // No services registered under this type<br>	}</pre><pre>	// Get the initial list of services<br>	services, _, err := conn.Children(servicePath)<br>	if err != nil {<br>		return nil, err<br>	}</pre><pre>	log.Printf(&quot;Available services for %s: %v&quot;, serviceType, services)</pre><pre>	// Set a watcher to listen for changes<br>	go watchServices(conn, servicePath)</pre><pre>	return services, nil<br>}</pre><pre>// watchServices sets a watcher on the service node to listen for changes<br>func watchServices(conn *zk.Conn, servicePath string) {<br>	for {<br>		_, _, events, err := conn.ChildrenW(servicePath)<br>		if err != nil {<br>			log.Printf(&quot;Error watching services: %v&quot;, err)<br>			return<br>		}</pre><pre>		// Wait for an event<br>		event := &lt;-events<br>		if event.Type == zk.EventNodeChildrenChanged {<br>			// Fetch the updated list of services<br>			services, _, err := conn.Children(servicePath)<br>			if err != nil {<br>				log.Printf(&quot;Error fetching updated services: %v&quot;, err)<br>				continue<br>			}<br>			log.Printf(&quot;Updated services for %s: %v&quot;, servicePath, services)<br>		}<br>	}<br>}</pre><ul><li><strong>discoverServices:</strong> Retrieves current services and initiates watchers.</li><li><strong>watchServices:</strong> Continuously monitors service registrations and logs updates, ensuring clients have real-time information.</li></ul><h4>main.go</h4><p>Initializes the server, sets up routes, and starts the HTTP server.</p><pre>import (<br>	&quot;log&quot;<br>	&quot;net/http&quot;</pre><pre>	&quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>	// Initialize the server with Zookeeper connection<br>	server, err := NewServer()<br>	if err != nil {<br>		log.Fatalf(&quot;Failed to initialize server: %v&quot;, err)<br>	}<br>	defer server.zkConn.Close()</pre><pre>	// Create a new Gorilla Mux router<br>	router := mux.NewRouter()</pre><pre>	// Register routes with appropriate handlers and methods<br>	router.HandleFunc(&quot;/register&quot;, server.handleRegister).Methods(&quot;POST&quot;)<br>	router.HandleFunc(&quot;/discover/{serviceType}&quot;, server.handleDiscover).Methods(&quot;GET&quot;)</pre><pre>	// Start the server<br>	log.Println(&quot;Starting server on :8080...&quot;)<br>	if err := http.ListenAndServe(&quot;:8080&quot;, router); err != nil {<br>		log.Fatalf(&quot;Failed to start server: %v&quot;, err)<br>	}<br>}</pre><ul><li><strong>Route Definitions:</strong> Associates endpoints with their respective handlers.</li><li><strong>Server Initialization:</strong> Ensures Zookeeper is connected before handling requests.</li></ul><h3>Running and Testing the API</h3><p>With the code in place, let’s run the Go server and test our Service Discovery implementation.</p><h3>Start the Go Server</h3><ol><li><strong>Run the Go Application:</strong></li></ol><p>go run main.go server.go handlers.go service.go discovery.go</p><p><strong>Output:</strong></p><p>Created base path: /services Starting server on :8080...</p><h3>Register a Service</h3><p>Use curl or <strong>Postman</strong> to register a service.</p><p><strong>Using </strong><strong>curl:</strong></p><pre>curl -X POST http://localhost:8080/register \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;name&quot;: &quot;web&quot;, &quot;address&quot;: &quot;192.168.1.10&quot;, &quot;port&quot;: 8080}&#39;</pre><p><strong>Response:</strong></p><pre>Service registered successfully</pre><p><strong>Terminal Output:</strong></p><pre>Service registered: /services/web/service-0000000000 at 192.168.1.10:8080</pre><h3>Discover Services</h3><p>Retrieve the list of registered services for a specific service type.</p><p><strong>Using </strong><strong>curl:</strong></p><pre>curl http://localhost:8080/discover/web</pre><p><strong>Expected Response:</strong></p><pre>{<br>  &quot;services&quot;: [<br>    &quot;service-0000000000&quot;<br>  ]<br>}</pre><p><strong>Terminal Output:</strong></p><pre>Available services for web: [service-0000000000]</pre><h3>Testing Watchers with Dynamic Updates</h3><p>To test the watcher functionality, register another instance of the web service and observe the updates.</p><ol><li><strong>Register Another Service Instance:</strong></li></ol><ul><li>curl -X POST http://localhost:8080/register \ -H &quot;Content-Type: application/json&quot; \ -d &#39;{&quot;name&quot;: &quot;web&quot;, &quot;address&quot;: &quot;192.168.1.11&quot;, &quot;port&quot;: 8081}&#39;</li></ul><p><strong>Response:</strong></p><ul><li>Service registered successfully</li></ul><p><strong>Terminal Output:</strong></p><p>Service registered: /services/web/service-0000000001 at 192.168.1.11:8081 Updated services for /services/web: [service-0000000000 service-0000000001]</p><p><strong>Verify Updated Services:</strong></p><p>curl <a href="http://localhost:8080/discover/web">http://localhost:8080/discover/web</a></p><p><strong>Response:</strong></p><p>{ &quot;services&quot;: [ &quot;service-0000000000&quot;, &quot;service-0000000001&quot; ] }</p><h3>Verifying Ephemeral Nodes</h3><p>Ephemeral nodes ensure that service registrations are temporary and tied to the client’s session. If a service instance disconnects (e.g., the server stops), its registration is automatically removed.</p><ol><li><strong>Register a Service:</strong></li></ol><p>curl -X POST http://localhost:8080/register \ -H &quot;Content-Type: application/json&quot; \ -d &#39;{&quot;name&quot;: &quot;db&quot;, &quot;address&quot;: &quot;192.168.1.20&quot;, &quot;port&quot;: 5432}&#39;</p><p><strong>Expected Response:</strong></p><p>Service registered successfully</p><p><strong>Terminal Output:</strong></p><p>Service registered: /services/db/service-0000000002 at 192.168.1.20:5432</p><p><strong>2. Verify Registration:</strong></p><p>curl <a href="http://localhost:8080/discover/db">http://localhost:8080/discover/db</a></p><p><strong>Response:</strong></p><p>{ &quot;services&quot;: [ &quot;service-0000000002&quot; ] }</p><p><strong>3. Stop the Server:</strong></p><ul><li>Stop the server.</li><li>Verify Zookeeper Automatically Removes the Node, reconnect to zkCli.sh and list the services:</li><li>zkCli.sh ls /services/web</li></ul><p><strong>Output:</strong></p><ul><li>[ ]</li></ul><p>The znode for the web service should be removed automatically, indicating that ephemeral nodes are functioning correctly.</p><h3>Conclusion</h3><p>Implementing Service Discovery using <strong>Apache Zookeeper</strong> and <strong>Golang</strong> provides a robust solution for dynamic microservices architectures. By leveraging Zookeeper’s hierarchical namespace, watchers, and session management, services can seamlessly register themselves and discover other services in real-time. This setup enhances scalability, resilience, and maintainability, essential traits for modern distributed systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*3ccYAmRT8UJ77k2pw2_hdQ.gif" /></figure><p><strong>Github link: </strong><a href="https://github.com/Jitender271/go-service-discovery">https://github.com/Jitender271/go-service-discovery</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ec16bf072d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Space and Time: Creating a Scalable Bloom Filter in Go]]></title>
            <link>https://medium.com/@jitenderkmr/optimizing-space-and-time-creating-a-scalable-bloom-filter-in-go-d775fe8c5a96?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/d775fe8c5a96</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 02:33:51 GMT</pubDate>
            <atom:updated>2024-10-12T02:36:21.150Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of computer science, efficient data structures are pivotal for optimizing performance and resource utilization. One such ingenious structure is the <strong>Bloom Filter</strong> — a probabilistic data structure renowned for its space efficiency and speed in set membership testing. This article delves deep into understanding Bloom Filters, explores their scalable variants, and walks you through implementing a <strong>Scalable Bloom Filter (SBF)</strong> in Go. By the end, you’ll not only grasp the theoretical underpinnings but also gain practical insights into leveraging Bloom Filters in real-world applications.</p><h3>Table of Contents</h3><ol><li>What is a Bloom Filter?</li><li>How Does a Bloom Filter Work?</li><li>Introducing Scalable Bloom Filters</li><li>Implementing a Scalable Bloom Filter in Go</li><li>Applications of Bloom Filters</li><li>Best Practices and Considerations</li><li>Conclusion</li></ol><h3>What is a Bloom Filter?</h3><p>A <strong>Bloom Filter</strong> is a space-efficient probabilistic data structure designed to test whether an element is a member of a set. Unlike traditional data structures like hash tables or binary search trees, Bloom Filters do not store the elements themselves. Instead, they use multiple hash functions to map elements to positions in a bit array.</p><p><strong>Key Characteristics:</strong></p><ul><li><strong>Probabilistic Nature:</strong> Bloom Filters can yield false positives (indicating an element is in the set when it’s not) but <strong>never</strong> false negatives. This means if a Bloom Filter says an element is not present, it <strong>definitely</strong> isn’t.</li><li><strong>Space Efficiency:</strong> They require significantly less memory compared to other data structures, making them ideal for large datasets.</li></ul><h3>How Does a Bloom Filter Work?</h3><p>A Bloom Filter operates using a simple yet powerful mechanism involving a bit array and multiple hash functions. Here’s a step-by-step breakdown:</p><ol><li><strong>Initialization:</strong></li></ol><ul><li><strong>Bit Array:</strong> Start with a bit array of size <em>m</em>, all initialized to 0.</li><li><strong>Hash Functions:</strong> Choose <em>k</em> independent hash functions. Each function maps an element to one of the <em>m</em> array positions uniformly.</li></ul><p><strong>2. Adding an Element:</strong></p><ul><li>For each element to be added, pass it through the <em>k</em> hash functions to obtain <em>k</em> indices.</li><li>Set the bits at all these <em>k</em> positions to 1.</li></ul><p><strong>3. Checking Membership:</strong></p><ul><li>To check if an element is in the set, hash it using the same <em>k</em> hash functions to get <em>k</em> indices.</li><li>If <strong>all</strong> the bits at these positions are 1, the element is <strong>probably in the set</strong>.</li><li>If <strong>any</strong> of the bits is 0, the element <strong>definitely is not in the set</strong>.</li></ul><p><strong>Visualization:</strong></p><p>Imagine a series of light bulbs (bits), all initially off. Adding an element turns on specific bulbs based on the hash functions. Checking for an element involves verifying the state of those bulbs: if any are off, the element wasn’t added; if all are on, the element might have been added (or it’s a false positive).</p><h3>Introducing Scalable Bloom Filters</h3><p>While standard Bloom Filters are excellent for fixed-size datasets, many real-world applications involve dynamic data where the number of elements isn’t known upfront or can grow unpredictably. Enter the <strong>Scalable Bloom Filter (SBF)</strong>.</p><h3>Why Scalable?</h3><p>A Scalable Bloom Filter addresses the limitations of traditional Bloom Filters by allowing dynamic growth while maintaining a controlled false positive rate. Unlike its predecessor, an SBF can:</p><ul><li><strong>Dynamically Adjust Size:</strong> Automatically add new Bloom Filters as the dataset grows.</li><li><strong>Maintain False Positive Rates:</strong> Ensure the overall false positive probability remains within a predefined threshold.</li></ul><h3>How Does It Achieve Scalability?</h3><p>An SBF comprises multiple Bloom Filters, each with its own bit array and hash functions. When the current Bloom Filter reaches its capacity (i.e., the desired false positive rate is about to be exceeded), a new Bloom Filter is added to the sequence with adjusted parameters to maintain the overall false positive rate.</p><h3>Implementing a Scalable Bloom Filter in Go</h3><p>Let’s dive into implementing an SBF in Go, incorporating features like dynamic capacity adjustment, parameter validation, and configuration flexibility.</p><h3>Understanding the Go Code</h3><p>Here’s the comprehensive Go implementation of a Scalable Bloom Filter:</p><p>Let’s dissect the code to understand its components and functionalities.</p><h4>1. Configuration Struct (Config)</h4><pre>type Config struct {<br>	InitialFP       float64 `json:&quot;initial_fp&quot;`       // Initial false positive rate<br>	GrowthFactor    float64 `json:&quot;growth_factor&quot;`    // Factor by which capacity grows<br>	TighteningRatio float64 `json:&quot;tightening_ratio&quot;` // Ratio to reduce false positive rate<br>	InitialCapacity int     `json:&quot;initial_capacity&quot;` // Initial expected number of elements<br>}</pre><p><strong>Purpose:</strong> Holds the configurable parameters for the Scalable Bloom Filter.</p><p><strong>Fields:</strong></p><ul><li>InitialFP: The starting false positive rate.</li><li>GrowthFactor: Determines how the capacity (n) of each new Bloom filter scales.</li><li>TighteningRatio: Controls the reduction in false positive rate for each subsequent Bloom filter.</li><li>InitialCapacity: The expected number of elements in the first Bloom filter.</li></ul><h4>2. Scalable Bloom Filter Struct (ScalableBloomFilter)</h4><pre>type ScalableBloomFilter struct {<br>	filters         []*BloomFilter<br>	initialFP       float64<br>	growthFactor    float64<br>	tighteningRatio float64<br>	initialCapacity int<br>	mutex           sync.RWMutex<br>}</pre><p><strong>Fields:</strong></p><ul><li>filters: A slice holding individual Bloom filters.</li><li>initialFP, growthFactor, tighteningRatio, initialCapacity: Configuration parameters.</li><li>mutex: Ensures thread-safe operations.</li></ul><h4>3. Constructor: NewScalableBloomFilter</h4><pre>func NewScalableBloomFilter(config Config) (*ScalableBloomFilter, error) {<br>	// Parameter Validation<br>	if config.TighteningRatio &lt;= 0 || config.TighteningRatio &gt;= 1 {<br>		return nil, errors.New(&quot;tighteningRatio must be between 0 and 1&quot;)<br>	}<br>	if config.GrowthFactor &lt;= 1 {<br>		return nil, errors.New(&quot;growthFactor must be greater than 1&quot;)<br>	}<br>	if config.InitialFP &lt;= 0 || config.InitialFP &gt;= 1 {<br>		return nil, errors.New(&quot;initialFP must be between 0 and 1&quot;)<br>	}<br>	if config.InitialCapacity &lt;= 0 {<br>		return nil, errors.New(&quot;initialCapacity must be greater than 0&quot;)<br>	}</pre><pre>	return &amp;ScalableBloomFilter{<br>		filters:         []*BloomFilter{},<br>		initialFP:       config.InitialFP,<br>		growthFactor:    config.GrowthFactor,<br>		tighteningRatio: config.TighteningRatio,<br>		initialCapacity: config.InitialCapacity,<br>	}, nil<br>}</pre><ul><li>Validates configuration parameters to ensure they are within acceptable ranges.</li><li>Initializes an empty slice of Bloom filters with the provided configurations.</li></ul><h4>4. Adding Elements: AddCopy code</h4><pre>func (sbf *ScalableBloomFilter) Add(item string) error {<br>	sbf.mutex.Lock()<br>	defer sbf.mutex.Unlock()</pre><pre>	// If there are no filters or the last filter cannot accommodate the item, create a new filter<br>	if len(sbf.filters) == 0 || !sbf.filters[len(sbf.filters)-1].Add(item) {<br>		// Calculate new false positive probability using tighteningRatio<br>		newFP := sbf.initialFP * math.Pow(sbf.tighteningRatio, float64(len(sbf.filters)))</pre><pre>		// Calculate new capacity using growthFactor<br>		// Each new filter has capacity = initialCapacity * (growthFactor ^ number_of_filters)<br>		newCapacity := float64(sbf.initialCapacity) * math.Pow(sbf.growthFactor, float64(len(sbf.filters)))</pre><pre>		// Create a new Bloom filter with scaled capacity and adjusted false positive rate<br>		newFilter := NewBloomFilter(int(math.Ceil(newCapacity)), newFP)</pre><pre>		// Add the item to the new filter<br>		newFilter.Add(item)</pre><pre>		// Append the new filter to the list of filters<br>		sbf.filters = append(sbf.filters, newFilter)<br>	}<br>	return nil<br>}</pre><ul><li>Attempts to add an item to the latest Bloom filter.</li><li>If the current filter is saturated (i.e., cannot accommodate more elements without exceeding the desired false positive rate), a new Bloom filter is instantiated with scaled capacity and a reduced false positive rate.</li><li>The new filter is then added to the filters slice.</li></ul><h4>5. Checking Membership: MightContain</h4><pre>func (sbf *ScalableBloomFilter) MightContain(item string) bool {<br>	sbf.mutex.RLock()<br>	defer sbf.mutex.RUnlock()</pre><pre>	for _, filter := range sbf.filters {<br>		if filter.MightContain(item) {<br>			return true<br>		}<br>	}<br>	return false<br>}</pre><ul><li>Iterates through all Bloom filters in the SBF.</li><li>If any filter indicates that the item might be present, it returns true.</li><li>Otherwise, it confidently returns false, ensuring no false negatives.</li></ul><h4>6. Individual Bloom Filter Struct (BloomFilter)</h4><pre>type BloomFilter struct {<br>	bitset       []uint8<br>	bitSize      uint<br>	numHashFuncs uint<br>	mutex        sync.RWMutex<br>}</pre><p><strong>Fields:</strong></p><ul><li>bitset: Byte slice representing the bit array.</li><li>bitSize: Total number of bits in the array.</li><li>numHashFuncs: Number of hash functions used.</li><li>mutex: Ensures thread-safe operations.</li></ul><h4>7. Constructor: NewBloomFilter</h4><pre>func NewBloomFilter(n int, fp float64) *BloomFilter {<br>	m := optimalBitSize(n, fp)<br>	k := optimalHashFuncs(m, n)<br>	// Initialize the bitset with the number of bytes needed<br>	byteSize := (m + 7) / 8 // Round up to the nearest byte<br>	return &amp;BloomFilter{<br>		bitset:       make([]uint8, byteSize),<br>		bitSize:      m,<br>		numHashFuncs: k,<br>	}<br>}</pre><ul><li>Calculates the optimal bit array size (m) based on the expected number of elements (n) and the desired false positive probability (fp).</li><li>Determines the optimal number of hash functions (k) using the formula: k=mnln⁡2k = \frac{m}{n} \ln 2k=nm​ln2</li><li>Initializes the bit array accordingly.</li></ul><h4>8. Adding Elements: Add in BloomFilter</h4><pre>func (bf *BloomFilter) Add(item string) bool {<br>	bf.mutex.Lock()<br>	defer bf.mutex.Unlock()</pre><pre>	hashes := bf.getHashes(item)<br>	isNew := false<br>	for _, hash := range hashes {<br>		byteIndex := hash / 8<br>		bitIndex := hash % 8<br>		if (bf.bitset[byteIndex] &amp; (1 &lt;&lt; bitIndex)) == 0 {<br>			isNew = true<br>			bf.bitset[byteIndex] |= (1 &lt;&lt; bitIndex)<br>		}<br>	}<br>	return isNew<br>}</pre><ul><li>Generates multiple hash indices for the item.</li><li>Sets the corresponding bits in the bit array.</li><li>Returns true if at least one bit was newly set, indicating the item might be new to the set.</li></ul><h4>9. Checking Membership: MightContain in BloomFilter</h4><pre>func (bf *BloomFilter) MightContain(item string) bool {<br>	bf.mutex.RLock()<br>	defer bf.mutex.RUnlock()</pre><pre>	hashes := bf.getHashes(item)<br>	for _, hash := range hashes {<br>		byteIndex := hash / 8<br>		bitIndex := hash % 8<br>		if (bf.bitset[byteIndex] &amp; (1 &lt;&lt; bitIndex)) == 0 {<br>			return false<br>		}<br>	}<br>	return true<br>}</pre><ul><li>Generates hash indices for the item.</li><li>Checks if all corresponding bits are set.</li><li>Returns true if the item might be present; otherwise, false.</li></ul><h4>10. Hash Generation: getHashes</h4><pre>func (bf *BloomFilter) getHashes(item string) []uint {<br>	data := md5.Sum([]byte(item))<br>	hash1 := binary.BigEndian.Uint32(data[0:4])<br>	hash2 := binary.BigEndian.Uint32(data[4:8])<br>	hashes := make([]uint, bf.numHashFuncs)<br>	for i := uint(0); i &lt; bf.numHashFuncs; i++ {<br>		combinedHash := hash1 + uint32(i)*hash2<br>		hashes[i] = uint(combinedHash) % bf.bitSize<br>	}<br>	return hashes<br>}</pre><ul><li>Utilizes <strong>double hashing</strong> to generate multiple hash values from two base hashes derived from the MD5 hash of the item.</li><li>Ensures efficient computation of multiple hash functions without significant overhead.</li></ul><h4>11. Optimal Bit Size and Hash Functions</h4><pre>func optimalBitSize(n int, p float64) uint {<br>	m := -float64(n) * math.Log(p) / (math.Pow(math.Log(2), 2))<br>	return uint(math.Ceil(m))<br>}</pre><pre>func optimalHashFuncs(m uint, n int) uint {<br>	k := (float64(m) / float64(n)) * math.Log(2)<br>	return uint(math.Round(k))<br>}</pre><p><strong>Purpose:</strong> Calculate the optimal size of the bit array and the number of hash functions to minimize the false positive rate.</p><h4>12. Configuration Loading: loadConfig</h4><pre>func loadConfig(filepath string) (Config, error) {<br>	var config Config<br>	data, err := ioutil.ReadFile(filepath)<br>	if err != nil {<br>		return config, err<br>	}<br>	err = json.Unmarshal(data, &amp;config)<br>	return config, err<br>}</pre><p><strong>Functionality:</strong> Loads configuration parameters from a JSON file, enabling dynamic configuration.</p><h3>Configuration and Usage</h3><p>The implementation allows for dynamic configuration either through a JSON file or by using default parameters via command-line flags.</p><h4>1. Configuration File (config.json)</h4><p>Create a config.json file with the following structure:</p><pre>{<br>    &quot;initial_fp&quot;: 0.01,<br>    &quot;growth_factor&quot;: 2.0,<br>    &quot;tightening_ratio&quot;: 0.5,<br>    &quot;initial_capacity&quot;: 1000<br>}</pre><p><strong>Parameters:</strong></p><ul><li>initial_fp: Initial false positive rate (e.g., 1%).</li><li>growth_factor: Factor by which the capacity grows for each new Bloom filter (e.g., 2.0 doubles the capacity).</li><li>tightening_ratio: Ratio to reduce the false positive rate for each new Bloom filter (e.g., 0.5 halves the false positive rate).</li><li>initial_capacity: Expected number of elements in the first Bloom filter.</li></ul><h4>2. Running the Program</h4><ul><li><strong>Using Default Configuration:</strong></li></ul><p>go run main.go -defaults=true</p><p><strong>Using Custom Configuration:</strong></p><ul><li>go run main.go -config=config.json</li></ul><h4>3. Sample Output</h4><pre>Contains &#39;apple&#39;: true<br>Contains &#39;banana&#39;: true<br>Contains &#39;cherry&#39;: true<br>Contains &#39;date&#39;: true<br>Contains &#39;kiwi&#39;: false<br>Contains &#39;lemon&#39;: false</pre><p><strong>Note:</strong> Due to the probabilistic nature of Bloom Filters, false results are definitive negatives, whereas true results indicate that the element might be present (with a controlled false positive rate).</p><h3>Applications of Bloom Filters</h3><p>Bloom Filters are versatile and find applications across various domains, especially where space and speed are critical.</p><ol><li><strong>Databases and Caches:</strong></li></ol><ul><li><strong>Caching Systems:</strong> Quickly check if a data item is present in the cache to avoid unnecessary database queries.</li><li><strong>Database Queries:</strong> Filter out non-existent records early in the query process, enhancing performance.</li></ul><p><strong>2. Networking:</strong></p><ul><li><strong>Packet Routing:</strong> Efficiently determine if a packet has been processed or detect duplicate packets.</li><li><strong>Web Crawlers:</strong> Prevent visiting the same URL multiple times, optimizing crawling efficiency.</li></ul><p><strong>3. Security:</strong></p><ul><li><strong>Spam Filters:</strong> Check if an email is in a blacklist.</li><li><strong>Intrusion Detection Systems:</strong> Recognize malicious patterns efficiently.</li></ul><p><strong>4. Distributed Systems:</strong></p><ul><li><strong>Big Data Processing:</strong> Manage large datasets across distributed nodes with minimal memory overhead.</li><li><strong>Content Delivery Networks (CDNs):</strong> Efficiently manage and distribute content requests.</li></ul><p><strong>5. Blockchain and Cryptocurrencies:</strong></p><ul><li><strong>Bitcoin:</strong> Use Bloom Filters for compact representation of transaction data.</li><li><strong>Ethereum:</strong> Employ Bloom Filters for efficient log searching.</li></ul><h3>Best Practices and Considerations</h3><p>While Bloom Filters are powerful, their effectiveness hinges on appropriate parameter selection and understanding their limitations.</p><ol><li><strong>Choosing Optimal Parameters:</strong></li></ol><ul><li><strong>False Positive Rate (</strong><strong>initial_fp):</strong> Lower rates reduce false positives but increase memory usage.</li><li><strong>Growth Factor:</strong> Determines how aggressively the filter scales. A higher factor reduces the number of filters but increases each filter’s capacity exponentially.</li><li><strong>Tightening Ratio:</strong> Controls the reduction in false positive rates for subsequent filters. A balance ensures efficient scaling without excessive memory consumption.</li></ul><p><strong>2. Efficient Hash Functions:</strong></p><ul><li>While the implementation uses MD5 for hashing, consider using faster, non-cryptographic hash functions like <strong>MurmurHash</strong> or <strong>FNV</strong> for performance-critical applications.</li></ul><p><strong>3. Memory Management:</strong></p><ul><li>Monitor the cumulative size of all Bloom filters to ensure memory usage remains within acceptable bounds, especially in large-scale deployments.</li></ul><p><strong>4. Concurrency:</strong></p><ul><li>The implementation employs sync.RWMutex for thread-safe operations. In highly concurrent environments, consider optimizing lock granularity or exploring lock-free data structures.</li></ul><p><strong>5. Serialization and Persistence:</strong></p><ul><li>For distributed systems, consider serializing Bloom filters for network transmission or persistent storage. Implement serialization methods (e.g., JSON, Gob) to facilitate easy transmission and storage.</li></ul><p><strong>6. Monitoring and Metrics:</strong></p><ul><li>Track metrics like the number of Bloom filters, total capacity, and actual false positive rates to ensure the system operates as expected.</li></ul><p><strong>7. Testing:</strong></p><ul><li>Rigorously test the Bloom Filter with diverse datasets to validate its accuracy and performance. Implement unit tests and benchmarks to measure efficiency.</li></ul><h3>Conclusion</h3><p>Bloom Filters, with their remarkable space efficiency and speed, are indispensable tools in modern computing. Their scalable variants, like the Scalable Bloom Filter implemented above, extend their utility to dynamic and large-scale applications, making them ideal for distributed systems where data grows unpredictably.</p><p>By understanding the core principles, implementing robust configurations, and adhering to best practices, you can harness the full potential of Bloom Filters in your projects. Whether you’re optimizing database queries, enhancing network protocols, or securing systems, Bloom Filters offer a blend of efficiency and reliability that is hard to match.</p><p>Embrace the power of probabilistic data structures and elevate your application’s performance to new heights!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*x9vk92j4E-axvFBIrK706w.gif" /></figure><p><strong>Github link:</strong> <a href="https://github.com/Jitender271/go-bloom-filter/tree/main">https://github.com/Jitender271/go-bloom-filter/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d775fe8c5a96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Raft Algorithm: Consensus and Leader Election Explained]]></title>
            <link>https://medium.com/@jitenderkmr/understanding-raft-algorithm-consensus-and-leader-election-explained-faadf28fd047?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/faadf28fd047</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Wed, 15 May 2024 14:49:19 GMT</pubDate>
            <atom:updated>2024-05-15T15:01:02.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*bDsKmut0k5j43VbgMktjbw.jpeg" /></figure><h3>Introduction</h3><p>In the world of distributed systems, ensuring that nodes can agree on a single, consistent state is crucial. Raft is a consensus algorithm designed to achieve this by providing fault tolerance and ensuring that a single leader is elected to coordinate operations. In this article, we’ll delve into Raft’s core concepts, focusing on consensus and leader election. We’ll also provide a practical example in Go to illustrate how Raft works in action.</p><h3>What is Raft Algorithm?</h3><p>Raft is a consensus algorithm developed by Diego Ongaro and John Ousterhout at Stanford University. It’s designed to be easier to understand than previous algorithms like Paxos while providing strong fault tolerance and leader election capabilities.</p><h3>Core Concepts:</h3><ol><li><strong>Nodes (Servers): </strong>In Raft, the network is composed of several nodes or servers.</li><li><strong>Leader:</strong> One of the nodes in the Raft cluster is elected as the leader. The leader is responsible for managing the replication of logs across the cluster.</li><li><strong>Follower:</strong> All other nodes in the cluster are followers. They respond to requests from the leader and forward client requests to the leader.</li><li><strong>Candidate:</strong> When a leader fails, a new leader needs to be elected. Nodes transition to the candidate state and initiate an election.</li><li><strong>Term:</strong> Raft operates in terms, where each term begins with an election and ends with a new leader being elected or re-elected.</li><li><strong>Log Replication:</strong> Raft ensures that all logs across the cluster are replicated and maintained in the same order.</li></ol><h3>Consensus and Leader Election:</h3><p>The primary goal of Raft is to achieve consensus among nodes in the cluster regarding the state of the system. Here’s how it works:</p><ol><li><strong>Leader Election:</strong></li></ol><ul><li>At the beginning of each term, nodes start as followers.</li><li>If a follower doesn’t hear from the leader for a certain period (election timeout), it transitions to the candidate state.</li><li>The candidate requests votes from other nodes. If it receives votes from the majority, it becomes the leader.</li><li>If no node receives a majority, a new election is started in the next term.</li></ul><p>2. <strong>Log Replication and Consistency:</strong></p><ul><li>The leader accepts client requests and appends them to its log.</li><li>It then sends the log entry to followers, which replicate the log entry.</li><li>Once a majority of followers acknowledge the entry, it’s committed to the log and applied to the state machine.</li></ul><p>We can definitely elaborate more on the Raft consensus algorithm and its components for a deeper understanding. Here’s a more detailed explanation of the components and syncing process:</p><h3>Consensus in Raft</h3><p>Raft’s approach to consensus is crucial for ensuring the integrity and consistency of the distributed system. Consensus is achieved through a series of steps:</p><ol><li><strong>Log Replication:</strong></li></ol><ul><li>When a client initiates an operation, such as setting a key-value pair, the leader node receives the request.</li><li>The leader appends the operation to its log and broadcasts this log entry to all other nodes in the cluster, including peer nodes.</li><li>Each node in the cluster appends the log entry to its log.</li></ul><p>2. <strong>Majority Agreement:</strong></p><ul><li>Raft operates on the principle of majority agreement. Before committing an operation to its state machine, the leader node waits for acknowledgments from most nodes.</li><li>If most of the nodes(Say N/2 + 1) acknowledge the operation by replicating it in their logs, the leader commits the operation to its state machine.</li><li>This ensures that the operation is officially part of the system’s state and will be applied consistently across all nodes.</li></ul><p>Additionally, the leader regularly sends updates to the other servers to keep them in sync. This ensures that even if a server falls behind or crashes, it can quickly catch up with the latest state of the key-value store.</p><p>Now, for a <strong>demo</strong>: <br>Let’s say we have 3 servers, <strong>server1, server2 and server3</strong>. Server1 becomes the leader through a process called leader election (we’ll talk more about that later). When the client sends requests to set keys (like A, B) to certain values, server1 waits for a majority of the servers to agree before confirming to the client. <br>Meanwhile, it sends the request to server2 and server3 for backup. Once it gets confirmation from the majority, it tells the client it’s done and keeps the other servers updated. During this process, you’ll see messages indicating that the leader is waiting for agreement while the client waits for a response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GlxOOXbxcRCDk5MLFD0qQ.png" /><figcaption>Consensus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkefvK5gamyHSR-qLukL9w.png" /></figure><h3>Syncing with Peer Nodes</h3><p>Syncing with peer nodes is a crucial aspect of Raft’s design to maintain consistency and bring new nodes up to speed. Here’s how it works:</p><ol><li><strong>Syncing New Servers:</strong></li></ol><ul><li>When a new server (e.g., ServerThree) joins the Raft cluster, it needs to catch up with the current state of the key-value store.</li><li>To achieve this, the leader node sends a series of log entries to the new server, ensuring that it has a complete copy of the log.</li><li>These log entries include all previous operations, such as SET A 1, SET B 2.</li></ul><p>2. <strong>Determining Logs for Sync-Up:</strong></p><ul><li>The leader server determines which logs to send for the sync-up process based on the last acknowledged log index for each peer node.</li><li>If a peer node has acknowledged logs up to index k, the leader sends logs from index k+1 to the last log (n) for syncing.</li><li>This process ensures that the new server receives all operations it missed and brings it up to date with the latest state of the key-value store.</li></ul><p>3. <strong>Handling Sync-Up Errors:</strong></p><ul><li>If the leader node is not aware of the last acknowledged log index of a peer node, it uses a hit-and-trial approach.</li><li>The leader starts from the end of its log index and decrements the index based on responses from the peer node.</li><li>If the peer node does not have the logs before the index sent as part of the sync-up request, it returns an error.</li><li>This iterative process ensures that the new server receives the correct logs for syncing.</li></ul><p>The sync-up process should be triggered at a pre-defined interval, taking into account factors such as the number of nodes in the system and the frequency of node additions or removals. In the above use case, a sync-up interval of 3 seconds is used, meaning the leader server sends a sync-up message every 3 seconds to ensure all peer nodes are updated.</p><h3><strong>Leader Election</strong></h3><p>In case the leader node fails, peer nodes monitor for a sync-up request from the leader within a set threshold. If this threshold is exceeded, a peer node assumes leadership is unavailable and triggers a leader election. It requests votes from other nodes, and upon receiving a majority, announces itself as the new leader. Each node randomizes its threshold to prevent simultaneous elections. This threshold must exceed the sync-up interval to prevent premature leader declarations.</p><p>In a demonstration, if we have three servers and server1 becomes leader, and then server1 fails, server3 detects the failure and initiates an election. After obtaining a majority vote, it becomes the new leader. The client seamlessly resumes operations with the new leader, ensuring continuity in the key-value store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlWIOGf8zOfn5NINFoaSoA.png" /><figcaption>server1 is leader</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8a3jzLLdF74YxFrDa4vBSQ.png" /><figcaption>server3 is leader</figcaption></figure><h3>Used in Production</h3><p>The Raft algorithm has been adopted by several popular distributed systems for ensuring reliability and consistency. Some notable systems that use Raft include:</p><ul><li><strong>Apache Kafka:</strong> Kafka, a distributed streaming platform, employs Raft for managing metadata and coordinating brokers in the cluster.</li><li><strong>ScyllaDB:</strong> ScyllaDB, a high-performance NoSQL database, utilizes Raft for leader election and coordination among nodes for consistency and fault tolerance.</li><li><strong>etcd:</strong> etcd is a distributed key-value store used for configuration management, service discovery, and coordination. It relies on Raft for distributed consensus to ensure consistency and fault tolerance.</li><li><strong>TiKV:</strong> TiKV is a distributed transactional key-value database built to support the TiDB distributed SQL database. It uses Raft for distributed coordination and replication of data across nodes.</li><li><strong>Consul:</strong> Consul is a service mesh and service discovery tool that provides key-value storage for configuration, health checking, and distributed coordination. It employs Raft for consensus among nodes in a Consul cluster.</li></ul><p>There are lot of improvements that can be done, some which are:</p><ol><li><strong>Binary Search for Log Index:</strong> Instead of decrementing the log index by one during sync-up, a binary search can optimize the process, particularly with large log sizes, reducing back-and-forth iterations.</li><li><strong>Handling Split Brain Problem:</strong> Currently, the implementation doesn’t address the split brain problem, where two nodes may both assume leadership. This can lead to inconsistencies in the key-value store. Strategies need to be implemented to prevent such scenarios and ensure consistency.</li><li>Reference to <strong>Martin Kleppmann’s Explanation</strong>: Martin Kleppmann’s detailed explanation of the Raft algorithm provides valuable insights, aiding in debugging and understanding the consensus and leader election processes.</li></ol><p>The implementation code is available on <a href="https://github.com/Jitender271/go-raft"><strong>GitHub</strong></a>, offering a hands-on understanding of the Raft algorithm. Exploring more technical papers in this manner could be beneficial for deeper insights into distributed systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*-Gz4dan28YqRUsnNkGthgw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faadf28fd047" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a System Like Pastebin: Key Components and Strategies]]></title>
            <link>https://medium.com/@jitenderkmr/designing-a-system-like-pastebin-key-components-and-strategies-07f7bdcf5c04?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/07f7bdcf5c04</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Wed, 08 May 2024 06:18:34 GMT</pubDate>
            <atom:updated>2024-05-08T06:18:34.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*qxDTQrA1zV8QlFvQEy6uaQ.jpeg" /></figure><h3>What is Pastebin?</h3><p>Pastebin serves as an online platform where users can seamlessly paste and store text for a designated period. Upon visiting the website, users simply input their text into a provided box. Following this, they have the option to specify the duration for which the text remains accessible, ranging from months to years.</p><p>Once the text is pasted, Pastebin generates a unique URL, facilitating easy sharing with others. This URL enables recipients to view the text content. However, upon expiry of the designated time frame, the URL becomes inactive, leading to the deletion of the text from Pastebin’s servers.</p><p>Primarily, Pastebin serves two key functions: temporary storage of text and effortless sharing capabilities. It eliminates the necessity of owning a personal website or server for text-sharing purposes.</p><p><strong>Clarifying the System Design</strong></p><p>To ensure clarity in system design, it’s essential to address several key questions:</p><ul><li><strong>Text Size Limit:</strong> Are there any restrictions on the size of text that users can paste?</li><li><strong>Granularity of Expiry Options:</strong> How detailed are the expiry options provided to users?</li><li><strong>Inclusion of Title:</strong> Do pastes come with an option for users to include a title?</li><li><strong>Custom ID Feature:</strong> Is there a provision for users to choose custom IDs for their pastes?</li><li><strong>Premium User Features:</strong> Are there premium tiers with additional benefits?</li><li><strong>Access Control:</strong> Is there an access layer allowing users to share pastes selectively or make them private?</li><li><strong>Guest Access:</strong> Can users utilize Pastebin without the need for authentication?</li><li><strong>Expected Scale:</strong> What level of traffic and usage are we anticipating?</li></ul><p><strong>System Requirements</strong></p><p>In formulating the system’s requirements, we aim to cater to both functional and non-functional aspects:</p><p><strong>Functional Requirements</strong></p><ul><li>Users should be able to paste and save text.</li><li>Unique URLs must be generated for shared content.</li><li>Default expiry durations need to be set.</li><li>Access to expired links should be restricted.</li><li>Logged-in users should have access to their paste history.</li><li>Premium users should have access to enhanced features.</li></ul><p><strong>Non-functional Requirements</strong></p><ul><li>High <strong>availability</strong> is a priority for uninterrupted access.</li><li><strong>Minimal latency</strong> is required for optimal user experience.</li><li>Non-predictable IDs must be used for URL generation.</li><li><strong>Horizontal scalability</strong> is needed to accommodate increased traffic.</li><li>Rate limiting mechanisms should be implemented to prevent abuse and manage quotas effectively.</li></ul><p><strong>Resource Estimation</strong></p><p>To ensure our system can handle the anticipated scale effectively, we need to estimate the hardware resources required. Let’s break down our estimations:</p><p><strong>Approximation Tips</strong></p><ul><li>Number of seconds in a day: 24 * 60 * 60 = 86,400</li><li>1 million requests per day =&gt; 10⁶ / 86,400 ≈ 12 requests per second</li></ul><p><strong>Load Assumptions</strong></p><ul><li>10 million write requests per day</li><li>On average, each user generates 10 links per day, implying 1 million daily active users (DAU)</li><li>Assuming reads are 10 times more frequent than writes, resulting in 100 million reads per day</li><li>Peak traffic is 10 times the average traffic, translating to approximately 12 requests per second for 1 million requests per day, 120 requests per second for 10 million requests per day, and 1,200 requests per second during peak traffic.</li></ul><p><strong>Storage Estimation</strong></p><ul><li>Considering text sizes, we assume:</li><li>50% of pastes are &lt;5KB (2KB average)</li><li>30% of pastes are 5–25KB (15KB average)</li><li>20% of pastes are 25–100KB (60KB average)</li><li>With an average of 20KB per paste, we estimate storage requirements.</li><li>Additional data fields like title, created_at, and userInfo are negligible.</li><li>We’ll store text data in blob storage (e.g., AWS S3), optimizing by storing smaller text sizes directly and linking larger text sizes.</li><li>For 10 years, with 10 million objects of 1KB per day, our total database storage requirement would be approximately 11TB.</li><li>Assuming 80% of requests have text larger than 1KB, our blob storage requirement would be around 180TB.</li></ul><p><strong>Cache Estimation</strong></p><ul><li>Assuming 20% of URLs contribute to 80% of the traffic, and with 100 million read requests per day, we estimate a cache size of 20GB to accommodate frequently accessed content.</li></ul><p><strong>Bandwidth Estimation</strong></p><ul><li>During peak hours, with 1,200 write requests per second and an average object size of 20KB, incoming data would be approximately 24MBps.</li><li>Similarly, with reads being 10 times more frequent than writes, outgoing data would be around 240MBps.</li></ul><p>By meticulously estimating these factors, we can ensure our system is adequately provisioned to handle the expected load while maintaining optimal performance and scalability.</p><p><strong>High-Level Design for a Pastebin System</strong></p><p>Before delving into the design phase, it’s crucial to explore various database options along with their advantages and disadvantages. When considering the database choice, analyzing our data and access patterns, including query, read, and write patterns, is imperative.</p><p><strong>Database Options</strong></p><ul><li><strong>MongoDB:</strong> A popular NoSQL document database storing data in flexible JSON-like documents. It scales well and offers features like indexing and query optimizations for quick paste retrieval.</li><li><strong>PostgreSQL:</strong> A relational open-source database with reliability, scalability, and data integrity. It supports the JSONB datatype for flexible document-style storage.</li><li><strong>DynamoDB:</strong> A fully managed NoSQL database provided by AWS, offering low latency and high throughput performance. It automatically handles backups and scaling.</li><li><strong>Elasticsearch:</strong> Often used as a search engine database, capable of document-style storage and advanced search queries.</li></ul><p><strong>Choice of Database:</strong></p><p>For the Pastebin system:</p><ul><li><strong>Main Storage:</strong> Utilize a key-value store like DynamoDB.</li><li><strong>Text Storage:</strong> Use Blob storage like AWS S3 for texts exceeding 10KB.</li><li><strong>Cache:</strong> Implement Redis for caching and subscribing to expired events for efficient paste deletion.</li></ul><p><strong>High-Level Design:</strong></p><p><strong>Read Flow</strong></p><ol><li><strong>Client Request for Paste:</strong> User initiates a request to access a specific paste.</li><li><strong>CDN Check:</strong> Client checks local or CDN cache for the paste.</li><li><strong>Cache Hit:</strong> If paste is found and fresh, CDN serves it directly to the user.</li><li><strong>Cache Miss:</strong> If paste is stale or not found, CDN requests it from Pastebin’s origin server.</li><li><strong>Origin Server Processing:</strong> Pastebin’s server processes the request, retrieves the paste, and sends it to CDN.</li><li><strong>CDN Update:</strong> CDN caches the paste and serves it to the user.</li><li><strong>User Receives Paste:</strong> User receives the paste from the CDN.</li><li><strong>Subsequent Requests:</strong> CDN serves subsequent requests from its cache or fetches a new copy if necessary.</li></ol><p><strong>Write Flow</strong></p><ol><li><strong>Client Request to Create Paste:</strong> User requests to create a new paste.</li><li><strong>API Gateway Check Rate Limiter:</strong> API Gateway checks request frequency.</li><li><strong>Forward Request to Write Load Balancer:</strong> API Gateway forwards the request to the Write Load Balancer.</li><li><strong>Write Server Processes Request:</strong> Write server checks key availability and writes paste metadata to the key-value store.</li><li><strong>Large Paste Data Handling:</strong> If data exceeds 10KB, Write server stores it in an Object Store.</li><li><strong>Update Bloom Filter:</strong> Write server updates Bloom filter for efficient membership tests.</li><li><strong>Write Key to Redis:</strong> Write server stores key in Redis with expiration time.</li><li><strong>Paste Deletion Service:</strong> Service subscribed to Redis events for automatic paste metadata deletion.</li><li><strong>Response to Client:</strong> Write server returns the key associated with the created paste to the client.</li></ol><p>This design ensures efficient creation and retrieval of pastes while maintaining data integrity and scalability. Integration of Redis and Bloom filter enhances system efficiency and reliability.</p><p><strong>Bloom Filter:</strong></p><p>A space-efficient probabilistic data structure used for set membership tests, indicating whether a key is possibly in the set or definitely not.</p><p><strong>High-Level Design Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTr___RBr_anq_Sbpv93Qw.png" /></figure><p><strong>Deep Dive: Exploring the Key Generation Service</strong></p><p>In our journey through designing the Pastebin system, it’s crucial to dissect specific components to understand their intricacies fully. One such critical element is the Key Generation Service, which plays a central role in ensuring the seamless creation of pastes while maintaining system resilience and scalability.</p><p><strong>Attributes of Paste Keys:</strong></p><ol><li><strong>Compact PasteId Length</strong>: PasteIds ideally range from 8 to 12 characters, creating concise URLs for easy sharing. This enhances usability by simplifying the sharing process.</li><li><strong>Integer Mapping for Query Performance:</strong> Correlating PasteIds to integers boosts query performance, enabling faster data retrieval. This optimization enhances the system’s efficiency.</li><li><strong>Randomization Property: </strong>Incorporating randomness in key generation strengthens security by thwarting predictable sequences, thus mitigating security risks.</li><li><strong>Rapid Key Generation and Distribution:</strong> A swift and efficient key generation process ensures seamless operations, even during peak traffic scenarios.</li></ol><p><strong>Approach for Key Generation Service:</strong></p><p><strong>Range Generation Service:</strong></p><ul><li><strong>Long Integer Capacity:</strong> Leveraging snowflake ids allows for a vast range of values, ensuring an extensive supply of keys for an extended period, even with high consumption rates.</li><li><strong>Lightweight, Highly Available Service:</strong> A lightweight service maintains a record of distributed snowflake ids, ensuring resilience and availability.</li><li><strong>Key Distribution Request:</strong> Write servers request new sets of snowflake ids from the key generation service, which promptly responds to these requests.</li><li><strong>Range Distribution:</strong> The key generation service assigns designated ranges of snowflake ids to write servers, based on the current distribution point, enabling local management.</li><li><strong>Local Key Management:</strong> Write servers manage distributed snowflake ids locally, proactively requesting new sets as exhaustion nears.</li><li><strong>Random Key Selection:</strong> Write servers autonomously select snowflake ids from their assigned range, adding unpredictability to the assignment process and enhancing system security.</li></ul><p>By employing this range-based key generation strategy and considering the use of snowflake ids, the Pastebin system ensures sustained key availability, high availability, and scalability across multiple write servers.</p><p>If you’re interested in learning more about Snowflake Key Generation, feel free to explore it further by visiting <a href="https://medium.com/@jitenderkmr/demystifying-snowflake-ids-a-unique-identifier-in-distributed-computing-72796a827c9d">here</a>.</p><p>In summary, the Pastebin system intricately balances key components to ensure user-friendly functionality and efficiency. Utilizing an SQL or NoSQL database, thoughtful key generation, and additional security measures like a Bloom filter, the system remains robust. Moreover, the integration of a Content Delivery Network enhances global content delivery, showcasing adaptability and foresight. As we navigate the complexities of large data handling, rate limiting, and content expiration, the Pastebin system exemplifies a versatile and effective solution, embodying modern web application design principles.</p><p><strong>Food for Thought:</strong></p><ol><li><strong>Implementing Premium User Features:</strong> Enhance user experience and revenue generation by offering exclusive benefits or advanced functionalities to premium users.</li><li><strong>Enabling Custom URLs:</strong> Allow users to personalize their paste URLs for a more tailored and user-friendly experience.</li><li><strong>Pastebin as a Service:</strong> Explore the potential of offering Pastebin services tailored for corporate use, addressing unique needs such as enhanced security and collaboration features.</li></ol><p>Thank you for taking the time to engage with my article. Your interest and attention are truly appreciated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*8knZvAH9Ae9D36T6rEaDvA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07f7bdcf5c04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leader Election Using Bully Algorithm in Go]]></title>
            <link>https://medium.com/@jitenderkmr/leader-election-using-bully-algorithm-in-go-60ec03bd277c?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/60ec03bd277c</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Tue, 19 Mar 2024 17:43:03 GMT</pubDate>
            <atom:updated>2024-03-19T17:43:38.108Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leader Election: Using Bully Algorithm in Golang</h3><p>Distributed systems often require a way to elect a leader among a group of nodes to ensure efficient coordination and decision-making. <br>The Bully Algorithm is one such algorithm used for leader election in distributed systems. In this article, we’ll implement the Bully Algorithm in Go to understand how nodes in a cluster can elect a leader.</p><h3>Introduction to Bully Algorithm</h3><p>The Bully Algorithm is a simple and effective method for leader election in a distributed system. It works as follows:</p><ol><li>Node Hierarchy: Each node in the system has a unique ID, and nodes are aware of each other’s IDs.</li><li>Leader Detection: If a node detects that the current leader is unresponsive (failed), it initiates an election process.</li><li>Election: The node initiating the election (the “bully”) sends an election message to all nodes with higher IDs. If no higher ID node responds, the “bully” wins and becomes the new leader.</li><li>Coordinator: The leader acts as a coordinator for the system, making decisions and managing the distributed tasks.</li></ol><h3>Process Overview</h3><p>In the <a href="https://en.wikipedia.org/wiki/Bully_algorithm">bully algorithm</a>, the fundamental idea is <strong>rank</strong>. It assumes that every node has a rank within the cluster, and the leader must be the highest. So it uses the node’s rank value during the election.</p><p>There are two situations for election.</p><ul><li>The system is newly initialized, so there is no leader</li><li>One of the nodes notices that the leader is down.</li></ul><p>The election is implemented as follows:</p><ol><li>The node sends <strong>ELECTION</strong> messages to the other nodes with higher ranks than their own.</li><li>The node waits for <strong>ALIVE</strong> responses.</li></ol><ul><li>If no higher-ranked node responds, it makes itself a leader.</li><li>Otherwise, it is notified of the new leader who has the highest rank.</li></ul><p>Let’s illustrate these scenarios:</p><p>We assumed that the highest rank order, like: <strong>node-04 &gt; node-03 &gt; node-02 &gt; node-01</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNYpPVx_bapjsQ2ajo06NA.png" /><figcaption>Election State</figcaption></figure><p>Since node-04 has the highest rank in this cluster, it didn&#39;t receive any ALIVE messages from nodes with higher ranks. So, node-04 decided to become the leader and sent an ELECTED message to inform the other nodes about the election results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*G9LH38hm_d0ateTTzCWwtg.png" /><figcaption>Leader Elected(Node-4)</figcaption></figure><h3>When the leader is down</h3><p>The other nodes periodically send <strong>PING</strong> messages to notice the leader is down and wait for the leader’s <strong>PONG</strong> responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*HOXJT4-foqENi5dyok04tw.png" /><figcaption>Ping-Pong(Leader — Node4)</figcaption></figure><p>If the leader is down and the first node doesn’t get a <strong>PONG</strong> message, that node starts the election process again.</p><h3>Implementing the Bully Algorithm in Go</h3><h4>Node.go</h4><pre>var nodeAddressByID = map[string]string{<br>	&quot;node-01&quot;: &quot;node-01:6001&quot;,<br>	&quot;node-02&quot;: &quot;node-02:6002&quot;,<br>	&quot;node-03&quot;: &quot;node-03:6003&quot;,<br>	&quot;node-04&quot;: &quot;node-04:6004&quot;,<br>}<br><br>type Node struct {<br>	ID       string<br>	Addr     string<br>	Peers    *Peers<br>	eventBus event.Bus<br>}</pre><ul><li>Hardcoded all nodes for simplicity.</li><li>This file defines the Node struct, which represents a single node in the distributed system. The node has an ID, network address (Addr), a list of known peers (Peers), and an event bus (eventBus) for communication.</li><li>nodeAddressByID: This map holds the addresses of all nodes in the cluster. Each node has a unique ID mapped to its network address.</li></ul><pre>func NewNode(nodeID string) *Node {<br>	node := &amp;Node{<br>		ID:       nodeID,<br>		Addr:     nodeAddressByID[nodeID],<br>		Peers:    NewPeers(),<br>		eventBus: event.NewBus(),<br>	}<br><br>  node.eventBus.Subscribe(event.LeaderElected, node.PingLeaderContinuously)<br>  return node<br>}</pre><ul><li>NewNode(nodeID string): Creates a new Node with the given ID, initializing its address, peer set, and event bus.</li><li>eventBus.Subscribe: Subscribes the node to the LeaderElected event, triggering the PingLeaderContinuously function when this event occurs</li></ul><pre>func (node *Node) NewListener() (net.Listener, error) {<br>	addr, err := net.Listen(&quot;tcp&quot;, node.Addr)<br>	return addr, err<br>}</pre><ul><li>NewListener(): This method creates a new TCP listener on the node&#39;s network address (node.Addr) for handling incoming connections from other nodes.</li></ul><pre>func (node *Node) ConnectToPeers() {<br>	for peerID, peerAddr := range nodeAddressByID {<br>		if node.IsItself(peerID) {<br>			continue<br>		}<br><br>		rpcClient := node.connect(peerAddr)<br>		pingMessage := Message{FromPeerID: node.ID, Type: PING}<br>		reply, _ := node.CommunicateWithPeer(rpcClient, pingMessage)<br><br>		if reply.IsPongMessage() {<br>			log.Debug().Msgf(&quot;%s got pong message from %s&quot;, node.ID, peerID)<br>			node.Peers.Add(peerID, rpcClient)<br>		}<br>	}<br>}</pre><ul><li>ConnectToPeers(): Establishes RPC connections to all peers in the cluster. It iterates through each peer in nodeAddressByID, connecting to them and sending a PING message.</li><li>If a peer responds with a PONG message, it adds the peer to its list of known peers.</li></ul><pre>func (node *Node) connect(peerAddr string) *rpc.Client {<br>retry:<br>	client, err := rpc.Dial(&quot;tcp&quot;, peerAddr)<br>	if err != nil {<br>		log.Debug().Msgf(&quot;Error dialing rpc dial %s&quot;, err.Error())<br>		time.Sleep(50 * time.Millisecond)<br>		goto retry<br>	}<br>	return client<br>}</pre><ul><li>connect(peerAddr string) *rpc.Client: Establishes an RPC client connection to the given peerAddr (peer&#39;s network address).</li><li>If there’s an error dialing, it retries with a 50ms delay using a goto statement.</li></ul><pre>func (node *Node) CommunicateWithPeer(RPCClient *rpc.Client, args Message) (Message, error) {<br>	var reply Message<br><br>	err := RPCClient.Call(&quot;Node.HandleMessage&quot;, args, &amp;reply)<br>	if err != nil {<br>		log.Debug().Msgf(&quot;Error calling HandleMessage %s&quot;, err.Error())<br>	}<br><br>	return reply, err<br>}</pre><ul><li>CommunicateWithPeer: This method sends a message args to a peer via RPC client RPCClient and waits for a reply.</li></ul><p><strong>Peer.go</strong></p><pre>type Peer struct {<br> ID        string<br> RPCClient *rpc.Client<br>}<br><br>type Peers struct {<br> *sync.RWMutex<br> peerByID map[string]*Peer<br>}<br><br>func NewPeers() *Peers {<br> return &amp;Peers{<br>  RWMutex:  &amp;sync.RWMutex{},<br>  peerByID: make(map[string]*Peer),<br> }<br>}<br><br>func (p *Peers) Add(ID string, client *rpc.Client) {<br>                ...<br>}<br><br>func (p *Peers) Delete(ID string) {<br>                ...<br>}<br><br>func (p *Peers) Get(ID string) *Peer {<br>                ...<br>}</pre><p>These are the Peer and Peers structs along with their methods. Peer represents an individual node in the system, and Peers is a collection of peers with methods to add, delete, get, and convert to a list or IDs.</p><h3>Implementation</h3><ul><li>Docker Compose was used to simulate nodes in the cluster, with each node based on the same docker file.</li><li>For the algorithm to work, each node needs to know about the others, which ideally requires a service discovery mechanism.</li><li>Instead of a full service discovery implementation, each node was hardcoded with network information of other nodes.</li><li>This simplification was made for demonstration purposes. A more robust implementation would include a proper service discovery mechanism to dynamically handle node additions and removals.</li></ul><p>During this communication, if the leader is down, its connection is dropped and returns an error so that a new election process will start.</p><ol><li>When the nodes start up, Node-04 becomes the leader because it has the highest rank based on its ID. With no existing leader, Node-04 initiates an election, declares itself as the leader, and broadcasts an ELECTED message to notify the other nodes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZsaRPE7ezccyKVrvMgEZQ.png" /><figcaption>Node-04 Elected as Leader</figcaption></figure><p>2. Next, let’s simulate the scenario where Node-04 is terminated to observe how a new leader is elected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8IIWL4GaKXEMa7Ry2a2mA.png" /><figcaption>Node-03 Elected as Leader</figcaption></figure><h3>Challenges in the Algorithm</h3><ul><li>The algorithm violates the safety guarantee when network partitions occur, leading to the possibility of multiple leaders in different subsets of nodes. This situation, known as “split brain,” can arise.</li><li>There’s a strong bias towards high-ranked nodes, which can be problematic if they are unstable. This bias can result in a constant cycle of reelections when an unstable high-ranked node repeatedly fails and attempts to become the leader again.</li></ul><p>Despite these challenges, the Bully Algorithm provides a clear and practical approach to leader election, making it valuable for fault-tolerant distributed systems.</p><p><strong>GitHub Link: </strong><a href="https://github.com/Jitender271/go-leader-election-bully-algorithm">https://github.com/Jitender271/go-leader-election-bully-algorithm</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Vr0LDMylhE6SYro7GRL0XA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60ec03bd277c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Snowflake IDs: A Unique Identifier in Distributed Computing]]></title>
            <link>https://medium.com/@jitenderkmr/demystifying-snowflake-ids-a-unique-identifier-in-distributed-computing-72796a827c9d?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/72796a827c9d</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 18:33:08 GMT</pubDate>
            <atom:updated>2024-03-18T18:48:46.818Z</atom:updated>
            <content:encoded><![CDATA[<p>In distributed systems, generating unique IDs is crucial for various operations such as logging, database sharding, and data consistency. Snowflake is a popular algorithm used for generating unique IDs in distributed environments. In this article, we’ll explore how to implement a Snowflake-like ID generator in Go.</p><h3>Understanding Snowflake Algorithm</h3><p>The Snowflake algorithm generates unique IDs with the following components:</p><ul><li>Timestamp: The ID’s timestamp indicates when it was generated.</li><li>Node ID: A unique identifier for the node generating the ID.</li><li>Step: A counter that increments for each ID generated within the same timestamp.</li></ul><h3>Setting Up the Go Environment</h3><p>Before diving into the code, ensure Go is installed on your system. You can download it from the official Go website.</p><h3>Implementing the ID Generator</h3><p>Let’s start by defining our requirements and constants:</p><ul><li>Epoch: The starting point for our timestamp. By default, it uses the Twitter Snowflake epoch of Nov 04 2010 01:42:54 UTC in milliseconds (1288834974657).</li><li>NodeBits and StepBits: These represent the number of bits allocated for Node ID and Step. By default, it uses 10 bits for Node and 12 bits for Step.</li></ul><p>Here’s the initial setup:</p><pre>var (<br>	Epoch     int64 = 1288834974657<br>	NodeBits  uint8 = 10<br>	StepBits  uint8 = 12<br>	nodeMax   int64 = -1 ^ (-1 &lt;&lt; NodeBits)<br>	nodeMask        = nodeMax &lt;&lt; StepBits<br>	stepMask  int64 = -1 ^ (-1 &lt;&lt; StepBits)<br>	timeShift       = NodeBits + StepBits<br>	nodeShift       = StepBits<br>)</pre><ul><li>Epoch: Starting timestamp for our IDs.</li><li>NodeBits and StepBits: We decide on 10 bits for the Node ID and 12 bits for the Step.</li><li>nodeMax, nodeMask, stepMask: Masks and max values for bit manipulation.</li><li>timeShift and nodeShift: Shifts for combining timestamp, node ID, and step.</li></ul><h3>Customizing the Snowflake ID Generator</h3><p>You can customize the number of bits used for the node ID and step number (sequence) by setting the snowflake.NodeBits and snowflake.StepBits values. Remember that there is a maximum of 22 bits available that can be shared between these two values. You do not have to use all 22 bits.</p><h3>Setting a Custom Epoch</h3><p>By default, this package uses the Twitter Epoch of 1288834974657 or Nov 04 2010 01:42:54. You can set your epoch value by setting snowflake.Epoch to a time in milliseconds to use as the epoch.</p><h3>Implementing the Node Structure</h3><p>Next, we define the Node structure:</p><pre>type Node struct {<br>	mu    sync.Mutex<br>	epoch time.Time<br>	time  int64<br>	node  int64<br>	step  int64<br>	nodeMax   int64<br>	nodeMask  int64<br>	stepMask  int64<br>	timeShift uint8<br>	nodeShift uint8<br>}</pre><ul><li>Node: Contains fields for timestamp, node ID, step, and necessary bit manipulation values.</li></ul><h3>Creating a New Node</h3><p>We create a NewSnowflakeNode function to initialize a new node:</p><pre>func NewSnowflakeNode(node int64) (*Node, error) {<br><br> if NodeBits+StepBits &gt; 22 {<br>  return nil, errors.New(&quot;Remember, you have a total 22 bits to share between Node/Step&quot;)<br> }<br> // re-calc in case custom NodeBits or StepBits were set<br> mu.Lock()<br> nodeMax = -1 ^ (-1 &lt;&lt; NodeBits)<br> nodeMask = nodeMax &lt;&lt; StepBits<br> stepMask = -1 ^ (-1 &lt;&lt; StepBits)<br> timeShift = NodeBits + StepBits<br> nodeShift = StepBits<br> mu.Unlock()<br><br> n := Node{}<br> n.node = node<br> n.nodeMax = -1 ^ (-1 &lt;&lt; NodeBits)<br> n.nodeMask = n.nodeMax &lt;&lt; StepBits<br> n.stepMask = -1 ^ (-1 &lt;&lt; StepBits)<br> n.timeShift = NodeBits + StepBits<br> n.nodeShift = StepBits<br><br> if n.node &lt; 0 || n.node &gt; n.nodeMax {<br>  return nil, errors.New(&quot;Node number must be between 0 and &quot; + strconv.FormatInt(n.nodeMax, 10))<br> }<br><br> var curTime = time.Now()<br> // add time.Duration to curTime to make sure we use the monotonic clock if available<br> n.epoch = curTime.Add(time.Unix(Epoch/1000, (Epoch%1000)*1000000).Sub(curTime))<br><br> return &amp;n, nil<br>}</pre><p>This function NewSnowflakeNode creates a new Node object.</p><ul><li>It first checks if the sum of NodeBits and StepBits exceeds 22 bits, which is the maximum allowed for sharing between Node and Step.</li><li>If custom NodeBits or StepBits are set, it recalculates the related values such as nodeMax, nodeMask, stepMask, timeShift, and nodeShift.</li><li>It initializes a new Node struct n with the provided node ID.</li><li>It checks if the node ID is within the valid range (between 0 and nodeMax).</li><li>It then calculates the epoch time-based on the provided Epoch, adjusting for the monotonic clock if available, and assigning it to the Node object.</li><li>Finally, it returns a pointer to the created Node object and nil error if everything is successful. If there&#39;s an error (like an invalid node ID), it returns nil and an error message.</li></ul><h3>Generating Unique IDs</h3><p>The Node struct includes a GenerateID method to create unique IDs:</p><pre>func (n *Node) GenerateID() ID {<br><br> n.mu.Lock()<br> defer n.mu.Unlock()<br><br> now := time.Since(n.epoch).Milliseconds()<br><br> if now == n.time {<br>  n.step = (n.step + 1) &amp; n.stepMask<br><br>  if n.step == 0 {<br>   for now &lt;= n.time {<br>    now = time.Since(n.epoch).Milliseconds()<br>   }<br>  }<br> } else {<br>  n.step = 0<br> }<br><br> n.time = now<br><br> r := ID((now)&lt;&lt;n.timeShift |<br>  (n.node &lt;&lt; n.nodeShift) |<br>  (n.step),<br> )</pre><p>The GenerateID method generates a unique ID based on the current timestamp, node ID, and step count.</p><ul><li>This method Generate creates and returns a unique snowflake ID for the given Node.</li><li>It first locks the mutex (n.mu) to ensure the function is goroutine-safe.</li><li>It calculates the current time since the epoch in milliseconds.</li><li>If the current time is the same as the last time an ID was generated (n.time), it increments the step by 1 and applies the stepMask.</li><li>This check ensures that if multiple IDs are generated within the same millisecond, the step continues incrementing but is limited by the stepMask.</li><li>If the step reaches its maximum value and wraps around to 0, it waits until the next millisecond by looping until now is greater than n.time.</li><li>If the current time is different from the last time an ID was generated, it resets the step to 0.</li><li>It then updates the n.time to the current time.</li><li>Finally, it calculates the final snowflake ID r using bitwise operations to combine the timestamp, node ID, and step.</li></ul><h3>Mutex (n.mu)</h3><p>The n.mu mutex is used to ensure that the GenerateID method is goroutine-safe, meaning it can be safely called from multiple goroutines concurrently without causing issues related to data race conditions.</p><h3>Converting IDs</h3><p>We provide methods to convert IDs to various formats:</p><pre>func (f ID) Int64() int64 {<br>  // Convert Snowflake ID to int64<br>}<br>func (f ID) String() string {<br>  // Convert Snowflake ID to string<br>}<br>func (f ID) Base2() string {<br>  // Convert Snowflake ID to base2 string<br>}</pre><p>These methods allow converting IDs to int64, string, and base2 formats.</p><h3>Explaining the 64 Bits</h3><p>In this Snowflake-like ID generator, we use a 64-bit integer (int64) to represent the generated IDs. Here&#39;s how the bits are divided:</p><ul><li>Timestamp (41 bits): The timestamp is the most significant bits, representing milliseconds since the epoch (Epoch). This allows the IDs to be ordered chronologically.</li><li>Node ID (10 bits): The next NodeBits bits represent the unique node ID. Each node in the system is assigned a unique ID to ensure IDs are unique across nodes.</li><li>Step/Sequence (12 bits): The least significant bits represent the sequence number or step within the same millisecond. This ensures uniqueness in case multiple IDs are generated within the same millisecond and node.</li></ul><p>With this setup, we have a total of 64 bits:</p><ul><li>41 bits for timestamp</li><li>10 bits for node ID</li><li>12 bits for step/sequence</li></ul><pre>+--------------------------------------------------------------------------+<br>| 1 Bit Unused | 41 Bit Timestamp |  10 Bit NodeID  |   12 Bit Sequence ID |<br>+--------------------------------------------------------------------------+</pre><p>Using the default settings allows 4096 unique IDs to be generated every millisecond, per Node ID.</p><h3>Usage</h3><p>Import the package into your project then construct a new snowflake Node using a unique node number. The default settings permit a node number range from 0 to 1023. If you have set a custom NodeBits value, you will need to calculate what your node number range will be. With the node object, call the GenerateID() method to generate and return a unique snowflake ID.</p><p>Here’s an example program:</p><pre>func main() {<br>	// Create a new Node with a Node number of 1<br>	node, err := snowflake.NewSnowflakeNode(1)<br>	if err != nil {<br>		fmt.Println(err)<br>		return<br>	}</pre><pre>	// Generate a snowflake ID.<br>	id := node.GenerateID()</pre><pre>	// Print out the ID in a few different ways.<br>	fmt.Printf(&quot;Int64  ID: %d\n&quot;, id)<br>	fmt.Printf(&quot;String ID: %s\n&quot;, id)<br>	fmt.Printf(&quot;Base2  ID: %s\n&quot;, id.Base2())<br>	fmt.Printf(&quot;Base64 ID: %s\n&quot;, id.Base64())</pre><pre>	// Print out the ID&#39;s timestamp<br>	fmt.Printf(&quot;ID Time  : %d\n&quot;, id.Time())</pre><pre>	// Print out the ID&#39;s node number<br>	fmt.Printf(&quot;ID Node  : %d\n&quot;, id.Node())</pre><pre>	// Print out the ID&#39;s sequence number<br>	fmt.Printf(&quot;ID Step  : %d\n&quot;, id.Step())<br>}</pre><p>Keep in mind that each node you create must have a unique node number.</p><h3>Conclusion</h3><p>In this article, we’ve explored how to implement a Snowflake-like ID generator in Go. We started by understanding the core components of the Snowflake algorithm, including timestamps, node IDs, and sequence numbers. By leveraging these components, we created a simple and efficient ID generator suitable for distributed systems.</p><p>Key highlights of our implementation include:</p><ul><li>Customization: The ability to customize NodeBits and StepBits provides flexibility in tailoring the generator to specific requirements. Remember that the total of NodeBits and StepBits should not exceed 22.</li><li>Epoch Configuration: The Snowflake Node allows for setting a custom epoch, enabling compatibility with different systems and requirements.</li><li>Safety and Efficiency: The implementation ensures safety in concurrent environments through the use of mutexes and provides efficient ID generation even in high-throughput scenarios.</li><li>Usage Example: We demonstrated how to create a Snowflake Node, generate IDs, and convert them to various formats. This included examples of generating, printing, and utilizing the generated IDs in a simple Go program.</li></ul><p>By following this guide, you can implement a robust and scalable ID generation solution for your distributed systems. Feel free to experiment further with different Node and Step configurations to suit your application’s needs.</p><p><strong>GitHub Link: </strong><a href="https://github.com/Jitender271/go-snowflake">https://github.com/Jitender271/go-snowflake</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*eOsFytscu3-qCT1t2410LA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72796a827c9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing gRPC Gateway in Golang: Crafting a Reverse Proxy for Effortless RESTful Integration]]></title>
            <link>https://medium.com/@jitenderkmr/exploring-grpc-gateway-in-golang-building-a-reverse-proxy-for-seamless-restful-integration-d342fe5248c4?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/d342fe5248c4</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 19:31:53 GMT</pubDate>
            <atom:updated>2023-11-20T18:18:25.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lK0wxREgKpfon5tSArmmeg.jpeg" /></figure><h4>Introduction</h4><p>Greetings, fellow enthusiasts of Golang, gRPC, and the powerful ScyllaDB! Our recent exploration marked not the end but a new beginning in the vast landscapes of these technologies. The possibilities are limitless, and as we stride forward, the next chapter beckons with exciting prospects.</p><h4>Continuing the Journey</h4><p>Continuing our journey from the intersection of <a href="https://medium.com/@jitenderkmr/how-to-build-a-golang-grpc-microservice-with-scylladb-a-step-by-step-guide-c146797e8b1c"><strong>Golang, gRPC, and ScyllaDB</strong></a>, we venture deeper into uncharted territories. This time, we unravel the art of seamlessly integrating a RESTful JSON API with the stalwart gRPC architecture. Welcome to the second chapter of our saga, where innovation knows no bounds.</p><h4>A Sneak Peek</h4><p>Today, we embark on a mission to fuse an HTTP+JSON interface with our gRPC service, unveiling a world where minimal configuration adjustments lead to the effortless generation of a reverse proxy. This endeavor not only enhances the adaptability of your service but sets the stage for catering to an even broader spectrum of application scenarios.</p><p>Today, we unravel the art of modifying our beloved protobufs to seamlessly integrate a RESTful JSON API with the robust gRPC architecture. Buckle up as we explore the transition from the familiar to the extraordinary, using the same old proto but with a touch of innovation.</p><h4>Set Up for Grpc Gateway</h4><p>Install the grpc gateway packages by running the below command:</p><pre>go install \<br>    github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway \<br>    github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2 \<br>    google.golang.org/protobuf/cmd/protoc-gen-go \<br>    google.golang.org/grpc/cmd/protoc-gen-go-grpc</pre><p>This command ensures the availability of key tools:</p><ul><li>protoc-gen-grpc-gateway: Generates Go code for gRPC Gateway, facilitating communication between gRPC and RESTful APIs.</li><li>protoc-gen-openapiv2: Enables automatic creation of OpenAPIv2 specifications for gRPC services, enhancing API documentation.</li><li>protoc-gen-go: Generates Go code from Protobuf definitions, allowing seamless integration of Protobuf structures in Go programs.</li><li>protoc-gen-go-grpc: Creates Go code to support gRPC communication for a given Protobuf file, enabling the development of gRPC servers and clients in Go.</li></ul><h4>Exploring the Proto Transformations: A Deep Dive</h4><p>In the dynamic landscape of gRPC, understanding the role of reverse proxies is pivotal. These gatekeepers hold the key to seamless communication between gRPC services and the diverse world of HTTP clients. In this exploration, we unravel the purpose of a reverse proxy in the gRPC context, shedding light on its profound benefits. Additionally, we’ll introduce the game-changing google.api.http option and uncover how it orchestrates HTTP-specific configurations for each gRPC service method.</p><h4>Section 1:</h4><p>Unveiling the google.api.http Option: Enter the game-changer — the google.api.http option. This option, when integrated into your protobuf definitions, empowers gRPC services to expose HTTP-specific configurations. Let&#39;s delve into its intricacies:</p><ul><li><strong>Purpose and Usage:</strong> The google.api.http option serves as a declarative way to define how each gRPC service method should be exposed over HTTP. By embedding this option in your proto file, you dictate how clients can interact with your gRPC service through HTTP.</li><li><strong>Syntax:</strong> The syntax involves specifying HTTP methods, paths, request and response body configurations, and more, providing a comprehensive blueprint for translating gRPC operations into HTTP endpoints.</li></ul><h4>Section 2:</h4><p><strong>Transforming gRPC Methods into HTTP Endpoints: </strong>Concrete examples bring concepts to life. Let’s explore how specific gRPC methods undergo a metamorphosis, emerging as HTTP endpoints:</p><p><strong>Example 1:</strong> Creating a Movie — From gRPC to HTTP:</p><pre>rpc CreateMovie(MovieRequest) returns (MovieResponse) {<br>    option (google.api.http) = {<br>        post: &quot;/api/V1/create/movie&quot;<br>        body:  &quot;*&quot;<br>    };<br>}</pre><ul><li>In this snippet, the CreateMovie gRPC method is transformed into an HTTP POST endpoint at the path /api/V1/create/movie.</li></ul><p><strong>Example 2:</strong> Getting All Movies — A GET Endpoint Emerges:</p><pre>rpc GetAllMovies(GetAllMoviesRequest) returns (GetAllMoviesResponse) {<br>    option (google.api.http) = {<br>        get: &quot;/api/V1/get/all/movies&quot;<br>    };<br>}</pre><p>The GetAllMovies method effortlessly transitions into an HTTP GET endpoint at /api/V1/get/all/movies.</p><p>Once the changes are done in proto files, compile the proto files into Go files with gRPC support, use below command</p><pre>protoc --proto_path= proto/*.proto --go_out=resources/ --go-grpc_out=resources/ --grpc-gateway_out=resources/</pre><ul><li>--proto_path=proto/: Specifies the directory where your Proto files are located. Update this path based on your project&#39;s structure.</li><li>--go_out=resources/: Indicates the output directory for the generated Go files. The resources/ directory will be created in the same location as your proto/ directory.</li><li>--go-grpc_out=resources/: Specifies the output directory for the generated gRPC Go files. The resources/ directory will be created in the same location as your proto/ directory.</li><li>proto/*.proto: Specifies the Proto files to be compiled. Adjust this pattern based on the actual names and locations of your Proto files.</li><li>--grpc-gateway_out=resources/: Generates Go files for gRPC Gateway, which allows your gRPC service to be accessible via RESTful HTTP. The generated files are placed in the resources/ directory.</li></ul><h4>Creating a Foundation: The Router Structure</h4><p>The role of an HTTP router is pivotal. In this section, we explore the creation of a versatile HTTP router, utilizing the Gorilla Mux package. From dynamic routing to health checks and profiling.</p><p><strong>http/router.go</strong></p><p><strong>Initiating the Router</strong></p><pre>type RouteConfig struct {<br>    Path    string<br>    Handler http.Handler<br>    Methods []string<br>}<br><br>type Router interface {<br>    AddRoute(config RouteConfig)<br>    StaticRoute()<br>    Mux() http.Handler<br>}<br><br>type router struct {<br> mux *mux.Router<br> sync.Mutex<br>}<br><br>func NewRouter() Router {<br>    r := &amp;router{<br>        mux: mux.NewRouter().StrictSlash(true),<br>    }<br>    r.debugRoutes()<br>    r.healthCheckRoute()<br>    return r<br>}</pre><p>At the heart of our HTTP router is a well-defined structure. RouteConfig captures essential details for each route, while the Router interface outlines the core methods, including adding routes, defining static routes, and obtaining the underlying HTTP handler.</p><p>Creating an instance of our router involves initializing a mux.Router. This sets the stage for further customization and dynamic routing. Additionally, we establish default routes for debugging and health checks.</p><p><strong>Adding Routes Dynamically</strong></p><pre>func (r *router) AddRoute(route RouteConfig) {<br>    r.Lock()<br>    defer r.Unlock()<br>    handler := route.Handler<br><br>    rt := r.mux.Handle(route.Path, handler)<br>    if route.Methods != nil &amp;&amp; len(route.Methods) &gt; 0 {<br>        rt.Methods(route.Methods...)<br>    }<br>}</pre><p>The AddRoute method empowers dynamic route addition. It supports various HTTP methods, providing flexibility in configuring our router based on specific service requirements.</p><p><strong>Enabling Static File Serving</strong></p><pre>func (r *router) StaticRoute() {<br>    mux := r.mux<br>    mux.PathPrefix(&quot;/&quot;).Handler(http.FileServer(http.Dir(&quot;/tmp/static&quot;)))<br>}</pre><p>Our HTTP router goes beyond dynamic routes, offering static file serving capabilities. The StaticRoute method designates a path prefix for serving static files, enhancing the versatility of our router.</p><p><strong>Accessing the Underlying Mux</strong></p><pre>func (r *router) Mux() http.Handler {<br>    return r.mux<br>}</pre><p>The Mux method provides a seamless way to access the underlying mux.Router. This feature enables integration into larger applications and middleware, ensuring a smooth development experience.</p><p><strong>Unlocking Debugging and Profiling</strong></p><pre>func (r *router) debugRoutes() {<br>    mux := r.mux<br>    mux.HandleFunc(&quot;/debug/pprof/&quot;, pprof.Index)<br>    mux.HandleFunc(&quot;/debug/pprof/cmdline&quot;, pprof.Cmdline)<br>    mux.HandleFunc(&quot;/debug/pprof/profile&quot;, pprof.Profile)<br>    mux.HandleFunc(&quot;/debug/pprof/symbol&quot;, pprof.Symbol)<br>    mux.HandleFunc(&quot;/debug/pprof/trace&quot;, pprof.Trace)<br>    mux.Handle(&quot;/debug/pprof/goroutine&quot;, pprof.Handler(&quot;goroutine&quot;))<br>}</pre><p>Our HTTP router is equipped with debugging and profiling capabilities. The debugRoutes method adds routes for Go&#39;s pprof package, allowing developers to gain insights into performance characteristics.</p><p><strong>Health Checks Made Easy</strong></p><pre>func (r *router) healthCheckRoute() {<br>    r.mux.HandleFunc(&quot;/health_check&quot;, healthCheck)<br>}<br><br>func healthCheck(w http.ResponseWriter, req *http.Request) {<br>    w.Write([]byte(&quot;Health Check Passed&quot;))<br>}</pre><p>Ensuring the health of our services is paramount. The healthCheckRoute method adds a straightforward health check endpoint, responding with a reassuring &quot;Health Check Passed&quot; message.</p><h4>Unveiling the Server Structure</h4><p><strong>http/server.go</strong></p><p>Crafting a robust HTTP server is key to unlocking the full potential of your services. In this segment, we delve into the implementation of a feature-rich HTTP server, seamlessly integrating with the HTTP router. From CORS configuration to graceful shutdowns, join us in exploring the intricacies of our Go HTTP server</p><p><strong>Initializing the Server</strong></p><pre>type Server struct {<br>    *zap.Logger<br>    config *config.AppConfig<br>    srv    *http.Server<br>    mux    http.Handler<br>}<br><br>func NewServer(config *config.AppConfig, router Router) *Server {<br>    return &amp;Server{<br>        config: config,<br>        mux:    router.Mux(),<br>        Logger: log.Logger,<br>    }<br>}</pre><p>At the core of our HTTP server lies a well-architected structure. The Server type integrates a Zap logger, application configurations, an HTTP server instance, and the router&#39;s multiplexer, setting the stage for a harmonious collaboration.<br>The NewServer function serves as the gateway to our HTTP server, bringing together application configurations and the router. This function creates and returns a pointer to a configured Server instance.</p><p><strong>Commencing the Server</strong></p><pre>func (s *Server) Start() {<br>    srv := &amp;http.Server{<br>        Handler:      handlers.CORS(handlers.AllowedHeaders([]string{&quot;X-Requested-With&quot;, &quot;Content-Type&quot;, &quot;Authorization&quot;}), handlers.AllowedMethods([]string{&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;}), handlers.AllowedOrigins([]string{&quot;*&quot;}))(s.mux),<br>        ReadTimeout:  s.config.HttpReadTimeout,<br>        WriteTimeout: s.config.HttpWriteTimeout,<br>        IdleTimeout:  s.config.HttpIdleTimeout,<br>    }<br>    s.srv = srv<br><br>    err := srv.ListenAndServe()<br>    if err != nil &amp;&amp; !strings.Contains(err.Error(), &quot;http: Server Closed&quot;) {<br>        s.Logger.Fatal(&quot;failed to start server %v&quot;, zap.Error(err))<br>    }<br>}</pre><p>Embarking on the server journey is the Start method. It configures CORS support, sets up timeouts, and initiates the HTTP server. The graceful handling of errors ensures a resilient and reliable server start-up.</p><h3>HTTP Initialization: A Symphony of Components</h3><p><strong>main.go</strong></p><pre>func initHttpModules(router http.Router, cfg *config.AppConfig) {<br>    log.Logger.Info(&quot;adding static asset route&quot;)<br>    router.StaticRoute()<br>    server := http.NewServer(cfg, router)<br>    log.Logger.Info(&quot;HTTP Server running&quot;)<br>    go server.Start()<br>}</pre><ul><li>server := http.NewServer(cfg, router): Creates a new HTTP server instance using the NewServer function from the http2 package. This function takes the application configuration (cfg) and the configured router.</li><li>go server.Start(): Launches the HTTP server concurrently using a goroutine, allowing it to handle incoming HTTP requests independently.</li></ul><h4>Gateway Integration</h4><pre>func runGatewayServer(configurations *config.AppConfig, movieServer *grpcserver.MovieGrpcServer) {<br>    ctx, cancel := context.WithCancel(context.Background())<br>    defer cancel()<br><br>    grpcMux := runtime.NewServeMux(<br>        runtime.WithMetadata(func(c context.Context, req *nethttp.Request) metadata.MD {<br>            return metadata.Pairs(&quot;x-forwarded-method&quot;, req.Method)<br>        }))<br>    opts := []grpc2.DialOption{grpc2.WithTransportCredentials(insecure.NewCredentials())}<br>    grpcServerEndpoint := flag.String(grpcServerEndpointName, constants.ColonSeparator+configurations.GRPCPort, grpcEndpointNameUsage)<br>    if err := moviepb.RegisterMoviePlatformHandlerFromEndpoint(ctx, grpcMux, *grpcServerEndpoint, opts); err != nil {<br>        log.Logger.Fatal(&quot;cannot register gateway handler server&quot;)<br>    }<br>    if err := nethttp.ListenAndServe(constants.ColonSeparator+configurations.ReverseProxyHttpPort, grpcMux); err != nil {<br>        log.Logger.Fatal(&quot;Failed to serve to&quot;, zap.String(&quot;port&quot;, configurations.ReverseProxyHttpPort), zap.Error(err))<br>    }<br>}</pre><ul><li>ctx, cancel := context.WithCancel(context.Background()): Creates a new context for the gateway server, allowing cancellation to be propagated through the cancel function.</li><li>grpcMux := runtime.NewServeMux(...): Initializes a new ServeMux for the gRPC gateway using the runtime package. This serves as the multiplexer for handling gRPC requests translated to HTTP.</li><li>opts := [...]: Defines gRPC dial options, including using insecure transport credentials.</li><li>grpcServerEndpoint := flag.String(...): Retrieves the gRPC server endpoint from command-line flags, specifying the address and port.</li><li>moviepb.RegisterMoviePlatformHandlerFromEndpoint(...): Registers the gRPC gateway handler, translating gRPC calls to HTTP requests.</li><li>http.ListenAndServe(...): Initiates the HTTP server for the gRPC gateway, serving on the specified port. Any errors during server startup are logged, and fatal errors lead to the termination of the application.</li></ul><p>These methods collectively lay the foundation for HTTP integration and gRPC gateway functionality within your Go application. The orchestration of routers, servers, and gateway registration enables a cohesive and performant HTTP service.</p><h3>Deploying and Testing the Http Endpoints</h3><p><strong>Build and Run the Application:</strong> Execute go build to compile the Golang code, preparing the binary for deployment. Once compiled, initiate the application using either of the following commands:</p><pre>go build<br><br>go run main.go<br>    or<br>./go-grpc-service<br></pre><p><strong>Endpoint Verification</strong></p><p>Let’s validate each accessible HTTP endpoint in our service. Begin by triggering the creation of a movie, storing its details in the database. Subsequently, retrieve the same information using a GET endpoint to ensure its accuracy. Finally, assess the update endpoint to confirm the successful modification of data in the datastore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AA-kaQmSE3gpRDKdUwQC1Q.png" /><figcaption>Create Movie</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6de5iiBMu_KHKW3KGiSRQw.png" /><figcaption>Get Movie By Movie Name</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvxqUahgHl-Kt6lnoRUDEg.png" /><figcaption>Update Movie Details</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeDMO-8pEjAXkopHs4xi-g.png" /><figcaption>Get All movies</figcaption></figure><h4>Conclusion: Unlocking the Potential of gRPC Gateway in Golang</h4><p>As we bring this exploration of gRPC Gateway in Golang to a close, the horizon of possibilities expands. The journey doesn’t conclude here; it marks a new beginning in the realm of seamless integration. We’ve delved into the intricacies of building a reverse proxy, seamlessly blending RESTful HTTP APIs with the robust gRPC architecture.</p><p>In our quest for a versatile and adaptable solution, we embarked on a journey that unveiled the power of gRPC Gateway. By leveraging the Google protocol buffers compiler protoc, we transformed routine service definitions into endpoints capable of generating a reverse proxy server. This transformation facilitates the translation of RESTful HTTP APIs into the language of gRPC, offering a unified and efficient communication mechanism.</p><p>The journey included the modification of protobuf service definitions, introducing the magic of google.api.http options. These adjustments allowed us to effortlessly bridge the gap between the HTTP and gRPC worlds, enabling a smooth integration that caters to diverse application requirements.</p><p>As we conclude, this exploration invites continuous innovation. Embrace these technologies, contribute to the evolving landscape, and shape the future of microservices. The journey doesn’t end; it marks a new chapter in modern application development. Happy coding!</p><p><strong>GitHub Link: </strong><a href="https://github.com/Jitender271/go-grpc-service">https://github.com/Jitender271/go-grpc-service</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*LZxfKb_KnD9mM5qQanQiXA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d342fe5248c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Golang gRPC Microservice with ScyllaDB: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@jitenderkmr/how-to-build-a-golang-grpc-microservice-with-scylladb-a-step-by-step-guide-c146797e8b1c?source=rss-8baee8074916------2</link>
            <guid isPermaLink="false">https://medium.com/p/c146797e8b1c</guid>
            <dc:creator><![CDATA[Jitender Kumar]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 18:23:08 GMT</pubDate>
            <atom:updated>2023-11-20T18:14:42.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qT6SHryC8GF0N-GP37riKw.png" /></figure><h3><strong>Introduction</strong></h3><p>Microservices architecture has revolutionized the way we design and deploy applications, providing scalability, flexibility, and maintainability. One of the key technologies driving this shift is gRPC, a high-performance, open-source framework developed by Google. In this article, we’ll explore the advantages of gRPC in building microservices and guide you through the process of creating a Golang gRPC microservice integrated with ScyllaDB.</p><p>gRPC: Empowering Microservices</p><p><strong>What is gRPC?</strong><br>gRPC stands for “gRPC Remote Procedure Calls” and is an open-source RPC (Remote Procedure Call) framework. It enables efficient communication between services, allowing them to communicate seamlessly, regardless of the programming language they are implemented in. gRPC uses HTTP/2 as its transport protocol, offering features such as bidirectional streaming, multiplexing, and low-latency connections.</p><p><strong>Advantages of gRPC in Microservices:</strong><br>- Performance: gRPC is known for its speed and efficiency, making it ideal for microservices that require low-latency communication.<br>- Language Agnostic: Write microservices in your preferred language; gRPC supports multiple languages, including Golang, Java, Python, and more.<br>- IDL (Interface Definition Language): gRPC uses protobuf (Protocol Buffers) as its IDL, allowing for efficient serialization and deserialization of data structures.<br>- Bidirectional Streaming: Supports streaming requests and responses, enabling real-time communication.</p><p><strong>ScyllaDB: A Powerful Database for Microservices</strong></p><p>Microservices generate and process vast amounts of data, requiring a reliable and scalable database solution. Enter ScyllaDB, a NoSQL database that offers high performance, fault tolerance, and scalability. Here’s a brief look at why ScyllaDB is an excellent choice for microservices:</p><p><strong>Key Features of ScyllaDB:</strong><br>- <strong>Distributed Architecture:</strong> Built for distributed environments, ScyllaDB ensures high availability and fault tolerance.<br>- <strong>CQL (Cassandra Query Language) Compatibility:</strong> ScyllaDB is compatible with Cassandra, making it easy to transition from Cassandra to ScyllaDB.<br>- <strong>Low Latency:</strong> Designed for low-latency applications, ScyllaDB excels in scenarios where response time is critical.<br>- <strong>Linear Scalability:</strong> As your microservices grow, ScyllaDB scales horizontally, adding nodes to handle increased workloads.</p><p>In the upcoming sections, we will guide you through setting up your development environment, defining the microservice architecture, creating the Golang gRPC microservice, integrating ScyllaDB for data storage, and deploying your microservice. Let’s embark on a step-by-step journey to build a robust and scalable microservice architecture.</p><h3>Setting Up Your Development Environment</h3><p>To embark on our journey of building a Golang gRPC microservice with ScyllaDB, let’s begin by setting up your development environment. This section will guide you through the installation of Golang, the creation of a basic Golang project structure, and an introduction to protocol buffers (protobuf) — a crucial component for defining the service interface.</p><h4>Installing Golang</h4><p>Step 1: Download Golang Visit the official Golang website at <a href="https://golang.org/dl/">https://golang.org/dl/</a> and download the latest stable version of Golang for your operating system, also follow the below links to set up golang :</p><ul><li><a href="https://sourabhbajaj.com/mac-setup/Go/README.html">Mac OS X Setup Guide</a></li><li><a href="https://medium.com/golang-learn/quick-go-setup-guide-on-mac-os-x-956b327222b8">Quick Go Setup Guide on Mac OS X</a></li></ul><p><strong>Go plugins</strong> for the protocol compiler:</p><ol><li>Install the protocol compiler plugins for Go using the following commands:</li></ol><p>$ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28</p><p>$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2</p><p>2. Update your PATH so that the protoc the compiler can find the plugins:</p><ul><li>$ export PATH=&quot;$PATH:<strong>$(</strong>go env GOPATH<strong>)</strong>/bin&quot;</li></ul><p>or, you can follow the below link to setup the protoc</p><p><a href="https://grpc.io/docs/languages/go/quickstart/">Quick start</a></p><p><strong>Setup Scylla Db in Local</strong></p><p>Run below commands:</p><pre><br>docker run --name scylla-local -p 9042:9042 -d scylladb/scylla<br>docker exec -it scylla-local nodetool status<br>docker exec -it scylla-local cqlsh<br><br>Create KeySpace<br><br>CREATE KEYSPACE book_my_show WITH replication = {&#39;class&#39;: &#39;SimpleStrategy&#39;, &#39;replication_factor&#39;: 1};<br><br>Create tables<br><br>CREATE TABLE IF NOT EXISTS movies (movie_id TEXT, name TEXT PRIMARY KEY, genre TEXT, description TEXT, rating TEXT );</pre><p><strong>Download all dependencies</strong></p><pre>go mod vendor</pre><p><strong>Project Structure</strong></p><pre>go-grpc-service/<br>|-- cmd/<br>|   |-- server/<br>|       |-- gogrpcsrvr<br>|          |-- main.go<br>|-- commons/<br>|   |-- constants/<br>|   |-- utils/<br>|-- config/<br>|   |-- aap.env<br>|-- helper/<br>|   |-- request-validator.go<br>|-- internal/<br>|   |-- config/<br>|   |-- dao/<br>|   |-- db/<br>|   |-- grpc/<br>|       |-- interceptor/<br>|       |-- server.go<br>|   |-- log/<br>|   |-- models/<br>|   |-- service/<br>|-- pkg/<br>|   |-- grpcserver/<br>|-- proto/<br>|   |-- movie.proto<br>|   |-- movie-service.proto<br>|-- |resources<br>|-- go.mod<br>|-- go.sum</pre><ul><li>cmd/: Contains the main application entry point (main.go).</li><li>internal/: Holds internal packages, including db/ ,dao/, server service/.</li><li>proto/: Houses protocol buffer definitions (movies.proto and movie)</li><li>go.mod and go.sum: Files generated by Go modules.</li></ul><h3><strong>Defining the Microservice Architecture</strong></h3><p>Now that we’ve set up our development environment, let’s dive into the core of our Golang gRPC microservice architecture. This section will provide an in-depth explanation of the chosen technologies, gRPC for communication, and ScyllaDB for efficient data storage.</p><p>gRPC: Efficient Communication Protocol</p><p><strong>Understanding gRPC</strong><br>gRPC, or gRPC Remote Procedure Call, is an open-source RPC (Remote Procedure Call) framework developed by Google. It utilizes HTTP/2 as the transport protocol and Protocol Buffers (Protobuf) as the interface description language. gRPC offers several advantages for microservices communication, including:</p><p>- <strong>Efficiency:</strong> gRPC uses HTTP/2, enabling multiplexing and reducing latency, making it more efficient than traditional REST APIs.<br> <br>- <strong>Language Agnostic:</strong> gRPC supports multiple programming languages, allowing developers to build services in their language of choice.</p><h4><strong>Microservices Components and Responsibilities</strong></h4><p>Our Golang gRPC microservice will be composed of various components, each responsible for specific tasks. Here’s an overview:</p><p><strong>1. Service Definition (Protobuf):</strong><br> — The proto/ directory contains the movie.proto and movie-service.proto files, which defines the service interface using Protobuf syntax. It outlines the RPC methods and data structures.</p><p><strong>2. gRPC Server (Golang):</strong><br> — The internal/grpc/server.go and pkg/grpcserver/ directories will house the gRPC server implementation. This server will handle incoming RPC requests, execute the corresponding logic, send responses, and also act as a bridge between the gRPC server and the core business logic. It interprets gRPC requests, invokes the service functions, and formats the responses.</p><p><strong>4. ScyllaDB Integration:</strong><br> — The microservice will integrate with ScyllaDB, a highly performant NoSQL database. ScyllaDB’s strengths in handling large amounts of data with low-latency responses make it an excellent choice for microservices that demand high throughput.</p><p>As we progress in our step-by-step guide, we will delve into the implementation of these components, creating a cohesive architecture for our Golang gRPC microservice with ScyllaDB. Stay tuned for the upcoming sections, where we’ll focus on coding the gRPC server, defining RPC methods, and seamlessly integrating ScyllaDB into our microservice.</p><h3>Crafting the Movie Protobuf</h3><p>In this section, we’ll embark on the journey of building a robust Golang gRPC microservice specifically designed for managing movie data. We’ll go through each step of the process, from defining the protobuf messages to implementing service methods for CRUD (Create, Read, Update, Delete) operations on movies.</p><h4>Step 1: Defining Protobuf Messages</h4><p>proto/movie.proto</p><pre>syntax = &quot;proto3&quot;;<br><br>option go_package = &quot;moviepb/&quot;;<br><br>message MovieDetails {<br>    string id = 1;<br>    string movie_name = 2;<br>    string genre = 3;<br>    string description = 4;<br>    string ratings = 5;<br>}<br><br>enum MovieStatus {<br>    CREATED = 0;<br>    UPDATED = 1;<br>    FAILED = 2;<br>    DUPLICATE_ENTRY = 3;<br>}</pre><h4>Step 2: Defining Request/Service Methods</h4><p>proto/movie-service.proto</p><pre>syntax = &quot;proto3&quot;;<br><br>option go_package = &quot;moviepb/&quot;;<br>import &quot;proto/movie.proto&quot;;<br><br>message MovieRequest{<br>    string movie = 1;<br>    string genre = 2;<br>    string desc = 3;<br>    string rating = 4;<br>}<br><br>message MovieResponse{<br>    MovieDetails movieDetails = 1;<br>    MovieStatus status = 2;<br>}<br><br>message GetMovieRequest{<br>    string movie = 1;<br>}<br><br>message GetMovieResponse{<br>    MovieDetails movieDetails = 1;<br>}<br><br>message GetAllMoviesRequest{<br>   string movies = 1;<br>}<br><br>message GetAllMoviesResponse{<br>   repeated MovieDetails movieDetails = 1;<br>}<br><br>message UpdateMovieRequest{<br>    string movie = 1;<br>    string genre = 2;<br>    string desc = 3;<br>    string rating = 4;<br>}<br><br>message UpdateMovieResponse{<br>    MovieDetails movieDetails = 1;<br>    MovieStatus status = 2;<br>}<br><br>service MoviePlatform{<br>    rpc CreateMovie(MovieRequest) returns (MovieResponse);<br>    rpc GetMovie(GetMovieRequest) returns (GetMovieResponse);<br>    rpc GetAllMovies(GetAllMoviesRequest) returns (GetAllMoviesResponse);<br>    rpc UpdateMovie(UpdateMovieRequest) returns (UpdateMovieResponse);<br>}</pre><p>To Compile the proto files into Go files with gRPC support, use below command</p><pre>protoc - proto_path= proto/*.proto - go_out=resources/ - go-grpc_out=resources/</pre><ul><li>--proto_path=proto/: Specifies the directory where your Proto files are located. Update this path based on your project&#39;s structure.</li><li>--go_out=resources/: Indicates the output directory for the generated Go files. The resources/ directory will be created in the same location as your proto/ directory.</li><li>--go-grpc_out=resources/: Specifies the output directory for the generated gRPC Go files. The resources/ directory will be created in the same location as your proto/ directory.</li><li>proto/*.proto: Specifies the Proto files to be compiled. Adjust this pattern based on the actual names and locations of your Proto files.</li></ul><p>Ensure that you run this command from the root directory of your project and update the paths accordingly. After running the command, you should see the generated Go files with gRPC support in the resources/ directory.</p><h3><em>Integrating ScyllaDB for Data Storage</em></h3><p>In this section, we’ll focus on seamlessly integrating ScyllaDB into our Golang gRPC microservice for efficient and reliable data storage. We’ll cover the necessary configurations, connection setups, and the design of the database schema tailored to store movie information.</p><h4><strong>Creating Scylla db Session</strong></h4><p><strong>internal/db/session.go</strong></p><pre>package db<br><br>import (<br> configs &quot;github.com/go-grpc-service/internal/config&quot;<br> &quot;github.com/go-grpc-service/internal/log&quot;<br> &quot;github.com/gocql/gocql&quot;<br> &quot;github.com/scylladb/gocqlx/v2&quot;<br> &quot;go.uber.org/zap&quot;<br> &quot;sync&quot;<br>)<br><br>var (<br> once                  sync.Once<br> sessionWrapperService SessionWrapperService<br>)<br><br>type SessionWrapperService interface {<br> Query(stmt string, names []string) QueryXService<br>}<br><br>type SessionWrapperImpl struct {<br> Session *gocqlx.Session<br>}<br><br>func (s *SessionWrapperImpl) Query(stmt string, names []string) QueryXService {<br> queryX := s.Session.Query(stmt, names)<br> return &amp;QueryXServiceImpl{<br>  QueryX: queryX,<br> }<br>}<br><br>func GetSession(configs configs.DbConfigs) SessionWrapperService {<br> once.Do(func() {<br>  scyllaDbCluster := gocql.NewCluster(configs.DBHosts...)<br>  scyllaDbCluster.Keyspace = configs.DBKeyspace<br>                        ...<br>  s, err := gocqlx.WrapSession(scyllaDbCluster.CreateSession())<br>  if err != nil {<br>   log.Logger.Fatal(&quot;failed to create scylla db session &quot;, zap.Error(err))<br>  }<br>  sessionWrapperService = &amp;SessionWrapperImpl{<br>   Session: &amp;s,<br>  }<br> })<br> return sessionWrapperService<br>}</pre><ol><li>SessionWrapperService: This is an interface that defines the contract for a service that wraps a gocqlx.Session. It has a Query method.</li><li>SessionWrapperImpl: This is the implementation of SessionWrapperService. It has a Query method that returns a QueryXService.</li><li>GetSession: This function initializes and returns an instance of SessionWrapperService. It uses a sync.Once to ensure that the initialization code is executed only once. The ScyllaDB session is configured based on the provided DbConfigs.</li></ol><p><strong>internal/db/query.go</strong></p><pre>package db<br><br>import (<br> &quot;context&quot;<br> &quot;github.com/scylladb/gocqlx/v2&quot;<br>)<br><br>type QueryXService interface {<br> BindStruct(arg interface{}) QueryXService<br> BindMap(arg map[string]interface{}) QueryXService<br> Exec(ctx context.Context) error<br> SelectRelease(ctx context.Context, dest interface{}) error<br> GetRelease(ctx context.Context, dest interface{}) error<br>}<br><br>type QueryXServiceImpl struct{<br> QueryX *gocqlx.Queryx<br>}<br><br>func (q *QueryXServiceImpl) BindStruct(arg interface{}) QueryXService{<br> return &amp;QueryXServiceImpl{<br>  QueryX: q.QueryX.BindStruct(arg),<br> }<br>}<br><br>func (q *QueryXServiceImpl) BindMap(arg map[string]interface{}) QueryXService{<br> return &amp;QueryXServiceImpl{<br>  QueryX: q.QueryX.BindMap(arg),<br> }<br>}<br><br>func (q *QueryXServiceImpl) Exec(ctx context.Context) error{<br> return  q.QueryX.Exec()<br>}<br><br>func (q *QueryXServiceImpl) SelectRelease(ctx context.Context, dest interface{}) error{<br> return q.QueryX.SelectRelease(dest)<br>}<br><br>func (q *QueryXServiceImpl) GetRelease(ctx context.Context, dest interface{}) error{<br> return q.QueryX.GetRelease(dest)<br>}</pre><ul><li>QueryXService: This interface defines methods for binding parameters to queries (BindStruct and BindMap), executing queries (Exec), and retrieving results (SelectRelease and GetRelease).</li><li>QueryXServiceImpl: This struct implements the QueryXService interface. It contains a gocqlx.Queryx field, and its methods delegate to the corresponding methods of gocqlx.Queryx.</li></ul><h3>Decoding the Dao Layer: Managing Data Access in Golang and gRPC</h3><p><strong>dao/db_helper.go</strong></p><pre>package dao<br><br>var (<br> movieColumns       = []string{&quot;movie_id&quot;, &quot;name&quot;, &quot;genre&quot;, &quot;description&quot;, &quot;rating&quot;}<br> moviePartitionKeys = []string{&quot;name&quot;}<br> updateMovieColumns = []string{&quot;genre&quot;, &quot;description&quot;, &quot;rating&quot;}<br> movieSortKeys      []string<br>)<br><br>const (<br> movieTableName = &quot;movies&quot;<br> name           = &quot;name&quot;<br> id             = &quot;id&quot;<br>)<br><br>func getTable(tableName string, cols, partitionKeys, sortKeys []string) db.Table {<br> tableMeta := table.Metadata{<br>  Name:    tableName,<br>  Columns: cols,<br>  PartKey: partitionKeys,<br>  SortKey: sortKeys,<br> }<br> return table.New(tableMeta)<br>}<br><br>func insertMoviesInDb(ctx context.Context, session db.SessionWrapperService, movies *daomodels.Movies) error {<br>                               ...<br>}<br><br>func getMovieFromDb(ctx context.Context, session db.SessionWrapperService, movieName string) (*daomodels.Movies, error) {<br>                               ...<br>}<br><br>func getAllMoviesFromDb(ctx context.Context, session db.SessionWrapperService) ([]daomodels.Movies, error) {<br>                               ...<br>}<br><br>func updateMoviesInDb(ctx context.Context, session db.SessionWrapperService, movies *daomodels.Movies) error {<br>                               ...<br>}</pre><p>To effectively manage movie data in our microservice, we’ve created a dedicated file named db_helper.go. This file encapsulates essential functions for interacting with ScyllaDB, allowing us to seamlessly perform operations like inserting, fetching, updating, and retrieving movie information.</p><p>Let’s take a closer look at the key components:</p><p>Constant Declarations:</p><ul><li>movieColumns: Represents the columns in the ScyllaDB table for movies.</li><li>moviePartitionKeys: Denotes the partition keys used in the movie table.</li><li>updateMovieColumns: Specifies the columns that can be updated for a movie.</li><li>movieSortKeys: Reserved for future use.</li><li>movieTableName: Defines the name of the ScyllaDB table for movies.</li><li>name: Represents the name of the movie (a partition key).</li><li>id: Represents the unique identifier for a movie.</li></ul><p>Functionality:</p><ul><li>getTable: A utility function to create a ScyllaDB table definition with specified columns, partition keys, and sort keys.</li><li>insertMoviesInDb: Inserts movie data into ScyllaDB.</li><li>getMovieFromDb: Retrieves movie details from ScyllaDB based on the movie name.</li><li>getAllMoviesFromDb: Fetches all movies from ScyllaDB.</li><li>updateMoviesInDb: Updates movie information in ScyllaDB.</li></ul><p><strong>internal/movie_dao.go</strong></p><pre>package dao<br><br><br>var (<br> initSync sync.Once<br> movieDao MovieDao<br>)<br><br>type MovieDao interface {<br> InsertMovie(ctx context.Context, req *models.Movie) (*models.Movie, error)<br> GetMovie(ctx context.Context, movieName string) (*daomodels.Movies, error)<br> GetAllMovies(ctx context.Context) ([]daomodels.Movies, error)<br> UpdateMovies(ctx context.Context, req *models.Movie) (*models.Movie, error)<br>}<br><br>type MovieImpl struct {<br> SessionWrapper db.SessionWrapperService<br>}<br><br>func NewMovieDaoImpl(dbConfigs config.DbConfigs) MovieDao {<br> initSync.Do(func() {<br>  movieDao = &amp;MovieImpl{<br>   SessionWrapper: db.GetSession(dbConfigs),<br>  }<br> })<br> return movieDao<br>}<br><br>func (dao *MovieImpl) InsertMovie(ctx context.Context, req *models.Movie) (*models.Movie, error) {<br>                                 ...<br>}<br><br>func (dao *MovieImpl) GetMovie(ctx context.Context, movieName string) (*daomodels.Movies, error) {<br>                                 ...<br>}<br><br>func (dao *MovieImpl) GetAllMovies(ctx context.Context) ([]daomodels.Movies, error) {<br>                                 ...<br>}<br><br>func (dao *MovieImpl) UpdateMovies(ctx context.Context, req *models.Movie) (*models.Movie, error) {<br>                                  ...<br>}<br>}</pre><p>Notable Points:</p><ol><li><strong>Singleton Pattern for DAO Initialization:</strong></li></ol><ul><li>The initSync sync.Once ensures that the NewMovieDaoImpl function is only executed once, creating a singleton instance of the MovieImpl struct.</li></ul><p>2. <strong>Error Handling:</strong></p><ul><li>Error messages are descriptive, providing information about the context of the failure.</li></ul><p>3. <strong>Context Usage:</strong></p><ul><li>The functions accept a context.Context parameter, which is good practice for managing deadlines, cancellations, and other request-scoped values.</li></ul><p>Overall, this file encapsulates the logic for interacting with ScyllaDB for movie-related CRUD operations. The use of interfaces and singleton patterns contributes to a modular and maintainable design.</p><h3>Building the Service Layer: Connecting Protobuf with Business Logic</h3><p><strong>service/movie_service.go</strong></p><p>This file serves as the service layer that orchestrates interactions between the gRPC endpoints and the DAO layer for movie-related operations.</p><pre>package service<br><br>type MovieService interface {<br> CreateMovie(ctx context.Context, request *moviepb.MovieRequest) (*models.Movie, error)<br> GetMovie(ctx context.Context, request *moviepb.GetMovieRequest) (*models.Movie, error)<br> GetAllMovies(ctx context.Context) ([]*models.Movie, error)<br> UpdateMovies(ctx context.Context, request *moviepb.UpdateMovieRequest) (*models.Movie, error)<br>}<br><br>type MovieServiceImpl struct {<br> movieDao dao.MovieDao<br>}<br><br>func NewMovieImpl(dbConfigs config.DbConfigs) MovieService {<br> return &amp;MovieServiceImpl{<br>  movieDao: dao.NewMovieDaoImpl(dbConfigs),<br> }<br>}<br><br>func (m *MovieServiceImpl) CreateMovie(ctx context.Context, request *moviepb.MovieRequest) (*models.Movie, error) {}<br><br>func (m *MovieServiceImpl) GetMovie(ctx context.Context, request *moviepb.GetMovieRequest) (*models.Movie, error) {}<br><br>func (m *MovieServiceImpl) GetAllMovies(ctx context.Context) ([]*models.Movie, error) {}<br><br>func (m *MovieServiceImpl) UpdateMovies(ctx context.Context, request *moviepb.UpdateMovieRequest) (*models.Movie, error) {}<br></pre><p>Overall, this file encapsulates the business logic operations. The separation of concerns between the service layer and the DAO layer promotes modularity and maintainability in your application. The use of interfaces allows for easy testing and future extensibility.</p><h3>Implementing gRPC Communication</h3><p>In the process of building a robust gRPC communication system for the movie platform microservice, we leverage two essential components: movie_grpc_server.go and server.go. Together, these files play a pivotal role in establishing and managing the gRPC server, ensuring seamless communication between clients and the movie service.</p><p><strong>grpcserver/movie_grpc_server.go — Connecting the Dots</strong></p><pre>type MovieGrpcServer struct {<br> moviepb.UnimplementedMoviePlatformServer<br> service.MovieService<br>}<br><br>func NewGrpcServer(server *grpc.Server) *MovieGrpcServer {<br> dbConfig := config.Configurations.DbConfigs<br> s := &amp;MovieGrpcServer{<br>  MovieService: service.NewMovieImpl(dbConfig),<br> }<br> moviepb.RegisterMoviePlatformServer(server.GrpcServer, s)<br> return s<br>}<br><br>func (m *MovieGrpcServer) CreateMovie(ctx context.Context, request *moviepb.MovieRequest) (*moviepb.MovieResponse, error) {}<br><br>func (m *MovieGrpcServer) GetMovie(ctx context.Context, request *moviepb.GetMovieRequest) (*moviepb.GetMovieResponse, error) {}<br><br>func (m *MovieGrpcServer) GetAllMovies(ctx context.Context, request *moviepb.GetAllMoviesRequest) (*moviepb.GetAllMoviesResponse, error) {}<br><br>func (m *MovieGrpcServer) UpdateMovie(ctx context.Context, request *moviepb.UpdateMovieRequest) (*moviepb.UpdateMovieResponse, error) {}</pre><p>movie_grpc_server.go serves as the bridge between the gRPC server and the movie service. Key points include:</p><ul><li>Initialization: The NewGrpcServer function initializes the movie gRPC server. It creates an instance of the MovieGrpcServer struct, which embeds the moviepb.UnimplementedMoviePlatformServer interface and the MovieService interface.</li><li>CreateMovie, GetMovie, GetAllMovies, UpdateMovie Functions: These functions implement the respective gRPC methods for creating, retrieving, listing, and updating movie information. They seamlessly connect with the MovieService to handle business logic.</li></ul><p><strong>grpc/server.go — The Guts of the gRPC Server</strong></p><pre><br>type Server struct {<br> Config       *config.AppConfig<br> GrpcServer   *grpc.Server<br> HealthServer *health.Server<br>}<br><br>func NewServer(config *config.AppConfig) *Server {<br> grpcServer := grpc.NewServer(<br>  grpc.ChainUnaryInterceptor(interceptor.RequestInterceptor),<br>  grpc.ConnectionTimeout(config.GRPCConnectionTimeout),<br> )<br> healthServer := health.NewServer()<br> healthServer.SetServingStatus(grpcHealthService, healthv1.HealthCheckResponse_SERVING)<br> healthv1.RegisterHealthServer(grpcServer, healthServer)<br> return &amp;Server{<br>  Config:       config,<br>  GrpcServer:   grpcServer,<br>  HealthServer: healthServer,<br> }<br>}<br><br>func (s *Server) Start() {<br> listener, err := net.Listen(tcp, &quot;:&quot;+s.Config.GRPCPort)<br> if err != nil {<br>  log2.Logger.Fatal(&quot;failed to listen to&quot;, zap.String(port, s.Config.GRPCPort), zap.Error(err))<br> }<br> s.HealthServer.SetServingStatus(&quot;go-grpc-service&quot;, healthv1.HealthCheckResponse_SERVING)<br> log2.Logger.Info(&quot;grpc server started&quot;)<br> if err := s.GrpcServer.Serve(listener); err != nil {<br>  s.HealthServer.SetServingStatus(&quot;go-grpc-service&quot;, healthv1.HealthCheckResponse_NOT_SERVING)<br>  log2.Logger.Fatal(&quot;failed to serve&quot;, zap.Error(err))<br> }<br>}</pre><p>In server.go, we create and configure the gRPC server.</p><ul><li>NewServer Function: This function initializes and returns a new gRPC server instance. It configures the server with unary interceptors, and connection timeout, and sets up the health server.</li><li>Start Function: The Start function initiates the server by creating a network listener and serving incoming gRPC requests. It also manages health check status and logs server startup information.</li></ul><h3>Initializing and Starting the Application</h3><p><strong>main.go</strong></p><p>main <strong>Function</strong>: The primary entry point of the application. Here&#39;s what happens step by step:</p><pre>func main() {<br> cfg := config.InitConfig(false)<br> initLogger(cfg)<br> defer func() {<br>  if r := recover(); r != nil {<br>   log.Logger.Fatal(&quot;Error while starting app&quot;)<br>  }<br> }()<br> _, server := initGrpcModules(cfg)<br> server.Start()<br> log.Logger.Info(&quot;Application Started successfully on port 80&quot;)<br>}<br><br>func initGrpcModules(configuration *config.AppConfig) (*grpcserver.MovieGrpcServer, *grpc.Server) {<br> log.Logger.Info(&quot;starting grpc server ...&quot;)<br> server := grpc.NewServer(configuration)<br> movieServer := grpcserver.NewGrpcServer(server)<br> return movieServer, server<br>}</pre><p><strong>Configuration Initialization</strong>: config.InitConfig(false) initializes the application configuration, loading configuration parameters from environment variables and possibly configuration files.</p><ul><li><strong>Logger Initialization</strong>: initLogger(cfg) sets up the application logger based on the configured log level.</li><li><strong>Panic Recovery</strong>: A deferred function with recover() is used to recover from panics, preventing the application from crashing unexpectedly. It logs a fatal message if a panic occurs.</li><li><strong>gRPC Server Initialization</strong>: initGrpcModules(cfg) initializes the gRPC server and related modules. It returns a MovieGrpcServer and a Server.</li><li><strong>Server Start</strong>: server.Start() starts the gRPC server, making it ready to handle incoming requests.</li></ul><p>This main.go file serves as the central orchestrator, setting up configuration, logging, and initiating the gRPC server and related modules. It plays a crucial role in starting and managing the entire application.</p><h3>Deploying and Testing the Golang gRPC Service</h3><ol><li><strong>Build the Application:</strong> Execute the “go build” command to compile the Golang code and prepare the executable. This step is crucial for generating the binary that can be deployed in various environments.</li></ol><pre>go build</pre><p>2. <strong>Run the Application:</strong> Initiate the application by running the compiled binary. This can be done using either of the following commands:</p><pre>go run main.go<br>    or<br>./go-grpc-server</pre><p>Let’s now verify each accessible endpoint in our service. The journey starts by initiating the creation of a Movie and storing its specifics in the database. Following that, we will retrieve the identical information using a GET endpoint to validate its accuracy. To conclude, we’ll evaluate the update endpoint to affirm the successful updating of data in the datastore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9i1vwl6p6BtB-TxHdU_HQ.jpeg" /><figcaption>create movie</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxguMeRj3n8jl_UCYCcVXg.jpeg" /><figcaption>get by name</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MIL4GeSiseqwNSpiVWpCFQ.jpeg" /><figcaption>get all</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NeUo57NMrRhw-Lt3EDxjw.jpeg" /><figcaption>update movie</figcaption></figure><h3>Conclusion</h3><p>In this journey through the realms of Golang, gRPC, and ScyllaDB, we’ve witnessed the seamless integration of these powerful technologies to build a robust and scalable microservice. Let’s recap our key achievements and explore the advantages that make this trifecta a compelling choice for modern application development.</p><h3>Summary of Key Achievements</h3><ul><li><strong>Microservice Harmony:</strong> Our microservice now stands tall, harmonizing the efficiency of Golang, the versatility of gRPC, and the scalability of ScyllaDB. The culmination of these technologies has paved the way for a resilient and high-performing system.</li><li><strong>Data Handling Precision:</strong> Through meticulous data handling, we’ve achieved precision in storing and retrieving information. The usage of ScyllaDB ensures our distributed database meets the demands of our microservices architecture, providing both speed and reliability.</li></ul><h3>Advantages of Golang and gRPC</h3><ul><li><strong>Golang’s Prowess:</strong> Golang’s performance and simplicity have played a pivotal role in our success. Its concurrency model, coupled with a robust standard library, has empowered us to develop a microservice that thrives in dynamic environments.</li><li><strong>Efficient Communication with gRPC:</strong> Leveraging gRPC for communication between microservices has proven to be a game-changer. With its binary protocol and HTTP/2 support, we’ve achieved efficient and secure communication, reducing latency and optimizing resource utilization.</li></ul><h3>Closing Remarks</h3><p>As we conclude this exploration of Golang, gRPC, and ScyllaDB, the horizon of possibilities expands. The journey doesn’t end here; it merely marks a new beginning. The openness of these technologies invites continuous exploration and innovation.</p><p>Embrace the advantages, experiment with variations, and contribute to the thriving communities surrounding Golang, gRPC, and ScyllaDB. Our microservices landscape is evolving, and your ideas and contributions can shape its future.</p><p>In our next article <a href="https://medium.com/@jitenderkmr/exploring-grpc-gateway-in-golang-building-a-reverse-proxy-for-seamless-restful-integration-d342fe5248c4"><strong>Unleashing gRPC Gateway in Golang</strong></a>, we will delve deeper into the integration of a RESTful JSON API alongside the robust gRPC architecture. This project is specifically designed to seamlessly merge an HTTP+JSON interface with your gRPC service. By making minimal configuration adjustments in your service to incorporate HTTP semantics, you can effortlessly generate a reverse proxy. This approach enhances the versatility of your service, allowing it to cater to a broader range of scenarios, making it an inclusive and adaptable solution for diverse application requirements.</p><p>Here’s to the synergy of technology, the spirit of open-source collaboration, and the exciting possibilities that lie ahead. Happy coding!</p><p><strong>GitHub Link: </strong><a href="https://github.com/Jitender271/go-grpc-service">https://github.com/Jitender271/go-grpc-service</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*CvmxSDpTuaMHRb3FX8kWWw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c146797e8b1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>