<?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 Habib Fikri on Medium]]></title>
        <description><![CDATA[Stories by Habib Fikri on Medium]]></description>
        <link>https://medium.com/@habibfikri?source=rss-2a37c432ea03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nsvzskjcTUKTUgUeDj-azw.jpeg</url>
            <title>Stories by Habib Fikri on Medium</title>
            <link>https://medium.com/@habibfikri?source=rss-2a37c432ea03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:55:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@habibfikri/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[Quicksort]]></title>
            <link>https://habibfikri.medium.com/quicksort-dcbd8a8ab5b4?source=rss-2a37c432ea03------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcbd8a8ab5b4</guid>
            <category><![CDATA[quicksort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Habib Fikri]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 10:57:13 GMT</pubDate>
            <atom:updated>2021-02-15T06:57:55.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*S5yN5xi5At55sTCj.gif" /><figcaption>Animated visualization of quicksort¹</figcaption></figure><p>Quicksort is a sorting method that uses a divide-and-conquer algorithm. The basic idea is to pick an element as a pivot. Put another smaller member than the pivot to its left side, and put another larger member than the pivot to its right side. After this process, we can make sure that the pivot is in the correct position. There are many different versions of quicksort that pick pivot in different ways².</p><ol><li>Always pick the first element as a pivot</li><li>Always pick the last element as a pivot</li><li>Pick a random element as a pivot</li><li>Pick median as a pivot</li></ol><p>Here is some example of Go code implementing the quicksort algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2daae0e2caf803773988961f47d152f/href">https://medium.com/media/b2daae0e2caf803773988961f47d152f/href</a></iframe><p>Output:</p><pre>Unsorted: [5 3 2 8 6 1 4]<br>Sorted  : [1 2 3 4 5 6 8]</pre><p>Let’s break down the idea based on above implementation. In this story, we will always pick the last element as a pivot. Let say we have an integer array A consisting of these elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*kktL3q0wwUTp7iJYBbRDOQ.png" /><figcaption>The initial state of the array.</figcaption></figure><p>First, we initiate two variables, which are left and right, to indicate the first index (zero) and last index (length of array-1). We will use the first variable (left) to make sure that the elements on the left side of the pivot index are smaller than the pivot value. And the second variable (right) is the pivot index itself. Since the last element represents the pivot, we will iterate the array from the 0th index to the element before the last index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*OWxauHSxahWVw0FYpHbbEg.png" /><figcaption>First iteration.</figcaption></figure><p>At the beginning of the iteration, we always compare the value of A[i] and A[right]. In this first iteration, the value of A[i] is not less than A[right]. So we continue to the next iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*1k-La8UInreAOuRW5y7rQg.png" /><figcaption>Second iteration. A[i] is less than A[right].</figcaption></figure><p>In the second iteration, compare the value of A[i] and A[right]. This time, the value of A[i] is smaller than A[right]. So we swap the value of A[left] and A[i].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*hGywVMdopbJw4iWV31I4fA.png" /><figcaption>Swapping A[i] and A[left].</figcaption></figure><p>Now we are sure that the element of A[left] is smaller than A[right]. So we increase the value of left to find the next index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Ku9JKx0XdGkcgnatOhVgGw.png" /><figcaption>Increasing the value of left.</figcaption></figure><p>The iteration continued. This time, we find that A[i] is less than A[right], so we are swapping A[i] and A[left] again, then increase the value of left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*s4_5MevIcLMx1MUISROJnQ.png" /><figcaption>Third iteration. A[i] is less than A[right].</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*-AU1t-Yqb8hMEzk14MYbHw.png" /><figcaption>Swapping A[i] and A[left].</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*9KBksYhTOGnlQwBW3L_FKA.png" /><figcaption>Increasing the value of left.</figcaption></figure><p>We continue the iteration. At the 4th and 5th iteration, A[i] is not less than A[right]. So the iteration continued until the 6th iteration, which is the last iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*K_5TDDIgZxzcIfUNADiPnQ.png" /><figcaption>Fourth iteration.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*iKFmL5BApqsBRkZjWEwLYQ.png" /><figcaption>Fifth iteration.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Ed9trmLLGjhZ6cJ4wybk4w.png" /><figcaption>Sixth iteration</figcaption></figure><p>At the 6th iteration, A[i] is less than A[right]. So we are swapping A[i] and A[left], then increase the value of left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*h8biXddt7vp-04vdZocT5Q.png" /><figcaption>Swapping A[i] and A[left].</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*px0r7EyBqBhEVr3DBNp72g.png" /><figcaption>Increasing the value of left.</figcaption></figure><p>After done iterating, we are doing the last swap between A[left] and A[right]. Finally, the elements at the left side of the pivot are smaller than the pivot itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*TnxvokVbbSyU-cnOi8sLIQ.png" /><figcaption>Swapping A[left] and A[right]</figcaption></figure><p>Now, we are sure that the pivot is in the right position at the array. Finally, recursively call the quicksort function for the elements at both sides of the pivot. We are using the left variable to indicate the pivot index since the pivot is now there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*5An1QIybDa7UtNRPYEoclg.png" /><figcaption>Recursively call quicksort function for the elements at both sides of the pivot.</figcaption></figure><h3>References</h3><p>[1] <a href="https://en.wikipedia.org/wiki/Quicksort">https://en.wikipedia.org/wiki/Quicksort</a></p><p>[2] <a href="https://www.geeksforgeeks.org/quick-sort/">https://www.geeksforgeeks.org/quick-sort/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcbd8a8ab5b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graceful shutdown in go]]></title>
            <link>https://habibfikri.medium.com/graceful-shutdown-in-go-548fd7d8094c?source=rss-2a37c432ea03------2</link>
            <guid isPermaLink="false">https://medium.com/p/548fd7d8094c</guid>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[graceful-shutdown]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Habib Fikri]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 23:36:44 GMT</pubDate>
            <atom:updated>2021-02-03T23:59:11.474Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing graceful shutdown in go</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TnVaLiQZ6v-x5ohk.jpg" /><figcaption><a href="https://en.wikipedia.org/wiki/Gracefulness">The swan is often referenced in literature as an example of a “graceful” animal.</a></figcaption></figure><p>The purpose of a graceful shutdown is to make a go application stop receiving new requests while completing the ongoing request before finally going to shutdown. That usually happens when rolling update pods. The old pods will terminate after new pods are ready.</p><p>Usually, the pod will terminate after receiving the OS interrupt signal. To achieve graceful shutdown, we can create a context with a cancel callback and a built-in shutdown method provided by http.Server interface. We can use the created context to keep listening for OS interrupts via a channel and call the cancel function right after receiving the signal.</p><p>Here is an example of a server that implements the graceful shutdown. We will breakdown the code later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0009fac5d3b2454a2c249cf534e6c73a/href">https://medium.com/media/0009fac5d3b2454a2c249cf534e6c73a/href</a></iframe><p>To see how this graceful shutdown works, we can modify the handler to simulate the processing time when there is a request.</p><pre><strong>func</strong> handler() http.Handler {<br>  mux := http.NewServeMux()<br>  mux.Handle(&quot;/healthz&quot;, http.HandlerFunc(<br>    <strong>func</strong>(w http.ResponseWriter, r *http.Request) {<br>      fmt.Fprintf(w, &quot;ok&quot;)<br>      <strong>for</strong> i := 1; i &lt;= 7; i++ {<br>        log.Println(i)<br>        time.Sleep(time.Second)<br>      }<br>    },<br>  ))<br>  <strong>return</strong> mux<br>}</pre><p>Then send a request to the endpoint. While the program process the request, press Ctrl+C to send an interrupt signal. The server will stop, but it still processes the ongoing requests. On the other hand, if there is another request after the server stop, it will be refused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmqAFgZZnwV5hCjncu5eGg.gif" /><figcaption>Graceful shutdown in action</figcaption></figure><p>Let’s breakdown the code. First, in the main function, we create a channel that will listen to os.Interrupt signal.</p><pre>c := make(<strong>chan</strong> os.Signal, 1)<br>signal.Notify(c, os.Interrupt)</pre><p>Then we create a context with a cancel function. The context will block a process (in this case, preventing the server from shutdown) until we call the cancel function.</p><pre>ctx, cancel := context.WithCancel(context.Background())</pre><p>After that, we create an anonymous function that runs in a separated goroutine, which waits for an interrupt signal then calls the cancel function.</p><pre><strong>go</strong> <strong>func</strong>() {<br>  osCall := &lt;-c<br>  log.Printf(&quot;system call: %+v&quot;, osCall)<br>  cancel()<br>}()</pre><p>We also create a &amp;http.Server and logger instance for later use.</p><pre>server := &amp;http.Server{<br>  Addr:    &quot;:8080&quot;,<br>  Handler: handler(),<br>}<br>stdLog := log.New(os.Stderr, &quot;&quot;, log.LstdFlags)</pre><p>Finally, pass the context, server, and logger instance to the serve function.</p><pre><strong>if</strong> err := serve(ctx, server, stdLog); err != nil {<br>  log.Printf(&quot;serve(ctx, server, stdLog)=%+s&quot;, err)<br>}</pre><p>In the serve function, we will run the server in a separate goroutine. Then, block the process with &lt;-ctx.Done() so the program will wait for the call of cancel function (called in the main function after receiving the interrupt signal).</p><pre><strong>go</strong> <strong>func</strong>() {<br>  <strong>if</strong> err = server.ListenAndServe(); err != nil &amp;&amp; err != http.ErrServerClosed {<br>    logger.Fatalf(&quot;ListenAndServe()=%+s&quot;, err)<br>  }<br>}()</pre><pre>&lt;-ctx.Done()</pre><p>We will gracefully shutdown the server by calling the Shutdown function from the server instance after calling the cancel function. Because the function calls require a context, we also create a context with a timeout to give a time window for the server to shutdown.</p><pre>ctxShutDown, cancel := context.WithTimeout(context.Background(), 30*time.Second)<br><strong>defer</strong> <strong>func</strong>() {<br>  cancel()<br>}()</pre><pre><strong>if</strong> err = server.Shutdown(ctxShutDown); err != nil {<br>  logger.Fatalf(&quot;server.Shutdown(ctxShutdown)=%+s&quot;, err)<br>}</pre><p>You might notice that I use Server and Logger interface. The purpose of that is to make the serve function easier to test. I will update the story soon regarding this.<br>That’s it! The application should finish the ongoing process and reject the upcoming request.</p><p><strong>References</strong></p><ul><li><a href="https://en.wikipedia.org/wiki/Gracefulness">https://en.wikipedia.org/wiki/Gracefulness</a></li><li><a href="https://medium.com/@pinkudebnath/graceful-shutdown-of-golang-servers-using-context-and-os-signals-cc1fa2c55e97">https://medium.com/@pinkudebnath/graceful-shutdown-of-golang-servers-using-context-and-os-signals-cc1fa2c55e97</a></li><li><a href="https://pkg.go.dev/os/signal#Notify">https://pkg.go.dev/os/signal#Notify</a></li><li><a href="https://pkg.go.dev/net/http#Server.Shutdown">https://pkg.go.dev/net/http#Server.Shutdown</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=548fd7d8094c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>