Skip to content

Commit 18f412e

Browse files
Meemawclaude
andauthored
netty: drain before closing a gracefully shut down server connection (#13086)
Fixes #9566. After the second GOAWAY of a graceful shutdown (`maxConnectionAge`, `maxConnectionIdle`, `Server.shutdown()`), `Http2ConnectionHandler` closes the socket as soon as the last stream's final frame has been written to the kernel. If the client hasn't read the response yet, the response is still in the server's send queue. The client's next frame (a BDP PING or WINDOW_UPDATE) then reaches a socket the server has closed, so the server's kernel answers with RST and drops the unsent bytes, trailers included. The client fails an RPC the server completed, with `UNAVAILABLE: Connection closed after GOAWAY. HTTP/2 error code: NO_ERROR, debug data: max_age`. The response headers had already arrived, so the call is committed and isn't retried. The full analysis and a standalone reproducer are in #9566 (comment). ### Change Once the second GOAWAY has been sent and no streams are active, `NettyServerHandler` keeps the connection open and reading for up to 1 second before closing. The client normally closes first, as soon as it has read the GOAWAY and its streams have completed, so the drain usually ends early. This is the approach Go's HTTP/2 server took (golang/net@cd69bc3). - It overrides `isGracefulShutdownComplete()`, the hook `NettyClientHandler` already uses, so the close still goes through `Http2ConnectionHandler` and works the same with TLS. - It never extends the grace time: if `maxConnectionAgeGrace` (or the shutdown grace) runs out first, the connection closes then. - The drain is cancelled when the channel becomes inactive. ### Tests - `NettyServerHandlerTest`: 9 tests asserted that the channel closes immediately after the second GOAWAY. They now advance the fake clock by the drain time first. Two new tests: `maxConnectionAge_drainStartsWhenLastStreamCloses` and `maxConnectionAgeGrace_shorterThanDrain_closesAtGrace`. - New `NettyServerGracefulCloseTest`: an end-to-end regression test over a real loopback connection, using only public APIs and the server's default transport. A unary call outlives the max age, and the client's event loop stalls 300 ms while the 256 KiB response is sent. Without the fix it fails on Linux with the error above (3/3 runs); with the fix it passes (3/3, about 6 s). macOS loopback doesn't lose the data, so there it passes either way. Note that `maxConnectionAge` has a 1 s floor, which is why the call runs 1.5 s. - All 655 `grpc-netty` tests pass. The standalone reproducer from the issue, on Linux (`master` against this branch, 20 iterations each, `parkMs` = client event-loop stall): | Scenario | `master` | this PR | |---|---|---| | No hooks | 5/20 fail | 0/20 | | 100 / 500 / 900 ms client stall | 49/60 fail | 0/60 | | 1500 ms client stall (longer than the drain) | 1/20 | 3/20 | A client stalled for longer than the drain can still lose the race, as in Go. ### Relation to Netty The root cause is in Netty's `Http2ConnectionHandler`, so I've also opened netty/netty#17701 (issue netty/netty#17700). It adds an opt-in `gracefulShutdownDrainMillis`. Once a Netty release includes it, the override here can be replaced by calling `gracefulShutdownDrainMillis(1000)`. This PR fixes grpc-java without waiting for that release. ### Not included `OkHttpServerTransport` closes the same way after the second GOAWAY and is probably affected too. I haven't tested it, and I'm happy to follow up if you want both transports to behave the same. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fe4f145 commit 18f412e

3 files changed

Lines changed: 271 additions & 8 deletions

File tree

‎netty/src/main/java/io/grpc/netty/NettyServerHandler.java‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,14 @@ class NettyServerHandler extends AbstractNettyHandler {
122122
@VisibleForTesting
123123
static final long GRACEFUL_SHUTDOWN_PING = 0x97ACEF001L;
124124
private static final long GRACEFUL_SHUTDOWN_PING_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(10);
125+
/**
126+
* How long to keep the connection open and reading after the second GOAWAY, once no streams are
127+
* active. Closing a socket while the peer is still sending (WINDOW_UPDATE, PING) makes the kernel
128+
* answer with RST, which discards response bytes that have not been transmitted yet (#9566).
129+
* The peer normally closes first, as soon as it has read the GOAWAY and its streams completed.
130+
*/
131+
@VisibleForTesting
132+
static final long GRACEFUL_SHUTDOWN_DRAIN_NANOS = TimeUnit.SECONDS.toNanos(1);
125133
/** Temporary workaround for #8674. Fine to delete after v1.45 release, and maybe earlier. */
126134
private static final boolean DISABLE_CONNECTION_HEADER_CHECK = Boolean.parseBoolean(
127135
System.getProperty("io.grpc.netty.disableConnectionHeaderCheck", "false"));
@@ -369,6 +377,9 @@ public void onStreamClosed(Http2Stream stream) {
369377
if (maxConnectionIdleManager != null) {
370378
maxConnectionIdleManager.onTransportIdle();
371379
}
380+
if (gracefulShutdown != null) {
381+
gracefulShutdown.drainIfIdle();
382+
}
372383
}
373384
}
374385
});
@@ -694,6 +705,9 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
694705
if (maxConnectionAgeMonitor != null) {
695706
maxConnectionAgeMonitor.cancel(false);
696707
}
708+
if (gracefulShutdown != null) {
709+
gracefulShutdown.cancelDrain();
710+
}
697711
final Status status =
698712
Status.UNAVAILABLE.withDescription("connection terminated for unknown reason");
699713
// Any streams that are still active must be closed
@@ -745,6 +759,12 @@ public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exce
745759
ctx.flush();
746760
}
747761

