<?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 Abdelrahman Ibrahim on Medium]]></title>
        <description><![CDATA[Stories by Abdelrahman Ibrahim on Medium]]></description>
        <link>https://medium.com/@aibrahimblog?source=rss-7c199a3ca7a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nGEu7BTqa5Hbn0ANfiCFOA.png</url>
            <title>Stories by Abdelrahman Ibrahim on Medium</title>
            <link>https://medium.com/@aibrahimblog?source=rss-7c199a3ca7a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:28:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aibrahimblog/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[Clocks, Chaos and Consensus]]></title>
            <link>https://medium.com/@aibrahimblog/clocks-chaos-and-consensus-20145139f7f9?source=rss-7c199a3ca7a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/20145139f7f9</guid>
            <category><![CDATA[vector-clocks]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[consensus]]></category>
            <dc:creator><![CDATA[Abdelrahman Ibrahim]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 17:14:48 GMT</pubDate>
            <atom:updated>2025-09-30T17:16:29.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>What time is it?</h4><p>Easy question, right? You look at your phone and it confidently say 11:30 pm, your laptop agrees, even your smart watch nods along. The world feels synchronized.</p><p>But behind the scenes, these devices might actually be arguing about what “now” really means. One thinks it’s a few milliseconds ahead, another is slightly behind, and the last one is living in the future.</p><p>In the physical world, we take time for granted but in distributed systems, time is messy. Every machine has its own clock, its own idea of the “present” and it’s not guaranteed that they are always in sync.</p><p>Those tiny disagreements might sound harmless, but they add up. Before you know it, you’re wondering who wrote some data first, or why your logs are <em>going back in time</em>.</p><h4><strong>What is the computer clock, anyways?</strong></h4><p>To understand how the computer keeps track of time we must first understand the foundational heartbeat of a computer, the <strong>CPU clock speed or frequency.</strong></p><p>The CPU runs at specific frequency, this is expressed in <strong>Hz </strong>where 1 Hz = 1 cycle per second. While it’s tempting to think that 1 Hz equals 1 instruction per second, the reality is more complex and depends on the CPU’s architecture. A processor’s clock speed measures how many cycles/opportunities to compute, it gets per second. A very simple instruction might finish in one cycle, but a more complex one can take many.</p><p>But for simplicity lets <strong><em>assume</em> </strong>we have a single core processor that can run 1 instruction per second but normally this isn’t the case.</p><p>Let’s apply this logic to a 2 GHz CPU (2 Billion instructions / second), if we want to keep track of time we can simply <strong><em>count</em> </strong>how many cycles have passed, for example if we count 1B cycles we can say that 0.5 seconds have passed. However counting every simple cycle is not efficient as running a program that keeps track of counts for every cycle would leave no resources for other programs that run.</p><p>To address this, computers use something called a <strong><em>clock oscillator</em></strong><em>, </em>the oscillator basically takes the CPU frequency and tones it down to a more manageable frequency to keep track of time, such as 100 Hz or 100 cycles.<br>Now this 100 Hz frequency can be used to interrupt the processor to execute a program that keeps track of time.</p><p>This however creates two problems<br>1- Accuracy<strong><br></strong>The accuracy of the system depends on the accuracy of the oscillator. If the interrupt is fired 100 times per second (every 10 milliseconds), the time accuracy can never be smaller than 10 ms<br>2- Power Loss<br>If the computer is turned off then the CPU is off as well, and it can’t keep track of time anymore</p><h4><strong>The persistent Clock</strong></h4><p>Computers have a dedicated component called RTC (Real Time Clock), it is a tiny chip responsible for keeping track of time, even when power is off.</p><p>The RTC keeps time by running a small amount of electricity through a <strong>quartz crystal. </strong>This makes the quartz vibrate at a precise, specific frequency, which is <strong>32,768 </strong>Hz<strong>, </strong>by counting these vibrations the RTC is able to keep track of time.</p><p>Just like watches, RTC is powered by a small battery which that keeps it running when computer is off. A dead RTC is often the reason why old machines lose track of time and revert to a default date.</p><p>An RTC isn’t 100% accurate, depending on the temperature, aging of crystals and manufacturing variations it can gain or lose up few seconds every 30 days, this phenomenon is called <em>clock drift.</em></p><h4><strong>Network Time Protocol</strong></h4><p>NTP is an application layer protocol in the TCP/IP protocol suite. It is used to synchronize the clock between the client and the server to provide time correction. The NTP servers receive accurate (UTC) from an <strong>authoritative clock source, such as an atomic clock or GPS</strong>. Then, the clients request and receive time from the NTP server.</p><p>NTP uses a hierarchical structure of time sources, each level of this hierarchy is called a <strong>stratum</strong> and these <strong>strata</strong> determine <em>how accurate (synchronized) a device clock is</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JRgAUazEGDcT9HFcZcLBg.png" /></figure><p>There are 16 <strong>strata</strong> numbered from 0 to 15</p><ul><li>Stratum 0: A server directly connected to an authoritative clock, those are the <em>“ground truth of time”</em></li><li>Stratum 1: Servers that sync directly with a stratum 0 device. They provide highly accurate time to other servers or devices.</li><li>Stratum 2–15: Each stratum level syncs with servers in the stratum above it. The higher the stratum number, the farther it is from the authoritative clock and <strong><em>the less precise it may be</em></strong></li></ul><h4><strong>Synchronization Mechanism</strong></h4><p>The most typical NTP mode is client/server mode where client requests the NPT server to correct its time.</p><ul><li>Client sends a request packet to one of NTP’s servers, the packet contains <em>Timestamp 1</em> <em>when packet leaves the client</em></li><li>NTP server receives the packet at <em>Timestamp 2</em> and returns a response packet to the client at <em>Timestamp 3</em></li><li>Client receives the response at <em>Timestamp 4</em></li></ul><p>The client then calculates the round trip delay and offset as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*58metLXDn_MHfBWAhciCsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*zKkTW5PI1XqoOpHKZ4cAZQ.png" /></figure><p>The NTP client adjusts its clock based on delay and the offset value.<br>Curious about what stratum your machine is? you can run <em>ntpq -p on linux</em></p><pre>ntpq -p<br>     remote           refid      st t when poll reach   delay   offset   jitter<br>===============================================================================<br> 0.ubuntu.pool.n .POOL.          16 p    -  256    0   0.0000   0.0000   0.0001<br> 1.ubuntu.pool.n .POOL.          16 p    -  256    0   0.0000   0.0000   0.0001<br> 2.ubuntu.pool.n .POOL.          16 p    -  256    0   0.0000   0.0000   0.0001<br> 3.ubuntu.pool.n .POOL.          16 p    -  256    0   0.0000   0.0000   0.0001<br>+prod-ntp-5.ntp1 183.160.133.132  2 u  248  256  377 185.0831 -51.2555  41.3536<br>+89.36.162.11    103.250.184.52   3 u   25  256  377  13.9614 -43.0095  13.0531<br>+89.44.86.85     194.190.168.1    2 u  249  256  377 172.0101 -17.4887  35.6020<br>-47.91.111.180   192.36.143.150   2 u  204  256  377  19.4982 -15.7658   8.8693<br>*2a13:8a40::368  204.9.54.119     2 u  237  256  377  12.7947 -33.3931   5.6809<br>-2001:ac8:81:65: 185.125.190.58   3 u  374  512  377  88.8850  22.4443  38.2365<br>-2001:ac8:81:65: 185.125.190.58   3 u  466  512  377  89.9264  17.0021  32.4577</pre><p>The machine is configured to use multiple NTP servers. The first 4 entries are Ubuntu pool servers (configured as pools), and the rest are individual servers your system discovered and is monitoring. We can see that we tried to connect to multiple servers, the ones prefixed with “+” are considered good servers, “-” are rejected (maybe too far or unreliable) and our machine synced to the server prefixed with “*” (2a13:8a40::368) which has a st of 2, this means our machine has stratum of 3.</p><h4>The Causality Puzzle: When ‘Before’ Isn’t Simple</h4><p>A distributed system consists of collection of separated nodes which communicate through messages. In such systems even if the nodes clocks are perfectly synchronized it is sometimes hard to know the order of events “messages” especially when <strong><em>causality</em></strong> is involved.</p><p>Let’s look at an example, imagine we are in a chat room, A sends a message “What’s your fav. color” to users B and C. Due to some network delay the message arrives late to user C (marked in red).</p><p>User B replies after receiving the message with “Blue” and sends this to both A and B. Surprisingly the reply is sent earlier to user C, intuitively the second message was a reply to the first message but for user C it will appear like this</p><ul><li>Blue</li><li>What’s your fav. color?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*-Fsph7XCH9X7P3arG1bePQ.png" /></figure><p>Now you might be thinking, easy we can just sort them by timestamp right? From the figure we can see that at T1 (which is user A’s machine physical time) the first message was sent and at T2 (user B’s machine physical time) the second message was sent. So sorting these timestamps at user C machine should get us this output</p><ul><li>What’s your fav. color?</li><li>Blue</li></ul><blockquote>However this is not the case, because it’s actually possible that T2 is <strong>less than</strong> T1</blockquote><p>Why T₂ Can Be Less Than T₁ (even with NTP, clocks are not perfectly aligned)</p><ul><li>Clock Skew<br>- Imagine A’s clock is 5 milliseconds fast, and B’s clock is 3 milliseconds slow. <br>- The total skew between them is 8ms (A’s clock is 8ms ahead of B’s)</li><li>Network Delay (One way)<br>- Assume the message takes 2 ms to go from A to B</li></ul><p>Now, let’s follow the event in “true” time</p><ul><li>At true time 1000 ms, A sends the message. Its fast clock reads T1 = 1000 + 5 = 1005</li><li>The message travels for 2ms, arriving at B at true time 1002 ms</li><li>B immediately replies. Its slow clock reads T2 = 1002 – 3 = 999 ms</li></ul><p>So now T2 &lt; T1 even though message one happened before message two in real time.</p><blockquote><strong>This time ordering failure happened because the clock skew (8ms) was greater than the network delay (2ms).</strong> If the delay had been longer than the skew (e.g 10ms), T2 would have been greater than T1, and physical timestamps would have worked. Since we can’t guarantee this, we cannot rely on physical clocks to order events”</blockquote><h4><strong>Causality</strong></h4><p>In distributed systems what we really care about is</p><ul><li>Did one even <em>happen before </em>another?</li><li>Is one message <em>response</em> to another?</li></ul><p>Physical clocks are very useful but as we have seen so far they are inconsistent with causality, so let’s introduce another concept which is <strong>logical clock. </strong>Logical clock is basically the count of events that have occurred so far.<br>In a sense they are clocks that are not related to physical time, it’s just incrementing a counter whenever an event happens and as expected this counter is always <strong>increasing.</strong></p><p>There are two ways to solve this ordering issue, Lamport Clocks &amp; Vector clocks.<br>But before diving into them lets introduce a simple happens before annotation, <strong>A → B</strong> means A <em>happened before</em> B</p><h4><strong>Lamport Clocks</strong></h4><p>We define a clock Cᵢ for each Nodeᵢ in the system to be a function which assigns a number Cᵢ(a) for each event at Nodeᵢ. Each node would have a local counter with default value of 0. Lets say initially Node₀ counter is 0 then Node₀ does some internal event a, this is what happens on Node₀</p><ul><li>Node₀(a) = counter + 1</li><li>counter = counter + 1</li></ul><p>Now based on logical clocks, for a system of clocks to be correct (synchronized) our definition must be based on the <strong>order</strong> of events, the most reasonable condition is that if event a happened before b then a should happen at earlier time than b, or more formally</p><blockquote>if a → b then C(a) &lt; C(b)</blockquote><p>However the converse is not true, why?</p><p>We <strong>cannot</strong> definitively say that a caused b. They might be completely unrelated events that occurred on different machines and just happened to get those clock values. Lamport clocks give us <strong>partial</strong> ordering, but they can&#39;t distinguish between causal and concurrent events given the logical clock.</p><p>Also if we said that the opposite is true it would imply that concurrent events happen at the same time which would contradict the clock condition we agreed on already, lets illustrate this with a simple example</p><ul><li>Imagine A sends an event at logical time 5</li><li>At the same physical time, B sends an event at logical time 7</li><li>These two events are concurrent, and no one caused the other</li></ul><p>If we forced “smaller logical time” to always <strong><em>imply causality</em></strong>, we’d incorrectly conclude that A must have happened before B, even though they are unrelated.</p><p>Even worse, if C(a) = C(b), we would be forced to say they happened <em>at the same time</em>, which might not be true either, they just coincidentally got the same clock value.</p><p>To include, <strong><em>causality</em></strong> (a → b) implies C(a) &lt; (b) but the inverse doesn’t imply causality.</p><h4><strong>Lamport Clock Algorithm</strong></h4><p>Each Nodeᵢ in the system initially has a local counter set to 0</p><ul><li>Increment on every event<br>Whenever a node performs any event (process message, internal event, …etc) it increments the counter</li><li>When a node sends a message to another node, it attaches its current logical clock to the message</li><li>When a node receives a message from another node with logical clock T it updates its local clock as the following<br>C = max(C, T) + 1, where C is the receiving node local clock</li></ul><p>This ensures the receiver clock always move forward to ensure the causal order, however the limitation mentioned earlier still exists.<br>Given two clocks for two events C(a) and C(b) we can’t say whether a → b or a concurrent with b</p><h4><strong>Vector Clocks</strong></h4><p>Vector clocks take this a step further by allowing one to compare any two events and check to see if they are causally dependent or concurrent. Put another way, not only can you show that if a“happens before” b, then C(a) &lt; C(a), you can also assert the converse: if C(a) &lt; C(b) then a &quot;happened before&quot; b</p><p>Suppose we have N nodes</p><ul><li>Each Nodeᵢ has Vᵢ which is a vector of logical clocks for all Nodes<br>Assume N = 3, then initially every Nodeᵢ will have vector Vᵢ = {0, 0, 0}, these are the logical clocks of all nodes including Nodeᵢ<em> </em>itself</li><li>On internal events at Nodeᵢ it would just increment the ith position in the Vᵢ, so assuming Node₀ does some internal event and V₀ = {1, 3, 0} then the new V₀ becomes {2, 3, 0}</li><li>On sending a message, Nodeᵢ attaches the Vᵢ to the message</li><li>On receiving<br>- Nodeᵢ merges its vector clock Vᵢ with the received vector clock in the message by taking the element wise maximum between the two vectors<br>- Nodeᵢ increments its entry in Vᵢ to mark the receiving event<br>e.g Vᵢ = {2, 4, 3} and received vector Rⱼ = {1, 5, 6}. <br>After merging Vᵢ becomes {2, 5, 6} then increments its counter so final Vᵢ = {3, 5, 6}</li></ul><p>Let’s visualize this so we can have a better feel on what’s going on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*iGh4TjlHWj0wSWaKWvRCeA.png" /></figure><p>This diagram shows three processes (A, B, C) with vector clocks tracking events and message passing:</p><ul><li>Each process starts at {0, 0, 0}</li><li>B has an internal event and updates its vector clock to {0, 1, 0}</li><li>A has an internal event and updates its vector clock to {1, 0, 0}</li><li>A sends <strong>message 1</strong> with its clock {1, 0, 0} to B</li><li>B receives, merges (takes max element wise), increments its own counter → becomes {1, 2, 0}</li><li>B has another internal event → updates to {1, 3, 0}</li><li>B sends <strong>message 3</strong> with its clock to C</li><li>C merges, increments → becomes {1, 3, 2}</li><li>Meanwhile, C had its own internal event earlier → {0, 0, 1} → and sends <strong>message 2</strong> to A</li><li>A merges and increments → {2, 0, 1}</li></ul><p>So far this is great, but how does this help in identifying causality or concurrency based on the vector clocks?</p><p>Imagine C(a) = {x₁, x₂, x₃, … xₙ} and C(b) = {y₁, y₂, y₃, … yₙ}</p><p>Assume that <strong>xᵢ ≤ yᵢ</strong> for every element i ∈ {1 …. n} and there is <strong>at least one</strong> element <strong>xᵢ &lt; yᵢ.<br></strong>what does this imply?</p><ul><li>if <strong>xᵢ ≤ yᵢ </strong>for all i<br>Every node knows at least as much about past events at time b as it did at time a. (Meaning b &quot;happened after&quot; everything a had seen)</li><li>if at least one <strong>xᵢ &lt; yᵢ<br></strong>There is <strong>some process i</strong> where b knows strictly more than a did, this means that b is actually <strong>strictly</strong> later in causal time</li><li>if neither C(A) ≤ C(B) nor C(B) ≤ C(A) is true then we can safely say that A and B are concurrent</li></ul><p>An example of a causal event from our example can be</p><ul><li>The event at A with clock {1,0,0} causally precedes the event at B with clock {1,3,0}, because all elements in the first clock are ≤ the corresponding elements in the second clock and <strong>at least one is strictly less than than corresponding time </strong>(0 &lt; 3)</li></ul><p>while a concurrent event is</p><ul><li>The event at A with clock {2,0,1} is concurrent with the event at B with clock {1,3,0}<br>because neither {2, 0, 1} ≤ {1, 3, 0} or {1, 3, 0} ≤ {2, 0, 1} holds</li></ul><h4>From Chaos to Order: A Final Thought</h4><p>It’s funny. We spend our lives ruled by the clock, but we’ve seen that in the digital world of distributed systems, the clock can lie.</p><p>The big takeaway isn’t that we need better clocks. It’s that we need a better way to think about order. We need to stop asking “What time is it?” and start asking “What happened first?”</p><p>So while our devices may never truly agree on what “now” is, they have a clever way to agree on the story of what happened. And in a distributed world, that’s the only time that truly matters.</p><p>Anyways, the next time your chat messages appear in perfect order or an online purchase goes through without a hitch, take a second to appreciate the silent, invisible logic at work :))</p><h4>Resources</h4><ul><li><a href="https://en.wikipedia.org/wiki/Vector_clock">https://en.wikipedia.org/wiki/Vector_clock</a></li><li><a href="https://www.mobatime.com/technology/ntp-network-time-protocol/">https://www.mobatime.com/technology/ntp-network-time-protocol/</a></li><li><a href="https://lamport.azurewebsites.net/pubs/time-clocks.pdf">https://lamport.azurewebsites.net/pubs/time-clocks.pdf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20145139f7f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tagless Final]]></title>
            <link>https://medium.com/@aibrahimblog/tagless-final-e2407c20a0f8?source=rss-7c199a3ca7a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2407c20a0f8</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[final-tagless]]></category>
            <category><![CDATA[monads]]></category>
            <dc:creator><![CDATA[Abdelrahman Ibrahim]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 18:12:24 GMT</pubDate>
            <atom:updated>2025-09-29T18:12:24.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*o1lvdIeKNHY-bZblHQjOqw.jpeg" /></figure><p>If you’ve been working with Scala, especially in the pure functional programming world, you’ve probably heard of the <em>tagless final</em> pattern.</p><p>The tagless final pattern solves the difficulty of extending a data type with both new data variants and new operations on those data types without modifying existing code, while maintaining static type safety which is something called the <strong><em>Expression Problem</em></strong>.</p><p>Today we’re going to demystify this whole thing using a relatable example, we’ll simulate a simple payment processing system. Because let’s be honest, who hasn’t dealt with payments in their coding career?</p><h2>The problem that started it all</h2><p>Imagine we are building a simple payment system, where we have multiple operations like bank transfers, credit card operations, wallet transfers.</p><p>Let’s start with a naive approach and see where that takes us</p><pre>sealed trait Operation<br>case class CreditCardCharge(amount: Double, cardNumber: String) extends Operation<br>case class WalletTransfer(amount: Double, walletId: String) extends Operation<br>case class BankTransfer(amount: Double, accountNumber: String) extends Operation<br>def processOperation(op: Operation): String = op match {<br>  case CreditCardCharge(amount, cardNumber) =&gt; <br>    s&quot;Charged $amount to credit card ending in ${cardNumber.takeRight(4)}&quot;<br>  case WalletTransfer(amount, walletId) =&gt; <br>    s&quot;Transferred $amount from wallet $walletId&quot;<br>  case BankTransfer(amount, accountNumber) =&gt; <br>    s&quot;Transferred $amount from bank account $accountNumber&quot;<br>}</pre><p>here we just made a trait Operation and extended it for our three operations, notice how the return type of all three Operation is the same as the return type of processOperation, but is it always this simple?</p><h2>When reality hits</h2><p>This is when things get interesting, your Product Manager walks in while you’re sipping your coffee and goes <em>“The fraud team</em> wants risk scores as numbers <em>and we need to audit transactions with timestamps”</em></p><p>Now our previous solution needs to return <strong>different</strong> types based on each operation</p><pre>sealed trait Operation<br>case class CreditCardCharge(amount: Double, cardNumber: String) extends Operation<br>case class WalletTransfer(amount: Double, walletId: String) extends Operation<br>case class BankTransfer(amount: Double, accountNumber: String) extends Operation<br>// new operations<br>case class CalculateRiskScore(amount: Double, userId: String) extends Operation<br>case class TransactionLog(operation: String, userId: String) extends Operation<br>def processOperation(op: Operation): Any = op match {<br>  case CreditCardCharge(amount, cardNumber) =&gt; <br>    s&quot;Charged $amount to credit card ending in ${cardNumber.takeRight(4)}&quot;<br>  case WalletTransfer(amount, walletId) =&gt; <br>    s&quot;Transferred $amount from wallet $walletId&quot;<br>  case BankTransfer(amount, accountNumber) =&gt; <br>    s&quot;Transferred $amount from bank account $accountNumber&quot;<br>  case CalculateRiskScore(amount, userId) =&gt;<br>    if(amount &gt; 1000) 8.5 else 2.5 // just dummy values<br>  case TransactionLog(operation, userId) =&gt;<br>    AuditEntry(operation, userId, System.currentTimeMillis().toLong)<br>}<br>case class AuditEntry(operation: String, userId: String, timestamp: Long)<br>// compiles but will explode at runtime!<br>val result = processOperation(CalculateRiskScore(500, &quot;user123&quot;))<br>val description = result.asInstanceOf[String] // BOOOOOM, gotta be careful with the casts!</pre><p>Do you see the difference? Now the return type of our processOperation is Any as the new operations now return one of the following String, Double or AuditEntry</p><p>This means</p><ul><li>No type safety</li><li>Maintenance nightmare (good luck remembering what each operation do)</li><li>Wrong casts causing runtime exceptions</li></ul><p>a slightly better approach would be adding the ‘result type’ itself to our operations</p><pre>sealed trait Operation {<br>    def resultType: String<br>}<br>case class CreditCardCharge(amount: Double, cardNumber: String) extends Operation {<br>    override val resultType: String = &quot;string&quot;<br>}<br>case class WalletTransfer(amount: Double, walletId: String) extends Operation {<br>    override val resultType: String = &quot;string&quot;<br>}<br>case class BankTransfer(amount: Double, accountNumber: String) extends Operation {<br>    override val resultType: String = &quot;string&quot;<br>}<br>case class CalculateRiskScore(amount: Double, userId: String) extends Operation {<br>    override val resultType: String = &quot;double&quot;<br>}<br>case class TransactionLog(operation: String, userId: String) extends Operation {<br>    override val resultType: String = &quot;log&quot;<br>}<br>def processOperation(op: Operation): Any =  {<br>  val result = op match {<br>    case CreditCardCharge(amount, cardNumber) =&gt; <br>        s&quot;Charged $amount to credit card ending in ${cardNumber.takeRight(4)}&quot;<br>    case WalletTransfer(amount, walletId) =&gt; <br>        s&quot;Transferred $amount from wallet $walletId&quot;<br>    case BankTransfer(amount, accountNumber) =&gt; <br>        s&quot;Transferred $amount from bank account $accountNumber&quot;<br>    case CalculateRiskScore(amount, userId) =&gt;<br>        if(amount &gt; 1000) 8.5 else 2.5 // just dummy values<br>    case TransactionLog(operation, userId) =&gt;<br>        AuditEntry(operation, userId, System.currentTimeMillis().toLong)<br>    }<br>  op.resultType match {<br>    case &quot;string&quot; =&gt; result.asInstanceOf[String]<br>    case &quot;double&quot; =&gt; result.asInstanceOf[Double]<br>    case &quot;log&quot; =&gt; result.asInstanceOf[AuditEntry]<br>    case otherwise =&gt; throw new RuntimeException(s&quot;Unexpected result type: $otherwise&quot;)<br>  }  <br>}<br>case class AuditEntry(operation: String, userId: String, timestamp: Long)</pre><p>now we can at least check that we’re getting the type what we are expecting but we still have some issues</p><ul><li>We’re still using Any, no type safety</li><li>Type check happens on runtime</li><li>We have to manually write the return type for each new operation &amp; cast everywhere</li></ul><h2>GADTs: A step toward type safety</h2><p>Here we are going to use Generalized Algebraic Data Types (GADTs) to encode the return type in the operation itself</p><pre>sealed trait Operation[A]<br>case class CreditCardCharge(amount: Double, cardNumber: String) extends Operation[String]<br>case class WalletTransfer(amount: Double, walletId: String) extends Operation[String]<br>case class BankTransfer(amount: Double, accountNumber: String) extends Operation[String]<br>case class CalculateRiskScore(amount: Double, userId: String) extends Operation[Double]<br>case class TransactionLog(operation: String, userId: String) extends Operation[AuditEntry]<br>def processOperation[A](op: Operation[A]): A = op match {<br>    case CreditCardCharge(amount, cardNumber) =&gt; <br>        s&quot;Charged $amount to credit card ending in ${cardNumber.takeRight(4)}&quot;<br>    case WalletTransfer(amount, walletId) =&gt; <br>        s&quot;Transferred $amount from wallet $walletId&quot;<br>    case BankTransfer(amount, accountNumber) =&gt; <br>        s&quot;Transferred $amount from bank account $accountNumber&quot;<br>    case CalculateRiskScore(amount, userId) =&gt;<br>        if(amount &gt; 1000) 8.5 else 2.5 // just dummy values<br>    case TransactionLog(operation, userId) =&gt;<br>        AuditEntry(operation, userId, System.currentTimeMillis().toLong)<br>}<br>case class AuditEntry(operation: String, userId: String, timestamp: Long)<br>// The compiler knows exactly what types these are<br>val riskScore: Double = processOperation[Double](CalculateRiskScore(500, &quot;user123&quot;))<br>// This won&#39;t even compile<br>val description: String = processOperation(CalculateRiskScore(500, &quot;user123&quot;)) // Nope!</pre><p>not only we got rid of the manual types now we can check for type error during compile time, however this can be improved further, instead of defining intermediate data structures then process them why not just deal with our final value?</p><p>Each time we create an operation, we can immediately compute and embed the final result. Our processing function becomes almost empty because all the work happens when we construct the operation, lets look at how this can be achieved</p><pre>sealed trait Operation[A] {<br>    def value: A<br>}<br>case class CreditCardCharge(amount: Double, cardNumber: String) extends Operation[String] {<br>    override val value: String = s&quot;Charged $amount to credit card ending in ${cardNumber.takeRight(4)}&quot;<br>}<br>case class WalletTransfer(amount: Double, walletId: String) extends Operation[String] {<br>    override val value: String = s&quot;Transferred $amount from wallet $walletId&quot;<br>}<br>case class BankTransfer(amount: Double, accountNumber: String) extends Operation[String] {<br>    override val value: String = s&quot;Transferred $amount from bank account $accountNumber&quot;<br>}<br>case class CalculateRiskScore(amount: Double, userId: String) extends Operation[Double] {<br>    override val value: Double = if(amount &gt; 1000) 8.5 else 2.5<br>}<br>case class TransactionLog(operation: String, userId: String) extends Operation[AuditEntry] {<br>    override val value: AuditEntry = AuditEntry(operation, userId, System.currentTimeMillis().toLong)<br>}<br>def processOperation[A](op: Operation[A]): A = op.value<br>case class AuditEntry(operation: String, userId: String, timestamp: Long)<br>val chargeResult: String = processOperation(CreditCardCharge(99.99, &quot;4532123456789012&quot;))<br>val riskScore: Double = processOperation(CalculateRiskScore(1500, &quot;user789&quot;))<br>val auditLog: AuditEntry = processOperation(TransactionLog(&quot;DUMMY_OPERATION&quot;, &quot;user123&quot;))</pre><h2>The Expression Problem</h2><p>Here’s where GADTs start to show their limitations. Adding a new operation will require doing the following</p><ol><li><strong>Modify the sealed trait</strong> by adding a new case class</li><li><strong>Modify the</strong> processOperation <strong>function</strong> to handle the new case</li></ol><p>Our code isn’t open to extension without modification. Even worse, what if we want different ways to processOperations Maybe sometimes we want to:</p><ul><li>Actually execute them (like we do now)</li><li>Log them for debugging</li><li>Validate them without execution</li><li>Convert them to JSON for an API</li></ul><p>With our current approach, we’d need separate functions for each behavior, and every time we add a new operation, we’d have to update <em>all</em> of them.</p><p>This is exactly what the <strong>Expression Problem</strong> describes: we can easily add new operations (by extending the sealed trait), but we can’t easily add new ways of processing them without modifying existing code.</p><h2>Tagless Final</h2><p>You’re probably wondering:</p><blockquote>“Okay, but where’s all that F[_] stuff I see in every tagless final video or article?”</blockquote><p>Tagless Final solves this by representing operations as methods in a typeclass rather than data constructors (case classes).</p><p>The F[_] represents an <strong>effect type</strong>, it&#39;s a container that hold our result along with some computational context, here are a few examples</p><ul><li>Option[String] - might contain a String, or might be empty</li><li>Future[String] - will eventually contain a String (asynchronously)</li><li>Either[Error, String] - contains either an error or a String</li><li>IO[String] - represents a computation that will produce a String when executed</li></ul><p>By abstracting over the F[_] we separate between <strong>what</strong> our program does from <strong>how</strong> it does it, let’s see an example</p><pre>import cats.Monad<br>import cats.syntax.flatMap._<br>import cats.syntax.functor._<br>trait PaymentOps[F[_]] {<br>  def chargeCard(amount: Double, cardNumber: String): F[String]<br>  def walletTransfer(amount: Double, walletId: String): F[String]<br>  def bankTransfer(amount: Double, accountNumber: String): F[String]<br>}<br>trait RiskOps[F[_]] {<br>  def calculateRiskScore(amount: Double, userId: String): F[Double]<br>}<br>trait AuditOps[F[_]] {<br>  def logTransaction(operation: String, userId: String): F[AuditEntry]<br>}<br>case class AuditEntry(operation: String, userId: String, timestamp: Long)</pre><p>Now we have defined <em>capabilities or behaviors</em> instead of using data constructors, this let us write programs against these interfaces, an example would be making a chargeCard operation <strong>ONLY</strong> depending on the risk score</p><pre>def riskAwarePayment[F[_]: PaymentOps: RiskOps: Monad](<br>  amount: Double,<br>  cardNumber: String,<br>  userId: String<br>): F[Either[String, String]] = {<br>  val paymentOps = implicitly[PaymentOps[F]]<br>  val riskOps = implicitly[RiskOps[F]]<br>  <br>  for {<br>    risk &lt;- riskOps.calculateRiskScore(amount, userId)<br>    result &lt;- if (risk &gt; 7.0) {<br>      Monad[F].pure(Left(&quot;Payment rejected: high risk&quot;))<br>    } else {<br>      paymentOps.chargeCard(amount, cardNumber).map(Right(_))<br>    }<br>  } yield result<br>}</pre><p>if we opt to just make a normal payment without risk analysis we would just remove the RiskOps context from our payment and just leave the PaymentOps this gives us the advantage that we are using the <strong>least</strong> requirements for our operation to work.</p><h2>Composition Magic</h2><p>Let’s say we need to add notifications to our payment system. With our old approach, we’d have to modify existing code. With tagless final, we just add a new typeclass.</p><p>Let’s actually add a new behavior, payments are <strong>often</strong> followed by a <strong>notification</strong>, so let’s go with that</p><pre>import cats.Monad<br>import cats.syntax.flatMap._<br>import cats.syntax.functor._<br>trait PaymentOps[F[_]] {<br>  def chargeCard(amount: Double, cardNumber: String): F[String]<br>  def walletTransfer(amount: Double, walletId: String): F[String]<br>  def bankTransfer(amount: Double, accountNumber: String): F[String]<br>}<br>trait RiskOps[F[_]] {<br>  def calculateRiskScore(amount: Double, userId: String): F[Double]<br>}<br>trait AuditOps[F[_]] {<br>  def logTransaction(operation: String, userId: String): F[AuditEntry]<br>}<br>case class AuditEntry(operation: String, userId: String, timestamp: Long)<br>// new behavior<br>trait NotificationOps[F[_]] {<br>  def sendEmail(to: String, subject: String, body: String): F[Unit]<br>  def sendSMS(to: String, message: String): F[Unit]<br>}<br>// risk analysis payment WITH notification<br>def riskAwarePayment[F[_]: PaymentOps: RiskOps: NotificationOps: Monad](<br>  amount: Double,<br>  cardNumber: String,<br>  userId: String<br>): F[Either[String, String]] = {<br>  val paymentOps = implicitly[PaymentOps[F]]<br>  val riskOps = implicitly[RiskOps[F]]<br>  val notificationOps = implicitly[NotificationOps[F]]<br>  for {<br>    risk &lt;- riskOps.calculateRiskScore(amount, userId)<br>    result &lt;- if (risk &gt; 7.0) {<br>      Monad[F].pure(Left(&quot;Payment rejected: high risk&quot;))<br>    } else {<br>      paymentOps.chargeCard(amount, cardNumber).map(Right(_))<br>    }<br>    message = result match {<br>        case Left(err) =&gt; err<br>        case Right(_) =&gt; &quot;Payment finished successfully&quot;<br>    }<br>    _ &lt;- notificationOps.sendSMS(&quot;user_phone_number&quot;, message)<br>  } yield result<br>}</pre><p>We were able to <strong>extend</strong> riskAwarePayment with SMS notifications simply by adding NotificationOps[F] to the context bound, <strong>no changes</strong> to the core logic were necessary like before.</p><p>Notice now how this function doesn’t know or care about:</p><ul><li>How risk calculation actually works</li><li>How card charging actually work</li><li>What effect type F[_] actually is</li></ul><p>It only knows that these capabilities exist and can be composed together.</p><h2>Interpreters</h2><p>Now we need to implement these behaviors somehow. An Interpreter provide a concrete implementation of our abstract capabilities using an effect type. Here is how we might implement it using cats.effect.IO and Option monad</p><pre>import cats.effect.IO<br>import cats.Monad<br>import cats.syntax.flatMap._<br>import cats.syntax.functor._<br>import scala.util.Random<br>// interpreter using IO<br>implicit val ioPaymentOps: PaymentOps[IO] = new PaymentOps[IO] {<br>  def chargeCard(amount: Double, cardNumber: String): IO[String] = <br>    IO.pure(s&quot;Charged $$${amount} to credit card ending in ${cardNumber.takeRight(4)}&quot;)<br>  <br>  def walletTransfer(amount: Double, walletId: String): IO[String] = <br>    IO.pure(s&quot;Transferred $$${amount} from wallet $walletId&quot;)<br>  <br>  def bankTransfer(amount: Double, accountNumber: String): IO[String] = <br>    IO.pure(s&quot;Transferred $$${amount} from bank account $accountNumber&quot;)<br>}<br>implicit val ioRiskOps: RiskOps[IO] = new RiskOps[IO] {<br>  def calculateRiskScore(amount: Double, userId: String): IO[Double] = <br>    IO.pure(if (amount &gt; 1000) 8.5 else 2.5)<br>}<br>implicit val ioNotificationOps: NotificationOps[IO] = new NotificationOps[IO] {<br>  def sendEmail(to: String, subject: String, body: String): IO[Unit] = <br>    IO.println(s&quot;Email sent to $to: $subject&quot;)<br>  def sendSMS(to: String, message: String): IO[Unit] = <br>    IO.println(s&quot;SMS sent to $to: $message&quot;)<br>}<br>// interpreter using Option<br>// Note that Option is often for absence of value, this is probably not the<br>// place to use an option, but I am using it to demonstrate different monads<br>implicit val optionPaymentOps: PaymentOps[Option] = new PaymentOps[Option] {<br>  def chargeCard(amount: Double, cardNumber: String): Option[String] = <br>    if (amount &gt; 0) Some(s&quot;Charged $$${amount}&quot;) else None<br>  <br>  def walletTransfer(amount: Double, walletId: String): Option[String] = <br>    Some(s&quot;Transferred $$${amount}&quot;)<br>  <br>  def bankTransfer(amount: Double, accountNumber: String): Option[String] = <br>    Some(s&quot;Transferred $$${amount}&quot;)<br>}<br>implicit val optionRiskOps: RiskOps[Option] = new RiskOps[Option] {<br>  def calculateRiskScore(amount: Double, userId: String): Option[Double] = <br>    Some(Random.nextDouble() * 10)<br>}</pre><p>Now we can run the same business logic with different interpreters:</p><pre>// using the risk payment with 2 effect types :))<br>def riskAwarePayment[F[_]: PaymentOps: RiskOps: NotificationOps: Monad](<br>  amount: Double,<br>  cardNumber: String,<br>  userId: String<br>): F[Either[String, String]] = {<br>  val paymentOps = implicitly[PaymentOps[F]]<br>  val riskOps = implicitly[RiskOps[F]]<br>  val notificationOps = implicitly[NotificationOps[F]]<br>  for {<br>    risk &lt;- riskOps.calculateRiskScore(amount, userId)<br>    result &lt;- if (risk &gt; 7.0) {<br>      Monad[F].pure(Left(&quot;Payment rejected: high risk&quot;))<br>    } else {<br>      paymentOps.chargeCard(amount, cardNumber).map(Right(_))<br>    }<br>    message = result match {<br>        case Left(err) =&gt; err<br>        case Right(_) =&gt; &quot;Payment finished successfully&quot;<br>    }<br>    _ &lt;- notificationOps.sendSMS(&quot;user_phone_number&quot;, message)<br>  } yield result<br>}<br>val ioResult: IO[Either[String, String]] = <br>  riskAwarePayment[IO](500.0, &quot;4532123456789012&quot;, &quot;user123&quot;)<br>val optionResult: Option[Either[String, String]] = <br>  riskAwarePayment[Option](500.0, &quot;4532123456789012&quot;, &quot;user123&quot;)</pre><h2>Conclusion</h2><p>Tagless final isn’t a silver bullet. It adds abstraction overhead and can make simple things complex, its like an investment in flexibility that pays off when requirements change, when you need to test complex integrations, or when you’re building libraries that others will extend.</p><p>This pattern is particularly powerful in library design, where you want to provide functionality without dictating how users should handle effects. Personally, I’ve only used it in a <a href="https://github.com/abdelrahmanIEl-Batal/SNATS">side project</a> and I can imagine how complicated it might get at scale. Like most abstractions, whether you should reach for it depends entirely on your use case.</p><p>The key insight is this: by abstracting over effect types with F[_], we separate <em>what</em> our program does from <em>how</em> it does it. This separation gives us the flexibility to adapt our programs to different requirements without rewriting our core business logic.</p><p>Next time you find yourself struggling with tightly coupled code, hard-to-test side effects, or the need to support multiple execution contexts, remember the tagless final pattern. It might just be the abstraction you need.</p><h2>Resources</h2><ul><li><a href="https://okmij.org/ftp/tagless-final/index.html">https://okmij.org/ftp/tagless-final/index.html</a></li><li><a href="https://www.youtube.com/watch?v=IhVdU4Xiz2U">https://www.youtube.com/watch?v=IhVdU4Xiz2U</a></li><li><a href="https://docs.scala-lang.org/scala3/book/types-adts-gadts.html">https://docs.scala-lang.org/scala3/book/types-adts-gadts.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2407c20a0f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raft 101]]></title>
            <link>https://medium.com/@aibrahimblog/raft-101-464313707e36?source=rss-7c199a3ca7a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/464313707e36</guid>
            <category><![CDATA[raft]]></category>
            <category><![CDATA[fault-tolerance]]></category>
            <category><![CDATA[consensus]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Abdelrahman Ibrahim]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 18:03:58 GMT</pubDate>
            <atom:updated>2025-09-29T18:03:58.640Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eM5O17EPabV9nQDO" /></figure><p>Raft is a <strong>consensus</strong> <strong>algorithm</strong> for managing a <strong>replicated log</strong> (we will explain what this mean later on) and it is widely used in building Distributed Systems. The core of distributed systems is just a set of operating computers that are communicating with each other through in order to do some coherent tasks.</p><p>In this article we are going to go through two of the core mechanism for Raft which are Leadership election and Log replication, this is going to be a long one so grab your favourite drink and enjoy the read.</p><h2>Motives</h2><p>Before we talk about the motives I want to emphasize that if you’re designing a system/solving a problem you should always opt for a <strong>monolithic</strong> design <strong>if</strong> you can, as they are far more simpler, easier to build and maintain.</p><p>Sometimes the problem you want to solve might need something from the following</p><ul><li>High Performance (Parallelism)<br>You want lots of CPU, lots of memory, etc. A good example would be <strong>Map-Reduce</strong> model, which is used for processing and generating large data sets. It’s one of the simplest distributed systems examples, you can read more about it from the official paper <a href="https://research.google.com/archive/mapreduce-osdi04.pdf">here</a> and you can find a simple example implementation for it on my GitHub <a href="https://github.com/abdelrahmanIEl-Batal/mit-distributed-systems/tree/main/src/mr">repository</a></li><li>Fault Tolerance<br>Striving for a resilient system that can withstand software, hardware, or natural failures? By avoiding a single point of failure, you fortify your system against unexpected disruptions.</li><li>Physical Reasons<br>Some systems are inherently distributed due to physical constraints. Whether dealing with large data that defies storage in a single location or managing communication between geographically separated entities, such as bank branches in different locations, the need for distributed systems becomes evident</li></ul><p>These motives represent just a fraction of the considerations in system design. While there are additional factors at play, these are the most common ones.</p><h2>Raft</h2><p>We introduced Raft earlier as an algorithm that manages <strong>log replication</strong> but what does this actually mean? This requires us to have a closer look at what <strong>consensus</strong> <strong>algorithms</strong> are.</p><h3>Consensus Mechanism</h3><p>Consensus algorithms involves <strong>multiple</strong> machines/servers <strong>agreeing</strong> on some values <strong>(state)</strong> and once they reach a decision on some value, that decision is final.</p><p>Imagine having couple of servers running, a user sends a login request, the request get served by <strong>one</strong> of the servers and it generates some kind of auth token, stores it in the database and returns it to the user to be used in future requests, something unfortunate happens and our server (the one who served the login request) <strong>fails</strong> <strong>before replicating</strong> the auth token <strong>(state)</strong> to other servers, now whenever the user sends any request, the server would reply with some kind of “you need to login” message even though he has logged in before.</p><p>Consensus algorithms ensures that a system will continue working when the majority of machines/servers are <strong>available</strong> and agree on some <strong>state</strong>.</p><p>For example a majority for a system which has 5 servers would be able to make progress when <strong>at most 2 servers fail.</strong></p><p>Consensus algorithms typically have the following properties</p><ol><li>They must produce correct results under all non-<a href="https://en.wikipedia.org/wiki/Byzantine_fault">Byzantine</a> conditions, including network latency, network failures (packet loss, packet duplication, etc.)</li><li>They must be time independent to ensure log consistency</li><li>They must be fully functional, all servers can communicate with clients and each other, whenever a server fails, it can recover and has its state consistent with the rest of the cluster</li><li>Usually the reply is sent back to a client, when majority of servers have applied the <strong>request/command</strong> to their <strong>state,</strong> this ensures that not only other servers has a <strong>replica</strong> of the requests/commands but that they also applied them to their state</li></ol><p>now we know what log replication means, it’s just replicating whatever command a client sends amongst servers and applyinga it to the server <strong>state</strong>.</p><h3>Raft features</h3><ol><li>Strong Leader<br>One of Raft’s rules is that there has to be only <strong>one</strong> <strong>Leader</strong> at any given time, and this leader is responsible for replicating logs among servers and ensure that they have the latest log entries</li><li>Leadership Election<br>Leadership elections happens whenever <strong>non-Leader</strong> servers (we will call them <strong>followers</strong> from now on) don’t hear from the <strong>Leader</strong> for a certain amount of time, they assume the leader has failed and start an election to elect a new Leader.</li><li>Membership change<br>This refers to the scenario where you want to add or remove servers (nodes) in the Raft cluster. This might be necessary for various reasons, such as scaling the cluster up or down, replacing failed nodes, or reconfiguring the system.</li></ol><h3>Raft Server</h3><p>Each server represent a replicated state machine, in our Raft context the state machine refers to the data or the state that needs to be consistent across all servers in the cluster.</p><p>Each server stores a log containing a series of commands, which its state machine executes in order. Each log contains the same commands in the same order, so each state machine processes the same sequence of commands. Since the state machines are deterministic (hopefully), each computes the same state and the same sequence of outputs.</p><p><strong>Notice</strong> that not all commands are <strong>deterministic</strong>, an example for <strong>non</strong> <strong>deterministic</strong> command is generating a random number, in this case the Leader can’t replicate the command itself, as every other server is probably going to end up with a different result, a solution can be that the Leader execute this command and then try to replicate the result to other servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0obpzy7wo_j1tPft.png" /></figure><p>The <strong>consensus module</strong> on the server receives requests from client, add it to its log and communicate with other modules on other servers ensuring that their logs contain the same requests in the same order and only once the log is consistent each <strong>server’s state machine</strong> apply these commands in their order.</p><h2>Leadership Election</h2><p>Servers inside a cluster can be elected to being a Leader through a certain process, but first let’s explain the different <strong>states</strong> for the servers at any given <strong>time</strong>, and explain what we mean by <strong>time</strong> in the context of Raft</p><h3>Server States</h3><ol><li><strong>Follower<br></strong>Followers are passive, they <strong>don’t issue</strong> any requests on their own, they are only responding to requests from a <strong>Leader</strong> or a <strong>Candidates.</strong></li><li><strong>Candidate<br></strong>When a <strong>Follower</strong> doesn’t receive any communication (either a <strong>heartbeat</strong> or request) from a Leader within a time period called <strong>election timeout,</strong> it <strong>converts itself to a Candidate and starts and election,</strong> during the election it request votes from other servers, and if a Candidate receive majority of votes it becomes the leader for that time</li><li><strong>Leader<br></strong>The <strong>Leader</strong> is the active server responsible for handling client calls (if a client reaches out to a server which happens to be a follower it redirects the request to the leader) and <strong>managing log replication</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*VCmGYcaT0msx18yD.jpeg" /></figure><h3>Time in Raft ?</h3><p>Raft divides time into something called <strong><em>terms</em></strong> of arbitrary length, terms are numbered using <strong>consecutive</strong> <strong>integers</strong>, the following diagram illustrates this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*YHZuOzMnc-tR7LNa.jpeg" /></figure><p>Each term starts with an election, after an election only <strong>ONE</strong> leader manages the cluster until the end of the term. Sometimes a term can end with no leader being elected like <strong>Term 3</strong> in the figure.</p><p>Terms act as a <strong>logical clock</strong> for the servers, they allow server to detect obsolete information like <strong>stale Leaders or stale requests.</strong></p><p>Imagine we have a cluster of 5 servers, and <strong>server[1]</strong> is the leader for <strong>Term [1],</strong> due to some network issues or message delays, other servers elected another leader at <strong>Term [2], server [1]</strong> continues to act as a <strong>Leader</strong> until it receives a request from the new Leader at <strong>term [2],</strong> it finds that its term is outdated and and reverts to being a <strong>follower.</strong></p><p>The same happens to detect <strong>stale requests,</strong> whenever a server receives a request which has a <strong>term less than the current term for the receiving server</strong>, it ignores this request and replies back with it’s term for the <strong>calling server to update its state</strong>.</p><p>Rule of thumb, whenever a server detected that it’s term is outdated, it updates it’s term (in case that server is a Candidate/Leader it converts to being a follower)</p><h3>Elections</h3><p>Raft uses mechanism called <strong>heartbeat</strong> to trigger elections, a leader periodically sends <strong>heartbeats</strong> to the other servers to notify them that it is alive, these are called <strong>AppendEntries RPC</strong> calls, this RPC is not specific to sending heartbeats only, in fact whenever a leader receives a request/command and want to <strong>replicate</strong> it to other servers it sends them an <strong>AppendEntries RPC</strong> call which contains the <strong>logs</strong> to be replicated, in case leader hasn’t received any new entry, then the <strong>AppendEntries RPC</strong> acts as a heartbeat with an <strong>empty log.</strong></p><p>If a follower receives no AppendEntries RPC within some period of time called <strong>election timeout</strong> (these are random timeout specific for each server and we will know why in a second) it assumes the <strong>Leader</strong> <strong>died</strong> and starts a new election going through the following steps</p><ol><li>Converting from a Follower state to Candidate<br>- The server increments its <strong>current term</strong> (there can’t be two leaders on the same term)<br>- The server votes for itself</li><li>Sending <strong>RequestVote RPCs</strong> to other servers request their vote to become a leader</li><li>Candidate continues in this process until one of the following happens<br>- It wins the election by getting majority of votes (votesGranted &gt; n / 2, where n = no. servers in the cluster) from other servers having the same <strong>term</strong> number<br>- Another server establishes itself as a Leader, this could happen if a Candidate receives an AppendEntries RPC from another server claiming to be the leader during an election and the <strong>AppendEntries RPC has a term &gt;= the Candidate’s term</strong>, then the Candidate recognizes that their is a leader and converts to a <strong>Follower</strong> <strong>state and update its term to the Leader’s<br>- </strong>No one wins an election and the term ends with no <strong>leader<br></strong>This can happen if multiple <strong>Followers</strong> become a <strong>Candidate</strong> at the same time and a <strong>split vote</strong> happens (no one gets majority of votes but instead the votes are split).<br>- Raft solves the <strong>split vote</strong> problem by <strong>randomizing the election timeout</strong> for each server (notice this timeout is reset by certain actions that we will discuss later) because in case these timeouts are permanent to servers we can have in have multiple servers have close timeout that they become a Candidate at the same time.</li></ol><h3>Log Replication</h3><p>Once a Leader has been elected it is responsible for serving client requests, each request contains a command to be executed by the other state machines on each server. The leader operates through the following processes</p><ol><li>Send Heartbeat<br>- As soon as a Leader has been elected it sends <strong>heartbeats</strong> to every other server to notify them that leader is alive and reset their <strong>election timeouts,</strong> then periodically sends heartbeat every HEART_BEAT_INTERVAL, the paper discusses what values should be suitable for this</li><li>AppendEntries<br>- Whenever a leader receives a new command, it appends it to its log and sends AppendEntries RPC calls in parallel to other servers to replicate this new command, when the entry has been safe replicated (majority of servers) only then the Leader applies the command to its state machine and sends the result to the client.<br>- If some followers crash the Leader would continue sending them AppendEntry RPC indefinitely <strong>(even after responding to a client)</strong> until it has been replicated.</li></ol><h3>Sample Code</h3><p>Fortunately <a href="https://www.youtube.com/watch?v=cQP8WApzIQQ&amp;list=PLrw6a1wE39_tb2fErI4-WkMbsvGQk9_UB">MIT-Distributed-Systems</a> course provides us with a skeleton to build our own Raft version, we will only be discussing leadership election and log replication, also make sure to check out Distributed System playlist by Eng. Ahmed Farghal <a href="https://www.youtube.com/watch?v=s_p3I5CMGJw&amp;list=PLald6EODoOJW3alE1oPAkGF0bHZkPIeTK">here</a>. You can clone the skeleton from</p><pre>git clone git://g.csail.mit.edu/6.5840-golabs-2023 6.5840</pre><p>The skeleton provides us by means of communication between servers using <strong>RPC calls through Unix sockets,</strong> we will just need to write the logic.</p><p>Before jumping into the code let’s talk about how are we going to make our code concurrent and avoid race conditions. We will be using <a href="https://go.dev/tour/concurrency/1">locks</a>, <a href="https://pkg.go.dev/net/rpc">rpcs</a>, <a href="https://go.dev/tour/concurrency/2">channels</a> and <a href="https://go.dev/tour/concurrency/1">go routines</a> packages.</p><ul><li>Concurrency<br>- Imagine a server is sending RequestVote RPC to other servers, sending one RPC call then waiting for the answer and then sending the next one and so on is not very efficient, instead we wan’t to send them concurrently for performance, and that’s what is actually happening inside any distributed system.<br>- Fortunately Go provides us with <a href="https://go.dev/tour/concurrency/1">go routines</a> which are excellent to achieve this kind of behavior.</li><li>Locks<br>- We need <strong>locks</strong> to avoid race conditions for go routines sharing the same <strong>server shared data,</strong> lets look at the example we just provided, sending a VoteRequest looks like the following</li></ul><pre>rf.peers[server].Call(&quot;Raft.RequestVote&quot;, args, reply)</pre><ul><li>Inside the RequestVote RPC we are actually going to access shared data held by multiple routines so we are going to use locks basically everywhere in out code.</li></ul><p>You should familiarize yourself with the <a href="https://raft.github.io/raft.pdf">extended Raft paper</a> and especially <strong>Figure 2, and also how Raft guarantees safety</strong> and correctness. Also refer to <a href="https://raft.github.io/">this</a> for some visualization of Raft.</p><p><strong>Figure 2</strong> from the paper condenses the algorithm and the messages exchanged between servers (excluding server membership changes &amp; log compaction).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JqZFzOxms6qFQ1md.jpeg" /></figure><ol><li><strong>State</strong></li></ol><pre>type Raft struct {<br> mu        sync.Mutex          // Lock to protect shared access to this peer&#39;s state<br> peers     []*labrpc.ClientEnd // RPC end points of all peers<br> me        int                 // this peer&#39;s index into peers[]<br> dead      int32               // set by Kill()<br><br> currentTerm int<br> votedFor    int<br> log         []LogCommand<br> // volatile all followers<br> commitIndex int<br> lastApplied int<br> // volatile for leaders only<br> // gets re-initialised after each election<br> nextIndex  []int<br> matchIndex []int<br><br> state           state<br> lastHeartBeat   time.Time<br>}</pre><p>These are the states for each server, we will need a Mutex Lock to lock our shared data (<strong>data shared for the same server among multiple Go routines</strong>), a peers array which contains the all our servers (please check labrpc folder in the skeleton to get what really is going on), the rest are just states form Figure 2.</p><ul><li>State is just a type definition for an int</li></ul><pre>type state int<br><br>const (<br> Follower state = iota<br> Candidate<br> Leader<br>)</pre><ul><li>LogCommand looks like this</li></ul><pre>type LogCommand struct {<br> Term    int<br> Command interface{}<br>}</pre><p>just a struct holding the Command’s <strong>term</strong> number and the command itself (since we are not going to do any actually commands its just an empty interface)</p><ul><li>Creating a Raft server and initializing its state</li></ul><pre>type ApplyMsg struct {<br> CommandValid bool<br> Command      interface{}<br> CommandIndex int<br>}<br><br>func Make(peers []*labrpc.ClientEnd, me int,<br> persister *Persister, applyCh chan ApplyMsg) *Raft {<br> DebugPrint(&quot;[%v] starting&quot;, me)<br> rf := &amp;Raft{}<br> rf.peers = peers<br> rf.persister = persister<br> rf.me = me<br> rf.mu = sync.Mutex{}<br><br> rf.state = Follower<br> rf.lastHeartBeat = time.Now()<br> rf.currentTerm = 0<br> rf.votedFor = -1<br> rf.commitIndex = 0<br> rf.lastApplied = 0<br> rf.log = make([]LogCommand, 1)<br> rf.nextIndex = make([]int, len(rf.peers))<br> rf.matchIndex = make([]int, len(rf.peers))<br> for i := 0; i &lt; len(rf.peers); i++ {<br>  rf.matchIndex[i] = 0<br>  rf.nextIndex[i] = len(rf.log)<br> }<br>    // this will be used by the tester to test our output<br>    // whenever a log entry is commited it should send an<br>    // applyMsg to a channel<br> rf.applyChannel = applyCh<br> DebugPrint(&quot;[%v] initialised&quot;, rf.me)<br> // initialize from state persisted before a crash<br> rf.readPersist(persister.ReadRaftState())<br><br> // start ticker goroutine to start elections<br> go rf.LeaderElection()<br><br> return rf<br>}</pre><p>The make function is called whenever we want to create a new server (refer to the config.go which basically initializes servers and run tests), and fires up another go routine which calls <strong>rf.LeaderElection()</strong>.</p><p>The variable <strong>lastHeartBeat</strong> is store the last time this server received a <strong>AppendEntry RPC or a heartbeat if the log is empty</strong>, when we are creating a new server we initialize this with current time.</p><p><strong>2. Election Process</strong></p><pre>const (<br> ELECTION_INTERVAL = 150<br> HEART_BEAT_INTERVAL = 100<br>)<br><br>// The ticker go routine starts a new election if this peer hasn&#39;t received<br>// heartsbeats recently.<br>func (rf *Raft) LeaderElection() {<br> for rf.killed() == false {<br>  electionTimeout := ELECTION_INTERVAL + rand.Intn(200)<br>  startTime := time.Now()<br>  time.Sleep(time.Duration(electionTimeout) * time.Millisecond)<br>  rf.mu.Lock() // locking to avoid data races<br>  if rf.killed() {<br>   rf.mu.Unlock()<br>   return<br>  }<br>  if rf.lastHeartBeat.Before(startTime) {<br>   if rf.state != Leader {<br>    DebugPrint(&quot;[%v] peer : starting election&quot;, rf.me)<br>    go rf.StartElection()<br>   }<br>  }<br>  // rf.ApplyLog() we don&#39;t need this for now<br>  rf.mu.Unlock()<br> }<br>}</pre><p>Whenever a server is created, it should be up and listening for requests (either an AppendEntry/RequestVote RPC). So what we are doing here is basically checking if our server is not dead, <strong>sleep for a random duration of time (timeout)</strong> and check if we haven’t heard anything since <strong>lastHeartBeat</strong> we fire another go routine to start an election.</p><p><strong>3. Starting an Election</strong></p><pre>type RequestVoteArgs struct {<br> Term         int<br> CandidateId  int<br> LastLogIndex int<br> LastLogTerm  int<br>}<br>// field names must start with capital letters!<br>type RequestVoteReply struct {<br> Term        int // for candidate to get updated if his term is lower<br> VoteGranted bool<br>}<br><br>func (rf *Raft) StartElection() {<br> rf.mu.Lock()<br> rf.ConvertToCandidate()<br> DebugPrint(&quot;[%v] peer: attempting election at term %v&quot;, rf.me, rf.currentTerm)<br> term := rf.currentTerm<br> candidateId := rf.me<br> lastLogIndex := len(rf.log) - 1<br> lastLogTerm := rf.log[len(rf.log)-1].Term<br> votes := 1<br> finished := false<br> rf.mu.Unlock()<br> // now we need to send concurrent RPCs<br> for i := range rf.peers {<br>  if i == rf.me {<br>   continue<br>  }<br>  go func(server int) {<br>   rf.mu.Lock()<br>   request := RequestVoteArgs{<br>    Term:         term,<br>    CandidateId:  candidateId,<br>    LastLogIndex: lastLogIndex,<br>    LastLogTerm:  lastLogTerm,<br>   }<br>   reply := RequestVoteReply{}<br>   rf.mu.Unlock()<br>   ok := rf.sendRequestVote(server, &amp;request, &amp;reply)<br>   DebugPrint(&quot;[%v] voted: %v for candidate[%v]&quot;, server, reply.VoteGranted, request.CandidateId)<br>   rf.mu.Lock()<br>   defer rf.mu.Unlock()<br>   if !ok {     // connection issue we don&#39;t get a reply<br>    return<br>   }<br>   if reply.Term &gt; rf.currentTerm {<br>    rf.ConvertToFollower(reply.Term)<br>    return<br>   } else if reply.VoteGranted {<br>    votes++<br>   }<br>   if votes &lt;= len(rf.peers)/2 || finished {<br>    return<br>   }<br>   finished = true<br>   if rf.currentTerm != term || rf.state != Candidate {<br>    return<br>   }<br>   DebugPrint(&quot;[%v] is elected leader at term[%v] with votes[%v]&quot;, candidateId, term, votes)<br>   rf.ConvertToLeader()<br>   for j := 0; j &lt; len(rf.peers); j++ {<br>    if j != rf.me {<br>     go rf.LeaderOperation(j)<br>    }<br>   }<br>  }(i)<br> }<br>}<br><br>func (rf *Raft) ConvertToCandidate() {<br> DebugPrint(&quot;[%v] converting to candidate&quot;, rf.me)<br> rf.currentTerm += 1<br> rf.votedFor = rf.me<br> rf.lastHeartBeat = time.Now() // resetting election timer<br> rf.state = Candidate<br> // rf.persist()   // we don&#39;t need this now<br>}<br><br>func (rf *Raft) ConvertToFollower(correctTerm int) {<br> DebugPrint(&quot;[%v] converting to follower&quot;, rf.me)<br> rf.state = Follower<br> rf.votedFor = -1<br> rf.lastHeartBeat = time.Now() // reset timeout<br> rf.currentTerm = correctTerm<br> // rf.persist()<br>}<br><br>func (rf *Raft) ConvertToLeader() {<br> DebugPrint(&quot;[%v] converting to leader&quot;, rf.me)<br> rf.state = Leader<br> rf.lastHeartBeat = time.Now()<br> rf.votedFor = -1<br> rf.InitialiseLeaderState()<br> // rf.persist()<br>}<br>func (rf *Raft) InitialiseLeaderState() {<br> if rf.state != Leader {<br>  return<br> }<br> for i := 0; i &lt; len(rf.peers); i++ {<br>  rf.nextIndex[i] = len(rf.log)<br>  rf.matchIndex[i] = 0<br> }<br>}</pre><p>As we discussed, to start an election the server needs to convert its state to a <strong>Candidate,</strong> from <strong>Figure 2</strong> we can see what args should be sent to the server we are requesting a vote from. We then fire a go routines for each server we are requesting a vote from, the server can reply with one of the following</p><ul><li>The server grants us the vote (we will check the logic for RequestVote RPC in a second). Candidate increments the number of votes granted and check if it received majority of votes, if yes it converts to a leader.</li><li>The server replies with a higher term than the Candidate’s in this case the Candidate converts to being a follower and the election ends.</li></ul><p>There is actually a very important check we have to do before converting to a leader, <strong>during the election process the term for the Candidate might have changed from the term it originally started the election with (there might be another Leader in a higher term that sent an AppendEntries RPC to the Candidate to it converted to a Follow with the new term)</strong>, so even before converting to a leader we have to check that the <strong>current term for the Candidate</strong> is the <strong>same term it started the election</strong> with.</p><p><strong>4. RequestVote RPC<br></strong>From <strong>Figure 2</strong> we can see that the logic for granting votes is through the following</p><ul><li>If the <strong>Candidate’s term (args.Term) &lt; server term,</strong> that means that the Candidate is outdated and should convert to a follower and update its term, this happens inside the <strong>StartElection</strong> function we saw earlier, because <strong>reply.Term which is the term for the server that didn’t grant the vote is &gt; the Candidate’s.</strong></li><li>If the <strong>Candidate’s term &gt; server term</strong> then it converts to a <strong>follower</strong> (you would think this is redundant but it’s actually not, the server receiving the request vote might itself be in election at a lower term or even the leader)<br>- Check if the Candidate log is at least up to date as the server’s<br>A server should first check their last log <strong>index and term</strong> and compare them to the Candidate’s, the server’s log is better if it has a <strong>higher term than the Candidate’s last log term</strong> <strong>OR they have the same last log term but the server has more log entries for that term (i.e last log index &gt; Candidate’s last log index)</strong>, if the server log is better it doesn’t grant the vote.</li></ul><pre>func (rf *Raft) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {<br> rf.mu.Lock()<br> defer rf.mu.Unlock()<br> DebugPrint(&quot;[%v] receives request to vote from [%v] at term[%v]&quot;, rf.me, args.CandidateId, args.Term)<br> DebugPrint(&quot;current term for voter [%v]&quot;, rf.currentTerm)<br> if args.Term &lt; rf.currentTerm {<br>  reply.Term = rf.currentTerm<br>  reply.VoteGranted = false<br>  return<br> }<br> if args.Term &gt; rf.currentTerm {<br>  rf.votedFor = -1<br>  rf.ConvertToFollower(args.Term)<br> } else {<br>  if rf.votedFor == -1 {<br>   rf.votedFor = args.CandidateId<br>   // rf.persist()<br>  }<br> }<br> currentLastLogTerm := rf.log[len(rf.log)-1].Term<br> currentLastLogIndex := len(rf.log) - 1<br> currentLogIsBetter := (currentLastLogTerm &gt; args.LastLogTerm) ||<br>  (currentLastLogTerm == args.LastLogTerm &amp;&amp; currentLastLogIndex &gt; args.LastLogIndex)<br><br> grantVote := (rf.votedFor == -1 || rf.votedFor == args.CandidateId) &amp;&amp; !currentLogIsBetter<br> if grantVote {<br>  reply.VoteGranted = true<br>  reply.Term = args.Term<br>  return<br> }<br> reply.VoteGranted = false<br>}</pre><p><strong>5. Leader Operation</strong></p><p>Right after a server becomes the leader we fire a go routine which does the following for each server, it sends an <strong>AppendEntries RPC</strong> every HEART_BEAT_INTERVAL which we defined earlier to be 100 ms , the paper explores suitable values for heartbeats and timeouts, if at some point the server is not a leader anymore we exit from this function.</p><pre>func (rf *Raft) LeaderOperation(pid int) {<br>    for rf.killed() == false {<br>       rf.mu.Lock()<br>       if rf.state != Leader {<br>          DebugPrint(&quot;[%v] not leader anymore&quot;, rf.me)<br>          rf.mu.Unlock()<br>          return<br>       }<br>       DebugPrint(&quot;[%v] leader attempting to send heartbeat every %v milliseconds&quot;, rf.me, HEART_BEAT_INTERVAL)<br>       rf.mu.Unlock()<br>       go rf.sendAppendEntries(pid)<br>       time.Sleep(time.Duration(HEART_BEAT_INTERVAL) * time.Millisecond)<br>    }<br>}</pre><p><strong>6. Send AppendEntries RPC</strong></p><p>Following <strong>Figure 2</strong> rules for AppendEntries, we construct our arguments for the RPC call and notice we are only <strong>sending the logs starting from the next index that should be sent to a server (if any)</strong> Entries: rf.log[rf.nextIndex[server]:] .</p><p>Based on the reply from the server we do the following</p><ul><li>We get a successful reply (i.e the logs has been replicated successfully) we update the <strong>nextIndex and matchIndex</strong> for that server and <strong>check if we can actually update the Leader’s commitIndex</strong>, we can <strong>only update it once the logs has been replicated to majority of servers</strong> an then we apply the log (the first point in Figure 2 in Rules for servers section).</li><li>The reply has a <strong>higher term</strong> then we convert the current server to a <strong>follower</strong>.</li><li>There was a mismatch between the Leader’s log and the server’s, so we <strong>decrement the nextIndex[server] (so we will send older logs) and retry this RPC</strong> until we get a success reply.</li></ul><pre>func (rf *Raft) sendAppendEntries(server int) {<br>    rf.mu.Lock()<br>    if rf.state != Leader {<br>       rf.mu.Unlock()<br>       return<br>    }<br>    previousLogIndex := rf.nextIndex[server] - 1<br>    DebugPrint(&quot;current log: %v&quot;, rf.log)<br>    DebugPrint(&quot;prevLogIndex: %v, rf.nextIndex[%v]: %v&quot;, previousLogIndex, server, rf.nextIndex)<br>    args := AppendEntriesArgs{<br>       LeaderTerm:        rf.currentTerm,<br>       LeaderId:          rf.me,<br>       PrevLogIndex:      previousLogIndex,<br>       PrevLogTerm:       rf.log[previousLogIndex].Term,<br>       LeaderCommitIndex: rf.commitIndex,<br>       Entries:           rf.log[rf.nextIndex[server]:],<br>    }<br>    reply := AppendEntriesReply{}<br><br>    rf.mu.Unlock()<br>    DebugPrint(&quot;[%v] sending heartbeat to [%v]&quot;, rf.me, server)<br>    // remember don&#39;t lock while doing RPC call<br>    ok := rf.peers[server].Call(&quot;Raft.AppendEntries&quot;, &amp;args, &amp;reply)<br>    rf.mu.Lock()<br>    if !ok {<br>       rf.mu.Unlock()<br>       return<br>    }<br>    if reply.Success {<br>       rf.nextIndex[server] += len(args.Entries)<br>       rf.matchIndex[server] = rf.nextIndex[server] - 1<br>       // update commitIndex<br>       go func() {<br>          rf.mu.Lock()<br>          defer rf.mu.Unlock()<br>          for i := len(rf.log) - 1; i &gt; rf.commitIndex; i-- {<br>             count := 0<br>             for _, matchIndex := range rf.matchIndex {<br>                if matchIndex &gt;= i {<br>                   count++<br>                }<br>             }<br><br>             if count &gt; len(rf.peers)/2 {<br>                rf.commitIndex = i<br>                rf.ApplyLog()<br>                break<br>             }<br>          }<br>       }()<br>    } else {<br>       if reply.Term &gt; rf.currentTerm {<br>          rf.ConvertToFollower(reply.Term)<br>       } else {<br>          rf.nextIndex[server]--<br>       }<br>    }<br>    rf.mu.Unlock()<br>}<br><br>func (rf *Raft) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) {<br> rf.mu.Lock()<br> defer rf.mu.Unlock()<br> DebugPrint(&quot;[%v] received heartbeat from [%v]&quot;, rf.me, args.LeaderId)<br> rf.lastHeartBeat = time.Now()<br> reply.Term = rf.currentTerm<br> if rf.currentTerm &gt; args.LeaderTerm {<br>  reply.Success = false<br>  reply.Term = rf.currentTerm<br>  return<br> }<br> if args.LeaderTerm &gt; rf.currentTerm {<br>  rf.ConvertToFollower(args.LeaderTerm)<br> }<br> if len(rf.log)-1 &lt; args.PrevLogIndex || rf.log[args.PrevLogIndex].Term != args.PrevLogTerm {<br>  reply.Success = false<br>  reply.Term = rf.currentTerm<br>  return<br> }<br> if len(rf.log) == args.PrevLogIndex+1 || (len(args.Entries) &gt; 0 &amp;&amp; rf.log[args.PrevLogIndex+1].Term != args.Entries[0].Term) {<br>  rf.log = rf.log[:args.PrevLogIndex+1]<br>  rf.log = append(rf.log, args.Entries...)<br>  // rf.persist()<br> }<br> if args.LeaderCommitIndex &gt; rf.commitIndex {<br>  rf.commitIndex = min(args.LeaderCommitIndex, len(rf.log)-1)<br>  rf.ApplyLog()<br> }<br> reply.Term = rf.currentTerm<br> reply.Success = true<br>}<br><br>func (rf *Raft) ApplyLog() {<br> if rf.commitIndex &gt; rf.lastApplied {<br>  go func() {<br>   rf.mu.Lock()<br>   defer rf.mu.Unlock()<br>   for i := rf.lastApplied + 1; i &lt;= rf.commitIndex; i++ {<br>    var applyMsg ApplyMsg<br>                // command valid just indicated that this is a new entry<br>    applyMsg.CommandValid = true<br>    applyMsg.Command = rf.log[i].Command<br>    applyMsg.CommandIndex = i<br>                // sending the applyMsg to the tester in config.go<br>    rf.applyChannel &lt;- applyMsg<br>    rf.lastApplied = applyMsg.CommandIndex<br>   }<br>  }()<br> }<br>}</pre><p>Now let’s jump into the AppendEntries RPC and see what it do</p><ul><li><strong>Reset the server’s</strong> rf.lastHeartBeat to avoid an election</li><li>Check if the server’s term is higher than the Leader’s, if yes it <strong>reply with false and its term for the Leader to convert to a follower</strong></li><li>If the <strong>previousLogIndex’s term</strong> doesn’t match for both Leader and server, we reply with a false. <strong>Notice this is the case when we are decrementing the nextIndex[server] and retry the RPC call again</strong></li><li>If we have an <strong>entry conflicting with a new one</strong> (same index but different term) we should <strong>delete it and every entry after it</strong> rf.log = rf.log[:args.PrevLogIndex+1], then append the new entries to the log and update the commitIndex</li></ul><h3>Testing</h3><p>The code from MIT acutally consists of tests for multiple labs, leadership election and log replication are labs A and B respectively and you can run the tests by running the following in your terminal, but first cd to the raft package</p><ol><li>Leadership Election</li></ol><ul><li>go test -run 2A</li></ul><p>2. Log replication</p><ul><li>go test -run 2B</li></ul><p>please check out test_test.go file to see what the tests are actually doing, they will help understand why your code is failing. Its a good idea to run your program multiple times and check that all test cases all pass.</p><h2>Pitfalls</h2><p>This might seem easy enough right? just simple loops and if conditions, that’s what I thought at first too, I thought its as simple as reading the paper and watchin some lectures and you’re good to go, unfortunately it was the opposite.</p><ol><li>Figure 2<br>If you wan’t to save yourself long hours of debugging and shedding tears, you <strong>must follow Figure 2 instructions religiously</strong>, every tiny detail matter and will affect the correctness of your program.</li><li>Dead Locks<br>Make sure you’re handling your locks correctly, <strong>maybe your trying to lock a lock that hasn’t been unlocked or you are not unlocking before doing an RPC call</strong>. You probably should run your program using the race flag go test -race -run 2A it will tell you if you have a data race in your program.</li><li>Debugging<br>This can get pretty annoying, because there is so much going on that you actually don’t know whats the issue, is it the locks? the logic? heartbeats? timeouts? failures? delayed messages? you will have to think of every single thing there is, and the more you look at your buggy code the more you think it makes sense. My advice is to think of possible corner cases, build each component and see if it works first before advancing to another (you can manipulate the test_test.go according to your needs).<br>I found printing out logs everywhere super helpful, so you should do that it</li></ol><h2>Conclusion</h2><p>Raft is created to be easy to understand and also performant. It was designed for a large audience to understand the algorithm comfortably and its getting more popular by day, many technologies people use today actually use Raft as an underlying replication layer like Kafka, RabbitMQ, MongoDb and Kubernetes (etcd).</p><p>I have learnt a lot from the <a href="https://raft.github.io/raft.pdf">raft paper</a> and from the exercises provided by <a href="https://www.youtube.com/watch?v=cQP8WApzIQQ&amp;list=PLrw6a1wE39_tb2fErI4-WkMbsvGQk9_UB">MIT-Course</a>, despite all the hurdles it was the most interesting programming tasks I have every worked on.</p><h2>References</h2><ul><li><a href="http://nil.csail.mit.edu/6.824/2017/papers/raft-extended.pdf">http://nil.csail.mit.edu/6.824/2017/papers/raft-extended.pdf</a></li><li><a href="https://www.youtube.com/watch?v=cQP8WApzIQQ&amp;list=PLrw6a1wE39_tb2fErI4-WkMbsvGQk9_UB">https://www.youtube.com/watch?v=cQP8WApzIQQ&amp;list=PLrw6a1wE39_tb2fErI4-WkMbsvGQk9_UB</a></li><li><a href="https://raft.github.io/">https://raft.github.io/</a></li><li><a href="https://www.youtube.com/watch?v=s_p3I5CMGJw&amp;list=PLald6EODoOJW3alE1oPAkGF0bHZkPIeTK">https://www.youtube.com/watch?v=s_p3I5CMGJw&amp;list=PLald6EODoOJW3alE1oPAkGF0bHZkPIeTK</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=464313707e36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the power of implicits in Scala!]]></title>
            <link>https://medium.com/@aibrahimblog/exploring-the-power-of-implicits-in-scala-e74ca8237cc7?source=rss-7c199a3ca7a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e74ca8237cc7</guid>
            <category><![CDATA[typeclass]]></category>
            <category><![CDATA[scala-implicits]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Abdelrahman Ibrahim]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 17:12:43 GMT</pubDate>
            <atom:updated>2025-09-29T17:12:43.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*o6r4gZT9mOdJlITIMHypWA.png" /></figure><h3>Intro</h3><p>Have you ever wondered how something like this compiles in Scala?</p><pre>val aPair = &quot;Sugar&quot; -&gt; 25<br>// or maybe something even more absurd like<br>val check = 2.isEven</pre><p>we already know that operators in Scala are <em>methods</em> in which the first operand is the instance whose method is called and the second operand is passed to it, let’s look at an example</p><pre>val sum = 5 + 6<br>// this is identical to writing it as using the + method inside the Int class<br>// with 6 as an argument<br>val sum2 = 5.+(6)</pre><p>you might be wondering now how the first code block compiles even though neither the String class nor the Int class has a method -&gt; and isEven respectively, and that&#39;s where the power of implicits shines.</p><p>First, we will explain what exactly are implicits in Scala then we will explore the above code and some use cases.</p><h2>What exactly are implicits?</h2><p>When we talk about implicits in Scala we are mainly dealing with two things</p><ul><li>Implicit parameters</li><li>Implicit conversions</li></ul><p>Both of these involve the compiler <em>implicitly</em> (invisibly) resolving some <em>type errors</em> using some extra information that we have provided, for <em>implicit parameters</em> that would be when we are calling a method without supplying all the parameters, and for <em>implicit conversions</em> when we are passing something of a different type than the method accepts.</p><h3>Implicit parameters</h3><p>These are method parameters that we don’t need to explicitly pass to the method when we are calling it, if they are missing the compiler will look in the surrounding scope for some info that can help fix this problem, let’s look at an example</p><pre>def add(x: Int)(implicit y: Int) = x + y<br>println(add(5)(6))    // prints 11 to the console<br>println(add(5))       // doesn&#39;t compileimplicit val z: Int = 6<br>println(add(5))       // prints 11 to the consoleimplicit val k: Int = 10<br>println(add(5))       // doesn&#39;t compile</pre><p>let’s break down what’s happening here, we declared an add method which takes two parameters and returns their sum, but note that we are declaring the second parameter <em>implicitly</em> using the <strong>implicit</strong> keyword, which means that we can either explicitly supply it when calling the method, or just omit it, the compiler then would do a lookup in the current scope, searching for a value with the keyword “implicit” and an expected type of Int.</p><p>There is something to note here, the compiler matches the implicit parameters with an implicit value according to its <strong><em>type</em></strong> and will only supply if it finds exactly <strong><em>ONE</em></strong> value in scope that matches, that’s why we get a compilation error when we declared another implicit val k, the compiler is now confused as to which to provide for the add method because both of them declared with <em>implicit</em> keyword and match the type of Int.</p><h3>Implicit conversions</h3><p>Besides supplying implicit parameters, the compiler can implicitly also do some type conversions for us, whenever there is a type mismatch the compiler will try to resolve it using some extra information that we have provided, let’s look at an example</p><pre>class Person(val name: String) {<br>    def greet: String = s&quot;Hello my name is $name!&quot;<br>}<br>def StringToPerson(name: String): Person = new Person(name)<br>val person = new Person(&quot;Jack&quot;)<br>println(person.greet)    // prints Hello my name is Jack! to the console<br>println(StringToPerson(&quot;Jack&quot;).greet) // works fine</pre><p>Let’s break this out, we defined a class Person which has a name, a method called greet and a method that given a name returns a new Person instance.</p><p>Creating a new Person instance and then calling the greet method on it works fine, also calling StringToPerson(name).greet works as well since the method returns a Person instance which has a greet method, but wouldn’t it be nice if we can just write something like println(&quot;Jack&quot;.greet)? It makes our code so much simpler and more expressive, so let&#39;s use the power of implicits!</p><pre>// changing the declaration of StringToPerson<br>implicit def StringToPerson(name: String): Person = new Person(name)<br>println(&quot;Jack&quot;.greet)    // compiles!!!</pre><p>So what happened here? We declared the StringToPerson function to be <em>implicit</em>, so when we are calling &quot;Jack&quot;.greet the compiler doesn&#39;t give up, it looks for all implicit classes, objects, values and methods that can help turn this &quot;Jack&quot; string to <em>something</em> that has a greetmethod and it happens we have a class Person which has a greet method and a method that implicitly converts a String to a Person, so what happens behind the scenes is that the compiler rewrites our code to println(StringToPerson(&quot;Jack&quot;).greet)</p><p>Note that there has to be exactly <strong><em>ONE</em></strong> method that matches the conversion, or else the compiler will get confused and throw us an error!</p><p>Now we are ready to explore the very first code block we had at the beginning if we take a close look at the <a href="https://scala-lang.org/api/3.x/scala/Predef$.html"><strong><em>Predef object</em></strong></a> which provides definitions that are accessible in all Scala compilation units without explicit qualification, we will find this weird class</p><pre>final implicit class ArrowAssoc[A](self: A) extends AnyVal {<br>    def -&gt;[B](y: B): (A, B)<br>}</pre><p>here we have a class that has a method -&gt; <em>which takes an argument of type B and returns a tuple of</em> (A, B)<em>.</em></p><p>so writing something like val aPair = &quot;Sugar&quot; -&gt; 25 is valid, as the compiler looks up all implicit classes, objects and vals, and finds that there is an implicit class called ArrowAssoc which has a method -&gt; that takes two parameters and returns a tuple, so the compiler creates a new ArrowAssoc instance from &quot;Sugar&quot; and call the -&gt; method on it using the second operand &quot;25&quot; and returns a tuple of (&quot;Sugar&quot;, 25).</p><p>I will leave the example val check = 2.isEven as an exercise for you, you can follow the same pattern we did above with StringToPerson method, this kind of behavior is called <strong><em>type enrichment</em></strong> when we want to add some new functionalities to existing classes that we have no access to, like adding isEven functionality to the Int class.</p><p>So far we have discussed the ability to either implicitly supply a method with some parameters or implicitly convert from types to some other types. The combination of these is called <em>type classes</em>.</p><h2>Type classes</h2><p>A type class specifies a set of operations that can be applied to a given type, in Scala it means a trait that has at least one type variable, and a functionality that we want to add (ie. methods). Any class extending this trait should supply definitions for its methods.</p><h3>The need for type classes</h3><p>Imagine we want to add new functionalities to the Person class we defined before along with a new Class called Cat, and let’s assume that they are from a library whose source we don’t have access to so we can’t modify them. This would require us to pass a Person instance to some other method/class and add that functionality, does this ring a bell? Yes!, it’s like the adapter pattern.</p><pre>// we don&#39;t have access to this, thus we can&#39;t modify it<br>class Person(val name: String) {<br>    def greet: String = s&quot;Hello my name is $name!&quot;<br>}<br>class Cat(val name: String)<br><br>object PersonCanFly {<br>    def canFly(person: Person): String = s&quot;Person ${person.name} can fly!&quot;<br>}<br>object CatCanFly {<br>    def canFly(cat: Cat): String = s&quot;Meow, ${cat.name} can fly!&quot;    <br>}<br>val person: Person = new Person(&quot;Jack&quot;)<br>val cat: Cat = new Cat(&quot;fluffly&quot;)<br>println(PersonCanFlu.canFly(person))<br>println(CatCcanFly.canFly(cat))</pre><p>This allows us to add Fly as new functionality to both Person and Cat this looks fine right? well, It isn’t. It makes our Person and Cat fly, but nowhere is it captured that we are bestowing <em>common functionality</em> on different types in the way that this would be encoded in the <strong>type system</strong> if we make both Person and Cat extend some trait, we won’t be able to define a method that can fly and those who can’t.</p><h3>Solution using Type classes</h3><pre>// type class<br>trait CanFly[A] {<br>    def fly(x: A): String<br>}</pre><p>This is called a <strong>type class</strong> and it defines a set of types instead of just one type (<strong>A</strong> could be anything whether its an Int, String or even a user-defined Class) we can extend this trait to anything that we want to add the fly functionality to by creating what we call <strong>type class instances</strong>, and these instances contain the actual implementation for our <strong>different types</strong></p><pre>// type class instances<br>object PersonCanFly extends CanFly[Person] {<br>    def fly(person: Person): String = s&quot;Person ${person.name} can fly!!&quot;<br>}<br>object CatCanFly extends CanFly[Cat] {<br>    def fly(cat: Cat): String = s&quot;meow, cat ${cat.name} can fly!&quot;<br>}</pre><p>now that chat functionality is common to only a <strong><em>range of types (the ones we defined only)</em></strong>, we can define a method that accepts <em>anything</em> that flies</p><pre>object FlyUtility {<br>    def fly[A](x: A, canFly: CanFly[A]): String = canFly.fly(x)<br>}<br>val cat = new Cat(&quot;fluffy&quot;)<br>println(FlyUtility.fly(cat, CatCanFly))</pre><p>We can even add more implementation to a <strong>specific</strong> type only, imagine some cats can fly higher than other cats, then we can do something like this and call it with the same FlyUtility object</p><pre>object CatCanFlyHigher extends CanFly[Cat] = {<br>    def fly(x: Cat): String = s&quot;meow, cat ${cat.name} can fly higher!&quot;<br>}<br>val anotherCat = new Cat(&quot;garfield&quot;)<br>println(FlyUtility.fly(anotherCat, CatCanFlyHigher)</pre><p>So far so good! but we can improve this a bit, if you notice in the above code we are always passing an object instance to the FlyUtility which contains the actual implementation. In some sense, this feels repetitious of the information we already have, we have a cat and we know we want it to fly why do we need to pass in the <strong>type class instance</strong> <strong>every time</strong>? on the other hand, we may need to specify if we want our cat to <em>just fly</em> or <em>fly higher.</em> Wouldn&#39;t it be nice if we can just say println(FlyUtility.fly(cat))?</p><p>Let’s solve this by modifying our FlyUtility object and our <strong>type class instances</strong></p><pre>implicit object CatCanFly extends CanFly[Cat] {<br>    def fly(cat: Cat): String = s&quot;meow, cat ${cat.name} can fly!&quot;<br>}<br>object CatCanFlyHigher extends CanFly[Cat] {<br>    def fly(cat: Cat): String = s&quot;meow, cat ${cat.name} can fly higher!&quot;<br>}<br>implicit object PersonCanFly extends CanFly[Person] {<br>    def fly(person: Person): String = s&quot;Person ${person.name} can fly!!&quot;<br>}<br>object FlyUtility {<br>    def fly[A](x: A)(implicit canFly: CanFly[A]): String = canFly.fly(x)<br>}<br>println(FlyUtility.fly(cat))    // this works now!!</pre><p>By making the CanFly[A] argument implicit, the compiler will look for something in our scope that is marked implicit and matches the type expected by the method, and because of the <em>type parameter</em> <strong><em>[A]</em></strong>, <em>the matching type will be whatever the type of the first parameter</em> <em>is</em>, so when we call println(FlyUtility.fly(cat)) the compiler looks for an implicit match with type Cat, calling println(FlyUtility.fly(person)) matches with the PersonCanFly instead.<br>Note that I left the CatCanFlyHigher as it is without using implicit, because then the compiler would throw us an error. Because both objects would be a suitable match and the compiler won&#39;t know which one to use.</p><p>This is looking great! but as always we can do better, let’s make our FlyUtility object implicit and see what happens</p><pre>implicit class FlyUtility[A](x:A) {<br>    def fly(implicit canFly: CanFly[A]) = canFly.fly(x)<br>}<br>// now we can do something like this<br>val cat = new Cat(&quot;Garfield&quot;)<br>val person = new Person(&quot;Jack&quot;)<br>println(cat.fly)<br>println(person.fly)</pre><p>As you can see this is so much simpler and more expressive than what we had at the beginning, since FlyUtility defines a type that can fly, and our classes Person and Cat define a type that we would like to be able to fly, then by making our object implicit we can automatically convert our cat and person instances to a FlyUtility instance by calling the fly methods on cat and person.</p><h2>Pitfalls</h2><p>The most common pitfall is when the type for matching an implicit is too general, let’s look at a simple example</p><pre>implicit convertToInt(string: String): Int = string.toInt<br>def incOne(x: Int): Int = x + 1<br>// this compiles, but obviously gives a runtime error<br>println(incOne(&quot;haha&quot;)</pre><p>As we can see if we use an implicit parameter with a built-in type as we did in this example is not a good practice, because the odds of accidentally importing an explicit value of type Int are high, our code compiles but has unexpected behavior.</p><p>Mainly using implicits with type classes (<strong><em>type enrichment</em></strong>) exploits their usefulness while avoiding the pitfalls, as we saw before the implicit parameters used in the previous section (type classes example) were the parameters that we defined ourselves like CatCanFly extends CanFly[Cat] instead of any arbitrary existing types, it only works for Person and Cats that we defined, this is type-safe, if we try to use it with some other type like Int the compiler then would give us an error that it can&#39;t find a matching <strong>type class instance</strong> that works for Int (because simply we haven&#39;t defined one).</p><h2>Conclusion</h2><p>Conceptually, implicits are not too hard to understand, but their interaction with Scala’s sophisticated type system can be hard to grasp for a novice, especially with large or complex systems.</p><p>Although they are very powerful they can do as much harm as good, unconstrained use of implicits can make the code confusing to read and hard to debug.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e74ca8237cc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>