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:

  1. The direct memory the JVM sees: BufferPoolMXBean (direct, mapped), which is jvm.buffer.memory.used in Micrometer. Netty's own metric: PooledByteBufAllocator.DEFAULT.metric().usedDirectMemory().
  2. Whether the NMT Other section is growing.
  3. 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:MaxDirectMemorySize explicitly: if there is a leak, you get a clear OutOfMemoryError: Cannot reserve direct buffer memory instead of the container being OOMKilled;
  • use base classes that release by themselves, like SimpleChannelInboundHandler;
  • run the integration tests in CI at the paranoid level and fail the build if the word LEAK appears;
  • plan a separate place for direct memory in the container memory budget.