<?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 N S N Murthy Kancharla on Medium]]></title>
        <description><![CDATA[Stories by N S N Murthy Kancharla on Medium]]></description>
        <link>https://medium.com/@nsnmurthyk?source=rss-21f258918085------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YBYsQKUF3Kqil7jA</url>
            <title>Stories by N S N Murthy Kancharla on Medium</title>
            <link>https://medium.com/@nsnmurthyk?source=rss-21f258918085------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:50:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nsnmurthyk/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[How We Fixed Kafka Log Cleaner Corruption After a Failover/Restarts — A Step-by-Step Guide]]></title>
            <link>https://medium.com/@nsnmurthyk/how-we-fixed-kafka-log-cleaner-corruption-after-a-failover-restarts-a-step-by-step-guide-679495f5ea80?source=rss-21f258918085------2</link>
            <guid isPermaLink="false">https://medium.com/p/679495f5ea80</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[disaster-recovery]]></category>
            <category><![CDATA[kafka-internal]]></category>
            <dc:creator><![CDATA[N S N Murthy Kancharla]]></dc:creator>
            <pubDate>Thu, 18 Jun 2026 03:35:57 GMT</pubDate>
            <atom:updated>2026-06-18T03:35:57.426Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>After a failover/restarts, our Kafka log cleaner silently stalled on </em><em>__consumer_offsets, disk kept growing, and we had no alerts. Here&#39;s exactly what happened, how we diagnosed it, and how to fix and prevent it.</em></blockquote><h3>The Incident</h3><p>It started quietly. Our on-call engineer noticed disk utilization creeping up on Kafka brokers slowly at first, then alarmingly fast. No obvious spike in traffic. No new topics. No schema changes.</p><p>Then, buried in the broker logs, we found this:</p><pre>[XXXX-XX-XX] WARN [kafka-log-cleaner-thread-2]: <br>Unexpected exception thrown when cleaning log <br>Log(dir=/bitnami/kafka/data/__consumer_offsets-2, ...). <br>Marking its partition (__consumer_offsets-2) as uncleanable<br>....<br>....<br>kafka.log.LogCleaningException: Invalid record size: <br>expected to read 145 bytes in record payload, but instead read 121<br>    at kafka.log.LogCleaner$CleanerThread.cleanFilthiestLog(LogCleaner.scala:420)</pre><p>One line. One partition. Kafka silently marked it <strong>uncleanable</strong> and moved on and disk kept growing from that day forward.</p><p>Tracing back, the corruption had been introduced two months earlier. That single event had set off a chain reaction that nobody noticed until the disks were screaming.</p><h3>Why Failovers/Abrupt restarts Break Kafka Log Segments</h3><p>To understand the corruption, you need to understand how Kafka writes data to disk.</p><p>Kafka does <strong>not</strong> flush every record synchronously to disk. It writes to the OS page cache first and flushes periodically. When a broker shuts down <em>gracefully</em>, it creates a .kafka_cleanShutdown marker file and the OS flushes its page cache in an orderly way.</p><p>During a failovers/Abrupt restarts, this process is often skipped/failed. The broker may be killed abruptly (SIGKILL, OOM, or power cut), or a replica gets promoted before it has fully caught up with the leader.</p><p>Here’s what that looks like:</p><pre>Failover/Restarts Triggered<br>        │<br>        ▼<br>Broker receives SIGKILL (or power cut)<br>        │<br>        ├──► OS page cache NOT fully flushed<br>        │           │<br>        │           └──► Log segment partially written to disk<br>        │                   Record header says: 145 bytes<br>        │                   Actual bytes on disk: 121  ← CORRUPTION<br>        │<br>        ▼<br>Broker restarts / Replica promoted (possibly unclean leader election)<br>        │<br>        ▼<br>Log Cleaner thread reads __consumer_offsets-2<br>        │<br>        ▼<br>Hits corrupt record → LogCleaningException thrown<br>        │<br>        ▼<br>Partition marked UNCLEANABLE — compaction permanently stalled<br>        │<br>        ▼<br>__consumer_offsets accumulates old records → Disk grows continuously</pre><p>The three most common triggers for this corruption are:</p><blockquote>Unclean leader election — Out-of-sync replica promoted; log diverges from committed state</blockquote><blockquote>Abrupt broker kill — OS page cache not flushed; partial records written to segment</blockquote><blockquote>Replication lag at failover — Follower promoted before fully catching up; tail bytes missing</blockquote><h3>Understanding the Exception</h3><pre>LogCleaningException: Invalid record size: <br>  expected to read 145 bytes in record payload, but instead read 121</pre><p>Kafka’s log cleaner reads record headers to know how many bytes to read next. In a healthy segment, the header and payload always agree. When a broker crashes mid-write, the header gets written (145 bytes) but the payload is truncated (121 bytes). The cleaner sees the mismatch, throws an exception, and <strong>permanently marks the partition uncleanable</strong>.</p><p>This is not a bug, it is Kafka protecting itself from reading garbage data. The problem is that the silence around it can let disk usage balloon undetected for weeks.</p><h3>Step 1: Confirm the Corruption</h3><p>First, identify exactly which segment file is corrupt. Run kafka-dump-log.sh against the partition directory:</p><pre>kafka-dump-log.sh \<br>  --files /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.log \<br>  --print-data-log 2&gt;&amp;1 | tail -50</pre><p>Look for output like this:</p><pre>Dumping /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.log<br>Starting offset: 150000000<br>baseOffset: 150000100 ...  (last valid record)<br>*** INVALID RECORD SIZE: expected 145, got 121 at offset 150000101 ***</pre><p>Note down:</p><ul><li>The <strong>exact segment filename</strong> (e.g., 00000000000150000000.log)</li><li>The <strong>last valid offset</strong> before the corruption</li><li>The <strong>last valid byte position</strong> (you’ll need this for truncation)</li></ul><h3>Step 2: Identify All Files in That Segment</h3><p>Every Kafka log segment is a <strong>triplet</strong> of files. You must handle all three together:</p><pre>ls -lh /bitnami/kafka/data/__consumer_offsets-2/</pre><pre># You&#39;ll see:<br># 00000000000150000000.log       ← message data<br># 00000000000150000000.index     ← offset index<br># 00000000000150000000.timeindex ← timestamp index<br># 00000000000150000000.snapshot  ← (may exist for compacted topics)</pre><h3>Step 3: Determine If It’s an Old Segment or the Active One</h3><p>This changes your remediation approach:</p><pre># The LAST file alphabetically is the active (currently-writing) segment<br>ls -lt /bitnami/kafka/data/__consumer_offsets-2/*.log</pre><ul><li><strong>Old segment</strong> → safer to delete outright</li><li><strong>Active segment</strong> (latest .log) → requires truncation at a safe byte offset</li></ul><h3>Step 4: Back Up Before Touching Anything</h3><p>Non-negotiable. Always back up first:</p><pre>cp -rp /bitnami/kafka/data/__consumer_offsets-2/ \<br>       /bitnami/kafka/backup/__consumer_offsets-2-$(date +%Y%m%d_%H%M%S)/</pre><pre>ls -lh /bitnami/kafka/backup/__consumer_offsets-2-*/</pre><h3>Step 5a: Fix — Old or Middle Segment (Delete Approach)</h3><pre># 1. Stop the broker — MANDATORY before touching segment files<br>kafka-server-stop.sh<br>sleep 30<br><br># 2. Delete all 3 (or 4) files of the corrupt segment<br>rm /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.log<br>rm /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.index<br>rm /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.timeindex<br>rm -f /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.snapshot<br><br># 3. Delete the replication checkpoint so Kafka re-fetches from leader/replicas<br>rm /bitnami/kafka/data/__consumer_offsets-2/leader-epoch-checkpoint<br><br># 4. Restart - Kafka will re-replicate the missing segment from healthy replicas<br>kafka-server-start.sh -daemon /opt/bitnami/kafka/config/server.properties</pre><h3>Step 5b: Fix — Active Segment (Truncation Approach)</h3><p>When the corrupt record is in the segment that the broker is currently writing to, deleting the entire file would lose data that was successfully written before the corruption point. Instead, truncate at the last valid byte position:</p><pre># 1. Find the last valid byte position<br>kafka-dump-log.sh \<br>  --files /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.log \<br>  --print-data-log 2&gt;&amp;1 | grep &quot;position:&quot; | tail -5<br># Note the last valid position value, e.g. position: 10485200<br><br># 2. Stop the broker<br>kafka-server-stop.sh<br>sleep 30<br><br># 3. Truncate the .log file at that byte position<br>truncate -s 10485200 \<br>  /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.log<br><br># 4. Delete index files - Kafka rebuilds them automatically on startup<br>rm /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.index<br>rm /bitnami/kafka/data/__consumer_offsets-2/00000000000150000000.timeindex<br><br># 5. Restart broker<br>kafka-server-start.sh -daemon /opt/bitnami/kafka/config/server.properties</pre><h3>Step 6: Verify Recovery</h3><p>After restart, confirm everything came back healthy:</p><pre># 1. Watch broker logs for recovery<br>tail -100f /opt/bitnami/kafka/logs/server.log | grep -i &quot;consumer_offsets-2&quot;<br># Good signs: &quot;Recovering unflushed segment&quot;, &quot;Loading log&quot;<br># Bad signs: &quot;ERROR&quot;, &quot;corrupt&quot;<br><br># 2. Verify partition is back in ISR<br>kafka-topics.sh --describe \<br>  --topic __consumer_offsets \<br>  --bootstrap-server localhost:9092 | grep &quot;Partition: 2&quot;<br># Isr: should list this broker&#39;s ID<br><br># 3. Confirm log cleaner resumed<br>grep &quot;kafka-log-cleaner&quot; /opt/bitnami/kafka/logs/server.log | tail -20<br># Should see: &quot;Beginning cleaning of __consumer_offsets-2&quot;<br># Should NOT see: &quot;Marking its partition as uncleanable&quot;</pre><h3>Step 7: Force Log Cleaner to Resume (If Still Stalled)</h3><p>If the cleaner is still stuck after restart:</p><pre># Trigger a config touch to wake the cleaner<br>kafka-configs.sh \<br>  --bootstrap-server localhost:9092 \<br>  --alter \<br>  --topic __consumer_offsets \<br>  --add-config cleanup.policy=compact</pre><h3>Decision Flowchart</h3><pre>kafka-dump-log.sh shows corrupt offset<br>              │<br>              ▼<br>     Take backup (always)<br>              │<br>              ▼<br>    Is corrupt segment the<br>      latest (active) one?<br>       /              \<br>     YES               NO<br>      │                 │<br>  Truncate .log      Delete all 3<br>  at last valid      segment files<br>  byte position      (.log + .index<br>  Delete indexes     + .timeindex)<br>       \              /<br>        ▼            ▼<br>      Stop broker → Delete leader-epoch-checkpoint<br>                  → Start broker<br>                  → Verify ISR recovery<br>                  → Confirm cleaner resumes</pre><h3>How to Prevent This in Future</h3><h3>1. Graceful Shutdown Before Failover</h3><p>The most important prevention step. Add this to your runbook:</p><pre># server.properties<br>controlled.shutdown.enable=true<br>controlled.shutdown.max.retries=3<br>controlled.shutdown.retry.backoff.ms=5000</pre><p>Always stop brokers with kafka-server-stop.sh (SIGTERM), never SIGKILL, before cutting over.</p><h3>2. Disable Unclean Leader Election</h3><pre># server.properties<br>unclean.leader.election.enable=false   # Default in Kafka 3.x — verify yours</pre><p>This prevents out-of-sync replicas from being promoted as leaders, which is the primary source of log divergence during failovers.</p><h3>3. Ensure Strong Replication for Critical Topics</h3><pre>offsets.topic.replication.factor=3<br>min.insync.replicas=2</pre><p>With RF=3 and min ISR=2, even if one broker crashes mid-write, two other replicas have clean copies that can take over.</p><h3>4. Add Monitoring and Alerts</h3><p>The single biggest lesson from this incident: <strong>we had no alert on uncleanable partitions</strong>. Add these:</p><pre># Metrics to monitor (via JMX / Prometheus)<br>- kafka.log:type=LogCleanerManager,name=uncleanable-partitions   &gt; 0   → CRITICAL<br>- kafka.log:type=LogCleanerManager,name=uncleanable-bytes        &gt; 0   → WARNING<br>- Disk usage per broker                                          &gt; 75% → WARNING</pre><h3>5. Add Post Validation to Your Runbook</h3><p>After every failover event, before declaring success, run these checks:</p><pre># 1. Check for under-replicated partitions<br>kafka-topics.sh --describe --under-replicated-partitions \<br>  --bootstrap-server &lt;broker&gt;<br><br># 2. Verify log segment integrity on promoted broker<br>kafka-dump-log.sh \<br>  --files /bitnami/kafka/data/__consumer_offsets-*/*.log \<br>  --verify-index-only<br><br># 3. Check JMX metric for uncleanable partitions<br># kafka.log:type=LogCleanerManager,name=uncleanable-partitions<br># Value must be 0 before marking failover complete</pre><h3>Key Takeaways</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MBj80uW0WMxhvxwhOC37w.png" /></figure><p>Kafka is remarkably resilient, but it makes one quiet assumption: that brokers are allowed to shut down cleanly. When failover/restart violates that assumption, the log cleaner one of Kafka’s most important background processes, can stall silently while your disks fill up.</p><p>The fix is surgical once you know where to look. The prevention is procedural: graceful shutdowns, strong replication, meaningful monitoring, and a runbook that treats Kafka as a first-class citizen.</p><p>If this saved you a few hours of debugging, consider adding post validation steps to your runbook today before the next failover finds another quiet partition slowly filling your disk.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679495f5ea80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Generational ZGC Saved Our Kafka Consumer From Silent Stalls]]></title>
            <link>https://medium.com/@nsnmurthyk/how-generational-zgc-saved-our-kafka-consumer-from-silent-stalls-621bb5a7e316?source=rss-21f258918085------2</link>
            <guid isPermaLink="false">https://medium.com/p/621bb5a7e316</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jfr]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[zgc]]></category>
            <dc:creator><![CDATA[N S N Murthy Kancharla]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 10:50:02 GMT</pubDate>
            <atom:updated>2026-03-24T10:50:02.182Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Real-World Case Study on ZGC Allocation Stalls Causing Kafka Consumer Lag</h3><p>If your Java application uses ZGC and you’re seeing unexplained Kafka consumer lag without any rebalance or traffic spike — keep reading. We recently diagnosed and resolved a subtle but impactful production issue where <strong>ZGC Allocation Stalls</strong> were silently degrading our application’s throughput, causing Kafka consumer group lag to climb with no obvious cause.</p><h3>The Symptom: Growing Consumer Lag With No Obvious Cause</h3><p>We operate a Java-based microservice that consumes from Kafka. During routine monitoring, we noticed something concerning:</p><ul><li><strong>Kafka consumer group lag was steadily increasing.</strong></li><li><strong>No consumer rebalances</strong> were observed in the logs.</li><li><strong>No spike in inbound message rate</strong> — the producers were steady.</li><li><strong>No application errors or exceptions</strong> in the logs.</li></ul><p>The classic suspects — rebalances, increased traffic, network issues, slow downstream dependencies — were all ruled out. The consumers appeared healthy, yet they were falling behind.</p><p>Something was silently stealing processing time from our application threads.</p><h3>The Investigation: JFR to the Rescue</h3><p>We turned to <strong>Java Flight Recorder (JFR)</strong> for deep runtime diagnostics. What we found in the GC telemetry was the smoking gun: <strong>ZGC Allocation Stall</strong> events.</p><h3>What Is a ZGC Allocation Stall?</h3><p>ZGC is designed to keep GC pause times sub-millisecond, regardless of heap size. However, when the garbage collector <strong>cannot free memory fast enough</strong> to satisfy allocation requests from application threads, those threads are <strong>stalled</strong> — forced to wait until memory becomes available.</p><p>This is called an <strong>Allocation Stall</strong>, and it effectively turns a “pauseless” collector into a bottleneck. Unlike traditional STW (Stop-The-World) pauses, allocation stalls don’t freeze all threads simultaneously — they block individual allocating threads, making them harder to detect through conventional monitoring.</p><h3>What the JFR Data Showed (Before Fix)</h3><p>From the JFR recording of the affected pod:</p><pre>Metric                    Observation<br>─────────────────────────────────────────────────────────────<br>GC ID                     22,143 (extremely high — GC cycling rapidly)<br>GC Cause                  Allocation Stall<br>Longest Pause             ~20,819 µs (~20 ms per stall event)<br>Sum of Pauses             ~38,478 µs per cycle<br>Heap Usage                Sustained at 4–6 GiB, barely dropping after GC<br>Heap Post-GC              Hovering around ~5.6 GiB — very little reclaimed<br>Longest Pause (chart)     Frequent spikes up to 100 µs+<br>Sum of Pauses (chart)     Consistently hitting 500 µs+ per interval</pre><p>The <strong>Heap Post-GC</strong> chart was particularly alarming — it remained flat and high (~5.6 GiB), meaning ZGC was running collections but <strong>barely reclaiming any memory</strong>. The heap was essentially always near-full, and application threads were repeatedly stalling while waiting for allocations.</p><p>Over sustained periods, these stalls accumulated to <strong>over 3 seconds</strong> of blocked time, directly impacting Kafka poll/commit cycles and causing the consumer lag to grow.</p><blockquote><strong><em>Key Insight:</em></strong><em> ZGC’s “sub-millisecond pause” guarantee applies to STW pauses — not allocation stalls. If the collector can’t keep up with allocation rate, application threads pay the price.</em></blockquote><h3>The Root Cause: Non-Generational ZGC’s Collection Inefficiency</h3><p>Our original JVM flags were:</p><pre>-XX:+UseZGC<br>-XX:MaxRAMPercentage=75<br>-Dlog4j2.formatMsgNoLookups=true</pre><p>With a <strong>non-generational (single-generation) ZGC</strong>, the collector treats the entire heap uniformly. Every GC cycle must scan and process <strong>all live objects</strong>, regardless of their age. This has two consequences:</p><ol><li><strong>Longer collection cycles</strong> — scanning a multi-GiB heap filled with long-lived objects is expensive.</li><li><strong>Reduced reclamation efficiency</strong> — short-lived objects (which are the majority in most applications) are mixed with long-lived objects, making it harder for the collector to reclaim memory quickly.</li></ol><p>In our case, the service held significant long-lived state (caches, reference datasets, in-memory lookups) alongside high-throughput short-lived Kafka message processing objects. The single-generation approach meant ZGC was spending most of its effort scanning long-lived objects that wouldn’t be collected, while short-lived garbage accumulated faster than it could be freed.</p><h3>The Fix: Enabling Generational ZGC</h3><p>The solution was simple — a single JVM flag addition:</p><pre>-XX:+UseZGC<br>-XX:+ZGenerational          ← Added<br>-XX:MaxRAMPercentage=75<br>-Dlog4j2.formatMsgNoLookups=true</pre><h3>Why Generational ZGC?</h3><p>Generational ZGC (available since JDK 21) separates the heap into <strong>young</strong> and <strong>old</strong> generations, applying the <strong>weak generational hypothesis</strong> — most objects die young.</p><ul><li><strong>Young generation</strong> collections are frequent and fast, targeting short-lived objects (like Kafka message payloads, deserialized DTOs, intermediate computation results).</li><li><strong>Old generation</strong> collections are less frequent, only processing the smaller set of objects that survived multiple young collections.</li></ul><p>This separation means:</p><ul><li><strong>Less work per collection cycle</strong> → faster reclamation</li><li><strong>Allocation stalls become rare</strong> → memory is freed before threads need to wait</li><li><strong>Heap Post-GC stabilizes at a lower level</strong> → more headroom for allocation bursts</li></ul><h3>The Results:</h3><p>After deploying with Generational ZGC enabled, the JFR recording from the updated pod told a completely different story:</p><pre>Metric                Before (Non-Generational)     After (Generational)<br>───────────────────────────────────────────────────────────────────────────<br>GC Cause              Allocation Stall               CodeCache GC (routine)<br>GC ID                 22,143                          2,463<br>Longest Pause         20,819 µs                       46 µs (~450x improvement)<br>Sum of Pauses         38,478 µs                       134 µs (~287x improvement)<br>Heap Usage            4–6 GiB (near ceiling)          2–4 GiB (healthy sawtooth)<br>Heap Post-GC          ~5.6 GiB (flat, high)           ~2–3 GiB (significantly lower)<br>Longest Pause (chart) ~100 µs spikes                  ~25 µs (4x lower)<br>Sum of Pauses (chart) ~500 µs                         ~100 µs (5x lower)<br>Allocation Stalls     Frequent, multi-second          None observed</pre><h3>The Heap Tells the Story</h3><p><strong>Before:</strong> The heap consistently sat at 4–6 GiB, with Post-GC barely dropping to ~5.6 GiB — the collector couldn’t reclaim space fast enough.</p><p><strong>After:</strong> The heap shows a <strong>healthy sawtooth pattern</strong> between 2–4 GiB, with Post-GC consistently dropping to ~2 GiB. The generational approach efficiently reclaims short-lived garbage in young-gen collections, leaving ample headroom for new allocations.</p><h3>Impact on Kafka Consumer Lag</h3><p>With allocation stalls eliminated:</p><ul><li><strong>Consumer poll loops</strong> execute without being blocked on memory allocation.</li><li><strong>Heartbeat threads</strong> maintain consistent communication with the broker — no risk of session timeouts.</li><li><strong>Commit cycles</strong> complete on time, preventing offset lag accumulation.</li><li><strong>Consumer group lag returned to near-zero</strong> and remained stable.</li><li><strong>No slowness observed from the Kafka cluster side</strong> — confirming the issue was purely JVM/GC-related, not infrastructure.</li></ul><h3>Lessons Learned</h3><h3>1. “Pauseless” Doesn’t Mean “Stall-less”</h3><p>ZGC’s sub-millisecond STW pause guarantee is real — but allocation stalls are a different mechanism entirely. They don’t show up in typical GC pause metrics. <strong>Always check for Allocation Stall events in JFR.</strong></p><h3>2. JFR Is Non-Negotiable for GC Diagnostics</h3><p>Standard GC logs showed collections happening. It was only through JFR that we identified the <em>cause</em> as Allocation Stall something other than normal GC triggers. If you&#39;re running ZGC in production, enable continuous JFR recording:</p><pre>-XX:StartFlightRecording=filename=/tmp/recording.jfr,maxsize=500m,maxage=1h,settings=profile</pre><p>If continuous recording is not enabled, you can collect a JFR snapshot on-demand from a running JVM:</p><pre># Start a recording manually (10mins)<br>jcmd &lt;pid&gt; JFR.start name=diagnosis settings=profile duration=600s filename=/tmp/diagnosis.jfr</pre><pre># Or dump from an already-running default recording<br>jcmd &lt;pid&gt; JFR.dump name=1 filename=/tmp/dump.jfr</pre><p>Either way, ensure you have JFR data available when diagnosing GC behaviour — it’s the only reliable way to surface allocation stall events.</p><h3>3. Generational ZGC Should Be Your Default (JDK 21+)</h3><p>If you’re on JDK 21 or later and using ZGC, there’s very little reason <em>not</em> to enable -XX:+ZGenerational. In JDK 23+, generational mode becomes the default. The generational approach provides:</p><ul><li>Better throughput under mixed workloads</li><li>Dramatically lower allocation stall risk</li><li>More efficient heap utilization</li></ul><h3>4. Kafka Consumers Are Especially Sensitive to GC Stalls</h3><p>Kafka consumers operate on strict timing contracts (max.poll.interval.ms, session.timeout.ms, heartbeat.interval.ms). Even brief stalls can cascade:</p><ul><li>Stall → slow poll → lag accumulates</li><li>Prolonged stall → missed heartbeat → rebalance → even more lag</li></ul><h3>5. Monitor Heap Post-GC, Not Just Heap Usage</h3><p>A flat, high <strong>Heap Post-GC</strong> line is a leading indicator of GC trouble. It means the collector is running but not reclaiming — the first step toward allocation stalls.</p><h3>6. Rule Out Memory Leaks and Consider Scaling</h3><p>If your application is under heavy or unexpected load and memory consumption remains high even after enabling Generational ZGC, don’t stop at GC tuning. Investigate whether a <strong>memory leak</strong> is the real culprit — objects being held longer than necessary (e.g., growing caches, unclosed resources, listener accumulation). Use JFR’s <strong>Old Object Sample</strong> events and heap dumps to identify retained objects.</p><p>If memory usage is genuinely proportional to load and not a leak, consider <strong>increasing the container/pod memory limits</strong> or <strong>scaling horizontally</strong> by adding more consumer instances to distribute the processing load. GC tuning can only do so much — if the working set legitimately exceeds available heap, you need more resources.</p><h3>Recommended JVM Configuration for ZGC with Kafka Consumers</h3><pre># GC Configuration<br>-XX:+UseZGC<br>-XX:+ZGenerational</pre><pre># Memory<br>-XX:MaxRAMPercentage=75</pre><pre># Observability<br>-XX:StartFlightRecording=filename=/tmp/app.jfr,maxsize=500m,maxage=1h,settings=profile<br>-Xlog:gc*:file=/var/log/gc.log:time,level,tags:filecount=5,filesize=100m</pre><pre># Security<br>-Dlog4j2.formatMsgNoLookups=true</pre><h3><strong>The Transformation: Before &amp; After</strong></h3><h3>GC Behaviour — Before (Non-Generational ZGC)</h3><p>JFR Garbage Collection view showing frequent Allocation Stall events, heap stuck at 4–6 GiB, and Post-GC hovering at ~5.6 GiB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDxt2JD3TVwd7Do_CSKNcg.png" /><figcaption>ZGC Allocation Stall Events</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*Kq2pQItqUVTlS5TvH7d3lg.png" /></figure><h3>GC Behaviour — After (Generational ZGC)</h3><p>JFR Garbage Collection view after enabling -XX:+ZGenerational — healthy sawtooth heap pattern (2–5 GiB), Post-GC at ~2 GiB, longest pause ~46 µs, zero allocation stalls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8hVW9n_ZO0xm9jwO3brLA.png" /><figcaption>ZGC Allocation Stall Events</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*_dGqNKelMD_4y2Ar2PM0HQ.png" /></figure><h3>Kafka Consumer Lag Pattern</h3><p>Kafka consumer group lag timeline — lag climbing steadily during allocation stalls (left), dropping to near-zero after the fix (right).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zU7cm3QUMv5zGgBESi1Bg.png" /><figcaption>Consumer group lag Pattern</figcaption></figure><h3>TL;DR</h3><pre>Before                        After<br>───────────────────────────────────────────────────────────────────────────<br>ZGC Mode               Non-Generational               Generational (-XX:+ZGenerational)<br>GC Cause               Allocation Stall               Routine (CodeCache GC)<br>Pause Impact           ~20 ms per stall, 3s+ cum.     ~46 µs, negligible<br>Heap Post-GC           ~5.6 GiB (flat)                ~2 GiB (healthy)<br>Kafka Consumer Lag     Growing, unexplained           Stable, near-zero<br>JVM Change             -XX:+UseZGC                    Added -XX:+ZGenerational</pre><p><strong>One flag. 450x pause improvement. Zero consumer lag.</strong></p><p>If you’re using ZGC on JDK 21+ and haven’t enabled Generational mode yet — do it today. Your Kafka consumers will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=621bb5a7e316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Technical Deep-Dive: Netty Threading & OS Realities.md]]></title>
            <link>https://medium.com/@nsnmurthyk/technical-deep-dive-netty-threading-os-realities-md-e3e34e6d080c?source=rss-21f258918085------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3e34e6d080c</guid>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[netty]]></category>
            <dc:creator><![CDATA[N S N Murthy Kancharla]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 06:27:30 GMT</pubDate>
            <atom:updated>2026-02-22T06:33:24.720Z</atom:updated>
            <content:encoded><![CDATA[<h3>Technical Deep-Dive: Netty Threading &amp; OS Realities</h3><p><strong>A Case Study on Thread Over-provisioning: Matching Threads to CPU Limits</strong></p><h4>Context: Why We Did This</h4><p>This deep dive was triggered by specific <strong>customer-reported issues</strong> where our services experienced performance degradation. Upon investigation, we identified:</p><ul><li><strong>OS Thread Spikes:</strong> Rapid increases in thread counts leading to instability and “thread exhaustion.”</li><li><strong>OOM (Out of Memory) Errors:</strong> The service was crashing due to the high memory overhead of maintaining too many thread stacks.</li><li><strong>The “High Default” Trap:</strong> We discovered the service was configured with <strong>excessive thread counts</strong> that far exceeded the available <strong>CPU limits</strong>.</li></ul><p>We made critical changes to the service configuration to stop wasting OS resources and memory. This document explains the “why” behind those changes.</p><h4>Summary</h4><ul><li><strong>Netty Framework Context:</strong> Our applications leverage Netty for high-performance networking. We observed that configuring <strong>more threads than required</strong> by the workload leads to <strong>OS thread leaks</strong> and resource exhaustion.</li><li><strong>The 1:1 Rule:</strong> Every Netty EventLoop creates one permanent, dedicated OS thread.</li><li><strong>The Over-provisioning Trap:</strong> Setting thread counts significantly higher than CPU limits causes “CPU Starvation.” Threads appear RUNNABLE but are stuck in a &quot;traffic jam&quot; waiting for a CPU slice.</li><li><strong>The Fix:</strong> Limit Boss threads to 1, size Workers based on CPU count, and scale <strong>horizontally</strong> (replicas) instead of <strong>vertically</strong> (threads).</li></ul><h4>Before vs. After: Performance Impact</h4><p>The following graph illustrates the impact of these changes. Note the uncontrolled climb in thread counts (leaks) on the left, followed by the stable, flat line after we applied the optimised configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTL6IPlqYDzsMD6LmNLUQQ.png" /></figure><h4>1. The Architecture: Netty Boss vs. Worker Pools</h4><p>Netty uses a “Parent-Child” model to separate connection handling from data processing.</p><h4>The Boss Group (The Receptionist)</h4><ul><li><strong>Default Sizing:</strong> CPU * 2</li><li><strong>Responsibility:</strong> Listens for new connections (accept()).</li><li><strong>Best Practice:</strong> <strong>Set this to 1.</strong> One receptionist can handle thousands of connections/sec. Multiple boss threads can actually cause “lock contention” at the OS level.</li></ul><h4>2. Worker Pool Sizing: The Core Strategy</h4><p>The sizing of your Worker Group must match the nature of your infrastructure interactions (gRPC, REST, Kafka, etc.).</p><h4>Scenario A: Purely Non-Blocking (Reactive)</h4><p>If your application never “pauses” the thread (e.g., using fully reactive clients):</p><ul><li><strong>Recommended Sizing: CPU * 2</strong></li><li><strong>Impact:</strong> Adding more threads here <strong>decreases</strong> performance due to context switching.</li></ul><h4>Scenario B: Infrastructure Interaction (gRPC, REST, Kafka, DB &amp; ElasticSearch etc.)</h4><p>If your code involves waiting for external infrastructure that isn’t fully reactive:</p><ul><li><strong>The Problem:</strong> The Worker thread “hangs” until the external infra responds. While it waits, it cannot process any other requests for other clients.</li><li><strong>The Calculation:</strong> <strong>Threads = CPU Cores * 8</strong></li><li><strong>The Limit:</strong> Even with blocking, <strong>do not exceed 128–150 threads</strong>. If latency persists, do not increase threads further; instead, <strong>scale horizontally</strong> with more replicas.</li></ul><h4>3. The “Stickiness” Principle</h4><ul><li><strong>Connection Marriage:</strong> Once a client connects and is assigned to a specific Worker thread, <strong>every single request</strong> from that client is handled by that same thread for the life of that connection.</li><li><strong>Why?</strong> This ensures <strong>Thread Safety</strong>. You don’t need complex locks because only one thread ever touches that specific client’s data.</li></ul><h4>4. The Impact of Excessive Threads vs. CPU Limits</h4><h4>The “Traffic Jam” (Context Switching)</h4><p>When the thread count far exceeds the number of CPU cores, the OS spends more time “swapping” threads (saving/loading states) than actually executing code.</p><h4>The Memory Tax</h4><p>Each thread reserves ~1MB for its stack.</p><ul><li><strong>Over-provisioned:</strong> ~750MB RAM consumed just for threads.</li><li><strong>Optimized:</strong> ~100MB RAM consumed.</li><li><strong>Savings:</strong> Reclaims <strong>hundreds of megabytes</strong> of RAM instantly.</li></ul><h4>5. Troubleshooting: How to Read a Thread Dump</h4><ul><li><strong>The “Runnable” Mirage:</strong> If hundreds of netty-worker threads are RUNNABLE but latency is high, it’s <strong>CPU Starvation</strong>.</li><li><strong>The “Wait” Sign:</strong> If threads are WAITING on external infra, your pool is &quot;hanging.&quot; The fix is <strong>asynchronous I/O</strong>, not more threads.</li></ul><h4>6. Advanced Monitoring</h4><p>Run this command to see if the OS is forcing your threads to stop (Involuntary Context Switching):</p><pre># Monitor context switches every second<br>top -d 1 -b | grep -i Cswch</pre><ul><li><strong>High cswch:</strong> Confirms you have <strong>too many threads</strong> for your CPU limit.</li></ul><h4>7. Scaling Best Practices Checklist</h4><ul><li><strong>Boss Count:</strong> Manually set to <strong>1</strong>.</li><li><strong>Worker Count:</strong> Align with CPU cores (<strong>CPU * 2</strong> for I/O, max <strong>CPU * 16</strong> for infra-heavy apps).</li><li><strong>Avoid “Thread-per-Request”:</strong> Don’t try to solve external latency by adding more Netty threads.</li><li><strong>Horizontal Scaling:</strong> Use more replicas to distribute connections.</li></ul><h4>Final Thought</h4><p>Netty is designed for <strong>efficiency through a few threads</strong>. By aligning our configuration with the physical reality of our CPU limits, we successfully addressed the customer-reported issues, reclaimed memory, and built a much more resilient service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3e34e6d080c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>