762+
@Override
763+
protected boolean isGracefulShutdownComplete() {
764+
return super.isGracefulShutdownComplete()
765+
&& (gracefulShutdown == null || gracefulShutdown.drainComplete());
766+
}
767+
748768
/**
749769
* Returns the given processed bytes back to inbound flow control.
750770
*/
@@ -1090,6 +1110,13 @@ private final class GracefulShutdown {
10901110

10911111
Future<?> pingFuture;
10921112

1113+
ChannelHandlerContext ctx;
1114+
1115+
/** Scheduled once the second GOAWAY has been sent and no streams are active. */
1116+
Future<?> drainFuture;
1117+
1118+
boolean drained;
1119+
10931120
GracefulShutdown(String goAwayMessage,
10941121
@Nullable Long graceTimeInNanos) {
10951122
this.goAwayMessage = goAwayMessage;
@@ -1100,6 +1127,7 @@ private final class GracefulShutdown {
11001127
* Sends out first GOAWAY and ping, and schedules second GOAWAY and close.
11011128
*/
11021129
void start(final ChannelHandlerContext ctx) {
1130+
this.ctx = ctx;
11031131
goAway(
11041132
ctx,
11051133
Integer.MAX_VALUE,
@@ -1142,12 +1170,46 @@ void secondGoAwayAndClose(ChannelHandlerContext ctx) {
11421170
long overriddenGraceTime = graceTimeOverrideMillis(savedGracefulShutdownTimeMillis);
11431171
try {
11441172
gracefulShutdownTimeoutMillis(overriddenGraceTime);
1173+
// Closes once isGracefulShutdownComplete(), i.e. after the drain, or when the grace time
1174+
// runs out.
11451175
NettyServerHandler.super.close(ctx, ctx.newPromise());
11461176
} catch (Exception e) {
11471177
onError(ctx, /* outbound= */ true, e);
11481178
} finally {
11491179
gracefulShutdownTimeoutMillis(savedGracefulShutdownTimeMillis);
11501180
}
1181+
drainIfIdle();
1182+
}
1183+
1184+
boolean drainComplete() {
1185+
return !pingAckedOrTimeout || drained;
1186+
}
1187+
1188+
void drainIfIdle() {
1189+
if (!pingAckedOrTimeout || drainFuture != null || connection().numActiveStreams() != 0) {
1190+
return;
1191+
}
1192+
drainFuture = ctx.executor().schedule(
1193+
new Runnable() {
1194+
@Override
1195+
public void run() {
1196+
drained = true;
1197+
try {
1198+
// No streams are active, so this closes as soon as pending writes are flushed.
1199+
NettyServerHandler.super.close(ctx, ctx.newPromise());
1200+
} catch (Exception e) {
1201+
onError(ctx, /* outbound= */ true, e);
1202+
}
1203+
}
1204+
},
1205+
GRACEFUL_SHUTDOWN_DRAIN_NANOS,
1206+
TimeUnit.NANOSECONDS);
1207+
}
1208+
1209+
void cancelDrain() {
1210+
if (drainFuture != null) {
1211+
drainFuture.cancel(false);
1212+
}
11511213
}
11521214

11531215
private long graceTimeOverrideMillis(long originalMillis) {
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
/*
2+
* Copyright 2026 The gRPC Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.grpc.netty;
18+
19+
import static com.google.common.truth.Truth.assertThat;
20+
21+
import com.google.common.io.ByteStreams;
22+
import io.grpc.CallOptions;
23+
import io.grpc.ManagedChannel;
24+
import io.grpc.MethodDescriptor;
25+
import io.grpc.Server;
26+
import io.grpc.ServerServiceDefinition;
27+
import io.grpc.stub.ClientCalls;
28+
import io.grpc.stub.ServerCalls;
29+
import io.grpc.testing.GrpcCleanupRule;
30+
import io.netty.channel.EventLoopGroup;
31+
import io.netty.channel.MultiThreadIoEventLoopGroup;
32+
import io.netty.channel.nio.NioIoHandler;
33+
import io.netty.channel.socket.nio.NioSocketChannel;
34+
import java.io.ByteArrayInputStream;
35+
import java.io.IOException;
36+
import java.io.InputStream;
37+
import java.net.InetAddress;
38+
import java.net.InetSocketAddress;
39+
import java.util.concurrent.TimeUnit;
40+
import java.util.concurrent.atomic.AtomicReference;
41+
import org.junit.Rule;
42+
import org.junit.Test;
43+
import org.junit.runner.RunWith;
44+
import org.junit.runners.JUnit4;
45+
46+
/**
47+
* Regression test for https://github.com/grpc/grpc-java/issues/9566: a unary RPC that the server
48+
* completed must not fail because the server closed the connection after a max-age GOAWAY.
49+
*
50+
* <p>The client's event loop is stalled while the server sends the response, so the response is
51+
* still unread in the server's kernel send buffer when the server would close the connection. If
52+
* the server closes it then, the client's next frame (a BDP PING or WINDOW_UPDATE) makes the
53+
* server's kernel answer with RST, which discards the unsent trailers. This depends on the kernel:
54+
* without the fix it fails on Linux, while macOS loopback does not lose the data.
55+
*/
56+
@RunWith(JUnit4.class)
57+
public class NettyServerGracefulCloseTest {
58+
private static final int RESPONSE_BYTES = 256 * 1024;
59+
private static final int ITERATIONS = 3;
60+
private static final long CLIENT_STALL_MILLIS = 300;
61+
62+
private static final MethodDescriptor.Marshaller<byte[]> BYTES =
63+
new MethodDescriptor.Marshaller<byte[]>() {
64+
@Override
65+
public InputStream stream(byte[] value) {
66+
return new ByteArrayInputStream(value);
67+
}
68+
69+
@Override
70+
public byte[] parse(InputStream stream) {
71+
try {
72+
return ByteStreams.toByteArray(stream);
73+
} catch (IOException e) {
74+
throw new RuntimeException(e);
75+
}
76+
}
77+
};
78+
79+
private static final MethodDescriptor<byte[], byte[]> METHOD =
80+
MethodDescriptor.<byte[], byte[]>newBuilder()
81+
.setType(MethodDescriptor.MethodType.UNARY)
82+
.setFullMethodName("test.Test/Get")
83+
.setRequestMarshaller(BYTES)
84+
.setResponseMarshaller(BYTES)
85+
.build();
86+
87+
@Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
88+
89+
private final AtomicReference<EventLoopGroup> clientGroup = new AtomicReference<>();
90+
91+
@Test
92+
public void maxConnectionAge_unaryCallInFlight_succeeds() throws Exception {
93+
ServerServiceDefinition service = ServerServiceDefinition.builder("test.Test")
94+
.addMethod(METHOD, ServerCalls.asyncUnaryCall((request, responseObserver) -> {
95+
// Outlive the max age (1 second plus up to 10% jitter), so both GOAWAYs are sent while
96+
// the call is in flight.
97+
sleep(1500);
98+
clientGroup.get().execute(() -> sleep(CLIENT_STALL_MILLIS));
99+
responseObserver.onNext(new byte[RESPONSE_BYTES]);
100+
responseObserver.onCompleted();
101+
}))
102+
.build();
103+
Server server = grpcCleanup.register(
104+
NettyServerBuilder.forAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0))
105+
.maxConnectionAge(1, TimeUnit.SECONDS)
106+
.maxConnectionAgeGrace(30, TimeUnit.SECONDS)
107+
.addService(service)
108+
.build()
109+
.start());
110+
111+
for (int i = 0; i < ITERATIONS; i++) {
112+
EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory());
113+
clientGroup.set(group);
114+
ManagedChannel channel = NettyChannelBuilder
115+
.forAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), server.getPort()))
116+
.channelType(NioSocketChannel.class)
117+
.eventLoopGroup(group)
118+
.usePlaintext()
119+
.build();
120+
try {
121+
byte[] response =
122+
ClientCalls.blockingUnaryCall(channel, METHOD, CallOptions.DEFAULT, new byte[16]);
123+
assertThat(response).hasLength(RESPONSE_BYTES);
124+
} finally {
125+
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
126+
group.shutdownGracefully(0, 1, TimeUnit.SECONDS).sync();
127+
}
128+
}
129+
}
130+
131+
private static void sleep(long millis) {
132+
try {
133+
Thread.sleep(millis);
134+
} catch (InterruptedException e) {
135+
Thread.currentThread().interrupt();
136+
}
137+
}
138+
}

