I ran into a Direct memory failure on a server using Reactor Netty.
In Part 1, I covered how Direct memory is allocated and released. (Part 1)
This part covers the failure itself. AnOutOfMemoryErrorwas thrown, so why did the request neither fail nor succeed?
Part 1 showed that hitting the limit causes an OOM (OutOfMemoryError).
This post picks up from there and follows, through source code and reproduction experiments, where the request that hit the OOM disappeared to.
The environment is the same as in Part 1.
| Item | Version |
|---|---|
| Netty | 4.1.135.Final |
| Reactor Netty | 1.2.18 |
| Reactor Core | 3.7.19 |
| JDK | 21 |
| Category | Details |
|---|---|
| Symptom | One consumer that ran out of Direct memory got stuck, unable to either succeed or fail its request |
| Direct cause | retryWhen(...).block() without a timeout keeps waiting forever because the terminal signal never arrives |
| Root cause | A bare OutOfMemoryError thrown during the TLS handshake was rethrown by throwIfFatal inside sink.error, and Netty swallowed it after logging only a WARN, so the Mono never received a terminal signal |
| Why only this request | The same OOM propagates normally when it is wrapped in InternalNettyException · SSLException |
| Actions | An explicit timeout outside retryWhen · a higher Direct memory limit · issue #4504, reporting the behavior and proposing a fix |
The experiments were verified against tag-pinned source line numbers of reactor-netty · reactor-core · netty, along with reproduction logs.
An alert fired because certain requests had not been processed for 30 minutes.
When I traced it, a particular consumer had picked up a message and was sitting there without processing it.
The download code in question looked like this.
webClient…retrieve()
.bodyToMono(byte[].class)
.retryWhen(Retry.fixedDelay(2, Duration.ofSeconds(1)))
.block();There is no timeout. That is the biggest problem,
but what puzzled me more was that two jobs stuck at the same time & on the same line ended differently.
catch → alert → error report.-> Let's trace where this difference came from.
This scene is based on operational records, and the times · services · vendor names have been generalized.
Not much was left in production.
7 throwIfFatal … jvm fatal WARNs
6 Netty thrown by a user handler's exceptionCaught() WARNs
The OOM stack was SslHandler.channelInactive:1191 → … → unwrap → allocate
The Direct limit was limit: 201326592 (192 MiB)
The failed allocation was Cannot reserve 524288 bytes, which means it could not get a single chunk.
This splits into two questions.
Mono terminate?Both questions require knowing how a Mono sends and receives signals, so I'll explain that briefly.
A Mono is a specification of work that will produce zero or one result later.
Creating it does not run anything; the request goes out only when you subscribe.
Results arrive as three kinds of signals.
onNext — a valueonComplete — normal terminationonError — termination with an errorAn error has to arrive as the onError signal.
If the signal disappears somewhere in the middle, the waiting side waits forever.
Calling block() is what finally subscribes, and it parks the calling thread on a latch (CountDownLatch).
if (getCount() != 0) {
try {
await();
}
…
}
Throwable e = error;
if (e != null) {
RuntimeException re = Exceptions.propagate(e);reactor-core v3.7.19 BlockingSingleSubscriber.java#L85-L108
block() returns only when a terminal signal arrives and releases the latch. If no terminal signal comes, there is no way to release it.
The time-bounded blockingGet(timeout, unit) calls dispose() once the time is up and throws an IllegalStateException wrapping a TimeoutException. (L120-L130)
When retryWhen receives onError, it subscribes again to retry. Each retry may create a new connection.
Reactor Netty's HTTP client also has its own retryWhen inside.
}).retryWhen(Retry.indefinitely().filter(handler))reactor-netty v1.2.18 HttpClientConnect.java#L297
The retryWhen(Retry.fixedDelay(2, …)) written by the user operates downstream of this flow.
"Fatal" here means an unrecoverable error.
Exceptions.throwIfFatal rethrows the throwable if it is JVM fatal.if (isJvmFatal(t)) {
LOGGER.warn("throwIfFatal detected a jvm fatal exception, which is thrown and logged below:", t);
throw (Error) t;
}
public static boolean isJvmFatal(@Nullable Throwable t) {
return t instanceof VirtualMachineError ||
t instanceof ThreadDeath ||
t instanceof LinkageError;
}reactor-core v3.7.19 Exceptions.java#L504-L516
OutOfMemoryError is a subtype of VirtualMachineError.
-> The OOM is not turned into an onError signal; it is rethrown up the call stack as an Error.
A maintainer also replied that rethrowing JVM fatal errors instead of sending them as signals is by design.
reactor-netty #4407
In Netty, an exception thrown by a handler method is caught by Netty and passed to that handler's exceptionCaught.
However, an exception thrown inside exceptionCaught is caught by Netty, which only logs it and stops there.
try {
handler().exceptionCaught(this, cause);
} catch (Throwable error) {
…
logger.warn(
"An exception '{}' [enable DEBUG level for full stacktrace] " +
"was thrown by a user handler's exceptionCaught() " +
"method while handling the following exception:", error, cause);netty-4.1.135.Final AbstractChannelHandlerContext.java#L343-L360
=> If a rethrown Error comes up from inside the exceptionCaught call, both the signal and the thrown exception disappear.
I reproduced it with the same chain where the problem occurred and the same limit (192 MiB).
DirectByteBuffer pressureThe key to the setup is the order.

The handshake failures turned out as follows.
| Attempt | Success | Wrapped failure | Unwrapped OOM |
|---|---|---|---|
| #2 | 1,269 | 213 | 18 |
| #3 | 1,183 | 260 | 47 |
Among handshake failures, bare OOMs were 18/231 (7.8%) for #2 and 47/307 (15.3%) for #3.
What got stuck were the new connections opened after memory ran out.
They got stuck at the TLS handshake that opens the connection, before even receiving the image.
A TLS handshake needs a buffer to decrypt (unwrap) the data it receives.
A thread snapshot from a stuck run looks like this.
CountDownLatch.await → BlockingSingleSubscriber.blockingGet → Mono.blockreactor-http-nio-14) — waiting in the Selector=> block() is waiting on the latch, and the network thread is simply idle as well.
At first I thought the connection hadn't finished.
When I paired each stuck request with its connection (Channel), the connection had already been closed, and only the Mono was still waiting. The logs couldn't tell me which of the connection · pool · TLS hadn't finished.
Two clues changed my direction.
throwIfFatal and Netty's WARN showed up in pairs. That is a trace of something being rethrown and then swallowedSo I ran it 12 more times, recording the call stack wherever throwIfFatal was called. All 11 bare OOMs got stuck, and the path below showed up only in the stuck runs.
SslHandler — an OOM occurs while decrypting (unwrap) TLS data (L1396-L1419)
SslReadHandler — passes the failure event to exceptionCaught (L730-L736)ChannelOperationsHandler.exceptionCaught — there is no HTTP operations object yet, so it passes the OOM along as is (L149-L158)sink.error(OOM) — puts the error into the Mono waiting for the connection. (L223-L226)retryWhen — calls throwIfFatal while pulling out an error that isn't eligible for retry. (FluxConcatMapNoPrefetch L186-L190 · MonoError L56-L61)throwIfFatal — the OOM is JVM fatal, so it is rethrown. (L504-L516)exceptionCaught, and only logs a WARN. (L343-L360)
In the reproduction log, the same thread writes these two lines in the same millisecond. They have the same shape as the two kinds of WARNs left in production.
19:44:18.155 [reactor-http-nio-16] WARN reactor.core.Exceptions -- throwIfFatal detected a jvm fatal exception, which is thrown and logged below:
java.lang.OutOfMemoryError: Cannot reserve 524288 bytes of direct buffer memory (allocated: 200810504, limit: 201326592)
…
19:44:18.155 [reactor-http-nio-16] WARN io.netty.channel.AbstractChannelHandlerContext -- An exception 'java.lang.OutOfMemoryError: Cannot reserve 524288 bytes of direct buffer memory (allocated: 200810504, limit: 201326592)' [enable DEBUG level for full stacktrace] was thrown by a user handler's exceptionCaught() method while handling the following exception:So why did Job A finish?
Reactor Netty already has a mechanism that wraps OOMs.
else if (err instanceof OutOfMemoryError) {
return ReactorNetty.wrapException(err);
}reactor-netty v1.2.18 ChannelOperations.java#L566-L576
wrapInboundError
Once wrapped, it becomes an InternalNettyException (a RuntimeException), and throwIfFatal does not rethrow it.
-> It goes straight to onError, and the request finishes.
That mechanism is attached to only one branch of exceptionCaught.
@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable err) {
Connection connection = Connection.from(ctx.channel());
ChannelOperations<?, ?> ops = connection.as(ChannelOperations.class);
if (ops != null) {
ops.onInboundError(err);
}
else {
listener.onUncaughtException(connection, err);
}
}If the HTTP operations object (ops) doesn't exist yet, the OOM is handed to onUncaughtException without being wrapped.
What follows is steps 4–7 of the path above.
onUncaughtException calls sink.error(OOM)sink.error, the call continues into the inner retryWhen, whose throwIfFatal rethrows the OOMexceptionCaught (invokeExceptionCaught), where it is caught and only a WARN log is left-> Neither the error signal (onError) nor the thrown exception reaches the Mono. block() never receives a terminal signal and keeps waiting.
reactor-netty v1.2.18 ChannelOperationsHandler.java#L148-L158
| Branch | When | OOM |
|---|---|---|
ops != null | While receiving the response | Wrapped and passed on → the request ends with an error |
ops == null | During the TLS handshake · while acquiring a connection | Passed on as is → the terminal signal disappears |

