Repository navigation
Description
Describe the bug
The NettyRequestExecutor stores the RequestContext of a request in the channel attribute REQUEST_CONTEXT_KEY. Nothing clears the attribute when the request completes and the channel returns to the pool. An idle HTTP/1.1 connection therefore keeps its last request reachable, including the request body, until the connection serves another request or closes.
This matters when the request body is a byte array, for example one created with AsyncRequestBody.fromBytes or fromBytesUnsafe. The garbage collector cannot free the array while the idle connection still refers to it, even though the upload has finished and the application no longer uses the array.
Every idle connection in the pool can hold one such body. In the worst case the client keeps maxConcurrency bodies in memory after all requests have completed.
Example: with maxConcurrency(100) and 16 MB bodies, that is up to 100 x 16 MB = 1.6 GB of heap that the application cannot get back until the connections are reused or closed.
We found this in Apache Fluss, in a new S3 filesystem plugin that uploads 16 MB parts with S3AsyncClient.uploadPart.
This looks like the same root cause as #6307, seen with a single connection pool and large request bodies.
Regression Issue
- Select this option if this issue appears to be a regression.
Expected Behavior
After a request completes and its connection returns to the pool, the client holds no reference to the request body.
Current Behavior
The body stays reachable from the idle channel. In a heap profile (JFR, old object sample) of 8 concurrent multipart uploads with 16 MB parts, all 64 sampled live 16 MB arrays had the same path to a GC root:
byte[] <- ByteBuffersAsyncRequestBody <- AsyncExecuteRequest <- RequestContext
<- channel attribute REQUEST_CONTEXT_KEY <- NioSocketChannel (idle in the pool)
The application holds at most 72 part buffers (1152 MB) at a time. The live set after collections was 2.1 to 2.3 GB with a 3 GB heap. With a 1664 MB heap the process ended with OutOfMemoryError.
The client was configured with maxConcurrency(100).
Reproduction Steps
The program below needs only netty-nio-client on the classpath. It starts the JDK's built-in HTTP server, sends 4 concurrent PUT requests with 16 MB bodies, waits for all responses, and then counts how many body arrays are still reachable while the client stays open. The body publisher emits one buffer that wraps the array, like AsyncRequestBody.fromBytesUnsafe.
- Expected output:
retained 0 of 4 request bodies with the client still open - Output on
masterat379fe9e:retained 4 of 4 request bodies with the client still open
IdleConnectionRetainsRequestBody.java
import com.sun.net.httpserver.HttpServer;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
/**
* After N concurrent PUTs with byte-array bodies complete, the N connections sit idle in the pool and each one keeps
* its last request body reachable. Expected: "retained 0 of 4". Observed before the fix: "retained 4 of 4".
*/
public class IdleConnectionRetainsRequestBody {
static final int REQUESTS = 4;
static final int BODY_SIZE = 16 * 1024 * 1024;
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/", exchange -> {
try (InputStream in = exchange.getRequestBody()) {
byte[] buf = new byte[64 * 1024];
while (in.read(buf) != -1) {
// drain
}
}
exchange.sendResponseHeaders(200, -1);
exchange.close();
});
server.setExecutor(Executors.newCachedThreadPool());
server.start();
SdkAsyncHttpClient client = NettyNioAsyncHttpClient.builder().useIdleConnectionReaper(false).build();
try {
URI uri = URI.create("http://localhost:" + server.getAddress().getPort() + "/");
List<WeakReference<byte[]>> bodies = sendConcurrentPuts(client, uri);
long retained = REQUESTS;
for (int i = 0; i < 50 && retained > 0; i++) {
System.gc();
Thread.sleep(100);
retained = bodies.stream().filter(ref -> ref.get() != null).count();
}
System.out.println("retained " + retained + " of " + REQUESTS + " request bodies with the client still open");
} finally {
client.close();
server.stop(0);
}
}
private static List<WeakReference<byte[]>> sendConcurrentPuts(SdkAsyncHttpClient client, URI uri) throws Exception {
List<WeakReference<byte[]>> bodies = new ArrayList<>();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < REQUESTS; i++) {
byte[] body = new byte[BODY_SIZE];
bodies.add(new WeakReference<>(body));
CompletableFuture<Void> responseDone = new CompletableFuture<>();
SdkHttpRequest request = SdkHttpRequest.builder()
.uri(uri)
.method(SdkHttpMethod.PUT)
.putHeader("Content-Length", String.valueOf(BODY_SIZE))
.build();
futures.add(client.execute(AsyncExecuteRequest.builder()
.request(request)
.requestContentPublisher(new BytesPublisher(body))
.responseHandler(new DrainingHandler(responseDone))
.build()));
futures.add(responseDone);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(60, TimeUnit.SECONDS);
return bodies;
}
/** Emits one buffer wrapping the array, like AsyncRequestBody.fromBytesUnsafe. */
static final class BytesPublisher implements SdkHttpContentPublisher {
private final ByteBuffer buffer;
BytesPublisher(byte[] bytes) {
this.buffer = ByteBuffer.wrap(bytes);
}
@Override
public Optional<Long> contentLength() {
return Optional.of((long) buffer.capacity());
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
AtomicBoolean done = new AtomicBoolean();
s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
if (n > 0 && done.compareAndSet(false, true)) {
s.onNext(buffer.asReadOnlyBuffer());
s.onComplete();
}
}
@Override
public void cancel() {
done.set(true);
}
});
}
}
static final class DrainingHandler implements SdkAsyncHttpResponseHandler {
private final CompletableFuture<Void> done;
DrainingHandler(CompletableFuture<Void> done) {
this.done = done;
}
@Override
public void onHeaders(SdkHttpResponse headers) {
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(new Subscriber<ByteBuffer>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(ByteBuffer b) {
}
@Override
public void onError(Throwable t) {
done.completeExceptionally(t);
}
@Override
public void onComplete() {
done.complete(null);
}
});
}
@Override
public void onError(Throwable error) {
done.completeExceptionally(error);
}
}
}Possible Solution
Clear REQUEST_CONTEXT_KEY in ResponseHandler.finalizeResponse, in the keep-alive branch, before the channel is released to the pool. The other release paths close the channel, so the pool drops it and the context becomes unreachable with it. With this change the program above prints retained 0 of 4.
I can open a pull request with the change and a regression test.
Additional Information/Context
-
In the main sources of netty-nio-client,
REQUEST_CONTEXT_KEYhas one write (NettyRequestExecutor) and eight reads (ResponseHandler,FutureCancelHandler). It has no clearing write. This is the same on master at 379fe9e. -
Workaround in the application: wrap the body in an
AsyncRequestBodythat drops its reference to the array when the upload future completes. With the workaround, none of 62 sampled 16 MB arrays was reachable from a GC root. The live set dropped to 1148-1236 MB, and the same run passed with a 1664 MB heap.
AWS Java SDK version used
2.57.13 (measured). The reproduction was run against master at 379fe9e (2.59.3-SNAPSHOT).
JDK version used
Amazon Corretto 11 (java-11-amazon-corretto-headless). The exact build was not recorded.
Operating System and version
Amazon Linux 2023, x86_64, on EC2 m6i.2xlarge.
AI tools
- I have reviewed this issue myself, including any content generated by AI tools
Activity