‎netty/src/test/java/io/grpc/netty/NettyServerHandlerTest.java‎

Lines changed: 71 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,9 @@ public void closeShouldGracefullyCloseChannel() throws Exception {
367367
verifyWrite().writeGoAway(eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()),
368368
isA(ByteBuf.class), any(ChannelPromise.class));
369369

370-
// Verify that the channel was closed.
370+
// channel stays open while draining, then closes
371+
assertTrue(channel().isOpen());
372+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
371373
assertFalse(channel().isOpen());
372374
}
373375

@@ -389,7 +391,9 @@ public void gracefulCloseShouldGracefullyCloseChannel() throws Exception {
389391
verifyWrite().writeGoAway(eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()),
390392
isA(ByteBuf.class), any(ChannelPromise.class));
391393

392-
// Verify that the channel was closed.
394+
// channel stays open while draining, then closes
395+
assertTrue(channel().isOpen());
396+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
393397
assertFalse(channel().isOpen());
394398
}
395399

@@ -418,6 +422,8 @@ public void secondGracefulCloseIsSafe() throws Exception {
418422
channelRead(pingFrame(/*ack=*/ true , NettyServerHandler.GRACEFUL_SHUTDOWN_PING));
419423
verifyWrite().writeGoAway(eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()),
420424
isA(ByteBuf.class), any(ChannelPromise.class));
425+
assertTrue(channel().isOpen());
426+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
421427
assertFalse(channel().isOpen());
422428
}
423429

