<?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 Amareswar Reddy on Medium]]></title>
        <description><![CDATA[Stories by Amareswar Reddy on Medium]]></description>
        <link>https://medium.com/@amareswar-polimera?source=rss-6ec3ec345625------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pmBYzE9xv3MgLEw1.</url>
            <title>Stories by Amareswar Reddy on Medium</title>
            <link>https://medium.com/@amareswar-polimera?source=rss-6ec3ec345625------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:21:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amareswar-polimera/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[Basic Stateful word count using Apache Flink]]></title>
            <link>https://amareswar-polimera.medium.com/basic-stateful-word-count-using-apache-flink-c68fae97f2ba?source=rss-6ec3ec345625------2</link>
            <guid isPermaLink="false">https://medium.com/p/c68fae97f2ba</guid>
            <category><![CDATA[stateful]]></category>
            <category><![CDATA[flink]]></category>
            <category><![CDATA[flink-streaming]]></category>
            <category><![CDATA[word-count]]></category>
            <dc:creator><![CDATA[Amareswar Reddy]]></dc:creator>
            <pubDate>Mon, 07 Dec 2020 22:02:24 GMT</pubDate>
            <atom:updated>2020-12-07T22:10:11.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*B_Q5gliFkcjW2ef1WW5uYw.jpeg" /></figure><p>Started to learn about concepts of stream processing, being a java developer and going over different blogs about various stream processing engines, decided to learn Flink as it is a pure stream processing engine with the advanced stateful functions.</p><p>This section I want to walk you through a simple stateful function that helps newbies to understand what stateful stream processing is. As usual, I am going to solve the classic word count problem using stateful stream processing.</p><p>This is my first attempt at medium blogging and thanks for taking time in spending time in reading this.</p><p>As we all know, Flink is a fault-tolerant stateful stream processing engine that does all the heavy lifting of managing the state through cluster re-starts and node failures. The state is persisted in the configured state backend, updated periodically as specified in the job. Ideally the state backend storage should be durable and fault-tolerant, something like S3, HDFS or Azure Blob etc..,</p><p>Every stateful flink application/job contains sources, stateful functions and sinks where the results are written to. In my sample program, i am using <a href="https://en.wikipedia.org/wiki/Netcat"><em>netcat</em></a> to send the data that simply acts like an ingress for flink job. You need to install netcat based on the operating system and issue <em>nc -l 999</em> in the terminal. Now netcat is waiting for other program to connect to the socket at port number <em>9999. </em>Here is how it looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*Q7UvV-xPZmm8AfeUl1BqGw.png" /><figcaption>netcat waiting at port 9999</figcaption></figure><p>Now that we are ready to input some sample data to our flink application, let’s jump into the flink job’s main function. Here is the complete <a href="https://bitbucket.org/amarpolimera/flink-basics/src/master/src/main/java/com/flink/basics/WordCountWithCheckpoint.java">code</a> for your reference. It is a typical main program that starts with setting up filnk environment.</p><p><strong>Reference for Streaming Environment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*Vwvo3munzwiv28aOs5X_Nw.png" /><figcaption>Flink reference for streaming execution environment</figcaption></figure><p>Once the environment is retrieved, as we are trying to implement the stateful function, we need to define the state backend and check-point configuration.</p><p><strong>Check-point configuration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ceCMZPkgv_XPZ8P4Iy39g.png" /><figcaption>Check-point configuration with File State Backend</figcaption></figure><p>In the above code, the checkpoint location is derived from the arguments passed when running the flink program, this is where the state is stored periodically at every 5000ms or simply 5 sec. The <em>maxConcurrentCheckpoints </em>defines the number of max checkpoint operations that can be active at any given time. This is to ensure that the system resources are not taken up by too many checkpoints if the first one is delayed for a reason. Not a mandatory setting for this use case but worth mentioning.</p><p><strong>Ingress data from socket</strong></p><p>Now comes the actual part of the code where the text needs to be read from the port, using flatmap to convert the incoming line into words. It is simple and straight forward and no difference between non-stream based ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*rE0IGUzV2k7ZefKlB2Y9HA.png" /><figcaption>Ingress data from socket and split into words</figcaption></figure><p>We got a data-stream of words split based on the space as a result of flatmap, remember that we are not going with general <em>reduce</em> approach of converting the string to tuple with value of 1 and then passing it to reduce function, instead we are going to store the number of occurrences of the word as a state and for that we are going to make use of Value keyed-state.</p><p>Remember that keyed-state can be obtained only from keyed-stream and <em>words</em> is not a keyed-stream. To derive a keyed-stream from a normal data-stream, we need to use <strong>keyedBy </strong>operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*2CG-gfdo-ylZ5uTVcu3-Tw.png" /><figcaption>KeyedStream from Data Stream</figcaption></figure><p>Now we have the keyed stream, this can be leveraged to store the value state which is nothing but the number of occurrences of that word (used as key) till now.</p><p>Let us implement a process function that processes each element in the keyed stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*FBsM6W8gFHaJXcLQxn8sTg.png" /><figcaption>Process function used to process each word</figcaption></figure><p><strong>Stateful Process Function</strong></p><p>This is where it defers from traditional state-less functions. Let’s dive into the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kc8e9XP3wk9wwryJOlkvnQ.png" /><figcaption>Stateful process function</figcaption></figure><p>In the code snippet, a variable <strong>count </strong>is defined and that is used to store the current occurrence of the word in the context which is the key of the keyed stream. Please pay attention, this is where its a bit confusing. The state variable is associated with the <strong>operator</strong> (keyedBy) and the <strong>key, </strong>this means that there will be a value associated for each key in the stream. Let’s dive into each line of the process function.</p><p>Process function has a method called <strong>processElement </strong>which takes into the element, in this case word which is of type String passed a the first argument, <strong>context</strong> under which this operation is being performed and the <strong>collector</strong> where the response of the process function is collected. Here the output is of <strong>Tuple2 </strong>type where <strong>f0 (refer to </strong><a href="https://ci.apache.org/projects/flink/flink-docs-master/api/java/org/apache/flink/api/java/tuple/Tuple2.html"><strong>Tuple2</strong></a><strong> in flink java) </strong>which is a String refers the word and <strong>f1 </strong>which is the total number of occurrences of that word till that time.</p><p>The process function becomes stateful because of the implementation we have in the <strong>open </strong>method. Any state can be retrieved from the flink’s runtime context using a descriptor. Here we are using a ValueDescriptor that has a name as <strong>count </strong>and the value is of type <strong>Integer. </strong>There can be multiple descriptor types and multiple different state associated within a stateful function and we are going to have only one state for simplicity purposes.</p><p>This <strong>open</strong> method is called during the job start and the <strong>count </strong>value is restored to the previous stored value in case of restarts. Whenever <strong>value() </strong>method is called, flink core will do a look up in the <strong>stateTable </strong>for the value and returns the current value. So, use value() judiciously as it wont change unless it is updated.</p><p><strong>Running the flink job</strong></p><p>In this section, we perform steps to run the job.</p><p>To install Flink, you should have Java 8 installed on your machine. Make sure that before proceeding to the next steps. Skip the below steps if you have done the flink installation.</p><blockquote>wget — no-check-certificate <a href="https://apache.claz.org/flink/flink-1.11.2/flink-1.11.2-bin-scala_2.12.tgz">https://apache.claz.org/flink/flink-1.11.2/flink-1.11.2-bin-scala_2.12.tgz</a></blockquote><blockquote>tar — extract — file flink-1.11.2-bin-scala_2.12.tgz</blockquote><blockquote>cd flink-1.1.2/bin; ./start-cluster.sh</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iA72yVflrL81kiJYyz3ZCw.png" /><figcaption>Apache flink dashboard</figcaption></figure><p>Now we have standalone cluster started, you can check the cluster status at <a href="http://localhost:8081/">http://localhost:8081</a>. It looks something like this.</p><blockquote>git clone <a href="https://amarpolimera@bitbucket.org/amarpolimera/flink-basics.git">https://amarpolimera@bitbucket.org/amarpolimera/flink-basics.git</a><br>cd flink-basics<br>mvn clean compile assembly:single</blockquote><p>We now have a jar file in the target folder with name as <em>flink-basics-1.0-SNAPSHOT-jar-with-dependencies.jar. </em>Now we need to submit job with this jar as input. Remember that i used maven j<em>ar-with-dependencies </em>plugin which sets the main class and so you don’t need to refer it while executing the job</p><p>Go to the extracted <em>flink</em> floder and run the below command</p><blockquote>./flink run &lt;jar-file-location&gt; — checkpoint-path &lt;any-dir-to-save-state&gt;</blockquote><p>You will see a message that the job has been submitted with Job ID something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3J0-lKFqplb8MWi11WFEQ.png" /><figcaption>job run result</figcaption></figure><p>Now, go to the terminal where netcat is running and type in some words on the console.</p><p>Go to the flink-dashboard running on <a href="http://localhost:8081/">http://localhost:8081</a> and click on <strong>Task Managers. </strong>You should be seeing a job that is running, click on the job and select <strong>stdout </strong>tab. You can see the words and the number of occurances printed over there. You can type in more words and hit refresh on stdout (on the top right corner of the tab) and see the counts are the entries are changing. Here is the sample stdout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3FLcT9DQ8Q9uDJJdctZVQ.png" /></figure><p>Remember that this program supports sentences to be passed as input and so you can type in long sentences in the <em>nc</em> terminal.</p><p>You can see that my name appeared 4 times till now. Let’s cancel the job. To cancel the job, go to <strong>Running Jobs</strong> and click on the job row. You see a <strong>Cancel Job </strong>option, please click and confirm cancelling the job.</p><p>Lets start the job again and retain the counts we got. To retain status, we need to specifiy the savepoint from which the job should restore the state. Go to the directory that has been passed as <em>checkpoint-path </em>while running the job. You will see that a directory with the job id has been created and contains directories starting with <strong>chk-, </strong>the latest directory contains the most recent state.</p><p>Once the <em>chk-* </em>directory path is saved re-run the same job again but this time pass the directory as one of the options. You can pass the checkpoint directory as <strong>-s </strong>option</p><blockquote>./flink run -s &lt;-dir-to-checkpoint&gt;/…./chk-* &lt;jar-file-location&gt; — checkpoint-path &lt;dir-to-checkpoint&gt;</blockquote><p>Try entering more words again on the <em>nc </em>terminal. Enter the words as first time. Go to the stdout and the count incremented from the previous value and not from zero!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*27BhSs_sVzdTmlJ9tnHMtg.png" /></figure><p>Word counts from the previous run are retained!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c68fae97f2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>