gRPC服务端流式连接60秒无活动断连问题排查与解决
问题背景
我在搭建支持向客户端流式推送事件的gRPC API,核心逻辑是客户端完成订阅后,服务端借助gRPC的服务端流式能力推送所有新增事件。原本预期连接在空闲周期内会保持激活状态,但当前环境下无活动满60秒就会被切断,客户端抛出如下异常:
Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: An error occurred while sending the request. IOException: The request was aborted. IOException: The response ended prematurely, with at least 9 additional bytes expected.", DebugException="System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.IO.IOException: The request was aborted. ---> System.IO.IOException: The response ended prematurely, with at least 9 additional bytes expected.
核心疑问
- 该断连现象的根本原因是什么?
- 如何避免连接被异常切断?
部署环境
- API基于ASP.NET Core 3开发(计划近期升级至.NET 5),运行在Digital Ocean服务器的Docker容器中
- Nginx同样部署在该服务器的Docker容器内,作为API及其他服务的反向代理
- 客户端是基于.NET Core开发的简易C#程序,在本地运行
排查过程
一开始我尝试用grpc_cli直连服务器上Docker容器内的服务(绕过Nginx),空闲很长时间连接都能保持正常,因此初步怀疑问题出在Nginx侧,同时注意到Nginx多数默认超时配置为60秒。
我尝试了多种Nginx配置组合做调试,始终没找到有效方案,实际测试过的配置片段如下:
location /commands.CommandService/ { grpc_pass grpc://commandApi; grpc_socket_keepalive on; grpc_read_timeout 3000s; # 网上通用推荐的配置,实际对我的场景无效 grpc_send_timeout 3000s; grpc_next_upstream_timeout 0; proxy_request_buffering off; proxy_buffering off; proxy_connect_timeout 3000s; proxy_send_timeout 3000s; proxy_read_timeout 3000s; proxy_socket_keepalive on; keepalive_timeout 90s; send_timeout 90s; client_body_timeout 3000s; }
遇到同类问题的开发者最常建议调整grpc_read_timeout和grpc_send_timeout参数,但这些配置对我的场景不生效——考虑到当前场景下没有主动收发数据,这一现象也合乎逻辑。
我使用的客户端代码如下:
var httpClientHandler = new HttpClientHandler(); var channel = GrpcChannel.ForAddress("https://myapi.com", new GrpcChannelOptions() { HttpClient = new HttpClient(httpClientHandler) { Timeout = Timeout.InfiniteTimeSpan }, }); var commandService = channel.CreateGrpcService<ICommandService>(); var request = new CommandSubscriptionRequest() { HandlerId = _handlerId }; var sd = new CancellationTokenSource(); var r = new CallContext(callOptions: new CallOptions(deadline: null, cancellationToken: sd.Token)); await foreach (var command in commandService.SubscribeCommandsAsync(request, r)) { Console.WriteLine("Processing command: " + command.Id); } return channel;
这里明确几点实际表现:
- API调用链路本身是正常的,可正常接收服务端推送的命令
- 只要服务端持续推送命令,所有功能都运行正常
- 一旦停止推送达到60秒(已计时验证),连接就会断开
可行的临时方案是持续发送心跳包保持连接,但我希望找到更根本的解决方案,因此疑惑是否遗漏了关键配置。
最终验证结论
后续排查发现问题根源并非Nginx,在将API和客户端升级至.NET 5后问题直接消失,虽无法明确该问题是在哪个.NET版本被修复的,但至少在.NET 5环境下该问题不再出现。
内容的提问来源于stack exchange,提问作者MAV
相关产品推荐
相关产品推荐