@@ -1058,7 +1064,9 @@ public void maxConnectionIdle_goAwaySent_pingAck() throws Exception {
10581064
verifyWrite().writeGoAway(
10591065
eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
10601066
any(ChannelPromise.class));
1061-
// channel closed
1067+
// channel stays open while draining, then closes
1068+
assertTrue(channel().isOpen());
1069+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
10621070
assertFalse(channel().isOpen());
10631071
}
10641072

@@ -1088,7 +1096,9 @@ public void maxConnectionIdle_goAwaySent_pingTimeout() throws Exception {
10881096
verifyWrite().writeGoAway(
10891097
eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
10901098
any(ChannelPromise.class));
1091-
// channel closed
1099+
// channel stays open while draining, then closes
1100+
assertTrue(channel().isOpen());
1101+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
10921102
assertFalse(channel().isOpen());
10931103
}
10941104

@@ -1132,7 +1142,9 @@ public void maxConnectionIdle_activeThenRst_pingAck() throws Exception {
11321142
verifyWrite().writeGoAway(
11331143
eq(ctx()), eq(STREAM_ID), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
11341144
any(ChannelPromise.class));
1135-
// channel closed
1145+
// channel stays open while draining, then closes
1146+
assertTrue(channel().isOpen());
1147+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
11361148
assertFalse(channel().isOpen());
11371149
}
11381150

