Video in progress

The service is crashing with `OutOfMemoryError: Direct buffer memory` while the heap is half empty. How do you investigate, and what limit policy do you set?

Direct buffers live outside the heap and are released only when their Java object is collected by the GC. With Native Memory Tracking and BufferPoolMXBean you see who is allocating and how much; then you set MaxDirectMemorySize explicitly and tune the libraries' pools.

📖 Answer

This error comes from two kinds of causes: a real leak (someone is holding a buffer), or "delayed release": the buffers are no longer needed, but the heap is big and the GC ran rarely, so their Cleaners haven't run.

The order of investigation:

# at startup: -XX:NativeMemoryTracking=summary
jcmd $PID VM.native_memory summary          # is the "Other"/NIO section growing
jcmd $PID VM.native_memory baseline         # then later summary.diff

From the inside, ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class) gives the count and size of the direct and mapped pools. Micrometer already provides the jvm.buffer.memory.used metric; put it on a graph and the shape of the growth tells you a lot: a sawtooth means delayed release, steady linear growth means a leak.

Typical culprits:

  • Netty's pooled allocator: ByteBuf.release() not called. -Dio.netty.leakDetection.level=paranoid shows in testing which code path is to blame.
  • The JDK itself: when you write a heap ByteBuffer to a socket/channel, the JDK caches a temporary direct buffer per thread. Many threads and large buffers bloat this cache; -Djdk.nio.maxCachedBufferSize limits it.
  • allocateDirect on every request.

The limit policy is a question of planning container memory. The pod limit = heap + metaspace + thread stacks + code cache + direct + mapped + GC structures + the native memory of libraries. If you only set -Xmx and say "the rest will fit somehow", the kernel's OOM killer kills the process with no Java error at all. I set MaxDirectMemorySize explicitly (so the error shows up as a clear Java exception, not an OOMKill) and set the pod limit based on NMT measurements, with a 15-25% reserve.