On the write side, Netty wraps TLS failures in
SSLExceptionbefore passing them on. (SslHandler.java#L2053-L2061)
In the reproduction, I confirmed that every wrapped TLS failure terminated normally
=> So my guess was that Job A hit a wrapped OOM, while Job B hit an unwrapped one and never got handled.
Up to this point, it's a hypothesis and an explanation built on correlation and call stacks.
If this path really was the cause, I figured that cutting it at any one point would make the hang go away.
So I modified the reactor-netty code one point at a time to check.
ops == null branch in step 3 also wrap the OOM in a RuntimeExceptionthrowIfFatal in step 6 not rethrow the OOM.timeout(60s) outside retryWhen=> Cutting just one point, either step 3 or step 6, made the hang go away. With the path left intact and a timeout applied, it ended with an exception after 60 seconds.
Here is the one-line fix.
listener.onUncaughtException(connection,
err instanceof OutOfMemoryError ? reactor.netty.ReactorNetty.wrapException(err) : err);You can write a test that reproduces the same situation without actually filling up memory.
If you put a regular exception and anOutOfMemoryErrorinto the handshake failure event, only the OOM case fails to get a terminal signal within 5 seconds.
./gradlew :reactor-netty-http:test --tests 'reactor.netty.http.client.HttpClientFatalErrorBeforeOperationsTest'Tracing the cause backward from the symptom:
block() never received a terminal signalthrowIfFatal rethrew the OOM and Netty swallowed itops == null branch, which doesn't wrap OOMswebClient…retrieve()
.bodyToMono(byte[].class)
.retryWhen(Retry.fixedDelay(2, Duration.ofSeconds(1)))
.timeout(Duration.ofSeconds(30)) // outside retryWhen
.block();A timeout doesn't prevent the OOM. What it does is cut the time spent stuck from about 40–45 minutes down to the timeout value.
block(Duration) also ends with an exception once the time is up. (L120-L130)
Memory exhaustion and TLS failures are still there.
That's why memory needs to be monitored and improved.
-> We judged that our consumer servers had hit their memory threshold, so along with the timeout, we also raised the Direct memory limit.
Reactor Core rethrows fatal errors, and Netty swallows exceptions thrown inside handlers after just logging them.
-> Both are long-standing designs, but in the ops == null branch where the two meet, the terminal signal disappears.
For the same OOM, it gets wrapped while a response is being received (ops != null), but not during the handshake.
To confirm whether this difference was intentional, I filed an issue on reactor-netty.
OutOfMemoryError during the TLS handshake is signalled unwrapped, so the response Mono never terminatesThe issue includes three things.
1.3.x, only the OOM case fails to get a signalUnlike the patch from the verification step, the proposed fix wraps the OOM only when passing it to sink.error, and hands the original OOM to the observer as is.
try {
sink.error(error instanceof OutOfMemoryError ? wrapException(error) : error);
}
finally {
obs.onUncaughtException(connection, error);
}
DefaultPooledConnectionProviderandNewConnectionProviderin reactor-netty1.3.x
"The OOM was thrown, so why did the request neither fail nor succeed?"
The error did happen
-> it made it as far as sink.error, got rethrown inside it,
-> and Netty swallowed it after only logging.
=> With no terminal signal coming, a block() without a timeout just keeps waiting.
On a side note, going through reactor-netty, I found it pretty fascinating how a minor code path can lead to such an unintended result.