<?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 Sowmiya Nagarajan on Medium]]></title>
        <description><![CDATA[Stories by Sowmiya Nagarajan on Medium]]></description>
        <link>https://medium.com/@stackboxspace?source=rss-5eb689be736d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qL2Iu23eGYD0gf2PRgmbKg.png</url>
            <title>Stories by Sowmiya Nagarajan on Medium</title>
            <link>https://medium.com/@stackboxspace?source=rss-5eb689be736d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:53:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stackboxspace/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[Capture and Analyse Thread Dumps in JVM]]></title>
            <link>https://medium.com/swlh/capture-and-analyse-thread-dumps-in-jvm-42b604514ba0?source=rss-5eb689be736d------2</link>
            <guid isPermaLink="false">https://medium.com/p/42b604514ba0</guid>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Sowmiya Nagarajan]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 16:17:07 GMT</pubDate>
            <atom:updated>2020-06-20T09:54:41.801Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>So you’ve written some code in Java (probably a service) and either the perf test results or just some basic JVM metrics show that there’s a <strong>high thread utilisation</strong> in your app. So how to find the culprit here? It definitely has to be a buggy piece of code. This is where <strong>thread dumps are super helpful</strong> in getting to the root cause.</blockquote><h4>What are JVM threads anyways?</h4><p>Setting some context about JVM threads for the absolutely clueless readers out there (just as I was when my app was using up 2000+ threads). Java threads are basically an abstraction for the <strong>path followed when executing a process</strong>. JVM gives you one main thread for a java program and you can code your app to use multiple threads based on the use case. Usually multiple threads are used to serve purposes like background tasks like batch jobs. If your app is a web server, then based on the traffic you get into your app the number of threads will increase. Almost like 1 thread per incoming request to be served (the thread is freed once the response is returned).</p><p>If you see your app is using too many threads without much traffic/processes running or if these threads are increasing with time then it’s time to take a<strong> look at thread dumps for the root cause</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYFkpsHWCsNUUo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FYFkpsHWCsNUUo&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FYFkpsHWCsNUUo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="394" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c05f51a09df9307397162c97a0e8d60/href">https://medium.com/media/7c05f51a09df9307397162c97a0e8d60/href</a></iframe><h3>Capturing Thread Dumps</h3><p>Let’s get a snapshot of some stack traces of all threads assigned/running in your java process.</p><h4>Step 1: Start the java process</h4><p>Start you java process and keep it running. It can be a simple program, cron job, spring boot app or anything that runs in java. Now you need to know the pid of the process running to use it in capturing thread dump. There are multiple ways to find this. I stick to the following command since it comes with a java installation itself (comes in very handy if you have to get pids in docker containers)</p><pre>jps -l</pre><p>This lists all java processes running in your JVM. It lists processes with the main class names, so you should be able to get the right pid easily.</p><h4>Step 2: Reproduce high load</h4><p>If you want to reproduce high thread usage like in the case of traffic, set it up. For example, start your test scripts to generate traffic.</p><h4>Step 3: Let the process warm up</h4><p>Let the server or process warm up a bit. In most cases thread counts increase with time. You’d want to wait for some time to reproduce the thread usage for better analysis.</p><h4>Step 4: Capture thread dump</h4><p>This is the key step. There are multiple ways to take thread dumps (especially with all the modern APM tools available). But sticking to the basics, you can use jstack which comes packaged with java.</p><pre>jstack -l &lt;pid&gt; &gt;&gt; threaddump.log</pre><p>This command takes a single snapshot of your process thread usage (with stack traces of all threads) and puts it in the <em>threaddump.log </em>file<em>. Now if you want to take a series of thread dumps over a period of time (to track thread utilization over a period of time) you could write a script that just runs the above command in intervals. The following is a script I use,</em></p><pre>#!/bin/sh<br># Generate N thread dumps of the process PID with an INTERVAL between each dump.<br><br>if [ $# -ne 3 ]; then<br>   echo Generates Java thread dumps using the jstack command.<br>   echo<br>   echo usage: $0 process_id repetitions interval<br>   exit 1<br>fi<br><br>PID=$1<br>N=$2<br>INTERVAL=$3<br><br>for ((i=1;i&lt;=$N;i++))<br>do<br>   d=$(date +%Y%m%d-%H%M%S)<br>   dump=&quot;./threaddump/threaddump-$PID-$d.txt&quot;<br>   echo $i of $N: $dump<br>   jstack -l $PID &gt; $dump<br>   sleep $INTERVAL<br>done</pre><p>The above script can be run to take 5 dumps with an interval of 10 seconds like follows,</p><pre>mkdir ./threadump<br>./threaddump-script.sh &lt;pid&gt; 5 10s</pre><p>This puts all the 5 dumps into a threaddump directory.</p><h3>Analyze dumps</h3><p>Now let’s put the dumps we captured to some use. You could just open up the dumps in some editor and read through the stacks to find an obvious issue. Sometimes when the issue is due to a repetitive object creation (which in turn spawns threads), the thread stacks will all look similar and you might be able to find the issue. Or, you can use tools that analyse thread dumps for you. Many APM tools provide this capability. But my favourite is an online tool called Fast thread. Link below. Btw, It’s a free tool.</p><p><a href="https://fastthread.io/">fastthread.io</a></p><p>You just upload your dumps (a single file or a zip of multiple files) and the tool breaks down some useful metrics for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVRZ_dDjrJu8NgcbsP3_fw.png" /><figcaption>Thread count summary based on states</figcaption></figure><p>The above is a result from the site. It shows the states of all threads from your dumps. You can read up more about the meanings of thread states and what they mean in the context of a process. I’m just gonna skip that part and move to the debugging part.</p><h4><strong>Step 1: Look at thread count state breakups</strong></h4><p>Now what we’ve gotten from the summary here is that there are 2000+ threads in a waiting state and we need to figure out what are all these threads created for and is it a valid cause. In this particular case, the number of threads were increasing with time, so I had a hunch that they were definitely not useful threads (like threads that were actually needed to process the load).</p><h4><strong>Step 2: Look for similar stack traces</strong></h4><p>Usually this step clearly shows you where the issue is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lys4dDm4L5Dk9n-EnKYToA.png" /><figcaption>Threads grouped by similar stack traces</figcaption></figure><p>As you see almost all of the 2000+ threads in my case are grouped into a single stack trace type. Looking into that particular stack trace will tell me what the issue is. In other cases there might me multiple stack traces with issues (But usually it’s a single culprit, trust me 😛)</p><h4><strong>Step 3: Dig into the highest count stack trace</strong></h4><p>Now you can drill down to the specific stack trace in the tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mywtwy4GLnCYCvkUKihZBA.png" /></figure><p>Haaa, there is the issue, plain in front of your eyes!! This is a <strong><em>classic case of a client initialisation within some block of code that will be invoked multiple times by process</em></strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl4q83E0RjRSGLXBLO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Falexanderirl-alexander-irl-l4q83E0RjRSGLXBLO&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fl4q83E0RjRSGLXBLO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="271" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2f36b2bae7415dc83068865618199d4/href">https://medium.com/media/c2f36b2bae7415dc83068865618199d4/href</a></iframe><p>In my case, I had put a OkHttp client initialisation within a method (and not commonly in the class). For every incoming call served, an object was spawned. And OkHttp client internally takes up a separate thread to make the http call.</p><h3><strong>Fix the code</strong></h3><p>Now go back to your code and fix the issue that you just found. You could run the process again with the fix in place and take dumps to verify the fix.</p><p>My thread dump summary after the fix,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNerg8pGvgsJQM6uRTz1iQ.png" /><figcaption>Back to normal thread counts</figcaption></figure><h3>Conclusion</h3><p>That is how you fix high thread utilisation issues. If you’re wondering why you’d have to fix thread issues, it’s simply because JVM will run out of memory (OOM) once it runs out of available threads (the limit depends on your machine memory). This is definitely not how you’d want to let your code running in servers.</p><p><em>— Authored by </em><a href="https://medium.com/u/a640a517f7d8"><em>Sowmiya Nagarajan</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42b604514ba0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/capture-and-analyse-thread-dumps-in-jvm-42b604514ba0">Capture and Analyse Thread Dumps in JVM</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Packaging Github Projects using Homebrew]]></title>
            <link>https://medium.com/swlh/packaging-github-projects-using-homebrew-ae72242a2b2e?source=rss-5eb689be736d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae72242a2b2e</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[homebrew]]></category>
            <category><![CDATA[brew]]></category>
            <dc:creator><![CDATA[Sowmiya Nagarajan]]></dc:creator>
            <pubDate>Mon, 06 Apr 2020 17:49:40 GMT</pubDate>
            <atom:updated>2020-04-06T17:49:40.818Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>While it’s easy to package code in GitHub repos by setting up CI pipelines (like <a href="https://github.com/marketplace/travis-ci">Travis CI</a>, <a href="https://help.github.com/en/packages/using-github-packages-with-your-projects-ecosystem">Github packages</a> etc) and get the packages hosted on the specific package managers (like pip, npm etc), it’s a little harder to package repositories with code written in multiple languages. Sometimes you need to ship all the code into user machines and be able to work with it during or post the installation. I cracked one such problem for a project of mine using Homebrew formulas 🍺 .</blockquote><h4>Homebrew — Quick Intro</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzzLwn4XdpjXk-uzQe9vuA.png" /></figure><p>Homebrew is a package-manager that helps you install software on macOS and Linux. It’s just like apt-get or pip utilities. You’ll find most mac users choosing Homebrew for their installations mainly because it WORKS!!</p><p>Listing down a few pros of Homebrew.</p><ul><li>Very active project. Makes extensive use of GitHub to expand the support of several packages through user contributions.</li><li>Installs into /usr/local so does not need you to modify PATH anywhere</li><li>Every installed package is cleanly sandboxed into its own cellar so you don’t have stray files all over your system, just symlinks from bin, man, etc.</li><li>Super easy to package your own code and make it installable via brew 💛</li></ul><p>Now the last point is what made me write this post. So let’s get started on packaging Github repos using Homebrew.</p><h4>Step 1: Package your repo</h4><p>First things first, you need to have a packaged version of your code. It could be anything ranging from a pip package, docker image or even just a zip. For <a href="https://github.com/Stack-Box/stackbox">my project</a> I used a zip file as the packaging format. It has code in multiple languages and different builds, so zip was my only way to go. But if you have your code in one specific language, you should consider packaging it in the specific packaging format and then use that in the further steps. The reason why is, you want your package files to be as small as possible (not have tonnes of code just zipped up lazily) to make download quicker on machines. You have higher chance of people actually wanting/being able to use your package that way!</p><p>I used <a href="https://github.com/Stack-Box/stackbox/releases">Github releases</a> to get the tarball of my code. You should also be able to make releases for your repo easily from the releases tab. If you have a language specific code consider integrating with some CI service like <a href="https://github.com/marketplace/travis-ci">Travis</a> to have your packages created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3rtfHN3J2OoBGpgyxq10A.png" /><figcaption>Package your code using releases</figcaption></figure><p>Now what happens with Github releases is that Github creates tagged versions of your project with <strong><em>links to the compressed file</em></strong> of code for those particular releases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RR9V6qa8DUFdxWy7G__RhQ.png" /><figcaption>Sample release in GitHub</figcaption></figure><p>Now the zip or tar.gz are of importance to us here. We’ll use this in writing our homebrew formula — which are nothing but package descriptions that tell what to do with these tarballs on the installing machines.</p><h4>Step 2: Get started with Brew formula</h4><p>For a brew formula you’ll write a .rb (ruby) file. <strong>Refer to </strong><a href="https://github.com/Stack-Box/homebrew-tap/blob/master/stackbox.rb"><strong>my formula</strong></a>.</p><p>You could start fresh and write it all by yourselves or make use of brew itself to create the file for you. I would suggest the latter. Refer to <a href="https://docs.brew.sh/Formula-Cookbook#grab-the-url">Homebrew documentation</a>.</p><pre>brew create <a href="https://github.com/Stack-Box/stackbox/archive/v1.2.0.tar.gz">https://example.com/foo-0.1.tar.gz</a></pre><p>Here for the tar.gz link you will use your GitHub release tar link.</p><p>Doing this will create a formula for you in</p><pre>/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/foo.rb</pre><p>The .rb is named foo matching the tar name.</p><p>This formula is directly placed in the homebrew-core formulas. Homebrew core is where all cool projects want their formulas to be. If your formula is in Homebrew core then it will get listed like <a href="https://formulae.brew.sh/formula/">this</a>. But you’ll need to get it committed into the Homebrew repo. For which you have to have a website, good documentation for your project — basically the maintainers of Homebrew should be satisfied enough to make it a part of their core formuale! Once you make it to the core formulas, all brew users can directly install your package without having to <strong>tap</strong> to get your formula separately.</p><h4>What are taps??</h4><blockquote>Detour. I just said taps. What are taps?</blockquote><p>Homebrew has this amazing support wherein it helps people who want to quickly package their formula without going through the whole process of reviewing to make it to the core formulas.</p><p><em>And I used tap to make my project Homebrew installable.</em></p><p>Now everytime brew updates (which is pretty much everytime you run an install) it pulls in all new core formulas. Once a formula is in the user machine, then all they do is run “<em>brew install &lt;package-name&gt;”</em> to install the package. Now to get Third-party formulas into user machines we make use of tap.</p><p><strong><em>Users can tap into a third-party formula and then run install for that package.</em></strong></p><p>Now how do you create taps, to write and put in your non-core formula?</p><blockquote>Again, Github!</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQNFhOolVeCzPQ2Mx85%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcheckmatedigital-code-coding-monkey-QNFhOolVeCzPQ2Mx85&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQNFhOolVeCzPQ2Mx85%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/150c88c33b5ebddf071b1aa7571d693b/href">https://medium.com/media/150c88c33b5ebddf071b1aa7571d693b/href</a></iframe><h4>Step 3: Setup a tap</h4><p>We have a sample formula we created in Step 2. We’ll create a tap and move that formula to the tap.</p><ol><li>To create a tap, all we need is a GitHub repo with “<strong>homebrew-</strong>” as prefix in the repo’s name — like <a href="https://github.com/Stack-Box/homebrew-tap">this one</a>.</li><li>Now move the sample .rb created earlier into this repo and commit it.</li><li>Now try</li></ol><pre>brew tap &lt;username-or-orgname&gt;/&lt;tap-name&gt;</pre><p>Here tap name is the repo’s name without the homebrew prefix. For example, if your tap repo is named as “homebrew-randomtap” then you should use “randomtap” as tap name.</p><blockquote>I guess the homebrew prefix in repo names is for homebrew to keep track of third-party formulas.</blockquote><p>Now as a result of this tap command you will have the formula in your local homebrew taps. Path like below.</p><pre>/usr/local/Homebrew/Library/Taps/&lt;username-or-orgname&gt;/&lt;tap-name&gt;</pre><p>From here you can build changes on your formula and test it locally until you’re satisfied and then commit it to the tap repo for others to install using it.</p><h4>Step 4: Write Brew Formula</h4><p>Now let’s start editing the formula from our tap.</p><pre>class Stackbox &lt; Formula<br>  desc &quot;Create app stacks loaded with all your favourite clients,<br>        services and infra along with code boilerplates in under<br>        5 mins.&quot;<br>  url &quot;<a href="https://github.com/Stack-Box/StackBox/archive/v1.2.0.tar.gz">https://github.com/Stack-Box/StackBox/archive/v1.2.0.tar.gz</a>&quot;<br>  sha256  <br>  &quot;ea9bcc6905169868ac4f5ee54b7ace6ad8ed8416d482accbcf3fb7211027436b&quot;</pre><pre>depends_on &quot;docker&quot;<br>depends_on &quot;docker-compose&quot;<br>depends_on &quot;python&quot;<br>depends_on &quot;shc&quot;</pre><pre>def install<br>    system &quot;mkdir -p /usr/local/Cellar/stackbox/1.2.0/bin&quot;<br>    system &quot;cp -a . /usr/local/Cellar/stackbox/1.2.0/&quot;<br>    system &quot;shc -f ./brew/stackbox-brew.sh -o stackbox&quot;<br>    system &quot;cp ./stackbox /usr/local/Cellar/stackbox/1.2.0/bin/&quot;<br>  end<br>end</pre><p>This is how my formula looks. Running over some key points.</p><ol><li>Put the <strong>url to your tarball</strong> in the url field.</li><li>Find out the <strong>sha for your tar file</strong> and put that in the sha256 field (I usually just run an install and check the expected sha and replace it in the formula 😛)</li><li>Figure out if your package needs any dependencies to install/run and define them using “<strong>depends_on</strong>”</li><li>Then <strong>define the install</strong> block. You can use a make command, a configure script or just some cp move to get what you want to be done based on your use case.</li></ol><p>For my install I’m simply creating an executable binary from a bash script using shc and copying all installation/run files (in my case everything in repo) to the /usr/local/Cellar/&lt;package-name&gt; path.</p><blockquote>Anything within /bin in the cellar is an exec and in the executable path. So you can put your main executable in bin and refer to any files you need from there relatively.</blockquote><p>Now it might take multiple runs to figure out if all the commands work and modify them if needed.</p><p>To debug and test, you can simply run</p><pre>brew install &lt;package-name&gt;</pre><p>In my case the package name is same as the formula name “stackbox”. You will be able to debug your installation commands when you run this install.</p><h4>Step 5: Commit formula changes to tap</h4><p>So far you debugged using the local formula file. Just make sure to commit it back to the tap repo. Now you can ask your project fam to do just a tap and install to get your project up and running!</p><pre>brew tap &lt;username-or-orgname&gt;/&lt;tap-name&gt;<br>brew install &lt;package-name&gt;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT5LMMd0I0UUHxKUg0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fseason-17-the-simpsons-17x21-xT5LMMd0I0UUHxKUg0&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT5LMMd0I0UUHxKUg0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="328" frameborder="0" scrolling="no"><a href="https://medium.com/media/f91b18808d9ea1f11a41fc14de4bc35d/href">https://medium.com/media/f91b18808d9ea1f11a41fc14de4bc35d/href</a></iframe><p>That’s the end. Find some links to useful references below. Byee 👋</p><ul><li><a href="https://github.com/Stack-Box/homebrew-tap">My tap</a> + <a href="https://github.com/Stack-Box/stackbox">My code repo</a></li><li><a href="https://docs.brew.sh/Formula-Cookbook">Homebrew formula cookbook</a></li><li><a href="https://github.com/Homebrew/brew">Hoembrew Github</a></li></ul><p>— Authored by <a href="https://medium.com/u/a640a517f7d8">Sowmiya Nagarajan</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae72242a2b2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/packaging-github-projects-using-homebrew-ae72242a2b2e">Packaging Github Projects using Homebrew</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Flask APIs using SocketIO to Produce/Consume Kafka Messages]]></title>
            <link>https://levelup.gitconnected.com/build-flask-apis-using-socketio-to-produce-consume-kafka-messages-95a15df2d1bc?source=rss-5eb689be736d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95a15df2d1bc</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[Sowmiya Nagarajan]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 16:43:43 GMT</pubDate>
            <atom:updated>2021-02-25T14:48:48.383Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you have a Kafka cluster. You can produce and read messages from topics using some client code easily. What if you want to expose your Kafka cluster via endpoints to produce/consume messages. How would you do that?</p><p>We’ll need 3 abstract components to achieve this,</p><ol><li>Kafka setup</li><li>App with connectivity to the Kafka setup</li><li>Some web-page to test out the app endpoints</li></ol><p>This post has instructions to build and test the following architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cq2Mu4HPR48VJpmtYeeaXA.png" /><figcaption>Target architecture</figcaption></figure><p>So we’ll be using docker containers to setup Kafka and expose Kafka using Flask web-sockets. Let’s crack the architecture one component at a time!</p><h3>Step 1: Kafka setup using Docker</h3><p>Two docker images avaliable for kafka are <a href="https://hub.docker.com/r/spotify/kafka/">spotify/kafka</a> and <a href="https://hub.docker.com/r/wurstmeister/kafka/">wurstmeister/kafka</a>. The Wurstmeister one is a popular choice and we’ll be using it for this setup.</p><p>Refer to <a href="https://github.com/Stack-Box/stackbox-tutorials/tree/master/flask-kafka"><strong>Github folder</strong></a> for all code used to build this example.</p><blockquote><strong>NOTE:</strong> The code is updated continuously based on issues/PRs from the readers. Hence, there may be a few discrepancies between snippets mentioned here and in the repo. Refer to updates at the bottom of this post.</blockquote><p>Let’s use a <a href="https://github.com/Stack-Box/stackbox-tutorials/blob/master/flask-kafka/docker-compose.yml">docker-compose.yml</a> to bring up Kafka and Zookeper containers.</p><pre>version: &#39;3&#39; <br>services:  <br>   kafka:    <br>      environment:      <br>        KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>        KAFKA_ADVERTISED_HOST_NAME: &lt;your-ip&gt;  <br>      image: wurstmeister/kafka    <br>      ports:      <br>        - &quot;32770:9092&quot;    <br>      volumes:      <br>        - /var/run/docker.sock:/var/run/docker.sock    <br>      depends_on:      <br>        - zookeeper   <br>   zookeeper:    <br>      image: wurstmeister/zookeeper    <br>      ports:      <br>        - &quot;2182:2181&quot;</pre><h4>Decoding the docker-compose.yml</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZvgb12U8GNjvq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Flook-glasses-Zvgb12U8GNjvq&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZvgb12U8GNjvq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="291" frameborder="0" scrolling="no"><a href="https://medium.com/media/8847366ac896ceca8911b9ea34f66e7a/href">https://medium.com/media/8847366ac896ceca8911b9ea34f66e7a/href</a></iframe><p>We have defined two services, Kafka and Zookeeper in the compose file. Kafka internally would run on 9092 within the docker network and externally exposed on 32770 (localhost) and zookeeper internally 2181 and externally on 2182.</p><p>The <em>KAFKA_ZOOKEEPER_CONNECT </em>is set to <em>zookeeper:2181</em>. Here zookeeper is the service name within the docker network and the port is also the internal port. The <em>KAFKA_ADVERTISED_HOST_NAME has to be set to your machine’s en0 IP. For example, on a mac you can find this using ipconfig getifaddr en0</em></p><p>If you want to spin up more brokers or create topics while bringing up the brokers itself, refer to the <a href="https://github.com/wurstmeister/kafka-docker">wurstmeister/kafka-docker</a> readme for more useful config.</p><p>Back to the setup. Now run the following command to bring your containers up.</p><pre>docker-compose up </pre><p><strong>TIP</strong>💡 — If you’ve set your IP fine and if the ports are not occupied, then your containers should be up. Sometimes, when Kafka brokers won’t get created without any issues in particular, pruning the docker images, containers and volumes or even a docker restart have magically helped me fix the issue.</p><p>So we are done with our Kafka setup!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Flo3tKPgv7v6IkZqliN%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FCartoonNetworkLatam-sol-gafas-anteojos-lo3tKPgv7v6IkZqliN&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Flo3tKPgv7v6IkZqliN%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e4f760bd84d299271dfb5e2167bab0/href">https://medium.com/media/93e4f760bd84d299271dfb5e2167bab0/href</a></iframe><p>For those of you wondering, how do I bring this setup down. Use</p><pre>docker-compose down</pre><p>to bring down the containers. But just make sure you have the containers up while you test run your app or web-page. You could use the following command to list the running containers.</p><pre>docker ps</pre><h3>Step 2: Write Flask SocketIO app</h3><p>Now that we have our Kafka guy ready let’s write some connectivity to read and write messages.</p><p>Refer to the full working <a href="https://github.com/Stack-Box/stackbox-tutorials/blob/master/flask-kafka/app.py">app.py</a> while I explain some important pieces of code below.</p><p>Since we can’t exactly use REST APIs to read and write to our Kafka, we’ll write sockets to stay connected to the Kafka cluster while our app is running and we can stream these changes real-time to our web-page as well. Web-sockets are a cool programming paradigm used in applications where a simple get/post/put won’t work and you need a connection to persist longer to get/put data in real-time. Read more about web-sockets, SocketIO to understand and appreciate the concepts of sockets 💡</p><p>We’ll use <a href="https://github.com/miguelgrinberg/Flask-SocketIO"><strong>Flask-SocketIO</strong></a><strong> </strong>to write sockets in our app. All you need to do is add the <strong>@socket</strong> decorator instead of the usual route decorator to expose as a socket.</p><p>We have 3 socket endpoints in the app.</p><ol><li><strong>connect</strong>: just a socket to check if connection is established on a channel</li><li><strong>kafkaproducer</strong>: takes a message (from the web-page) and posts it to a configured kafka topic</li><li><strong>kafkaconsumer</strong>: reads all messages in the topic and emits them back to the same channel. This emitted list of messages can be picked up by web-page.</li></ol><p>We will stick to a single channel here which is named <em>kafka</em>.</p><p>Top connect to kafka from python, we’ll use <a href="https://pypi.org/project/kafka-python/"><strong>kafka-python</strong></a><strong>. </strong>All requirements can be found in <a href="https://github.com/Stack-Box/stackbox-tutorials/blob/master/flask-kafka/requirements.txt">requirements.txt</a>. I used python 3.6 for the implementation.</p><h4>Producer code</h4><p>The producer snippet is pretty straightforward.</p><pre>@socketio.on(&#39;kafkaproducer&#39;, namespace=&quot;/kafka&quot;)<br>def kafkaproducer(message):<br>    producer = KafkaProducer(bootstrap_servers=BOOTSTRAP_SERVERS)<br>    producer.send(TOPIC_NAME, value=bytes(str(message),<br>        encoding=&#39;utf-8&#39;), key=bytes(str(uuid.uuid4()),<br>        encoding=&#39;utf-8&#39;))<br>    emit(&#39;logs&#39;, {&#39;data&#39;: &#39;Added &#39; + message + &#39; to topic&#39;})<br>    emit(&#39;kafkaproducer&#39;, {&#39;data&#39;: message})<br>    producer.close()<br>    kafkaconsumer(message)</pre><ol><li>Connect to Kafka using KafkaProducer from kafka-python</li><li>Then post the message to Kafka (All messages and keys need to be bytes)</li><li>Then we emit some logs saying the message has been posted.</li><li>And then kafkaconsumer snippet is called (This is to show the produced message via consumer in the web-page)</li><li>The whole method is decorated using socketio with a name and a namesapce. Name is how the method will be called in the web-page and namespace is equivalent to channel in which all the emits and sends will be co-ordinated.</li></ol><h4>Consumer code</h4><p>The consumer needs some extra bit of code to stop after consuming all messages. Otherwise it would just keep listening for new messages and wouldn’t exit.</p><pre><a href="http://twitter.com/socketio">@socketio</a>.on(&#39;kafkaconsumer&#39;, namespace=&quot;/kafka&quot;)<br>def kafkaconsumer(message):<br>    consumer = KafkaConsumer(group_id=&#39;consumer-1&#39;,<br>                             bootstrap_servers=BOOTSTRAP_SERVERS)<br>    tp = TopicPartition(TOPIC_NAME, 0)<br>    consumer.assign([tp])<br>    consumer.seek_to_end(tp)<br>    lastOffset = consumer.position(tp)<br>    consumer.seek_to_beginning(tp)<br>    emit(&#39;kafkaconsumer1&#39;, {&#39;data&#39;: &#39;&#39;})<br>    for message in consumer:<br>        emit(&#39;kafkaconsumer&#39;, <br>             {&#39;data&#39;: message.value.decode(&#39;utf8&#39;)})<br>        if message.offset == lastOffset - 1:<br>            break<br>    consumer.close()</pre><ol><li>Connect to Kafka using KafkaConsumer from kafka-python</li><li>Find out the position of last message in stream</li><li>Read all messages till the last message and break connection</li><li>Also emit these messages read to the channel to enable the web-page to pick them up.</li><li>The initial emit to “kafkaconsumer1” is to tell the web-page that new set of messages are coming and to clear up the existing messages list in the page.</li></ol><p>Now when you run</p><pre>python app.py</pre><p>You will have your web-sockets up and running. Flask SocketIO doesn’t show any startup logs, so don’t be startled 😛</p><h3>Step 3: Write Web-page</h3><p>I wrote some <a href="https://github.com/Stack-Box/stackbox-tutorials/blob/master/flask-kafka/index.html">super-basic HTML</a> to connect to the app and show messages. It uses <a href="https://socket.io/">SocketIO</a> for scripts to stream data from the app. The html has a simple form that takes in some message and puts it to producer. There are sections that read back all messages from consumer and also show logs.</p><p>Now have your kafka setup running, run your app and open <a href="https://github.com/Stack-Box/stackbox-tutorials/blob/master/flask-kafka/index.html">index.html</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*iq7mLyfMPNSu-M7ZlHytUw.gif" /><figcaption>Working</figcaption></figure><p>It’s time to cel-eb-rateee! (Or head straight to comments to ask questions, or raise issues on <a href="https://github.com/Stack-Box/stackbox-tutorials">Github</a> and get the issue fixed and then.. CEL-EB-RATEEE!!)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYTbZzCkRQCEJa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fparty-excited-birthday-YTbZzCkRQCEJa&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYTbZzCkRQCEJa%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/c29b53ea32e8e3562b5c0d9b2e213981/href">https://medium.com/media/c29b53ea32e8e3562b5c0d9b2e213981/href</a></iframe><p>That’s the end. Find links to the code, packages and other useful resources below. Byeee 👋</p><ul><li><a href="https://github.com/Stack-Box/stackbox-tutorials">Code</a></li><li><a href="https://github.com/wurstmeister/kafka-docker">Kafka docker</a></li><li><a href="https://github.com/miguelgrinberg/Flask-SocketIO">Flask-SocketIO</a></li><li><a href="https://pypi.org/project/kafka-python/">kafka-python</a></li><li><a href="https://socket.io/">socket.io</a></li></ul><p><em>— Authored by </em><a href="https://medium.com/u/a640a517f7d8"><em>Sowmiya Nagarajan</em></a></p><blockquote><strong>02/25/2021 — Update</strong></blockquote><blockquote>Shoutout to readers <a href="https://github.com/halvnok">halvnok</a> and <a href="https://github.com/Exchizz">Exchizz</a> for their feedback and suggestions to the code.</blockquote><blockquote><strong>Changes</strong></blockquote><blockquote>1. The flask code is containerized now. Refer to <a href="https://github.com/Stack-Box/stackbox-tutorials/pull/2">stackbox-tutorials/pull/2</a>. There are also few updates to the dependency versions.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95a15df2d1bc" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-flask-apis-using-socketio-to-produce-consume-kafka-messages-95a15df2d1bc">Build Flask APIs using SocketIO to Produce/Consume Kafka Messages</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>