<?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 Anurag Prakash on Medium]]></title>
        <description><![CDATA[Stories by Anurag Prakash on Medium]]></description>
        <link>https://medium.com/@anurag2397?source=rss-8dcd30ab7797------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xB-ln8B-XmTSFhx8-HMzfQ.jpeg</url>
            <title>Stories by Anurag Prakash on Medium</title>
            <link>https://medium.com/@anurag2397?source=rss-8dcd30ab7797------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:33:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anurag2397/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[Solving Java’s core problems around Memory and CPU]]></title>
            <link>https://medium.com/@anurag2397/solving-javas-core-problems-around-memory-and-cpu-4d0c97748c43?source=rss-8dcd30ab7797------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0c97748c43</guid>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Anurag Prakash]]></dc:creator>
            <pubDate>Sat, 05 Nov 2022 10:28:21 GMT</pubDate>
            <atom:updated>2022-11-05T10:28:21.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tuning JVM containers for better CPU and memory utilisation in K8s environment.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*BsmaroeGf2Zowtio.png" /></figure><p>The JVM is one of the oldest yet powerful virtual machines ever built.</p><p>Whenever a new JVM process starts, all required classes are loaded into memory by an instance of the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ClassLoader.html">ClassLoader</a>. This process takes place in three steps:</p><ol><li><strong>Bootstrap Class Loading: </strong>The “<em>Bootstrap Class Loader</em>” loads Java code and essential Java classes such as <em>java.lang.Object </em>into memory. These loaded classes reside in <em>JRE\lib\rt.jar</em>.</li><li><strong>Extension Class Loading</strong>: The ExtClassLoader is responsible for loading all JAR files located at the <em>java.ext.dirs</em> path. In non-Maven or non-Gradle based applications, where a developer adds JARs manually, all those classes are loaded during this phase.</li><li><strong>Application Class Loading</strong>: The AppClassLoader loads all classes located in the application class path.</li></ol><p>This initialisation process is based on a lazy loading scheme.</p><p>Once class-loading is complete, all important classes (used at the time of process start) are pushed into the <a href="https://www.ibm.com/support/knowledgecenter/en/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/rdyn_tunediskcache.html">JVM cache (native code)</a> — which makes them accessible faster during runtime. Other classes are loaded on a per-request basis.</p><p>The first request made to a Java web application is often substantially slower than the average response time during the lifetime of the process. This initial startup period can usually be attributed to lazy class loading and just-in-time compilation.</p><p>Keeping this in mind, for low-latency applications, we need to cache all classes beforehand — so that they’re available instantly when accessed at runtime.</p><p><strong>This process of tuning the JVM is known as warming up.</strong></p><blockquote>High Latencies during JVM warm-up is a prominent problem. JVM-based applications deliver great performance but need some time to “warm-up” before reaching the top speed. When the application launches, it usually starts with reduced performance. It can be attributed to things like Just-In-Time (JIT) compilation which optimizes frequently used code by collecting usage profile information. The net negative effect of this is that the requests received during this warm-up period will have a very high response time as compared to the average. This problem can be exacerbated in containerised, high-throughput, frequent-deploys, and auto-scaled environment</blockquote><p><em>In this article, I will be discussing about JVM Warmup Issues, High Heap Memory Utilisation in our Kubernetes Cluster and how we approached the issue and our learnings from it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*_NBJdmEqyFTb4Mg8Y_f80A.png" /><figcaption>High response time whenever a new pod was scheduled</figcaption></figure><p>Initially when it was not clear that it was a JVM Warmup related issue the easiest way to solve this was increasing the pods to around 3 times our required number in steady state. This definitely solved our issue but resulted in high infra cost. On digging deeper in the problem we found out that there are other ways to solve the same issue as well.</p><p>JVM needs more CPU, in our case it was ~3x than the configured limit x during the initial warm-up phase which lasts a few minutes. After the warm-up, JVM can run at its full potential comfortably even with a x CPU . If the required CPU is not available, the pod CPU gets throttled to the available resources and that causes the entire issue.</p><p>There is an easy way to verify the same. Kubernetes exposes a per-pod metric container_cpu_cfs_throttled_seconds_total which denotes — how many seconds CPU has been throttled for this pod since its start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*SvWDXOMPEq6MeSYGhe3guw.png" /><figcaption>CPU Throttling</figcaption></figure><p>Because of the same throttling , Warmup takes time and until then the latency increases which results in request queuing and which therefore causes high thread states in waiting state.</p><blockquote><strong>Kubernetes schedules pods using “requests”, not the “limits”.</strong></blockquote><p>This was one very important piece of information we came across while debugging the issue.</p><p>Kubernetes assigns <a href="https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod/">QoS classes</a> to pods based on the configured resource requests and limits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*N8s4gjrfKIP6HUyV.jpg" /><figcaption>QoS Class in Kubernetes</figcaption></figure><p>The answer to our problem seemed pretty clear after getting this insight regarding QoS classes: Kubernetes Burstable QoS</p><p>Since Kubernetes uses the values specified in requests to schedule the pods, it’ll find nodes with x spare CPU capacity to schedule this pod. But since the limit is much higher at 3x , if the application needs more CPU than x at any time and if spare CPU capacity is available on that node, the application will not be throttled on CPU. It can use up to 3x if available.</p><p>This fits nicely with our problem statement. During the warm-up phase when JVM needs more CPU, it can get it by bursting. Once the JVM is optimised, it can go on at full speed within the request . This allows us to use the spare capacity in our cluster (we’ll still face the issue if we don’t have spare capacity, but 8/10 times we tend to have that extra capacity which is required for limits) to solve the warm-up problem without any additional cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*HePFaSSupTgy-E7txYQtQQ.png" /><figcaption>During warm-up (pod startup) CPU over 100% of requests by bursting</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*3d9cESyU_Ax2D9_00zl0gA.png" /><figcaption>Response Time during deployment with the new Configuration</figcaption></figure><h3><strong>After reducing the CPU resources it was time to look into the high memory usage of our system</strong></h3><p>While we were optimising our costs, we figured out there were very high memory resources allocated for our services because the heap size would keep on increasing and if the resources were not high the Pod would be in CrashLoop if the memory requirement is not met.</p><p><strong>Ineffective Garbage Collection </strong>was figured out as the main reason for the high heap size in our service, as the heap memory used to gradually keep on increasing until the major GC which Resulted in High Memory usage and eventually needed to provide high resources to keep service stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TiBxCbPn4Japu4OM" /><figcaption><strong>Heap Memory</strong>: Earlier vs Post Introducing G1GC</figcaption></figure><p><strong>Garbage Collection:</strong> Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To deallocate unused memory, Garbage collector track all the objects that are still in use and it marks the rest of the object as garbage. Basically garbage collector use <strong>Mark and Sweep algorithm</strong> to clear unused memory. These are the following types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*0vknejJsyGkMvC-P.jpg" /></figure><h4>1. Serial Garbage Collector</h4><p>Serial garbage collector works by holding all the application threads. It is designed for the single-threaded environments. It uses just a single thread for garbage collection. The way it works by freezing all the application threads while doing garbage collection may not be suitable for a server environment. It is best suited for simple command-line programs.</p><p>Turn on the -XX:+UseSerialGC JVM argument to use the serial garbage collector.</p><h4>2. Parallel Garbage Collector</h4><p>Parallel garbage collector is also called as throughput collector. It is the default garbage collector of the JVM. Unlike serial garbage collector, this uses multiple threads for garbage collection. Similar to serial garbage collector this also freezes all the application threads while performing garbage collection.</p><h4>3. CMS Garbage Collector</h4><p>Concurrent Mark Sweep (CMS) garbage collector uses multiple threads to scan the heap memory to mark instances for eviction and then sweep the marked instances. CMS garbage collector holds all the application threads in the following two scenarios only,</p><ol><li>while marking the referenced objects in the tenured generation space.</li><li>if there is a change in heap memory in parallel while doing the garbage collection.</li></ol><p>In comparison with parallel garbage collector, CMS collector uses more CPU to ensure better application throughput. If we can allocate more CPU for better performance then CMS garbage collector is the preferred choice over the parallel collector.</p><p>Turn on the XX:+USeParNewGC JVM argument to use the CMS garbage collector.</p><h4>4. G1 Garbage Collector</h4><p>G1 garbage collector is used for large heap memory areas. It separates the heap memory into regions and does collection within them in parallel. G1 also does compacts the free heap space on the go just after reclaiming the memory. But CMS garbage collector compacts the memory on stop the world (STW) situations. G1 collector prioritises the region based on most garbage first.</p><p>Turn on the –XX:+UseG1GC JVM argument to use the G1 garbage collector.</p><blockquote><strong>We switched from Java 8 default GC (Parallel GC) to G1 GC which is meant to tackle high Heap sizes effectively. Resulted in overall constant Heap Size and therefore we could reduce the memory resources and keep the same stability in our services, and the results were amazing</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*s-KjbBezrVjPPme3" /><figcaption>Overall memory utilisation got stabilised</figcaption></figure><p>This helped us reduce the cost of our infra by over 50% and now we’re much more stable than before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xe8kmQxOkD0T70zx" /><figcaption>Snapshot of the Reduced Infra Cost</figcaption></figure><h4><strong>Key Learnings</strong></h4><ul><li>We can still face CPU throttling if the node does not have the required limits as specified by us, since pods are scheduled basis the requests and not limits</li><li>We should not be banking too much on the limits for steady state but keep our requests sufficiently high to cater the steady state requirements of the application</li><li>While using G1 GC we should also try using String Deduplication as most web app heavily uses Strings so i think the advantage will be pretty evident. String Deduplication is a Java feature that helps you to save memory occupied by duplicate String objects in Java applications. To use it we need to add this in our JAVA_OPTS : <strong><em>- XX:+UseStringDeduplication</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0c97748c43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka : A New Age Messaging System]]></title>
            <link>https://medium.com/@anurag2397/kafka-a-new-age-messaging-system-1606c0e58a83?source=rss-8dcd30ab7797------2</link>
            <guid isPermaLink="false">https://medium.com/p/1606c0e58a83</guid>
            <dc:creator><![CDATA[Anurag Prakash]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 08:39:47 GMT</pubDate>
            <atom:updated>2020-06-29T08:06:19.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka : A New Age Messaging System</h3><blockquote>Apache Kafka’s popularity is exploding. Learn about what it is, and why it’s becoming a solution of big data and microservices applications</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGcXHCbIw0MAiTEZeTicgg.jpeg" /></figure><p>Kafka is a Publish/Subscribe messaging system. It allows <strong>producers</strong> to write <strong><em>records</em></strong> into Kafka that can be read by one or more <strong>consumers</strong>. These records that cannot be deleted or modify once they are sent to Kafka (this is known as “distributed commit log”).</p><p>Records are published into <strong>topics</strong>. Topics are like channels where all the records are stored. Consumers subscribe to one or more topics to read its records.</p><p>Kafka has a retention period, so it will store your records for the time or size you specify and can be set by topic.</p><p>Consumers label themselves with a <strong>consumer group </strong>name. In a consumer group, one or more consumers work together to consume a topic. When a new record arrives to the topic, it will be sent just to one consumer instance in the consumer group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QqLTumYuNrpmNoZr1QoEA.png" /></figure><blockquote><strong>Spring-Boot and Kafka : Not just another Love Story </strong>❤️</blockquote><p>We all know spring boot is an excellent framework where we can write <strong>web application</strong>, <strong>scheduler,command line runner etc. </strong>Most of the java based application are written in spring boot these days for simplicity and its features also readily available components that we can directly include in its dependency. Also when our applications are moving towards cloud and we are in the Data monetization era where we collect lots of data and convert its insights for planning, so traditionally we used to use publisher subscriber pattern in short pub-sub to distribute our process and nowadays we need more powerful tools and we have to distribute our process in higher magnitude, so lot of parallel processing tools emerged, and one such tool is <strong>Kafka</strong></p><blockquote><strong>&lt; Let’s start implementing it on our Systems /&gt;</strong></blockquote><h4><strong>Adding Maven Dependency</strong></h4><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-kafka&lt;/artifactId&gt;<br>   &lt;version&gt;2.1.0.RELEASE&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Working on Kafka Producer in Spring Boot</strong></h4><p>So to produce the message to Kafka we shall do it in two parts one is configuring properties and another one to publish messages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2baa168a8c64a4e787e26e5401322dae/href">https://medium.com/media/2baa168a8c64a4e787e26e5401322dae/href</a></iframe><p>In the above code we create producer factory bean method which sets basic properties of Kaka server, and the template bean is created to access the methods available from library. so in the next step we shall write the method to produce messages</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cfdbbd3ca0c531bd5acd1d4d904901a/href">https://medium.com/media/4cfdbbd3ca0c531bd5acd1d4d904901a/href</a></iframe><p>A simple code implementation of a producer</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18f018e866295197d6b4d353735fc0c2/href">https://medium.com/media/18f018e866295197d6b4d353735fc0c2/href</a></iframe><p><strong>Let us now consume messages in our Spring Boot Application</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8d4d785b28d4ed23f1c98a3560c39b4/href">https://medium.com/media/a8d4d785b28d4ed23f1c98a3560c39b4/href</a></iframe><blockquote>And then we can write the method in our main or any component class to receive message form and topic as show in the example below</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5675507d73982418dfce966caf509322/href">https://medium.com/media/5675507d73982418dfce966caf509322/href</a></iframe><blockquote>That is how simple it is to implement this one hell of a tool that makes our development lives a lot easier</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iRbyIMCYJFmCkU2vL-OVg.png" /><figcaption>Apache Kafka® is a distributed streaming platform</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1606c0e58a83" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>