<?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 Kulvir on Medium]]></title>
        <description><![CDATA[Stories by Kulvir on Medium]]></description>
        <link>https://medium.com/@kulvir.07?source=rss-cfe199c5b2c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3Qvpy0BDD-xrMnQQ</url>
            <title>Stories by Kulvir on Medium</title>
            <link>https://medium.com/@kulvir.07?source=rss-cfe199c5b2c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:54:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kulvir.07/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[1 Billion Row Challenge in Go]]></title>
            <link>https://medium.com/@kulvir.07/1-billion-row-challenge-in-go-cab59d56f879?source=rss-cfe199c5b2c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cab59d56f879</guid>
            <category><![CDATA[concurrency-in-golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[1-billion-row-challenge]]></category>
            <dc:creator><![CDATA[Kulvir]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 18:17:44 GMT</pubDate>
            <atom:updated>2024-07-15T09:55:51.226Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://1brc.dev/">1 Billion row challenge</a> is a very simple challenge. You have to read data from the file, do some calculations and print the output. But challenging part is file consist of 1 billion rows of data. You have to do this task as fast as possible.</p><p><strong>Challenge</strong><br>A text file contains temperature values for different weather stations. Each row is a single measurement &lt;station_name: string&gt;;&lt;temperature: float&gt;. For each unique station we have to calculate the min max and average temperature and print the final result in format {&lt;station_name&gt;: &lt;min&gt;/&lt;avg&gt;/&lt;max&gt;}. The stations should be in alphabetical ascending order.<br>The challenge was originally introduced for Java, but as it got more popular people started trying it in different languages. I&#39;ll be solving this using Go 1.22. All the benchmarks are run on Macbook Air M1 8GB. The input file generated is about 13GB. Now all the intro to challenge is done, lets dive into the implementation. BTW, this is link to <a href="https://github.com/kulvir-parmar/1brc">github repo</a> for implementation.</p><h3>#1 Solution that just works.</h3><p>Started with very naive solution that read file line by line using Go’s own <em>bufio scanner</em>. A map is maintained that store minimum, maximum, sum and count of all temperatures. We don’t need to store all the temperatures for a city for our calculations. We can maintain max, min and update them as we are proceeding further. Average can be obtained form sum of temperatures by dividing with count of temperatures. To print the solution in specified format, city names were sorted in alphabetical order and solution was printed.<br>No optimisations were done for this solution so this solution can be used as a benchmark so our next solutions.<br>It took 2m 12s to run. Not really bad for a brute force solution.</p><h3>#2 Using some concurrency</h3><p>In previous solutions we were reading the data and doing calculations in a sequential manner. We can leverage Go Routines to do these things concurrently. Go channels to be used for sharing data b/w go routines.</p><ul><li>Reader go routine read data from the file</li><li>Worker go routine performs calculations on the data and store in map.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0r_H1hDeZBESQKK1vaLNQ.png" /></figure><blockquote>Since we are using multiple go routines, we must take care of synchronisations between them. But by design the communication through channels b/w multiple go routines is synchronised. We explicitly don’t need to do anything from our side. Go getting huge Ws here.</blockquote><h3>Unbuffered Channels</h3><p>Using unbuffered channels increased the execution of program to 5m 10s from 2m 12s more than 2x the original solution.</p><blockquote>Unbuffered channels have no capacity, hence they are blocking channels and they will block the execution of code until there some go routine ready to read the value form channel.</blockquote><p>Because of this most of the time reader go routine is in suspended state until worker routine is done reading data from it.</p><h3>Buffered channels</h3><p>Buffered channels unlike unbuffered channels have capacity and they don’t block the execution until the channel is full. Therefore using buffered channel should reduce the execution time as the go routines wont block the execution. But what size should we use for our buffered channel. Tested multiple sizes 16, 64, 128, 256, 512, 1024 and the performance of channels with higher capacity has very marginal difference in performance. Hence 128 sized channel were used further.<br>The execution time was3m from 5m 10s, reduction of 42%. But this is still slower than brute force solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eivLm1sGmczuizsskS5iWA.png" /><figcaption>runtime profile for buffered channel code wihtout chunking</figcaption></figure><p>I ran profiling on my code using Go’s own profiling tools. As we can see still most of the time is consumed in managing and scheduling go routines. This is because we are still sending 1 billion lines of data over channels. This creates huge memory print. This also increases the work for the Garbage collector.</p><p>To reduce this, I decided to chunk some lines into into a slice and send slices of data over the channels. Copying the size of our buffered channels, slice of length 128 were used. This solution helped in massively reducing the execution time for our program to 1m 25s from 3m , reduction of more than 52%. Also this is our first ever solution that is any faster than our baseline solution by 37%. Finally seems like we are making some progress and not just like spreading more mess.</p><h3>#3 Optimising Bufio reader</h3><p>Go’s <em>Bufio</em> reader is very fast and reliable interface to read from files. It does some fancy optimisation making it perfect for use. But for this particular use case we might not need all the optimisations. Also because we already know the data of the file, we can easily write our own logic to read bytes from file and convert them to strings without Bufio scanner’s methods.<br> Go&#39;s os package provide us Read method that read bytes and store them in a slice. Converting string to byte is expensive operation, hence we need to optimise this too because just reading reading bytes don&#39;t reduce the runtime of our program.<br><em>Ackchyually</em>, there is builder type in go, which efficiently build string using Builder.Write method, which minimises memory copying.<br>And yes it works as advertised. The execution time of program went to 1m 5s from 1m25s reducing it by 20s. And 50% improvement from our baseline solution.</p><h3>#4 Parallel Calculation</h3><p>Rob Pike has some amazing videos on <a href="https://youtu.be/f6kdp27TYZs">concurrency patterns</a> in Go. For further optimisations I’ll be using one of the pattern discussed in the video, i.e. fan in fan out. The idea is spin multiple go routines for the time consuming task and use all the cores of your cpu, doing parallel computations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4QbBmtDUxcti9mDc4_PbA.png" /></figure><p>The worker go routine first process the bytes read, and then send a slice of processed lines to the channel, which in turn in stored in map. The worker go routine can work in parallel and can send the processed data to another go routine to add it to map. I have a 8 core CPU, so it should substantially reduce the execution time of our program. But that was not the case. It only gets reduced by 4 seconds to1m 1s from 1m 5s. But why is it so, we are doing so much parallel computation now, it should be much less right. To answer this I checked the profiler results again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmH2XtOQKFW9xHvVy-a_zw.png" /><figcaption>runtime profile for parallel code</figcaption></figure><p>As we can see go routines scheduling and management is consuming almost95%of our time. Even though we have chunked the lines into slices, still the memory footprint of our program is too large, after all we are processing 1 billion lines. To overcome this issue, the obvious solution that comes to mind is instead of sending processed data line by line, add it to map in worker go routines only. This will reduce the overhead of sending billion lines over maps and make computations much faster. But this can cause issues. We are doing parallel computations and multiple go routines writing to same memory resource can cause deadlock. Instead we can make map for each worker go routine, and send the little maps through channel to merge them into larger final map. This solution was pretty dang efficient by reducing the execution time from1m 1s to 21s. A total of84%reduction in runtime from our baseline solution.</p><h3>Done with optimisation</h3><p>To count the number of files using <em>Bufio</em> reader, it takes 20s. So my aim was to bring the runtime of program below 20s. But with my current knowledge of the language I could only bring it to 21s(skill issues). But I am happy with delta of 1s. There are further optimisation that could be made to the code further, that are out of my current knowledge.<br>Before attempting 1brc, I have consumed some posts already hence my optimisation ideas and their implementation may be similar to some of them. But got to know a lot about writing concurrent code. As the main goal of challenge was to learn new things, so I think I have done a good enough job.<br>These are some of the resources that have been very helpful for attempting 1brc:</p><ul><li><a href="https://www.bytesizego.com/blog/one-billion-row-challenge-go">1BRC in GO</a></li><li><a href="https://r2p.dev/b/2024-03-18-1brc-go/#:~:text=One%20Billion%20Row%20Challenge%20in%20Golang%20%2D%20From%2095s%20to%201.96s">1BRC in GO — From 95s to 1.96s</a></li><li><a href="https://kgrz.io/reading-files-in-go-an-overview.html#scanning-comma-seperated-string">Reading files in Go</a></li><li><a href="https://groups.google.com/g/golang-nuts/c/trmXxcyJxVo">Array Faster than channels</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cab59d56f879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lousy Editor and Skill Issues]]></title>
            <link>https://medium.com/@kulvir.07/lousy-editor-and-skill-issues-6db4b82057ee?source=rss-cfe199c5b2c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db4b82057ee</guid>
            <category><![CDATA[code-editor]]></category>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Kulvir]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 13:53:42 GMT</pubDate>
            <atom:updated>2024-01-02T13:53:42.188Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in high school, when I was first introduced to coding, the fact became evident that we needed a coding editor for a better coding experience. My first programming language was python, and my school us told to use Jupyter Notebook. It was decent. But I was not satisfied and refused to use it. So what if not jupyter notebook. VS Code was gaining popularity those days, so I installed it, and it was great.</p><p>VS Code had everything I ever needed. It had my favourite theme and an incredible set of extensions to make my life easier. It had familiar shortcuts and an excellent interface overall. The current configuration was carefully curated and refined until it was almost perfect for me. I was a cool person back then for using a cool editor. <em>I was happy with it until…</em></p><p>In university, I was introduced to <a href="https://www.twitch.tv/ThePrimeagen">ThePrimeagen</a> — <em>the harpoon man and an engineer at Netflix</em>. Watching him do those Vim motions and teleporting between files with a keyboard made me insecure whenever I used my mouse while coding. I was clearly missing out on some fun. I had everything I needed in VS Code. I made my own custom theme, had my favourite extensions and some useful keybinding that made my life easier. I have been using it for a long time and am very familiar with it. So I thought I could do all that cool stuff in VS Code, too. I didn’t need to spend <em>10 years </em>learning Vim motions first to do the most trivial things I can do in just <em>4 clicks</em>.</p><p>One fine day, I was watching <a href="https://www.youtube.com/watch?v=CpBXikakzks">video</a> where Theo Browne (<em>creator of T3 stack</em>) teaches Prime NextJS, and Theo said he was <strong>overwhelmed by Prime’s movements and couldn’t keep up with him</strong>. At that moment, I realised I didn’t want to grow up like Theo. Prime said there are only a few hundred keybindings I need to learn to be good at, and I didn’t want to have those skill issues. So I put my mouse to some rest there and installed Neovim</p><p>Before shifting to Neovim, everyone recommended using Vim keybinding in VS Code to get familiar with Vim motions. After a few days, I was getting familiar with Vim motions, but I couldn’t get that buttery smooth in VS Code. I guess it was the right time to shift to the <em>elite category editor</em>.</p><p>One <em>colossal</em> struggle while shifting to Neovim was writing its configuration. My VS Code was configured to the minute details that mattered to me. Doing that same thing in Neovim again was gonna be a nightmare. Also, editors like VS Code come preloaded with autocompletion and syntax highlighting. But had to set up myself in Neovim. But what a fun experience I had while setting it all up. Prime’s video on <a href="https://www.youtube.com/watch?v=w7i4amO_zaE">Neovim RC</a> was quite helpful in that process, also Neovim have good documentation.</p><p>After couple of days into it, I have built my own Neovim configuration, my <em>Personal Development Environment</em>. I was ready to use Neovim. At this point, my Neovim had everything my VS Code had. <strong>I was so happy to know that I would have a billion problems in the future, but lousy editor and skill issues ain’t gonna be one of them</strong>.</p><p>A couple of days into my PDE, it was amazing. It was blazingly fast, and I could teleport between files without a mouse. It is a fantastic feeling. I can’t describe it. To experience it, you must spend weeks learning Vim and configuring it yourself. Neovim not only makes you faster but also makes you learn stuff that you wouldn’t even bother while using VS Code.</p><h3>Some Pictures of my setup</h3><figure><img alt="My Neovim setup" src="https://cdn-images-1.medium.com/max/1024/1*sgAOMLJ4OkzhnYJUhqWaLQ.png" /><figcaption>My neovim setup</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUVfGyCzh3abtfdW9aL1Ag.png" /><figcaption>Fuzzy Finder (Telescope)</figcaption></figure><p>You can check out my configuration on github : <a href="http://github.com/Kulvir-parmar/dotFiles"><em>github.com/Kulvir-parmar/dotFiles</em></a><em>. </em>But I highly recommend you to build your own configuration from the scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db4b82057ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>