Video in progress
In a Netty-based service the heap is normal, but pods get OOMKilled. How do you find a direct memory leak, and how do you prevent it?
First I confirm with NMT and BufferPool metrics that direct memory is growing, then I turn on Netty's ResourceLeakDetector to find ByteBufs that weren't release()d. In the long run you need limits and code rules.
📖 Answer
Direct buffers live outside the heap. The GC frees them only when the Java object that owns them is collected, while Netty keeps its own accounting with a pooled allocator and relies on reference counting. If you forget release(), the memory doesn't come back, and the heap graphs show nothing about it.
The investigation steps:
- The direct memory the JVM sees:
BufferPoolMXBean(direct,mapped), which isjvm.buffer.memory.usedin Micrometer. Netty's own metric:PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory(). - Whether the NMT
Othersection is growing. - The leak detector:
-Dio.netty.leakDetection.level=paranoid # test/staging only, expensive
-Dio.netty.leakDetection.level=advanced # on a canary
The log shows LEAK: ByteBuf.release() was not called and where the buffer was last used.
The usual causes: a custom ChannelHandler neither passes the message on nor calls release(); a buffer is lost on the exception path; an extra retain().
Prevention:
- set
-XX:MaxDirectMemorySizeexplicitly: if there is a leak, you get a clearOutOfMemoryError: Cannot reserve direct buffer memoryinstead of the container being OOMKilled; - use base classes that release by themselves, like
SimpleChannelInboundHandler; - run the integration tests in CI at the
paranoidlevel and fail the build if the wordLEAKappears; - plan a separate place for direct memory in the container memory budget.
Sign up to mark studied questions and save your progress.