Nginx closes the upstream connection after a period of time
Author: leaner1000Created Oct 16, 2025Updated Sep 18, 2026
Labelsquestionwaiting-for-response
Environment
Nginx version: 1.27.1 OS kernel version: linux
Description
I want to use the gRPC keep-alive feature with Nginx, so I configured the keepalive parameters. However, this did not work, and the connection from Nginx to the server was rebuilt after about 18 seconds because Nginx sent a RST packet. After debugging, I found that in ngx_http_upstream_keepalive_module.c, the connection is closed regardless of whether the read is successful or not.
c->read->handler = ngx_http_upstream_keepalive_close_handler;static void
ngx_http_upstream_keepalive_close_handler(ngx_event_t *ev)
{
ngx_http_upstream_keepalive_srv_conf_t *conf;
ngx_http_upstream_keepalive_cache_t *item;
int n;
char buf[1];
ngx_connection_t *c;
ngx_log_debug0(NGX_LOG_DEBUG_HTTP, ev->log, 0,
"keepalive close handler");
c = ev->data;
if (c->close || c->read->timedout) {
goto close;
}
n = recv(c->fd, buf, 1, MSG_PEEK);
if (n == -1 && ngx_socket_errno == NGX_EAGAIN) {
ev->ready = 0;
if (ngx_handle_read_event(c->read, 0) != NGX_OK) {
goto close;
}
return;
}
close:
item = c->data;
conf = item->conf;
ngx_http_upstream_keepalive_close(c);
ngx_queue_remove(&item->queue);
ngx_queue_insert_head(&conf->free, &item->queue);
}Whether recv returns a value greater than 0 or not, we will always reach the close block. Should we put the return statement outside the parentheses? After making this change, the problem seems to have disappeared in my environment.
Source: nginx/nginx