<?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 Viswanath Kuchibhotla on Medium]]></title>
        <description><![CDATA[Stories by Viswanath Kuchibhotla on Medium]]></description>
        <link>https://medium.com/@viswanath.k?source=rss-f3c8ccc5d5bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1EbHqjf-JJ4Gjz1a</url>
            <title>Stories by Viswanath Kuchibhotla on Medium</title>
            <link>https://medium.com/@viswanath.k?source=rss-f3c8ccc5d5bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:00:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viswanath.k/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[Memory Tuning a High Throughput Microservice]]></title>
            <link>https://blog.flipkart.tech/memory-tuning-a-high-throughput-microservice-ed57b3e60997?source=rss-f3c8ccc5d5bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed57b3e60997</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Viswanath Kuchibhotla]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 12:36:00 GMT</pubDate>
            <atom:updated>2021-06-09T12:36:00.428Z</atom:updated>
            <content:encoded><![CDATA[<p>At Flipkart, over a billion recommendations are served to users every day. These recommendations help millions of users discover products and stores and guide them on their purchase journey. A performant recommendations system is crucial for a seamless shopping experience.</p><p>After adding many features over time, we recently took up a challenge to improve the performance of the system. After exhausting a series of optimisations based on profiling the application and addressing multiple bottlenecks, we identified an opportunity to merge two services into a unified service.</p><p>As a result, Recommendations can now handle 3x more content on 20% less hardware. In this post, we share some lessons we had along the way and cover two optimisations:</p><ol><li>Identifying long living memory areas and offloading them out of JVM managed heap for GC Optimisations</li><li>Identifying and fixing a native memory leak within JVM</li></ol><h3>What service setup did we have?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B_qxgcmNv8ehovmE" /><figcaption>Service Architecture</figcaption></figure><p>Serving recommendations can be broken down into:</p><ol><li>Understanding the user’s intent</li><li>Creating a content pool that fits the intent</li><li>Ranking the pool to provide the most relevant content first</li></ol><p><strong>Service</strong> (which handles Pt. 1 above) understands user intent. It spends most of the time waiting for responses from other services, and the garbage pressure is due to short-lived objects. This service is also less sensitive to GC pause times and follows the “most objects die young” philosophy behind garbage collectors. We use Java8 with a G1GC collector on 8 GB heap space for this service.</p><p><strong>Core</strong> does most of the heavy lifting and handles Pt. 2 and 3 above. It spends most of the time ranking and the garbage pressure is because of a mix of short-lived objects during candidate creation, and long-lived objects in Machine Learning (ML) models. This service is extremely sensitive to GC pause times. Any STW (Stop The World) GC pauses adds directly to the overall latency, taking CPU time away from ranking. We use Java8 with a G1GC collector on 16 GB heap space for this service.</p><p>These two services are tightly coupled — neither of them can exist independently without the other. Merging them would retain the business functionality and reduce the resources spent on data transport and improve the hardware utilization.</p><h3>As they say, God is in the details</h3><p>After removing the service hop in code, we ran a load test to validate the performance. The peak performance was 30% lower than expected!</p><p>The sinusoidal latencies and QPS indicated a potential GC issue, where pauses happen at a constant rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TUXbB1-BbfX5-T4u" /><figcaption>Green: RPS, Red: 5xx</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xznUMoXJeKHbpKi2" /><figcaption>Yellow: p95, Green: p50</figcaption></figure><h4>Problem 1: Higher core utilization post service unification</h4><p>We used JFR (Java Flight Recorder) and JVisualVM to identify GC issues. The results showed acceptable GC allocations and pause times, but we identified a significant increase in the overall CPU usage. There was also a 3x increase in the Load Average compared against the baseline performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*shEtUq9vQ275rScU" /><figcaption>G1 GC Young Collection Time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MZtjHg-zWNGJC0H6" /><figcaption>CPU Usage and GC Activity</figcaption></figure><p>How did we solve it?</p><p>While the telemetry tools reported normal GC CPU usage and pause times, the logs showed a significant increase in the concurrent time of the collector. When we analysed the CPU usage data via thread dump, we found that the top threads of the application were GC threads</p><p><strong>Let’s look at how the heap is used in the system:</strong></p><p>Recommendations is a personalisation problem domain, and we rely on many sophisticated ML models to determine what a user might find relevant. These models have millions of features pivoted on Demand, Supply and User Context. Including the experimental weblab models, at any point in time, 10+ models are active in the process memory.</p><p>Online Ranking is an expensive affair which requires feature transformations, lookups and scoring. Given that these operations are time sensitive, all the models are loaded in the JVM heap as a HashMap. These models contribute 100s of millions of long-lived objects that live through the life of the application and might occupy up to 60% of the heap.</p><p>Generational Garbage Collectors assume that most objects die young. By default, G1GC starts the initial mark phase (which starts marking all the live objects) when 45% of the heap is occupied. As the application’s heap is always occupied with many live objects, and new allocations happen constantly for the incoming requests, the garbage collector has to spend significant CPU time in the concurrent marking phase to identify the garbage in time, and meet the pause time goals. This resulted in a high CPU and frequent pauses that reduced the performance of the application threads and increased the utilization.</p><h4>How did we tame the increased utilization?</h4><p>Once the root cause for increased core usage was identified, we had the following choices:</p><p>1) Move the models out of the Heap so the G1GC has an environment for which it is designed for, OR</p><p>2) Tweak the GC settings to workaround this issue.</p><p>We went with the former as it enables us to load more models in future and not be limited by the heap memory.</p><p>Using <em>off-heap memory</em> for long-lived objects is not a new idea. It’s the fundamental implementation in many data systems like Hazelcast, Apache Flink and Druid, but to the best of our knowledge, they are rarely used alongside business logic in application systems.</p><p>Memory management in Java is split into three parts:</p><ol><li>Heap Memory (Managed by Garbage Collector) : Heap memory used by the application where all the objects are allocated.</li><li>Reserved Off Heap Memory by JVM Runtime (Not managed by GC) : Off heap memory used and managed by the Java Runtime (metaspace, symbol cache), and not given access to the application code.</li><li>Reserved Off Heap memory (Not managed by GC) : Off heap memory that we explore as an option, and used by big data systems, is the native system memory allocated and managed the “unsafe” way. It is reserved under the same Java process, but outside of the garbage collector’s domain.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*YEfbS6HxJZsgLHdc" /></figure><p>When objects are allocated on heap, Java understands that it’s a string, or an integer, or an object of a particular class. When objects are allocated out of the heap, they are stored and retrieved as a series of bytes, just as if they are fetched over a network. This involves an additional serialization and deserialization step for every update or retrieval of the data so that it can be translated to an object that can be used by the application.</p><p>For a high throughput user path service such as ours, we had two concerns in using off heap memory — CPU time in retrieving all the records and time spent in deserializing it.</p><p>We explored the performance impact of different options through JMH (Java Microbenchmark Harness).</p><p>Baseline was the HashMap implementation (loopGets).</p><p>Option 1 was using <em>Chronicle Maps</em> by OpenHFT (loopGetsChronicle)</p><p>Option 2 was a custom implementation using ByteBuffer using FST (loopGetsCustomBHM) which claims to be the fastest Java object serialization framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OoKQng-E7sGPiPiDtpqjQ.png" /><figcaption><em>One operation (op) is a 10,000 (N) sequential gets from the map. Throughput (thrpt) indicates the number of parallel ops that can be done every ms, and average time (avgt) is the time taken for each op in ms</em></figcaption></figure><p>From this benchmark, <em>Chronicle Maps</em> was the best performing Off Heap Implementation available off the shelf. However, there was a performance hit by moving from in-heap maps to any of the off heap maps. Average time to fetch the features increased from 7 ms to 21 ms and parallel calls that were handled reduced from 2 to 0.66 (at the same CPU usage).</p><p>While the performance of Chronicle Maps was worse than a HashMap in the micro-benchmark:</p><ol><li>The additional CPU usage would be offset by the reduced GC CPU</li><li>The latency numbers are under the acceptable threshold. We could also place an in-heap HashMap for a few of the features that have a high hit rate — further reducing the overall latency.</li></ol><p>We employed Chronicle Maps and migrated all the models to Off Heap memory. From the initial analysis, this resulted in approximately 150 million long lived objects that are no longer part of the GC consideration set. This had a direct impact on the time spent in the concurrent marking phase, and subsequently on the CPU usage. The top CPU consumers of the application are no longer GC threads after this change.</p><p>Comparing the detailed GC metrics through the logs for the same uptime:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*e5ypbXDiyx3kDtOWkxdxhw.png" /><figcaption>GC Metrics Before and After</figcaption></figure><p>While there is a 25% reduction in the pause time, <strong>there is a whopping 98% reduction in the concurrent time!</strong></p><p>It was now time for a real world validation with a scale test:</p><p>Throughput — Before and After</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2F3OYb4qU1jcbE0M" /><figcaption>Before. Green: RPS. Red: 5xx</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AxoFI8BN0rlC03qO" /><figcaption>After. Green: RPS. Red: 5xx</figcaption></figure><p>Latency — Before and After</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h-42RUbIcYOY3Oa5" /><figcaption>Before. Yellow: p95, Green: p50</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NIVZHdQ0JTya7nLR" /><figcaption>After. Yellow: p95, Green: p50</figcaption></figure><p>Overall, the throughput increased by approximately 40% and latency deviation fell from 300ms to 10ms.</p><h4>Is it the end of all our woes?</h4><p>No.</p><p>Though we could run the combined services as a single process with better throughput and lower latency, during the soak test for these changes, we noticed that all the application servers crashed unexpectedly after a few days of uptime. The log messages before the crash on each of the servers were almost identical, but also equally cryptic. They all crashed while trying to spawn a new thread:</p><pre>libgomp: Thread creation failed: Resource temporarily unavailable</pre><pre>libgomp: Thread creation failed: Resource temporarily unavailable</pre><pre>*** Error in `/usr/lib/jvm/jdk-8-oracle-x64/jre/bin/java’: free(): corrupted unsorted chunks: 0x00007fefe71bd750 ***</pre><h4>Problem 2: Leak in Native Memory</h4><p><em>libgomp</em> is a native library used in JNI calls for ranking. Given the error message, our first suspicion was a thread limit placed on our process group by <em>cgroup</em>. In the past, we had occurrences of our service breaching the cgroup limit, and immediately being killed by the OS.</p><p>Although this time, the kernel logs for cgroup limit breach were missing, indicating it wasn’t the reason for the crash. We identified the source of the issue from the system metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dXpgcGFrkHYypl-x" /></figure><p>We ran out of the memory on the host, and new threads could not be spawned. However, there were no ‘Out Of Memory’ messages in the process which indicated that a memory leak was happening outside of the application code, and we looked for anything that might allocate memory outside of heap (sockets, metaspace, etc).</p><p>We used NMT (Native Memory Tracking), to understand the native memory usage in java.</p><p>It gave us visibility into the application’s off-heap native memory usage at a more granular level by giving individual memory footprints of Heap, Class, Thread, Code, Compiler, Symbol etc parts of the Java Runtime.</p><p>We noted the baseline memory usage of each of the above modules on server start and recorded periodic updates on the memory added to each of these modules. Here, the <em>Symbol</em> module’s memory kept growing at the same rate, and the rate had a direct correlation with the QPS received on the host. The rate was lower during off hours, and higher during peak hours.</p><p><em>Symbols</em> are where <em>interned strings</em> are stored in Java, and given that we don’t use interned strings in our application code, and Garbage Collector clears them, it was odd to see consistently increasing memory usage. Turns out, the <a href="https://bugs.openjdk.java.net/browse/JDK-8180048">JVM version we were using had a bug</a> related to how G1GC clears strings, and because of this, strings leaked from the managed memory to the native memory over time, and eventually consumed the entire host’s memory.</p><p>Luckily, this was already fixed in an available JVM version, and the issue was resolved once we updated the version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YLj1VmTGXC9DwbyO" /><figcaption>Memory Usage of two hosts receiving similar traffic</figcaption></figure><p>The yellow line is the host with the updated Java version, and the green line is the host with the Control Java version.</p><h3>Conclusion</h3><ul><li>In our findings, if a user path system suffers from a performance issue, it’s almost always related to the Garbage Collector. It’s important to understand the nuances of GC, and to build applications that work within those bounds.</li><li>Off Heap Data Structures should be explored when holding a lot of long-lived objects in heap (long-lived caches etc).</li><li>Java has unparalleled support for tooling and telemetry, and it’s useful to know what is available so the right one can be picked to debug.</li><li>Eliminate issues in the most probable order — starting with application code, to libraries, but don’t eliminate JVM / OS issues by default.</li><li>Always keep JVM updated to the latest minor version.</li></ul><h3>Appendix:</h3><ul><li><a href="https://github.com/OpenHFT/Chronicle-Map">Chronicle-Map: Replicate your Key Value Store across your network, with consistency, persistence and performance.</a></li><li><a href="https://github.com/RuedigerMoeller/fast-serialization">FST: fast java serialization drop in-replacement</a></li><li><a href="https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr007.html">Native Memory Tracking</a></li><li><a href="https://flink.apache.org/news/2015/05/11/Juggling-with-Bits-and-Bytes.html">Apache Flink: Juggling with Bits and Bytes</a></li><li><a href="https://hazelcast.com/blog/introduction-hazelcast-hd-memory/">Introduction to Hazelcast HD Memory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed57b3e60997" width="1" height="1" alt=""><hr><p><a href="https://blog.flipkart.tech/memory-tuning-a-high-throughput-microservice-ed57b3e60997">Memory Tuning a High Throughput Microservice</a> was originally published in <a href="https://blog.flipkart.tech/">Flipkart Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>