<?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 Dubem Ezeagwu on Medium]]></title>
        <description><![CDATA[Stories by Dubem Ezeagwu on Medium]]></description>
        <link>https://medium.com/@dubemezeagwu?source=rss-dac50d9fbc0d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0W8yb1rZb2tUuF0zxYQQWA.png</url>
            <title>Stories by Dubem Ezeagwu on Medium</title>
            <link>https://medium.com/@dubemezeagwu?source=rss-dac50d9fbc0d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:07:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dubemezeagwu/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[Juxtaposing Byzantine Fault Tolerance and Proof of Stake as Paths to Blockchain Agreement]]></title>
            <link>https://medium.com/@dubemezeagwu/juxtaposing-byzantine-fault-tolerance-and-proof-of-stake-as-paths-to-blockchain-agreement-77474ae1477e?source=rss-dac50d9fbc0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/77474ae1477e</guid>
            <category><![CDATA[byzantine-fault-tolerance]]></category>
            <category><![CDATA[proof-of-stake]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[consensus]]></category>
            <dc:creator><![CDATA[Dubem Ezeagwu]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 19:52:34 GMT</pubDate>
            <atom:updated>2025-10-08T19:52:34.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYlPZ_Z9u1bIllqsxHnS0A.png" /></figure><p>Consensus is an integral part of building scalable and reliable distributed systems.</p><p>There is a fundamental challenge in defining certain measures and constructing mechanisms by which we can agree on the state of a system. This problem becomes far more critical in blockchain technology, where financial incentives and trust are at stake, and transparency becomes essential.</p><p>BFT refers to the ability of a decentralized network to correctly function and attain consensus even when some of its participating nodes are faulty, irregular, or malicious. The core aspect of BFT is to differentiate valid entities from fraudulent ones. For a system to prevent Byzantine failures, <strong>the total number of participants must be greater than three times the number of faulty (disloyal) participants—denoted by 3f + 1 nodes</strong>. PoS is typically a blockchain consensus mechanism where network validators (coin owners) are chosen to verify transactions and create new blocks based on the amount of cryptocurrency that has been staked. It uses financial incentives and penalties to ensure integrity is maintained. A key goal of PoS is to reduce the computational workload needed to verify transactions, which was a concern in PoW (Proof of Work), making it more energy efficient.</p><p>This brief paper aims to present a simple juxtaposition analysis between Byzantine Fault Tolerance and Proof of Stake.</p><p>Taking a closer look at Byzantine Fault Tolerance, a key feature is the network’s ability to function properly and attain consensus even when some nodes are faulty. For historical context, the Byzantine Generals’ Problem was first posed in 1987. A group of military officers surrounding a city must all agree on whether to attack or retreat. They can only communicate through messages, which may be intercepted or falsified by traitorous generals — resulting in untrustworthy information. Despite these challenges, a final decision must be made. A Byzantine failure occurs when a system cannot distinguish between functioning and faulty nodes, leading to confusion and fraudulent actions like double spending. BFT thrives in environments where high consistency, security, and fault tolerance are crucial. It ensures that all honest nodes share the same view of the system, eliminating conflicts. More specialized BFT-based algorithms — such as PBFT — are well-suited for private and permissioned networks, where participants are known and immediate finality is needed. Of course, BFT comes with trade-offs. It involves multiple rounds of communication and voting among validators and heavily relies on the assumption that a majority (typically more than two-thirds) of nodes are honest. If this threshold is not met, the system can be compromised. BFT systems can also be complex to implement due to their intricate design and communication overhead. Practical applications of BFT include corruption-resistant blockchains, safety-critical systems, and military environments where the integrity of information is vital.</p><p>Turning to Proof of Stake, this is an incentivized consensus mechanism that replaces the energy-intensive process of mining with validators. <strong>To become a validator, a coin owner must stake a specific amount of cryptocurrency, which serves as a form of economic security</strong>. This setup discourages malicious behaviour — since any attempt to cheat the system risks forfeiting the staked funds. Validators are selected at random, though those with a larger stake have a higher probability of being chosen.This stake-weighted approach ensures that participants with more to lose are more likely to act in the network’s best interest. Consensus is reached when validators propose and attest to adding new blocks. A proposal is typically validated if a specific proportion (often two-thirds or more) of validators have attested to it. PoS is notably energy-efficient, as it does not require heavy computation. It offers robust security by deterring Sybil attacks — where an attacker controls multiple nodes — since acquiring enough stake to dominate the network is financially prohibitive. It also avoids the resource-intensive competition for rewards seen in PoW systems, with validators earning transaction fees instead. However, PoS is not without drawbacks. It requires owning cryptocurrency to become a validator, which can limit participation. There’s also a risk of centralization in networks that demand a high minimum stake, restricting validator roles to a small group of wealthy participants. Nonetheless, PoS is widely adopted in public blockchain networks and cryptocurrency projects for implementing core consensus mechanisms. Comparing both consensus algorithms, we find similarities in their objectives but differences in execution. Both aim to secure distributed systems and ensure consensus, yet they adopt different methods. In BFT, nodes are fixed and typically authorized. In contrast, PoS allows participants to opt in by staking their funds. BFT relies on message-passing and explicit voting to achieve consensus, while PoS uses stake-weighted selection and economic incentives. As a result, PoS tends to scale better due to reduced communication overhead. In terms of fault tolerance, BFT sets mathematically provable limits, whereas PoS enforces economic penalties like slashing. Although PoS can, in theory, be vulnerable to 51% stake attacks, the cost of executing such an attack is prohibitively high.</p><p>In summary, BFT emphasizes deterministic agreement among a known group of participants and provides strong consistency guarantees — making it ideal for private blockchains and critical infrastructure. PoS, on the other hand, promotes open participation and scalability through economic incentives, and is widely used in public blockchain networks. It ensures energy efficiency and security by aligning validator interests with network integrity. To balance security, scalability, and decentralisation, hybrid consensus mechanisms — which combine elements of PoS and BFT — are gaining popularity in blockchain technology, offering more versatile solutions for a wider range of use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77474ae1477e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consensus in the Cluster: Locking Mechanism & How Raft Builds Reliable Distributed Systems]]></title>
            <link>https://medium.com/@dubemezeagwu/consensus-in-the-cluster-locking-mechanism-how-raft-builds-reliable-distributed-systems-ad11917fd441?source=rss-dac50d9fbc0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad11917fd441</guid>
            <category><![CDATA[raft]]></category>
            <category><![CDATA[distributed-locking]]></category>
            <category><![CDATA[consensus-algorithm]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Dubem Ezeagwu]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 13:29:02 GMT</pubDate>
            <atom:updated>2025-10-08T13:29:02.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpio296QoXHbfvxEwZ5Etw.jpeg" /></figure><h3>Introduction</h3><p>In distributed systems, it is a perpetual challenge figuring out how to maintain mutual exclusion and consistency across multiple nodes. In designing, building and implementing scalable and robust distributed systems, one must intentionally account for these requirements.</p><p>Distributed Locks play a vital role in ensuring harmonious and organised access to shared resources. Simplistically, it ensures that one process effectively gains access to a resource(s) at a given time, preventing conflicts and maintaining data integrity. Take for example — Scenario A (Absence of a lock) and Scenario B (Presence of a lock). In the first scenario, two users withdraw from the same bank account simultaneously. They will both read the same account balance, but let’s say, the cumulative amount to be withdrawn exceeds the current total amount in the account—this will lead to an overdraft. In the second scenario, we introduce a lock—still considering two users trying to initiate a transaction on an account. The lock allows exclusive access to whoever currently holds it. This will guarantee that each user gets the latest updated balance account on each transaction that is to be initiated. If the current balance on the account is less than the money to be withdrawn, the transaction fails. We can see that locks will ensure a synchronised input stream (only one transaction can be modified) and sequential ordering (User A’s transaction will be completed before User B’s transaction is processed).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-MbTmi6AdLk8kUXm.png" /><figcaption>Sequential Overview of Locks in a Distributed System</figcaption></figure><p>In this article, we will explore the design and implementation of a distributed lock using raft consensus algorithm written in Golang. The demonstration will be done further away from our data-store entity for the reasons being that we want to prevent unnecessary write operations which promotes system-wide coordination and concurrency-control improvements. I will highlight core cardinal principles related to Locks, Fault Recovery, Leader Election, Log Replications, etc., then technical implementations and approaches, then conclude by evaluating the performance, reliability, limitations and potential improvements to the approach.</p><p>• <strong>Problem Statement</strong> A crucial component of managing simultaneous operations is consistency and uniformity. A consistent view of the lock state should be available to all services when they execute write operations. A distributed lock ensures that only one operation can occur at a time by serialising access to critical components and making sure that no two activities interfere destructively. No system is 100% foolproof and are prone to crashes, errors, network failures, sudden restarts, irregular outputs, etc. But what makes distributed systems robust and reliable is the ability to handle the unforeseen and unpredictable circumstances. Without human assistance, the system must recognise a failure, decide what to do with the lock, and recover if a node holding it fails. Systems that lack this capabilities run the risk of experiencing repeated operations, deadlocks, orphaned locks. Handling scalability in high traffic systems to handle multiple users concurrently is important. Distributed locks guarantees the voluminous amounts of simultaneous requests are handled gracefully without having any performance bottleneck, even as the users base grows. There are three issues that need to be address which guarantee a foundational component for developing complex distributed coordinating systems — in this case, Locks.</p><ol><li>Ensure synchronised and ordered write operations.</li><li>Maintains a consistent lock state across all the nodes.</li><li>Automatic failure recovery and quick assignment of locks safely.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*vyVLfx7Yv5_URMlp6aDS-w.png" /><figcaption>Basic Raft Approach</figcaption></figure><p>• <strong>Proposed Solution</strong> Take for instance we are building a large-scale system that needs to be highly scalable, fault-tolerant and reliable. Our services are dispersed and deployed across multiple data centres in different regions and zones. These systems can be vital and important to the collective function of a bigger system like a database, or a message queue which needs to be highly available and consistent virtually at all times. There has to be a way where we can manage these services reliably to inform them about the state of their peers. This is singlehandedly usually the most challenging situation in building distributed systems — making multiple computer instances (node) act as one cohesive, reliable unit even when some of them fail. In distributed systems, like mentioned earlier, can have several factors that contribute to it’s failure which can result in messages and events getting delayed or dropped. In order to mitigate these pitfalls, we introduce <em>consensus algorithms</em>.</p><p>In simple terms, “consensus” means agreement. In our case, all nodes agree on the same value (want to access and update the value of a shared log or current leader of a cluster). But reaching consensus is far from being a straightforward approach.</p><p>In the past, Paxos was chosen as a go-to algorithm for distributed consensus. It’s logic is abstract, fragmented across different stages and parts such as prepare, promise, accept, etc., and getting it right in modern &amp; real-time systems is quite arduous. Other approaches that tried to address these concerns where prominent leader-based models such as Viewstamped Replication (VSR) and Zab (used by Zookeeper). Here a single coordinator (master node) will be responsible for handling all the write operations in the cluster and making sure all the peers are in the same state as itself.</p><p>Raft works by breaking down the logic into the following components:</p><ol><li><strong>Leader Election</strong>: One node in the cluster is elected to be the leader that handles all client requests.</li><li><strong>Log Replication</strong>: The leader appends the client commands to its write-ahead-logs and sends them to its peers to keep track of the active ones and replicate the latest logs with its peers.</li><li><strong>Safety Guarantees</strong>: Only the node which has the most up-to-date logs are elected to be leader to prevent inconsistencies.</li><li><strong>Term-based Voting</strong>: Elections are term-based to avoid confusion and split-brain scenarios. Splitting them into different processes makes it clearer and creates understandable modules making it easier to build it up from scratch. We will discuss the internal workings of Raft in detail and how we implemented them later in this report.</li></ol><blockquote>Raft is at the core of the popular container orchestration tool, Kubernetes’ distributed key-value store named etcd. Raft implementation on these projects help attain strong consistency and high availability requirements with transparent and predictable election process to heal itself in the background without little or no downtime.</blockquote><p>• <strong>Functional Capabilities</strong> The primary function is to ensure that for any given resource, only one client can hold a lock at time. With exclusive access to resources, coordinated by a Raft-elected leader. It maintains consistency through log-replication of lock operations, issues fencing tokens to prevent stale writes and supports TTL-based auto expiry of locks. FIFO queues fairly manage concurrent requests coming in, while clients interact through persistent WebSocket connections for real-time notifications and HTTP requests for data persistence. It will automatically recover from leader failures and support dynamic cluster membership, allowing servers to join or leave while maintaining a consistent state across the cluster.</p><h3>System Design</h3><h3>Core Components</h3><ol><li><strong>Data Store</strong>: A dedicated server listens on port 8000 and maintains a simple text file for persistence. Although not distributed in this implementation, it serves to demonstrate the interaction with our distributed lock mechanism. The data store exclusively handles client communications.</li><li><strong>Client</strong>: Clients connect to the server to acquire or release locks and to issue write requests. Multiple clients can be spawned to simulate various lock scenarios. After acquiring a lock on a specific key from one of the locking service servers, the client sends a write request to the data store.</li><li><strong>Cluster</strong>: The cluster is a group of servers participating in consensus. The system tolerates failures as long as a majority of nodes are operational. For simplicity, we consider a single cluster without advanced features like hinted handoff.</li><li><strong>Server</strong>: Each server in the cluster has a unique serverID. Servers listen for inter-server RPCs on ports starting at 8080 and for client HTTP (WebSocket) connections on ports starting at 50050 (offset by serverID). Every server hosts one Raft node, with the networking layer abstracted from the Raft logic.</li><li><strong>Node</strong>: The Node implements all Raft logic: it makes RPC calls to other nodes, coordinates consensus, grants locks to clients, and replicates lock operations across the cluster. It is the core of the distributed locking service.</li><li><strong>Log Entry</strong>: Each node maintains an in-memory storage structure called the Log. The Raft consensus algorithm revolves around keeping this log consistent across all nodes in the cluster. When a node becomes the leader for a term, it takes on the responsibility of appending new entries to the logs of its followers. Each log entry is associated with the term during which it was created, reflecting the leadership term at the time. An entry is considered committed when the leader receives acknowledgments from a majority of nodes in the cluster, ensuring that it is durably stored and agreed upon. Log entries can represent different types of commands, including: <strong>ADD SERVER, REMOVE SERVER, APPEND DATA, ACQUIRE LOCK, RELEASE LOCK.</strong></li><li><strong>Request Queue</strong>: Each Node maintains a <strong>FIFO</strong> queue for lock acquisition requests, organised by key. When a lock is released, the next request from the corresponding queue is processed. This mechanism minimises client polling by ensuring that a client receives a notification once its lock request is granted.</li><li><strong>Local Key-Value Store</strong>: Each node maintains a persistent key-value store to store its state. This store persists log entries, lock metadata, and other relevant information.</li><li><strong>Remote Procedure Call (RPC)</strong>: Each server communicates with its peers using RPC. We utilise <strong>Go’s built-in RPC library (net/rpc package)</strong> to handle inter-server communication. This mechanism is responsible for propagating lock operations and ensuring that all nodes in the cluster reach consensus.</li><li><strong>WebSocket</strong>: Clients establish a persistent WebSocket connection with the current leader to request lock operations. Once a lock is acquired, the leader uses the same connection to notify the client of the successful acquisition.</li><li><strong>HTTP</strong>: After acquiring a lock, the client sends write requests to the data store via <em>HTTP POST</em>. This decouples the lock service from the data persistence layer while maintaining a clear, standard interface for data operations.</li><li><strong>Fencing token</strong>: Upon lock acquisition, the server provides a monotonically increasing fencing token along with the notification. The data store uses this token to determine whether an update is the latest one. This mechanism prevents outdated or “dirty” writes if there is a disconnection between the client and the lock service.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j665HG9demrmGPFr.png" /><figcaption>Detailed view of interaction among Locking Service components</figcaption></figure><h3>APIs</h3><p>Here we are going to elaborate on all the APIs we have used and their roles in the design choice structure. We will represent the API interface definition using simple psuedo-TypeScript format for effectively describing the structure of the data being passed down different components.</p><h4>HTTP Protocol</h4><ol><li><strong>Write Data</strong>: The client communicates with the Data Store via an ==HTTP POST== request to write data. Along with the request, it includes the fencing token provided by the locking service. The Data store uses the token’s key and value to determine whether the write is valid, ensuring that only the latest, authorised requests are accepted and preventing stale writes.</li></ol><pre>// Write Request<br>interface WriteRequest {<br>    &quot;clientID&quot;: string<br>    &quot;fencingToken&quot;: {<br>        &quot;key&quot;: string<br>        &quot;value&quot;: number<br>    }<br>    &quot;data&quot;: string<br>}</pre><pre>// Write Response<br>interface WriteResponse {<br>    &quot;success&quot;: boolean<br>}</pre><h4>WebSocket Protocol</h4><ol><li><strong>Lock Acquire Release</strong>: After establishing a connection with the leader of the locking service, the client sends a lock acquisition request for a key. This allows for more accurate resource distribution as per request. The request includes a TTL (Time-To-Live) value, which specifies how long the client intends to hold the lock. This TTL allows the server to automatically release the lock after the specified duration, even if it does not receive an explicit release request from the client. This mechanism helps ensure fairness and prevents indefinite lock holding due to client failure or disconnection. If the server grants the lock, it responds over the same WebSocket connection with a message indicating success, along with a fencing token associated with the lock key. To release the lock, the client sends a release request using the same message format. However, no response is sent back from the server, as acknowledgment is not strictly necessary. The persistent WebSocket connection allows the client to wait passively for server notifications, eliminating the need for polling. This architecture reduces server load and keeps the server in control of lock state transitions.</li></ol><pre>// Lock Acquire Request<br>interface LockAcquireRequest {<br>    &quot;commandType&quot;: number<br>    &quot;key&quot;:         string<br>    &quot;clientID&quot;:    string<br>    &quot;ttl&quot;:         number <br>}</pre><pre>// Lock Acquire Response<br>interface LockAcquireReply {<br>    &quot;success&quot;: boolean<br>    &quot;fencingToken&quot;: {<br>        &quot;key&quot;: string<br>        &quot;value&quot;: number<br>    }<br>}</pre><h4>Remote Procedure Call (RPC) Protocol</h4><p>The RPC protocol is the foundation for all the inter-service communication we adopted in this system. Leveraging Go’s built in net\rpc package to communicate with it&#39;s peers.</p><ul><li><strong>Join Cluster</strong>: When a new server wants to join the cluster, it initiates a JoinCluster RPC call. First, a leader is discovered since only the current leader has the authority to add new members. It does this by connecting to any known server and &quot;hopping&quot; from one to another until it finds the node that identifies itself as the leader. To guarantee safety measures, Raft requires that the addition of a new server must be replicated and acknowledged by a majority of the cluster preventing outdated or partitioned nodes from impacting the cluster&#39;s consensus.</li></ul><pre>// Request from a server to join a cluster<br>interface JoinClusterArgs {<br>    &quot;serverId&quot;:   number<br>    &quot;serverAddr&quot;: string<br>}</pre><pre>// Response from the supposed leader of the cluster<br>interface JoinClusterReply {<br>    &quot;success&quot;:    boolean<br>    &quot;leaderId&quot;:   number<br>    &quot;leaderAddr&quot;: string<br>    &quot;term&quot;:       number<br>}</pre><ul><li><strong>Fetch Peer List</strong>: After a new server connects with a potential leader, the new server sends a FetchPeerList RPC to get the address of all the other members in the cluster. We need to know how account for handling possibilities here such as: handling leader changes and network instability. There&#39;s a chance from a practical viewpoint that a new leader has been elected between the time the join request was initiated and this request was sent. If the contacted server is no longer the leader, it will inform the joining node of the new leader&#39;s identity. This process is limited to a maximum of <em>5 retires</em> to avoid indefinite redirection. We do not necessarily require consensus for this RPC.</li></ul><pre>// Get all the members of the cluster<br>interface FetchPeerListArgs {<br>    &quot;term&quot;: number<br>}</pre><pre>// Response from the leader with list of all the peers in the cluster<br>interface FetchPeerListReply {<br>    &quot;success&quot;:    boolean<br>    &quot;term&quot;:       number<br>    &quot;leaderId&quot;:   number<br>    &quot;leaderAddr&quot;: string<br>    &quot;peerSet&quot;: { <br>        [id: number]: any <br>    }<br>    &quot;peerAddress&quot;: { <br>        [id: number]: string <br>    }<br>}</pre><ul><li><strong>Request Vote</strong>: When a follower’s election timer expires, it becomes a candidate and requests votes by sending a RequestVote RPC to all peers to initiate a new election. A candidate is elected leader if it secures a majority of votes. To maintain safety, followers only grant their vote if three conditions hold: the candidate’s term is higher than their own, they haven’t already voted in the current term (or voted for the same candidate), and the candidate’s log is at least as up-to-date as theirs. These voting rules ensure that only one leader can emerge per term and that the elected leader always has the most recent log entries.</li></ul><pre>// Request to contest in an election<br>interface RequestVoteArgs {<br>    &quot;term&quot;:         number<br>    &quot;candidateId&quot;:  number<br>    &quot;lastLogTerm&quot;:  number<br>    &quot;lastLogIndex&quot;: number<br>}</pre><pre>interface RequestVoteReply {<br>    &quot;term&quot;:        number<br>    &quot;voteGranted&quot;: boolean<br>}</pre><p>This code snippet below highlights the function implementing an intent to vote which is fundamental to leader elections.</p><pre>func (node *Node) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) error {<br>   node.mu.Lock()<br>   defer node.mu.Unlock()<br>  <br>   if node.state == Dead || !node.peerList.Exists(args.CandidateId) {<br>    return nil<br>   }<br>  <br>   lastLogIndex, lastLogTerm := node.lastLogIndexAndTerm()<br>  <br>   if args.Term &gt; node.currentTerm {<br>      node.becomeFollower(args.Term, int64(args.CandidateId))<br>   }<br>  <br>   if args.Term == node.currentTerm &amp;&amp;<br>      (node.votedFor == -1 || node.votedFor == int64(args.CandidateId)) &amp;&amp;<br>      (args.LastLogTerm &gt; lastLogTerm ||<br>       (args.LastLogTerm == lastLogTerm &amp;&amp; args.LastLogIndex &gt;= lastLogIndex)) {<br>    <br>      reply.VoteGranted = true<br>      node.votedFor = int64(args.CandidateId)<br>      node.electionResetEvent = time.Now()<br>   } else {<br>      reply.VoteGranted = false<br>   }<br>  <br>   reply.Term = node.currentTerm<br>   node.persistToStorage()<br>   return nil<br>}</pre><ul><li><strong>Append Entries</strong>: The AppendEntries RPC is a leader-only mechanism with two purposes: replicating new log entries and acting as a heartbeat when no new entries exist, preventing unnecessary elections. Each request carries the leader’s ID, current term, commit index, and details of the follower’s log state, enabling consistency checks. Followers validate the leader’s term and compare their logs at the specified index. If inconsistencies are found, they return a recovery index and term so the leader can quickly identify the divergence and resend the correct entries—an efficient alternative to step-by-step rollback.</li></ul><pre>interface AppendEntriesArgs {<br>    &quot;term&quot;:         number<br>    &quot;leaderId&quot;:     number<br>    &quot;lastLogIndex&quot;: number<br>    &quot;lastLogTerm&quot;:  number<br>    &quot;entries&quot;: {<br>        &quot;command&quot;: any<br>        &quot;term&quot;:    number<br>    }[]<br>    &quot;leaderCommit&quot;: number<br>}</pre><pre>interface AppendEntriesReply {<br>    &quot;term&quot;:          number<br>    &quot;success&quot;:       number<br>    &quot;recoveryIndex&quot;: number<br>    &quot;recoveryTerm&quot;:  number<br>}</pre><blockquote>This block of code below shows how the leader handles AppendEntries, and in a failed AppendEntries RPC uses recovery information from the follower.</blockquote><pre>func (node *Node) AppendEntries(args AppendEntriesArgs, reply *AppendEntriesReply) error {<br>    node.mu.Lock()<br>    defer node.mu.Unlock()    if node.state == Dead || !node.peerList.Exists(args.LeaderId) {<br>        return nil<br>    }<br>    if args.Term &gt; node.currentTerm || args.LeaderId != uint64(node.potentialLeader) {<br>        node.becomeFollower(args.Term, int64(args.LeaderId))<br>    }<br>    reply.Success = false<br>    if args.Term == node.currentTerm {<br>        if node.state != Follower {<br>            node.becomeFollower(args.Term, int64(args.LeaderId))<br>        }<br>        node.electionResetEvent = time.Now()<br>        if args.LastLogIndex == 0 ||<br>            args.LastLogIndex &lt;= uint64(len(node.log)) &amp;&amp; args.LastLogTerm == node.log[args.LastLogIndex-1].Term {<br>            reply.Success = true<br>            node.log = append(node.log[:args.LastLogIndex], args.Entries...)<br>            for _, entry := range args.Entries {<br>                switch cmd := entry.Command.(type) {<br>                case AddServer:<br>                    ...<br>                case RemoveServer:<br>                    ...<br>                case LockReleaseCommand:<br>                    ...<br>                }            }<br>            if args.LeaderCommit &gt; node.commitLength {<br>                node.commitLength = uint64(math.Min(float64(args.LeaderCommit), float64((len(node.log)))))<br>                node.newCommitReady &lt;- struct{}{}<br>            }<br>        } else {<br>            if args.LastLogIndex &gt; uint64(len(node.log)) {<br>                reply.RecoveryIndex = uint64(len(node.log)) + 1<br>                reply.RecoveryTerm = 0<br>            } else {<br>                reply.RecoveryTerm = node.log[args.LastLogIndex-1].Term<br>                reply.RecoveryIndex = 1<br>                for i := args.LastLogIndex - 1; i &gt; 0; i-- {<br>                    if node.log[i-1].Term != reply.RecoveryTerm {<br>                        reply.RecoveryIndex = i + 1<br>                        break<br>                    }<br>                }<br>            }<br>        }<br>    }<br>    reply.Term = node.currentTerm<br>    node.persistToStorage()<br>    return nil<br>}</pre><ul><li><strong>Append Data</strong>: all client read and write operations are routed through the current leader using the AppendData RPC. The leader appends the request as a new log entry and replicates it to followers via Append Entries. Once a majority acknowledge the entry, it is committed and applied to the leader’s state machine. This ensures a consistent global order of operations and prevents clients from seeing stale data.</li><li><strong>Remove Server</strong>: Any server that wishes to leave the cluster can use the RemoveServer RPC. The leader handles this request by appending a Remove Server command to its log, which is then replicated across the cluster to ensure all nodes agree on the new cluster membership.</li></ul><h3>Implementation Details</h3><h4>How the Raft Cluster Operates</h4><p>We have three distinct roles that define our cluster operation, which are: Follower, Candidate or Leader. Each node can assume any of these roles but not both or all. This system is implemented entirely in Golang.</p><ul><li><strong>Follower</strong>: Every node starts off as a follower. Its primary responsibility is to track the leader by listening for periodic heartbeats, which are sent as AppendEntries RPCs. Each follower maintains a <em>randomised election timer</em> in a background goroutine. If a heartbeat is received, the follower resets this timer. If the timer expires without a heartbeat, the follower transitions to the candidate state and initiates a new election. To optimize this, the implementation uses a Go ticker that checks the timer every 10 milliseconds rather than continuously.</li></ul><pre>func (node *Node) runElectionTimer() {<br>    timeoutDuration := node.electionTimeout()<br>    node.mu.Lock()<br>    termStarted := node.currentTerm<br>    node.mu.Unlock()<br>    ticker := time.NewTicker(10 * time.Millisecond)<br>    defer ticker.Stop()<br>    for {<br>        &lt;-ticker.C<br>        node.mu.Lock()<br>        if node.state != Candidate &amp;&amp; node.state != Follower {<br>            node.mu.Unlock()<br>            return<br>        }<br>        if termStarted != node.currentTerm {<br>            // fmt.Printf(&quot;Term changed from %v to %v for peer %v\n&quot;, termStarted, node.currentTerm, node.id)<br>            node.mu.Unlock()<br>            return<br>        }<br>        if elapsed := time.Since(node.electionResetEvent); elapsed &gt;= timeoutDuration {<br>            node.startElection()<br>            node.mu.Unlock()<br>            return<br>        }<br>        node.mu.Unlock()<br>    }<br>}<br><br>func (node *Node) electionTimeout() time.Duration {<br>    if os.Getenv(&quot;RAFT_FORCE_MORE_REELECTION&quot;) == &quot;true&quot; &amp;&amp; rand.Intn(3) &gt; 0 {<br>        return time.Duration(1500) * time.Millisecond<br>    } else {<br>        return time.Duration(1500+rand.Intn(1500)) * time.Millisecond<br>    }<br>}</pre><ul><li><strong>Candidate</strong>: the Candidate state is a transitional but critical role that ensures the cluster can always recover leadership when the current leader fails or becomes unreachable. A node becomes a Candidate when its election timer expires without receiving a heartbeat from the leader. At that moment, it assumes responsibility for initiating an election by incrementing its term, voting for itself, and broadcasting RequestVote RPCs to all peers. This process marks the node’s shift from a passive follower to an active participant vying for leadership. It&#39;s primary goal is to secure the votes from a majority of nodes, which grants it the authority to transition into the Leader role for that term. Randomized election timeouts help in reducing the likelihood of multiple simultaneous candidates and split votes. However, elections can result in 3 possible outcomes:</li><li>The candidate wins and becomes the leader.</li><li>Discovers another node that has been elected as the leader, or has a higher term during the election and therefore steps back down to be a Follower once again.</li><li>Or the election ends in a stalemate, prompting the Candidate to restart the process by incrementing the term and holding a new vote.</li></ul><pre>func (node *Node) startElection() {<br>    node.state = Candidate<br>    node.currentTerm += 1<br>    // fmt.Printf(&quot;Calling startElection() by %d for term %d with peers: %v\n&quot;, node.id, node.currentTerm, node.peerList)<br>    candidacyTerm := node.currentTerm<br>    node.electionResetEvent = time.Now()<br>    node.votedFor = int64(node.id)<br>    node.potentialLeader = int64(node.id)<br>    votesReceived := 1<br>    go func() {<br>        node.mu.Lock()<br>        defer node.mu.Unlock()<br>        if node.state == Candidate &amp;&amp; votesReceived*2 &gt; node.peerList.Size()+1 {<br>            node.becomeLeader()<br>        }<br>    }()<br><br>    for peer := range node.peerList.peerSet {<br>        go func(peer uint64) {<br>            node.mu.Lock()<br>            lastLogIndex, lastLogTerm := node.lastLogIndexAndTerm()<br>            node.mu.Unlock()<br>            args := RequestVoteArgs{<br>                Term:         candidacyTerm,<br>                CandidateId:  node.id,<br>                LastLogIndex: lastLogIndex,<br>                LastLogTerm:  lastLogTerm,<br>            }<br>            var reply RequestVoteReply<br>            if err := node.server.RPC(peer, &quot;RaftNode.RequestVote&quot;, args, &amp;reply); err == nil {<br>                // fmt.Printf(&quot;Got reply back from RequestVote on %d from peer %v -&gt; %v\n&quot;, node.id, peer, reply)<br>                //update nextIndex here?<br>                node.mu.Lock()<br>                defer node.mu.Unlock()<br>                if node.state != Candidate {<br>                    return<br>                }<br>                if reply.Term &gt; candidacyTerm {<br>                    node.becomeFollower(reply.Term, -1)<br>                    return<br>                }<br>                if reply.Term == candidacyTerm &amp;&amp; reply.VoteGranted {<br>                    votesReceived += 1<br>                    if votesReceived*2 &gt; node.peerList.Size()+1 {<br>                        node.becomeLeader()<br>                        return<br>                    }<br>                }<br>            }<br>        }(peer)<br>    }<br><br>    go node.runElectionTimer()<br>}</pre><p><strong>Leader</strong>: — Once elected, the leader handles all client requests and manages log replication. It processes different commands by appending them as entries to its log:</p><ul><li><strong>Log Replication</strong>: The leader runs a dedicated goroutine to send AppendEntries RPCs to all followers. This happens either when a heartbeat timer expires or is triggered immediately by a Go channel when a new log entry is added.</li><li><strong>Commitment</strong>: An entry is considered <em>committed</em> once the leader confirms it has been successfully replicated on a majority of nodes. The leader then notifies followers of the newly committed entry.</li><li><strong>Conflict Resolution</strong>: If a follower’s log is inconsistent with the leader’s, the follower returns a recovery index and recovery term. This allows the leader to efficiently find the point of divergence and resend only the necessary entries, which is much faster than decrementing its log index one by one to find the conflict point.</li></ul><p>This block of code below shows the process of a becoming a new leader. Here, we can observe how the leader queries the key-value store to find the keys corresponding to held locks, and then re-spawning the monitoring goroutines for each one to ensure they are eventually released.</p><pre>func (node *Node) becomeLeader() {<br>    fmt.Printf(&quot;Node %d has become Leader for Term %d\n&quot;, node.id, node.currentTerm)<br>    node.state = Leader<br>    node.potentialLeader = int64(node.id)<br>    for peer := range node.peerList.peerSet {<br>        node.nextIndex[peer] = uint64(len(node.log)) + 1<br>        node.matchedIndex[peer] = 0<br>    }<br>    lockKeyValues := node.getAllLockKeyValues()<br>    for key, lockInfo := range lockKeyValues {<br>        // fmt.Printf(&quot;key: %s, value %v\n&quot;, key, lockInfo)<br>        ctx, cancel := context.WithCancel(context.Background())<br>        node.activeLockExpiryMonitorCancel[key] = cancel<br>        go node.monitorLockExpiry(ctx, key, lockInfo.ExpiryTime)<br>        // fmt.Printf(&quot;added stuff for key %s\n&quot;, key)<br>    }<br>    go func(heartbeatTimeout time.Duration) {<br>        node.sendEntriesToFollowers()<br>        timer := time.NewTimer(heartbeatTimeout)<br>        defer timer.Stop()<br>        for {<br>            doSend := false<br>            select {<br>            case &lt;-timer.C:<br>                doSend = true<br>                timer.Stop()<br>                timer.Reset(heartbeatTimeout)<br>            case _, ok := &lt;-node.trigger:<br>                // fmt.Printf(&quot;becomeLeader running on node %d, leader, term = %v, %v\n&quot;, node.id, node.state, node.currentTerm)<br>                if ok {<br>                    doSend = true<br>                } else {<br>                    return<br>                }<br>                if !timer.Stop() {<br>                    &lt;-timer.C<br>                }<br>                timer.Reset(heartbeatTimeout)<br>            }<br>            if doSend {<br>                if node.state != Leader {<br>                    return<br>                }<br>                node.sendEntriesToFollowers()<br>            }<br>        }<br>    }(50 * time.Millisecond)<br>}</pre><pre>type NodeState int<br><br>const (<br>    Follower NodeState = iota<br>    Candidate<br>    Leader<br>    Dead<br>)</pre><p>The primary relationship between a server and a node is that the server provides the communication infrastructure, while the node running on the server is the logical entity that provides and facilitate consensus. They are distinctively two separate but essential components that work together to create a functional member of a Raft cluster.</p><pre>type Server struct {<br>    id          uint64<br>    mu          sync.Mutex<br>    peerList    Set<br>    peerAddress map[uint64]string<br>    rpcServer   *rpc.Server<br>    listener    net.Listener<br>    peers       map[uint64]*rpc.Client<br>    quit        chan interface{}<br>    wg          sync.WaitGroup<br>    wsClients   map[string]*websocket.Conn<br>    wsMu        sync.Mutex<br>    node        *Node<br>    db          *Database<br>    commitChan  chan CommitEntry<br>    ready       &lt;-chan interface{}<br>}<br><br><br>type Node struct {<br>    id                            uint64<br>    mu                            sync.Mutex<br>    peerList                      Set<br>    server                        *Server<br>    db                            *Database<br>    commitChan                    chan CommitEntry<br>    newCommitReady                chan struct{}<br>    trigger                       chan struct{}<br>    currentTerm                   uint64<br>    potentialLeader               int64<br>    votedFor                      int64<br>    log                           []LogEntry<br>    commitLength                  uint64<br>    lastApplied                   uint64<br>    state                         NodeState<br>    electionResetEvent            time.Time<br>    nextIndex                     map[uint64]uint64<br>    matchedIndex                  map[uint64]uint64<br>    activeLockExpiryMonitorCancel map[string]context.CancelFunc<br>    pendingLockQueue              map[string]*[]LockRequest<br>    pullLockRequestChan           map[string](chan struct{})<br>}</pre><h4>Lock Acquisition Process</h4><p>The process of acquiring a lock involves a carefully coordinated process between the leader and the client.</p><ol><li><strong>Client Leader Discovery</strong>: A client first discovers the current leader by randomly connecting to any known server in the cluster, which then redirects it to the actual leader. The client establishes a persistent <em>WebSocket connection</em> with the leader to send lock requests. If the leader fails or disconnects, the client’s discovery service <em>transparently re-initiates the process</em> and resends the original lock request to the newly elected leader.</li><li><strong>Request Queuing and Processing</strong>: The leader manages concurrent requests using a key specific <em>FIFO (First-In, First-Out)</em> queue. In the lock service, incoming lock requests are always added to a per-key queue. If the lock is free, the request is processed right away but still passes through the queue, coordinated by a dedicated Go channel (pullLockRequestChan). This design avoids client-side polling and reduces system load.</li><li><strong>Consensus and State Update</strong>: The lock acquisition is treated as a command that must achieve consensus. When handling a lock request, the leader generates a new fencing token and calculates an expiry time from the client’s TTL. It appends this information to its log and replicates the entry to followers. Once a majority commit, all nodes update their state to show the lock is held. To avoid inconsistencies, followers ignore any lock entries that have already expired by the time they are applied.</li><li><strong>Client Notification</strong>: After the log entry is committed, the leader notifies the client of the successful lock acquisition over the same WebSocket connection, sending back the fencing token.</li></ol><pre>func (node *Node) handleLockAcquireRequest(req LockRequest) {<br>    node.mu.Lock()<br>    if queuePtr, exists := node.pendingLockQueue[req.Key]; exists {<br>        *queuePtr = append(*queuePtr, req)<br>    } else {<br>        node.pendingLockQueue[req.Key] = &amp;[]LockRequest{req}<br>    }<br>    lockRequestPing, exists := node.pullLockRequestChan[req.Key]<br>    if !exists {<br>        lockRequestPing = make(chan struct{}, 1)<br>        node.pullLockRequestChan[req.Key] = lockRequestPing<br>        go node.registerLockAcquireRequest(node.pendingLockQueue[req.Key], lockRequestPing)<br>    }<br>    node.mu.Unlock()<br>    var value LockInfo<br>    lockKey := fmt.Sprintf(&quot;%s%s&quot;, LOCKING_KEY_PREFIX, req.Key)<br>    if found, readErr := node.readFromStorage(lockKey, &amp;value); readErr != nil {<br>        fmt.Printf(&quot;could not read from db for key %s\n&quot;, req.Key)<br>        return<br>    } else if !found {<br>        // fmt.Printf(&quot;sent ping\n&quot;)<br>        lockRequestPing &lt;- struct{}{}<br>    }<br>}</pre><h4>Lock Release Process</h4><p>A lock can be released either explicitly by the client or automatically by the server when its Time-To-Live (TTL) expires.</p><ul><li><strong>Client-Initiated Release</strong>: A client can send a release request asynchronously over its WebSocket connection. The client does not wait for a response, as acknowledgement is not required.</li><li><strong>Server-Initiated (Automatic) Release</strong>: When a lock is acquired, the leader spawns a <strong>dedicated background goroutine</strong> to monitor it. This goroutine waits efficiently until one of two events occurs: the lock’s <strong>TTL expires</strong> or a forced release is triggered. Once activated, the goroutine’s only task is to append a lock release command to the log, after which it terminates to conserve resources.</li><li><strong>Releasing Logic</strong>: When a lock release is triggered, the leader appends the release command to its log and immediately updates its state to mark the lock as free. The command is replicated to followers to keep the cluster consistent. Once committed, the leader signals its queue manager (pullLockRequestChan) to process the next pending request for that key, ensuring smooth handoff of the lock.</li></ul><pre>func (node *Node) monitorLockExpiry(ctx context.Context, key string, expiryTime time.Time) {<br>    duration := time.Until(expiryTime)<br>    select {<br>    case &lt;-ctx.Done():<br>        fmt.Printf(&quot;Lock %q expiry monitoring cancelled\n&quot;, key)<br>        return<br>    case &lt;-time.After(duration):<br>        var lockInfo LockInfo<br>        lockKey := fmt.Sprintf(&quot;%s%s&quot;, LOCKING_KEY_PREFIX, key)<br>        found, readErr := node.readFromStorage(lockKey, &amp;lockInfo)<br>        if readErr != nil {<br>            fmt.Printf(&quot;Reading the lock info from db went wrong&quot;)<br>            return<br>        }<br><br>        if found {<br>            if time.Now().After(lockInfo.ExpiryTime) {<br>                fmt.Printf(&quot;Lock %q automatically expired and called release lock\n&quot;, key)<br>                cmd := LockReleaseCommand{<br>                    Key:      key,<br>                    ClientID: lockInfo.Holder,<br>                }<br>                node.newLogEntry(cmd)<br>                return<br>            }<br>        }<br>    }<br>}</pre><h4>Fault Tolerance: Graceful Lock Recovery from Leader Crashes</h4><p>This system is designed to gracefully handle leader failures to ensure that locks are not permanently orphaned and that client requests are not lost.</p><ul><li><strong>The Challenge</strong>: A leader crash can leave locks in a “held” state without being properly released. Furthermore, the leader’s in-memory FIFO queues of pending lock requests are lost upon failure.</li><li><strong>The Solution</strong>: The system uses its <strong>persistent key-value store</strong> as the definitive source of truth for lock status, as this store is kept consistent via Raft.</li></ul><ol><li><strong>Lock Handoff</strong>: When a new leader is elected, it queries the persistent database to identify all locks that are still considered active (i.e., their keys still exist in the store) and retrieves their metadata, such as the owner and expiry time.</li><li><strong>Re-monitoring</strong>: The new leader then spawns new background goroutines to monitor these recovered locks, ensuring they will be released when their TTLs expire.</li><li><strong>Queue Reconstruction</strong>: Although the in-memory queues are lost, clients are designed to <em>automatically retry their requests</em> when they detect a leader failure. These retried requests allow the new leader to reconstruct a similar queue of pending requests.</li></ol><h3>Challenges &amp; Solutions</h3><p><strong>Inefficient Election Timing and Heartbeat Monitoring</strong></p><ul><li><strong>Challenge:</strong> The initial implementation for monitoring leader heartbeats and triggering elections was inefficient, leading to repeated or infinite election loops during network instability. Continuously tracking election timeouts was also resource-intensive and costly on the CPU.</li><li><strong>Solution:</strong> The system was optimized by using a <strong>Go ticker</strong> that fires every 10 milliseconds, combined with <strong>Go channels</strong> that act as triggers. This design wakes the monitoring goroutine only periodically or when a heartbeat is received, which significantly reduces CPU overhead and prevents “runaway elections” while still ensuring timely failure detection.</li></ul><p><strong>Eliminating Stale Writes</strong></p><ul><li><strong>Challenge:</strong> A client could acquire a lock, lose its connection, and then attempt to write to the data store with an outdated request. This created a risk of “dirty” or stale writes corrupting the data, which would render the locking mechanism ineffective.</li><li><strong>Solution:</strong> The system introduced <strong>fencing tokens</strong>. These are monotonically increasing counters issued by the locking service each time a lock is acquired. The separate Data Store uses these tokens to validate every write request, ensuring that only the request with the latest token is accepted and processed. There’s a slight caveat to our curent fencing token measure. It may not be robust, but it is pragmatic enough to handle basic race conditions involving uncommitted logs.</li></ul><p><strong>Handling Leader Crashes and Request Loss</strong></p><ul><li><strong>Challenge:</strong> The Raft algorithm by itself does not solve the problem of locks being held indefinitely if a leader crashes. Furthermore, the leader’s in-memory FIFO queues for pending lock requests would be lost upon failure, causing those requests to be dropped.</li><li><strong>Solution:</strong> A multi-step recovery mechanism was implemented. When a new leader is elected, it: <strong>Queries the persistent key-value store</strong> to identify all currently held locks and their metadata (like expiry time). <strong>Spawns new goroutines</strong> to resume monitoring these recovered locks for expiry. <strong>Reconstructs the request queues</strong> as clients automatically detect the disconnection and resend their pending lock requests to the new leader. This entire recovery process is transparent to the client.</li></ul><p><strong>Efficient Background Task Management</strong></p><ul><li><strong>Challenge:</strong> Naively implementing background tasks, such as monitoring the Time-To-Live (TTL) for lock expiry, by continuously checking timers was resource-intensive and not scalable under high load.</li><li><strong>Solution:</strong> An event-driven approach was used. For each acquired lock, a dedicated goroutine is spawned, but it <em>remains idle until triggered</em>. This goroutine is activated only when the lock’s TTL expires or a forced release is requested, making resource usage more efficient. Important to note, the project focuses on assuming clock accuracy across nodes and ignores the complexity of clock drift, which is a non-negotiable requirement for robust distributed locking in production environment.</li></ul><p><strong>Maintaining Monotonic Fencing Tokens</strong></p><ul><li><strong>Challenge:</strong> Ensuring fencing tokens were always strictly increasing was difficult. If multiple lock requests were in-flight, simply reading the last token value from the database before it was committed could lead to inconsistencies and race conditions.</li><li><strong>Solution (Current):</strong> A pragmatic solution was adopted where the system only retrieves and increments the token value at the moment it <em>pulls the next request from the queue</em>. Since this only happens when the lock is free, it is considered a “safe” operation for now, though the authors acknowledge it is not a robust long-term solution.</li></ul><p><strong>Planned Solutions for Future Challenges</strong></p><ul><li><strong>Byzantine Attacks:</strong> A malicious client could send a very high fencing token to force an outdated write. Future work plans to integrate the data store alongside the locking service and use an encrypted authentication token to validate requests.</li><li><strong>Log Divergence:</strong> In rare cases, a follower might apply an uncommitted log entry (e.g., Remove Server) and change its state, only for that entry to be replaced by a new leader, causing inconsistency. Future work would involve designing reconciliation processes to handle these subtle scenarios.</li></ul><h3>Conclusion</h3><p>The project produced a working prototype of a fault-tolerant and scalable distributed locking system built on the Raft consensus algorithm. Its central aim was to tackle the challenges of <strong>consistency, fault tolerance, and coordination</strong> that are common in distributed systems. The resulting system can process concurrent lock requests safely, recover from leader failures without disruption, and maintain a consistent view of lock states across all nodes. Beyond functionality, the project also provided practical insight into how consensus algorithms like Raft can be applied to create reliable and scalable distributed systems.</p><p>The implemented system offered a robust set of capabilities. It ensured exclusive access to resources through leader-based coordination and log replication, while also introducing fairness with FIFO queues for pending requests. Fault tolerance was built in through automatic leader detection and recovery, allowing clients to reconnect and continue seamlessly after failures. Stale writes were prevented using fencing tokens, which enforced freshness in client operations. Locks were also managed automatically using TTL values, ensuring they expired safely if clients disconnected. Finally, the cluster itself could scale dynamically, with Raft coordinating membership changes to keep all nodes synchronized.</p><p>Technologically, the system was written in Go, leveraging its concurrency features such as goroutines and channels for background processing and event-driven communication. Raft formed the foundation by providing leader election, log replication, and safety guarantees, while the architecture separated locking logic from data persistence to improve modularity. Internal communication between servers used RPC, while clients interacted with the leader over WebSockets for real-time notifications and communicated with the data store via HTTP. This design highlighted the value of combining consensus protocols with carefully chosen communication mechanisms to achieve efficiency and scalability.</p><p>From a learning perspective, the project underscored that Raft alone does not solve all application-level challenges. Mechanisms such as fencing tokens and recovery logic were essential to prevent stale writes and ensure robustness after leader crashes. It also demonstrated the importance of efficient resource management, showing how Go’s event-driven concurrency can reduce overhead in tasks like heartbeat monitoring. Additionally, the project highlighted that consensus is best reserved for critical state changes, rather than every operation, to balance consistency with system performance.</p><p>Despite its strengths, the system has room for improvement. Fencing token generation, while functional, is not fully safe against race conditions, and Byzantine attack resilience is limited by the possibility of malicious clients injecting invalid tokens. Edge cases such as log divergence also require reconciliation processes for better reliability. Finally, the use of leader-based clocks for TTL introduces a dependency on accurate timekeeping, leaving the system vulnerable to clock drift. Addressing these limitations in future iterations would make the system more resilient and production-ready.</p><h3>References and Sources</h3><ul><li><a href="https://github.com/dubemezeagwu/distributed-lock-raft">Github Repository</a></li><li>van Steen, M., &amp; Tanenbaum, A. S. (2023). Distributed systems (4th ed.) (Chapter 5.4, Election Algorithms)</li><li><a href="https://raft.github.io/raft.pdf">In Search of an Understandable Consensus Algorithm (Extended Version) <em>by Diego Ongaro and John Ousterhout</em></a></li><li><a href="https://www.youtube.com/watch?v=szw54UbPJRE">Distributed Locking Deep Dive</a> Youtube Video by Jordan has no Life</li><li><a href="https://thesecretlivesofdata.com/raft/">Nice visualization of Raft Algorithm</a></li><li><a href="https://www.youtube.com/watch?v=uXEYuDwm7e4&amp;list=PLeKd45zvjcDFUEv_ohr_HdUFe97RItdiB&amp;index=18&amp;ab_channel=MartinKleppmann">Raft Consensus Algorithm Explanation</a> Youtube Video by Martin Kleppmann</li><li><a href="https://github.com/debajyotidasgupta/raft-consensus">Great implementation of Raft Consensus Algorithm.</a> The project is highly inspired by it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad11917fd441" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BLoC (A Reactive Approach using RxDart & Streams).]]></title>
            <link>https://medium.com/@dubemezeagwu/bloc-a-reactive-approach-using-rxdart-streams-f480fb6a12c8?source=rss-dac50d9fbc0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f480fb6a12c8</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[rxdart]]></category>
            <dc:creator><![CDATA[Dubem Ezeagwu]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 18:24:51 GMT</pubDate>
            <atom:updated>2022-04-16T00:45:16.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*_JES7w4mR-7M8str.jpg" /></figure><p>Hello guys! I haven’t written an article in a while, and I felt I needed to put out something. I decided to cover a two-part series on the famous BLoC Pattern in Flutter. Hope you learn something at the end of this 🙂. Bless!</p><p>I will be starting with the first part of this series building a simple short app implementation that gets the latest tech news from an API. Before I start I will love to cover some key terminologies briefly and what they mean.</p><p><strong>What is Reactive Programming?</strong></p><p>Reactive programming is basically <strong>programming with asynchronous observable streams</strong>. In Dart, streams provide an asynchronous sequence of data.</p><p><a href="https://pub.dev/packages/rxdart"><strong>RxDart</strong></a> is a dart-based implementation of reactive programming. If you’re coming from the Android development world, RxJava + RxAndroid, Coroutines could be a good fit for you. A similar concept has been implemented in the Dart programming language. RxDart is a ReactiveX-supported reactive functional programming library for the Dart language. Dart already has a good package for working with Streams, but RxDart extends it with new features. But, you might be wondering, what exactly is <a href="https://dart.dev/tutorials/language/streams"><strong>Stream</strong></a>? I will try to visualize a scenario here.</p><p>Consider a pipe with two ends, only one of which allows you to insert things into it, to readily grasp the concept of Stream. When you put something into a pipe, it flows through the pipe and out the other end.</p><p>In Flutter the pipe is called a Stream. Ideally, we use a StreamController to pass something into a Stream where the StreamController exposes the entry point using the <strong>sink</strong> property. To exit the stream we use the <strong>stream</strong> property of the Controller. From a value, an event, an object, a collection, a map, an error or even another Stream, any type of data may be conveyed by a Stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*kLrCGm7rwmsmhKb5.png" /><figcaption>A basic stream channel</figcaption></figure><p>We can also subscribe to Streams so we listen to values, by using a StreamSubscription object. But all of these are out of scope for this article. I will add links below so you can learn more about Streams and its functionalities such as StreamTransformers and how RxDart creates subjects (BehaviourSubject, PublishSubject and ReplaySubject) as broadcast stream-controllers.</p><ol><li><a href="https://www.youtube.com/watch?v=53jIxLiCv2E"><em>Simple Beginners Guide to Streams by Filled Stacks</em></a> on YouTube.</li><li><a href="https://medium.com/@dltlabs/simplifying-subjects-in-rxdart-2ea6fe94495"><em>Let’s Look at Subjects in RxDart</em></a> by Dilshad Haidari, DLT Labs<em> </em>on Medium. (Personal Fav 💙)</li></ol><p><strong>BLoC! BLoC! What is BloC?</strong></p><p>It is a predictable state management library for Flutter recommended by Google developers. It helps in managing state and make access to data from a central place in your project. <a href="https://bloclibrary.dev/#/"><strong>BLoC</strong></a> is an abbreviation for Bussiness Logic Component. It can also be considered an architectural pattern whereby our project is divided predominantly into 3 layers. In Android, BLoC can easily be co-related to the MVVM and MVP architecture. ViewModel is your BLoC layer in Flutter. (<em>For my Android devs</em> 😁)</p><ol><li>The UI layer:- where we create our widgets and all visual components of our app. This is the layer the user sees and interacts with to create events.</li><li>The BLoC layer:- we write all our business logic functionalities here and do most of our error handling and exceptions. BloCs can interact with one another and subscribe to its streams and emitted states accordingly.</li><li>The Data layer:- We have our repositories, data providers (e.g. an API) and data models in this layer. Network requests are made here as well.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H3ReAIcdpHXvBwWZ.png" /><figcaption>The BLoC pattern</figcaption></figure><p>Under the hood of BLoC, it is just Streams quite abstracted.</p><p>Thanks to the decoupling of the Business Logic from the UI:</p><p>* We may change the Business Logic at any time, with a minimal impact on the application,</p><p>* We may change the UI without any impact on the Business Logic,</p><p>* We can easily write tests and their cases for our business logic.</p><h4>Let’s start building our app. 🤙🏽</h4><p>I assume you have Flutter and Dart installed on your local machine. And you know how to use the terminal in your IDE.</p><blockquote>1. First, create a new project and clear all the code in the main.dart file. Type the below command in your terminal:</blockquote><p>flutter create myProjectName</p><blockquote><em>2. Type the following code in your main.dart file</em></blockquote><pre><strong>import </strong>&#39;package:bloc_medium_post/ui/home_page.dart&#39;;<br><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>void </strong>main<em>() {<br>  </em>runApp<em>(</em><strong>const </strong>MyApp<em>())</em>;<br><em>}<br><br></em><strong>class </strong>MyApp <strong>extends </strong>StatelessWidget <em>{<br>  </em><strong>const </strong>MyApp<em>({</em>Key? key<em>}) </em>: <strong>super</strong><em>(</em>key: key<em>)</em>;<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build<em>(</em>BuildContext context<em>) {<br>    </em><strong>return </strong>MaterialApp<em>(<br>      </em>debugShowCheckedModeBanner: <strong>false</strong>,<br>      title: &#39;Bloc Medium Post&#39;,<br>      theme: ThemeData.dark<em>()</em>,<br>      home: <strong>const </strong>HomePage<em>()</em>,<br>    <em>)</em>;<br>  <em>}<br>}</em></pre><p>At this point, You should get an error indicating no instance or reference of the HomePage() widget.</p><blockquote>3. Inside the <strong>src</strong> package under the <strong>lib</strong> package, create a file and name it home_page.dart and add the following code. Add the code below:</blockquote><pre><strong>import </strong>&#39;package:flutter/material.dart&#39;;<br><br><strong>class </strong>HomePage <strong>extends </strong>StatefulWidget <em>{<br>  </em><strong>const </strong>HomePage<em>({</em>Key? key<em>}) </em>: <strong>super</strong><em>(</em>key: key<em>)</em>;<br><br>  @override<br>  State<em>&lt;</em>HomePage<em>&gt; </em>createState<em>() </em>=&gt; _HomePageState<em>()</em>;<br><em>}<br><br></em><strong>class </strong>_HomePageState <strong>extends </strong>State<em>&lt;</em>HomePage<em>&gt; {<br>  </em>@override<br>  Widget build<em>(</em>BuildContext context<em>) {<br>    </em><strong>return </strong>Scaffold<em>();</em><br>  <em>}<br>}</em></pre><blockquote>4. Now, we create a few packages i.e. bloc, data &amp; UI as shown in the below diagram and then we start adding the files of the project.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*5NIzSxH9FAnzuZ6lSJ75EA.png" /><figcaption>Project structure</figcaption></figure><p>Our BLOC implementation files will be stored in the bloc package. The model class of the JSON response we will receive from the server will be stored in the data package alongside the repository class and the network call implementation class will be in the data package. Our screens that will be visible to the user will be stored in the UI package. Move the home_page.dart file we created earlier into the UI package as well.</p><blockquote>5. One last thing we have to add is our dependencies (third-party libraries). It is advised to use the latest dependencies when working on a new project because at the time you might be reading this article, an upgraded version of this library might be available. Go to <a href="http://pub.dev/"><strong>pub.dev</strong></a> to view the latest version of each library. Open your <strong>pubspec.yaml</strong> file and add <strong>rxdart</strong>: ^0.27.3 and <strong>http </strong>^0.13.4 as shown below:</blockquote><pre><strong>dependencies</strong>:<br>  <strong>flutter</strong>:<br>    <strong>sdk</strong>: flutter<br><br><br>  <em># The following adds the Cupertino Icons font to your application.<br>  # Use with the CupertinoIcons class for iOS style icons.<br>  </em><strong>cupertino_icons</strong>: ^1.0.2<br>  <strong>rxdart</strong>: ^0.27.3<br>  <strong>http</strong>: ^0.13.4</pre><p>Sync the dependencies by running this command in your terminal.</p><p>flutter pub get</p><p>We are now finished creating the project’s skeleton. It’s time to tackle the project’s most fundamental layer, the data (network) layer. We would be going to a NewsAPI website, that has the API endpoint that we’ll be using. You’ll be directed to the news database API site if you click this <a href="https://newsapi.org/"><strong>link</strong></a>. From the home page of the website, sign up and acquire your API key. To receive the response, we’ll use the following URL:</p><p><a href="https://newsapi.org/v2/top-headlines?sources=techcrunch&amp;apiKey=API_KEY">https://newsapi.org/v2/topheadlines<strong>sources=techcrunch</strong>&amp;apiKey=</a><a href="http://api.themoviedb.org/3/movie/popular?api_key=802b2c4b88ea1183e50e6b285a27696e">“</a>your_api_key”</p><p>Please, do not expose your api_key publicly as it is unique and anyone who has access to it can change certain things from your API point. Remove the double quotes when inserting your api-key into the URL. If you test the URL the raw response you should be getting is something like this.</p><pre>&quot;status&quot;: &quot;ok&quot;,</pre><pre>&quot;totalResults&quot;: 10,</pre><pre>&quot;articles&quot;: [</pre><pre>{</pre><pre>&quot;source&quot;: {</pre><pre>&quot;id&quot;: &quot;techcrunch&quot;,</pre><pre>&quot;name&quot;: &quot;TechCrunch&quot;</pre><pre>},</pre><pre>&quot;author&quot;: &quot;Christine Hall&quot;,</pre><pre>&quot;title&quot;: &quot;Slope brings on new CFO, customers, capital as it rises to offer businesses buy now, pay later&quot;,</pre><pre>&quot;description&quot;: &quot;Its API technology can approve businesses for the BNPL in seconds so they can begin offering the installments.&quot;,</pre><pre>&quot;url&quot;: &quot;https://techcrunch.com/2022/04/15/slope-series-a-buy-now-pay-later-b2b-payments/&quot;,</pre><pre>&quot;urlToImage&quot;: &quot;https://techcrunch.com/wp-content/uploads/2022/04/L1020402.jpg?w=711&quot;,</pre><pre>&quot;publishedAt&quot;: &quot;2022-04-15T12:02:54Z&quot;,</pre><pre>&quot;content&quot;: &quot;Slope, which provides businesses an easy way to offer buy now, pay later services, has had a busy six months. Thats not much of a surprise, given that the buy now, pay later market size was valued at… [+4553 chars]&quot;</pre><pre>},</pre><pre>{</pre><pre>&quot;source&quot;: {</pre><pre>&quot;id&quot;: &quot;techcrunch&quot;,</pre><pre>&quot;name&quot;: &quot;TechCrunch&quot;</pre><pre>},</pre><pre>&quot;author&quot;: &quot;Manish Singh&quot;,</pre><pre>&quot;title&quot;: &quot;Swiggy backs bike taxi platform Rapido in $180 million funding&quot;,</pre><pre>&quot;description&quot;: &quot;Swiggy has led a $180 million financing round into bike taxi startup Rapido as the Indian food delivery giant looks to broaden its fleet network across the country, the two firms said on Friday. Rapido’s Series D financing round also saw participation from TV…&quot;,</pre><pre>&quot;url&quot;: &quot;https://techcrunch.com/2022/04/15/swiggy-rapido/&quot;,</pre><pre>&quot;urlToImage&quot;: &quot;https://techcrunch.com/wp-content/uploads/2022/04/GettyImages-1233588990.jpg?w=600&quot;,</pre><pre>&quot;publishedAt&quot;: &quot;2022-04-15T08:39:23Z&quot;,</pre><pre>&quot;content&quot;: &quot;Swiggy has led a $180 million financing round into bike taxi startup Rapido as the Indian food delivery giant looks to broaden its fleet network across the country, the two firms said on Friday.\r\nRap… [+2060 chars]&quot;</pre><pre>},</pre><blockquote>7. For this form of response, let’s create a model class. Make a new file called model.dart inside the data package. Inside the item model.dart file, add the code below</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ra5-nF54lf4T3kdrfXBKHw.png" /><figcaption>model.dart for the model classes.</figcaption></figure><p>It’s now time to get down to business with the network setup. Make a service.dart file in the data package. Inside the file, add the code below, and I’ll explain it to you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibUiQ8OYD0-69rpiEfIdfQ.png" /><figcaption>news_api_provider.dart</figcaption></figure><p>We created a variable for URL and the apiKey, getArticles() method is an asynchronous method making the network call to the API. Once the network call is successful (200) it’s returning a <a href="https://api.dartlang.org/stable/2.0.0/dart-async/Future-class.html"><strong>Future</strong></a><strong> </strong>List&lt;NewsArticle&gt;object, basically, a list of news articles, if the network call was successful it will return the list or it will throw an Exception.</p><blockquote>9. After that, we’ll make a new file called repository.dart inside the data package. Inside the file, copy and paste the following code:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4oSGZpNX4kZfq1Etktf0w.png" /><figcaption>repository.dart</figcaption></figure><p>Then we import the <strong>api_service.dart</strong> file which has the NewsApiProvider class and calls its <strong>fetchAllNews()</strong> method. This Repository class is the point from where the data will flow to the BLOC.</p><blockquote>10. Now comes the portion that is a little more difficult. Putting the bloc logic into action. Let’s make a new file called bloc.dart inside the bloc package. Add the code below, and I’ll explain it to you:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCdEqdpvbCd_mZ_i0WdRhw.png" /><figcaption>bloc.dart</figcaption></figure><p>Here we are importing a package called ‘package:rxdart/rxdart.dart,’ which will import all of the RxDart-related methods and classes in this file. We then create the Repository class object inside the NewsBloc class, which will allow us to make use of the fetchAllNews method (). We’re going to make a StreamController object whose job is to add the data it gets from the server to the sink in the form of a List&lt;NewsArticle&gt; object and stream it to the UI screen. We added another getter function allMovies(), whose return type is Stream, to pass the List&lt;NewsArticle&gt; object as a stream. As you can see in the last line, we’re making a bloc object. Whenever data is received from the server, The UI screen needs to be changed. To make this work more efficient, we inform the UI screen to keep an eye on any changes coming from the MoviesBloc class and update your content accordingly. RxDart can be used to accomplish this “observing” of fresh data.</p><blockquote>11. Finally, we add more implementation to our home_page.dart file in the UI package. The code is below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8L_RVzBhp3pfYocUvyYl4g.png" /><figcaption>home_page.dart</figcaption></figure><p>As I previously stated, the new data is passed as a stream to our NewsBloc class. To deal with streams, we have a handy built-in class called StreamBuilder that listens for incoming streams and updates the UI accordingly. We are providing the NewsBloc’s allNews() function, which returns a stream, to StreamBuilder, which expects a stream argument. We use the Floating Action Button which has an onPressed () argument, where we pass a callback function that calls fetchAllNews ()function from the bloc. As soon as a new stream of data arrives, StreamBuilder will automatically re-render the widget with the most recent data every time the latest news changes. The List &lt;NewsArticle&gt;object is held in the snapshot data. You may now use any Widget to show whatever is in the object (Here your creativity comes into the picture). I abstracted the widget by creating it as a standalone widget. In it, I used a ListView.builder to create a list of all the latest news available at the moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uw5Cx4rfe9I-zFmvzZfIwQ.png" /><figcaption>This is what the app should look like when it is launched.</figcaption></figure><p>Once we click the button to get the latest news, a network request is made which returns a list of news articles. Please make sure you’re connected to the internet unless it will not work. I am using an iPhone emulator here provided by XCode to demo my app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hPPcs3mxF4LWJI2NhYdpQ.png" /><figcaption>If your call is successful, we should get this.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSpCdFjUZgWjvSGm_H7P4A.png" /></figure><p>We have come to the end of this article 😅. Thanks for rocking with me till the end. I’m very sure at the end of this you have a basic understanding of working with streams and RxDart under the BLOC pattern. If you have any doubts or questions do connect with me on <a href="https://www.linkedin.com/in/dubemezeagwu/"><strong>Linkedin</strong></a> or <a href="https://twitter.com/wysdubem"><strong>Twitter</strong></a>. If you love listening to music, you can check out my playlist of the recent most played tracks on <a href="https://open.spotify.com/playlist/37i9dQZF1EpocwtlunZfyT?si=57eeacc9649b445c"><strong>Spotify</strong></a>. Please appreciate the article with some claps, comments and additions to improve this article as I will love to improve it with inputs.</p><p>Some other very interesting articles worth reading:</p><ul><li><a href="https://www.burkharts.net/apps/blog/">Fundamentals of Dart Streams</a> [Thomas Burkhart]</li><li><a href="https://pub.dartlang.org/packages/rx_command">rx_command package</a> [Thomas Burkhart]</li><li><a href="https://medium.com/flutter-io/build-reactive-mobile-apps-in-flutter-companion-article-13950959e381">Build reactive mobile apps in Flutter — companion article</a> [Filip Hracek]</li><li><a href="https://skillsmatter.com/skillscasts/12254-flutter-with-streams-and-rxdart">Flutter with Streams and RxDart</a> [Brian Egan]</li></ul><p>If you want the complete code. Here is the <a href="https://github.com/dubemezeagwu/bloc_medium_post"><strong>GitHub repository</strong></a> of the project. Bless!💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f480fb6a12c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between normal classes & data classes in Kotlin.]]></title>
            <link>https://medium.com/@dubemezeagwu/difference-between-normal-classes-data-classes-in-kotlin-a01f636e8900?source=rss-dac50d9fbc0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a01f636e8900</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[Dubem Ezeagwu]]></dc:creator>
            <pubDate>Thu, 04 Nov 2021 22:51:14 GMT</pubDate>
            <atom:updated>2022-04-15T18:25:41.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZl7IctlxajWrzZkp0gjjg.jpeg" /></figure><p>Recently, I got into a bootcamp for 6 months to further my career in becoming a Software Engineer (Mobile App Development) to be precise. I decided to write a short article on what a data class &amp; normal class in Kotlin and a few differences.</p><h4><strong>What is a class?</strong></h4><p>A class is a blueprint for an object; it shares common properties and behaviour in form of members and member functions.</p><p>In Kotlin, a class is declared with the class keyword. The class declaration consists of the class name, the class header (specifying its type parameters, the primary constructor etc.).</p><p>So technically, an object is an instance of a class.</p><pre>class Person {<br><br>    val name: String = &quot;Dubem&quot;<br>    val age: Int = 22<br>    fun info() = &quot;This is $name and my age is $age&quot;<br>}<br><br>fun main() {<br><br>    val person = Person()<br>    <em>println</em>(person)<br>    <em>println</em>(person.name)<br>    <em>println</em>(person.age)<br><br>}</pre><p>In the example, we declare a <strong>Person</strong> class and later create an object from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5bDDsaV_IjqyUunuKO76w.png" /><figcaption>This is the output we get when, we run the code</figcaption></figure><h4>What is a data class?</h4><p>Data class is a simple class which is used to hold data/state and contains standard functionality. A <strong>data</strong> keyword is used to declare a class as a data class. With data classes, we can considerably reduce the boilerplate code. Compiler automatically creates the equals, hashCode, toString, and copy functions.</p><pre>data class User(val name: String, val email: String)<br><br>fun main() {<br><br>    val u1 = User(&quot;Dubem Ezeagwu&quot;, &quot;dubemezeagwu@gmail.com&quot;)<br>    <em>println</em>(u1)<br><br>    <em>println</em>(u1.name)<br>    <em>println</em>(u1.email)<br><br>    val (name, email) = u1<br>    <em>println</em>(&quot;$name $email&quot;)<br><br>    val u2 = User(&quot;Dubem Ezeagwu&quot;, &quot;dubemezeagwu@gmail.com&quot;)<br><br>    <em>println</em>(u1 == u2)  // Structural equality<br>    <em>println</em>(u1 === u2)  // Referential equality<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOGunXim4tzAYXypIDoq_A.png" /><figcaption>This is the output we get when, we run the code.</figcaption></figure><h4>Differences between data classes and normal classes.</h4><ol><li>A data class must be declared with at least one primary constructor parameter which must be declared with val or var. A normal class can be defined with or without a parameter in its constructor.</li><li>Data classes have default implementations for the following methods using only properties that were declared in the primary constructor; toString(), hashCode(), copy(), componentN(), equals(). Implementation for those methods can be written in normal classes using properties that were and were not declared in the primary constructor.</li><li>A data class cannot be extended by another class. They are final classes by default. Normal classes can be extended by other classes, including data classes. Certain conditions should however be met.</li><li>Data classes cannot be sealed, open, abstract or inner. Normal classes can be any of these.</li></ol><blockquote>So there you have it! A brief overview of what classes &amp; data classes are, and how they are both different in their own specific ways. I hope I have been able to explain these concepts and you have a basic understanding. Cheers!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a01f636e8900" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>