<?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 Konstantin on Medium]]></title>
        <description><![CDATA[Stories by Konstantin on Medium]]></description>
        <link>https://medium.com/@senko.kostya?source=rss-ee0cb46867d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8gLBMYL4wK77DEygHZ0FsA.jpeg</url>
            <title>Stories by Konstantin on Medium</title>
            <link>https://medium.com/@senko.kostya?source=rss-ee0cb46867d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:45:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@senko.kostya/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 Java operates the memory]]></title>
            <link>https://medium.com/@senko.kostya/how-java-operates-the-memory-ee99676bcf39?source=rss-ee0cb46867d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee99676bcf39</guid>
            <dc:creator><![CDATA[Konstantin]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 16:07:20 GMT</pubDate>
            <atom:updated>2026-02-26T16:07:20.640Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple question: how is memory operated in Java? The usual answer is heap and stack. And that answer is incomplete.</p><p>The JVM is a native process written in C or C++. The operating system allocates memory to this process. That entire address space is JVM native memory. Inside it, the JVM organizes multiple regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*KkiBtbUC-NHTtjMUKlfMYA.png" /></figure><p><strong>C-Heap (Native Heap of the JVM)</strong></p><p>Since the JVM is implemented in C or C++, it uses its own native allocator. This area is often referred to as the C-heap. It is part of JVM native memory and is used for internal runtime structures.</p><p>The C-heap stores: GC internal structures, Symbol Table, String Table and various runtime data structures</p><p>If the JVM runs inside a container with a memory limit, that limit applies to the entire JVM native memory footprint, including <strong>heap</strong>, <strong>metaspace</strong>, <strong>code cache, thread stacks, direct buffers</strong>, and the <strong>C-heap</strong>.</p><p><strong>String</strong> <strong>Table</strong> and <strong>String</strong> <strong>Pool</strong></p><p>The <em>String Table</em> lives in the <em>C-heap</em>. It is a native hash table. It stores references to interned strings.</p><p>The actual string objects are stored in the heap, inside the <em>String Pool</em>. The <em>String Table</em> maps values to heap addresses of those interned strings.</p><p><strong>Heap and Generational Model</strong></p><p>The heap is a region inside JVM native memory managed by the garbage collector. It uses a generational model.</p><p><strong>Young Generation</strong> includes <strong>Eden</strong> (main allocation area), <strong>TLAB</strong>, (per-thread parts for fast allocation without synchronization), <strong>Survivor spaces</strong> <strong>S0</strong> and <strong>S1 </strong>(intermediate zones for objects that survived a minor GC)</p><p><strong>Old Generation </strong>with objects that survive several young collections are promoted here.</p><p><strong>Garbage Collector</strong></p><p>The garbage collector is a JVM subsystem. Its internal data structures reside in the C-heap. It manages the heap.</p><p>In simplified form, GC removes objects that are no longer reachable.</p><p>To determine reachability, it scans GC Roots (Thread stacks, static fields reachable through class metadata, references stored in metaspace)</p><p><strong>Thread Stacks</strong></p><p>Each thread has its own stack allocated in JVM native memory. Thread stacks serve as GC Roots. A thread stack contains:</p><ul><li>PC register</li><li>JVM stack with method frames and local variables</li><li>Native stack for JNI calls</li></ul><p><strong>Metaspace</strong></p><p>Metaspace is not part of the <strong>heap</strong>. It resides in <strong>JVM native memory</strong>. It consists of class metadata, method signatures and runtime constant pools</p><p><strong>Compressed Class Space</strong> is a part of <strong>Metaspace</strong> used when compressed class pointers are enabled.</p><p><strong>Code Cache</strong></p><p>The Code Cache is a native region that stores<strong> JIT-</strong>compiled machine code.</p><p><strong>Direct Byte Buffers and Off-Heap Memory</strong></p><p>Direct byte buffers allocate memory outside the heap but inside JVM native memory, typically via the C-heap. The DirectByteBuffer object lives in the heap, but the underlying memory is native.</p><p>Libraries such as <strong>Netty</strong> rely heavily on off-heap memory.</p><p><strong>Native Libraries</strong></p><p>Shared native libraries loaded via JNI are mapped into JVM native memory and contribute to the total memory usage.</p><p><strong>Complete Mental Model</strong></p><p>From the operating system perspective, there is one block of memory allocated to the JVM process: <strong>JVM native memory</strong>.</p><p>Inside it, the JVM logically separates:</p><ul><li>Heap</li><li>C-heap</li><li>Metaspace</li><li>Compressed Class Space</li><li>Code Cache</li><li>Thread stacks</li><li>Off-heap memory</li><li>Symbol Table</li><li>String Table</li><li>GC internal structures</li><li>Native libraries</li></ul><p>The <strong>GC</strong> manages the heap but operates using native structures from the <strong>C-heap</strong> and scans thread stacks and metaspace to determine reachability.</p><p>This model was something I built for myself to finally see the entire system as one coherent structure. I could not find an explanation that showed all regions together with their relationships in a single picture. Most materials either zoom into one subsystem or stay at a high abstraction level. I needed a model that preserves both completeness and structural connections, so I constructed it and decided to share it</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee99676bcf39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring vs Spring Boot: where a library ends and auto-configuration begins]]></title>
            <link>https://medium.com/@senko.kostya/spring-vs-spring-boot-where-a-library-ends-and-auto-configuration-begins-d5c737cfe51b?source=rss-ee0cb46867d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5c737cfe51b</guid>
            <dc:creator><![CDATA[Konstantin]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 16:48:05 GMT</pubDate>
            <atom:updated>2026-01-05T16:48:05.218Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Spring and Spring Boot: different abstraction levels that evolve together</strong></h4><p><strong>Spring </strong>and <strong>Spring Boot</strong> are often viewed as different generations of the same framework, the “old” and the “new”. In practice, they coexist together, evolve in parallel, and solve different problems. Confusion between them leads to false expectations: as if <strong>Spring Boot</strong> forbids manual configuration, and a <strong>Starter</strong> is just a “convenient library”. To understand why connecting a third-party <strong>library </strong>is fundamentally different from connecting a <strong>Starter</strong>, it is first necessary to draw a boundary of responsibility between<strong> Spring</strong> and <strong>Spring Boot</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgaXYzokhJXHcT5j37EaYg.png" /></figure><p><strong>Spring Framework</strong> is an infrastructural framework. It manages the creation, wiring, and execution of application code. It provides an IoC-container, bean lifecycle management, AOP, transactions, and abstractions for JDBC, JPA, the web layer, and security. At the same time, <strong>Spring</strong> deliberately does not provide <em>ready-made</em> solutions. Any integration in <strong>Spring</strong> requires <em>explicit</em> configuration: the developer explicitly describes which beans are created, how they are wired, and which parameters are used. Spring does nothing automatically.</p><p><strong>Spring Boot</strong> is a layer built on top of <strong>Spring</strong> that operates at a different level of abstraction. <strong>Spring Boot</strong> does not replace <strong>Spring</strong> and does not create a separate container. It uses the same Dependency Ihjection mechanism, the same<em> @Configuration</em>, and the same bean lifecycle. The difference is that <strong>Spring Boot</strong> adds a layer of auto-configuration and conventions. Its goal is to standardize typical scenarios and reduce the amount of <em>boilerplate</em> code without taking control away from the application.</p><p><strong>The key idea of Spring Boot: Convention over configuration, but only where it is possible and safe.</strong></p><h4><strong>Connecting a library in Spring:</strong></h4><p>A library consists of JAR files with APIs and implementations. <strong>Spring</strong> does not know how exactly to integrate it. Adding a library as a dependency in Spring by itself does not create a single bean and does not lead to any configuration. After adding the library, it is necessary to write configuration, create the required beans, and wire them to the <strong>Spring</strong> infrastructure for use. This is also valid for <strong>Spring Boot</strong>.</p><p>For example, when Apache HttpClient is added via Maven, only the library code appears in the application. To start using it, explicit configuration is required:</p><pre>@Configuration<br>public class HttpClientConfig {<br>@Bean<br>    public CloseableHttpClient httpClient() {<br>        return HttpClients.custom()<br>                .disableRedirectHandling()<br>                .build();<br>    }<br>}</pre><p>This approach fully matches the philosophy of <strong>Spring</strong>. The library provides capabilities, and the application decides how exactly to use them. <strong>Spring</strong> does not participate in this process, except for managing the lifecycle of the declared beans.</p><h4><strong>A starter in Spring Boot differs from connecting a library:</strong></h4><p>A starter is not a library, it solves a fundamentally different problem. A starter is a description of a typical use-case, packaged as a set of dependencies and auto-configurations. By connecting a starter, the developer does not just get JAR files, but agrees to a certain architectural convention: which technologies are used, which defaults are applied, and which beans should be created automatically.</p><p>For example, when <strong><em>spring-boot-starter-web</em></strong> is added, not a single module but an entire coordinated stack is brought into the application: <strong>Spring MVC</strong>, <strong>Jackson</strong>, an embedded server, validation, logging, and auto-configurations for all these components. <strong>Auto-configuration</strong> is the <em>key difference </em>between a starter and a regular library.</p><h4><strong>How auto-configuration works in Spring Boot:</strong></h4><p>Technically, auto-configuration in Spring Boot consists of ordinary <em>@Configuration</em> classes that are registered via metadata inside the JAR and picked up at application startup. Their distinguishing feature is that they are always wrapped in <em>@Conditional </em>conditions. These conditions determine whether the configuration should be applied in a particular application or not.</p><p>Simplified, auto-configuration can look like this:</p><pre>@Configuration<br>@ConditionalOnClass(CloseableHttpClient.class)<br>public class HttpClientAutoConfiguration {<br>@Bean<br>    @ConditionalOnMissingBean<br>    public CloseableHttpClient defaultHttpClient() {<br>        return HttpClients.createDefault();<br>    }<br>}</pre><p>The configuration is activated only if the required class is present on the classpath, here this is specified via <em>@ConditionalOnClass(CloseableHttpClient.class)</em><br> The bean is created only if the application has not declared it itself. This is a fundamental principle of <strong>Spring Boot</strong>.</p><h4><strong>Why user configuration always wins:</strong></h4><p><strong>Spring Boot</strong> follows a contract: user configuration has priority over auto-configuration. If a developer explicitly declares a bean, auto-configuration is not applied. This guarantees that <strong>Boot</strong> will never override application behavior without explicit consent.</p><p>Auto-configuration must never override user code. <strong>Spring Boot </strong>does not forbid manual configuration and does not force the use of <strong>Starters</strong>. User-defined <em>@Configuration</em> always has priority.</p><p>If a developer declares a bean themselves, auto-configuration steps back and does not interfere.</p><h4><strong>So what is the difference?</strong></h4><p>The difference between connecting a <strong>library</strong> and connecting a <strong>Starter</strong> is not about convenience, but about the level of responsibility. A library provides APIs and implementations, and the application takes care of integration. A <strong>Starter</strong> provides an architectural convention and a typical configuration that is applied automatically until the developer decides to take control.</p><p><strong>Spring</strong> and <strong>Spring Boot</strong> are not opposed to each other. <strong>Spring</strong> remains the foundation and the source of core mechanisms. <strong>Spring Boot </strong>adds a layer of auto-configuration and conventions that begins where the library ends, and ends exactly at the moment when user configuration appears.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5c737cfe51b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka: Succession and Reimagining MQ]]></title>
            <link>https://medium.com/@senko.kostya/kafka-succession-and-reimagining-mq-533cf81f7326?source=rss-ee0cb46867d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/533cf81f7326</guid>
            <dc:creator><![CDATA[Konstantin]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 20:43:15 GMT</pubDate>
            <atom:updated>2025-12-26T20:43:15.254Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Kafka</strong> and <strong>RabbitMQ</strong> address different architectural concerns. <strong>Kafka</strong> is a distributed event log designed for storing, distributing, and replaying domain facts. <strong>RabbitMQ</strong> is a queue broker optimized for executing commands and background tasks. In mature <strong>Java</strong> systems, they are often used together because events and actions have different semantics and require different processing models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4ZV4KBy0HqFSMUuokMGVQ.png" /></figure><p>Historically, inter-system messaging was implemented using queues. Classic message queue systems (<em>IBM MQ</em>, <em>ActiveMQ</em>, later <em>RabbitMQ</em>) are built around the concept of a <em>transient message</em>. A message exists only until one of the consumers confirms its processing (<em>ack</em>). Once acknowledged, the message is removed from the queue, and the system considers the task completed.</p><p>This model fits naturally with task execution: there is an action, an executor, and a result. The message broker actively manages the message lifecycle, it tracks <em>delivery, acknowledgments, redelivery attempts</em>, and routing to a <em>DLQ</em> (deadletter queue).</p><p>This approach does not scale well when the message represents an event rather than a command. An event is, by definition, an immutable fact, such as “order created”. Such a fact is often relevant to multiple consumers. These consumers may appear later, fail and recover, reprocess data, or consume it at different speeds. In a traditional MQ model, this typically leads to message duplication, complex routing logic, or data loss.</p><p>At <strong>LinkedIn</strong> in the late 2000s, this problem became critical. Massive volumes of user activity events had to be consumed simultaneously for logging, monitoring, recommendations, analytics, and offline processing. Queue-based systems could not handle this load reliably: they became overloaded and lost data. Kafka emerged directly from this problem as a <strong>distributed event log</strong>.</p><h3><strong>Why Kafka is not a queue</strong></h3><p>Kafka is built around the idea that an event is not a task or a command, but a fact. A fact cannot be “consumed and deleted”. It can only be recorded and read multiple times by different systems, at different times, and at different speeds, in a <strong>distributed</strong> manner. The following cases illustrate how this idea is applied in practice.</p><h3>LinkedIn: the birth of Kafka (early 2010s)</h3><p><strong>Task:</strong> centralize and scale the collection of website activity logs, metrics, and events to enable reliable streaming data delivery between systems and analytics platforms.</p><p><strong>Solution:</strong> development of a custom distributed commit-log system.</p><p><strong>Why Kafka:</strong> the system required high throughput, message ordering within partitions, event retention (so consumers could read at their own pace), horizontal scalability, and fault tolerance.</p><p>Kafka models messaging through <strong><em>topics</em></strong>, to which <strong><em>producers</em></strong> publish event records. <em>Consumers</em> subscribe to <strong><em>topics</em></strong> as part of <strong><em>consumer-groups</em></strong>, where each group maintains its own <strong><em>offset</em></strong> of already processed messages. Topic <strong><em>partitions</em></strong> enable parallel and asynchronous consumption within a consumer group. <strong><em>Replication</em></strong> across brokers ensures fault tolerance and overall system reliability.</p><p><strong>LinkedIn</strong> later donated Kafka to <strong>Apache</strong>, making it vendor-neutral, enterprise-ready, and a de facto standard for corporate event streaming.</p><h3><strong>Netflix: Kafka as the backbone of the event platform (2010–2020)</strong></h3><p><strong>Task:</strong> not to execute actions, but to record facts. A user started watching a video, a service responded with an error, a request passed through a chain of microservices, and so on. These facts were consumed simultaneously by monitoring, alerting, analytics, and recommendation systems.</p><p><strong>Solution:</strong> extensive use of Kafka as an event backbone (streaming platform) for asynchronous integration, monitoring, and ETL pipelines.</p><p><strong>Why Kafka:</strong> RabbitMQ is designed around the “execute and delete” model, while Netflix needed access to data after execution. Kafka serves as a unified event log where each service records facts about its behavior. Consumers can read this log independently, at different speeds, and can even be introduced months after data ingestion has begun.</p><h3><strong>Uber: Kafka under extreme load (2020–2024)</strong></h3><p><strong>Task:</strong> scale data streaming to multi-trillion–event volumes, including trips, status changes, and pricing calculations, while ensuring global availability, reducing broker storage costs, and improving security. At this scale, storing the full history on local broker disks became economically impractical.</p><p><strong>Solution:</strong> multi-cluster Kafka architectures combined with tiered storage. Kafka keeps recent data on local disks, while older data is automatically offloaded to object storage. From the perspective of Java consumers, nothing changes, they continue to read by offset, while Kafka transparently handles data placement.</p><p><strong>Why Kafka:</strong> requirements for extremely high throughput, strict delivery guarantees, and long-term stream processing (audit, replay) made Kafka the natural choice. Tiered Storage significantly reduced broker load. At Uber, Kafka functions as a long-term event store rather than a queue, a role RabbitMQ is not architecturally designed to fulfill.</p><h3><strong>SoundCloud: RabbitMQ in early scalable infrastructure (late 2000s–2010s)</strong></h3><p><strong>Task:</strong> provide an asynchronous task queue and message delivery between services during the transition to microservices, where tasks were modeled as commands.</p><p><strong>Solution:</strong> RabbitMQ aligned perfectly with a model in which a message represents a command.</p><p><strong>Why RabbitMQ:</strong> SoundCloud adopted RabbitMQ at a stage when the architecture was focused on executing actions rather than modeling events. Typical tasks included “transcode audio”, “send notification”, or “update metadata”. In Java terms, these are standard background jobs that must be executed <em>exactly once</em>, with retries and explicit error handling.</p><h3><strong>Combined case: Kafka + RabbitMQ</strong></h3><p>A team developed a Spring Boot order-processing service where it was crucial to separate the recording of business facts from the execution of side effects. When an order was placed, the service persisted data in PostgreSQL and, within the same transaction, wrote an <em>OrderCreated</em> event to an outbox table. An outbox processor then published this event to <strong>Kafka</strong>, which served as a stream of domain facts. The event needed to be available to multiple consumers, support replay, and allow new services to subscribe without modifying the producer.</p><p><strong>Kafka</strong> consumers reacting to <em>OrderCreated</em> did not perform external actions directly. Instead, they produced commands and sent them to <strong>RabbitMQ</strong>. <strong>RabbitMQ</strong> was used to execute side effects such as sending emails, because these operations required retry mechanisms, DLQ support, and explicit acknowledgment semantics. Handlers annotated with <em>@RabbitListener </em>acknowledged messages only after successful completion.</p><p>This separation allowed <strong>Kafka</strong> to remain a reliable log of business events, while <strong>RabbitMQ</strong> acted as the coordinator for action execution. <strong>Kafka</strong> was not burdened with retry logic, and <strong>RabbitMQ</strong> was not used as a historical data store. This pattern is widely used in enterprise Java systems where events and commands have distinct architectural semantics.</p><h3><strong>Conclusions</strong></h3><p><strong>Kafka</strong> and <strong>RabbitMQ</strong> are not competitors. They address different architectural responsibilities, and the choice between them is driven by data semantics rather than popularity.</p><p>In practice, the distinction is straightforward:</p><p><strong>Kafka is chosen when:</strong></p><ul><li>the system processes streams of domain events rather than one-off tasks</li><li>events must be retained and replayed</li><li>multiple services need to consume the same events</li><li>ordering within a key and high throughput are critical</li><li>data is used for stream processing, analytics, or CDC</li></ul><p><strong>RabbitMQ is chosen when:</strong></p><ul><li>a message represents a command or task that must be executed</li><li>acknowledgment semantics, retries, and dead-letter queues are required</li><li>message history is irrelevant after successful processing</li><li>RPC-style interactions or integration with external systems are needed</li></ul><p><strong>Kafka</strong> and <strong>RabbitMQ</strong> are complementary solutions. When their responsibilities are clearly defined, they can be used independently or together. In evolving enterprise systems that require flexibility without disrupting existing data flows, both can be combined effectively to work in synergy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=533cf81f7326" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Leaks in Java: What Actually Leaks and Where Does It Go?]]></title>
            <link>https://medium.com/@senko.kostya/memory-leaks-in-java-what-actually-leaks-and-where-does-it-go-87c33f1488a4?source=rss-ee0cb46867d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/87c33f1488a4</guid>
            <category><![CDATA[jvm-memory]]></category>
            <category><![CDATA[native-memory]]></category>
            <category><![CDATA[garbage-collector]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Konstantin]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 21:25:58 GMT</pubDate>
            <atom:updated>2025-12-11T21:25:58.881Z</atom:updated>
            <content:encoded><![CDATA[<p>Memory leaks are not similar to data leaks but still doesn’t bring any pleasure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibGCzSkwoFNJJYz9Nxycdw.png" /></figure><p>As is well known, a memory leak is <strong>a process of uncontrolled reduction of available physical or virtual memory</strong>. The term originates from the era of low-level languages, primarily <strong>C</strong> and <strong>Assembly</strong>, where memory had to be managed manually. Allocating memory without releasing it caused the situation where memory technically existed but could not be reused.</p><p><strong>Java</strong>, one of the most widely used enterprise languages, does not provide direct manual control over memory, but memory leaks can still occur. The main mechanisms preventing leaks in Java are the Generational <strong>Garbage Collector (GC)</strong>, weak references and data structures built on them, and resource-release mechanisms. All of this is used in modern development, yet none of it provides full protection from logical errors. Below we explore several real cases.</p><h4><strong>Uber: Memory Leak via ThreadLocal and Apache Thrift</strong></h4><p><strong>What happened</strong>: in Uber’s microservices, memory usage under load began to grow by 1–2% per minute until the JVM eventually crashed with <strong>OutOfMemoryError</strong>. GC was returning almost no memory.</p><p><strong>What caused it:</strong> the root cause was Apache Thrift, which uses large temporary byte[]-buffers for serialization. These buffers were placed into an object stored inside a <strong>ThreadLocal</strong>. Because the service ran on a thread pool, threads never terminated, which meant the <strong>ThreadLocalMap</strong> and everything inside it lived as long as the process. Each thread retained megabytes of data, and the total pool of continuously growing buffers increased with each request. Heap dump showed that almost the entire heap was retained through the buffer-creation chain:</p><pre>Thread -&gt; ThreadLocalMap -&gt; Entry(ThreadLocal, Value)</pre><p><strong>Attempts to fix and the final solution:</strong> initially there was a try to <strong>increase the heap (-Xmx)</strong> and to use different <strong>GC</strong>s, in the hope that they would reclaim memory, but <strong>GC</strong> cannot collect reachable objects. Reducing Thrift’s buffer size did not help either, because the issue was not the size but the effectively infinite lifetime of the buffer. The final solution was to remove <strong>ThreadLocal</strong> usage in that subsystem and replace it with an explicit buffer pool that returned buffers after use. In the remaining places, <strong>ThreadLocals</strong> were manually cleared via <strong>remove()</strong>. After that, memory growth stopped completely.</p><p><strong>Takeaway</strong>: <strong>ThreadLocal</strong> is one of the quietest but most dangerous places for leaks in Java. If a thread lives long, its value lives equally long.</p><h4><strong>LinkedIn: Leak Through RxJava / Observables</strong></h4><p><strong>What happened</strong>:<strong> </strong>LinkedIn services (Feed and Identity components) showed slow but steady <strong>heap growth</strong> despite stable traffic. After several hours, the process ended with <strong>OutOfMemoryError</strong>.</p><p><strong>What caused it:</strong> the issue occurred in reactive chains built with RxJava. Each subscription creates a graph of <strong>Observable</strong>, <strong>Observer</strong>, <strong>Subscription</strong>, and intermediate operators. In <strong>RxJava</strong>, every subscribe() creates a chain of objects:</p><pre>Observable -&gt; Observer -&gt; Disposable</pre><p>If the subscriber is not released via dispose(), the Observable continues holding a reference to it and to the entire operator graph. In background tasks, some error paths stopped the chain prematurely, and dispose() was never called. Thousands of orphaned subscriptions retained large object graphs, including big DTOs and user profiles. Heap dump showed many live Observer objects that were no longer used but still retained from Observable roots.</p><p><strong>Attempts to fix and the final solution: </strong>attempts to reduce the size of DTOs, switch versions of GC, or limit chain depth didn’t help, because objects remained reachable. <strong>JFR (Java Flight Recorder)</strong> allocation flame graph showed extremely high Observer allocations, and heap dump contained massive RxJava Subscriber collections. Manual code review revealed chains missing .dispose() or .take(1).</p><p>The issue was resolved by enforcing mandatory .dispose() in all chains, adding an auto-dispose mechanism, and implementing subscription scopes (similar to Spring @Scope). In new components, LinkedIn partially replaced <strong>RxJava</strong> with <strong>Project Reactor (Spring WebFlux)</strong>, which provides better lifecycle control. After the fixes, heap growth disappeared.</p><p><strong>Takeaway:</strong> Reactive frameworks create complex object graphs. <strong>Observable</strong> holds a strong reference to <strong>Observer</strong>. Modern approaches such as <strong>Spring WebFlux</strong> mitigate part of such risks.</p><h4><strong>Netflix: Native Memory Leak With Stable Heap</strong></h4><p><strong>What happened</strong>:<strong> </strong>high-load Netflix services using Netty showed stable heap usage, but <strong>RSS</strong> (Resident Set Size, memory pages allocated by the OS and actually residentin RAM) grew to gigabytes, cusing the process to crash with <strong>OutOfMemory</strong>.</p><p><strong>What caused it:</strong> <strong>Netty</strong> and <strong>Java NIO</strong> use <strong>DirectByteBuffer</strong>, buffers allocated outside the Java heap. Such memory is allocated via Unsafe.allocateMemory() and deallocated not by <strong>GC</strong> but by a <strong>Cleaner</strong> that runs only when the object becomes unreachable and is finalized. Native structures inside <strong>Netty</strong> and <strong>JNI</strong> code were not being released, and several long-lived buffer pools lost references. As a result, Java objects could be garbage collected, but their off-heap memory continued to exist because the cleaner never executed. This caused massive native memory growth invisible in heap dumps.</p><p><strong>Attempts to fix and the final solution: </strong>Changing <strong>GC</strong>, increasing heap, or limiting buffer pools did not affect native memory. <strong>Native Memory Tracking </strong>showed huge allocations retained by allocator pools. <strong>Netty ResourceLeakDetector</strong> identified specific locations where ByteBuf was not released. Fixing all ByteBuf.release() paths, enabling strict leak detection in test and development environments, and limiting <strong>MaxDirectMemorySize</strong> eliminated the issue.</p><p><strong>Takeaway: </strong>heap dumps can be useless if the leak is in native memory.</p><h4><strong>Summary</strong></h4><p>These examples represent only a fraction of possible leak scenarios. They are never the fault of the <strong>GC</strong>, but direct consequences of architecture and implementation choices. Almost always, they are caused by logical errors. Java does not protect you from mistakes in managing object lifetimes.</p><p>To avoid leaks, you need to understand <strong>JVM</strong> internals, control the lifecycle of resources, use heap and native memory analysis tools, and not rely solely on the <strong>GC</strong>. A memory leak in Java is not an anomaly but a natural consequence of complex architectural decisions</p><p>Effective leak prevention requires both disciplined coding and regular diagnostics of how the system behaves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87c33f1488a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>