@@ -1176,7 +1188,9 @@ public void maxConnectionIdle_activeThenRst_pingTimeoutk() throws Exception {
11761188
verifyWrite().writeGoAway(
11771189
eq(ctx()), eq(STREAM_ID), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
11781190
any(ChannelPromise.class));
1179-
// channel closed
1191+
// channel stays open while draining, then closes
1192+
assertTrue(channel().isOpen());
1193+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
11801194
assertFalse(channel().isOpen());
11811195
}
11821196

@@ -1230,7 +1244,9 @@ public void maxConnectionAge_goAwaySent_pingAck() throws Exception {
12301244
verifyWrite().writeGoAway(
12311245
eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
12321246
any(ChannelPromise.class));
1233-
// channel closed
1247+
// channel stays open while draining, then closes
1248+
assertTrue(channel().isOpen());
1249+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
12341250
assertFalse(channel().isOpen());
12351251
}
12361252

@@ -1261,7 +1277,54 @@ public void maxConnectionAge_goAwaySent_pingTimeout() throws Exception {
12611277
verifyWrite().writeGoAway(
12621278
eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
12631279
any(ChannelPromise.class));
1264-
// channel closed
1280+
// channel stays open while draining, then closes
1281+
assertTrue(channel().isOpen());
1282+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
1283+
assertFalse(channel().isOpen());
1284+
}
1285+
1286+
@Test
1287+
public void maxConnectionAge_drainStartsWhenLastStreamCloses() throws Exception {
1288+
maxConnectionAgeInNanos = TimeUnit.MILLISECONDS.toNanos(10L);
1289+
manualSetUp();
1290+
createStream();
1291+
1292+
fakeClock().forwardNanos(maxConnectionAgeInNanos);
1293+
channelRead(pingFrame(true /* isAck */, NettyServerHandler.GRACEFUL_SHUTDOWN_PING));
1294+
1295+
// second GO_AWAY sent
1296+
verifyWrite().writeGoAway(
1297+
eq(ctx()), eq(STREAM_ID), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
1298+
any(ChannelPromise.class));
1299+
// stream still active, so the drain has not started
1300+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS);
1301+
assertTrue(channel().isOpen());
1302+
1303+
channelRead(rstStreamFrame(STREAM_ID, (int) Http2Error.CANCEL.code()));
1304+
1305+
// the peer may still be reading the response and sending WINDOW_UPDATE or PING
1306+
fakeClock().forwardNanos(NettyServerHandler.GRACEFUL_SHUTDOWN_DRAIN_NANOS - 1);
1307+
assertTrue(channel().isOpen());
1308+
fakeClock().forwardNanos(1);
1309+
assertFalse(channel().isOpen());
1310+
}
1311+
1312+
@Test
1313+
public void maxConnectionAgeGrace_shorterThanDrain_closesAtGrace() throws Exception {
1314+
maxConnectionAgeInNanos = TimeUnit.MILLISECONDS.toNanos(10L);
1315+
maxConnectionAgeGraceInNanos = TimeUnit.MILLISECONDS.toNanos(100L);
1316+
manualSetUp();
1317+
1318+
fakeClock().forwardNanos(maxConnectionAgeInNanos);
1319+
channelRead(pingFrame(true /* isAck */, NettyServerHandler.GRACEFUL_SHUTDOWN_PING));
1320+
1321+
// second GO_AWAY sent
1322+
verifyWrite().writeGoAway(
1323+
eq(ctx()), eq(0), eq(Http2Error.NO_ERROR.code()), any(ByteBuf.class),
1324+
any(ChannelPromise.class));
1325+
fakeClock().forwardTime(99, TimeUnit.MILLISECONDS);
1326+
assertTrue(channel().isOpen());
1327+
fakeClock().forwardTime(1, TimeUnit.MILLISECONDS);
12651328
assertFalse(channel().isOpen());
12661329
}
12671330

0 commit comments

Comments
 (0)