grpc_socket_keepalive
The grpc_socket_keepalive directive enables TCP keepalive for gRPC connections in NGINX.
Description
The grpc_socket_keepalive directive is used to enable or disable the TCP keepalive feature for gRPC connections handled by NGINX. When enabled, this directive ensures that idle TCP connections remain active by sending periodic keepalive probes. This is essential for maintaining long-lived connections, which are commonly used in gRPC for service-to-service communication. By default, many operating systems may not have TCP keepalive enabled, which could result in closed connections and interruptions in communication after a period of inactivity.
This directive accepts a flag value, meaning it can be set to either 'on' (enabled) or 'off' (disabled). When set to 'on', NGINX will configure the socket options for keepalive, allowing it to send keepalive packets out as per the settings defined in the system (such as the tcp_keepalive_time, tcp_keepalive_intvl, and tcp_keepalive_probes options). Thus, adjusting these parameters at the system level is also necessary to ensure that keepalive behaves as expected. Note that enabling this feature without proper server settings may lead to performance issues or unnecessary network traffic, especially in high-scale environments.
Config Example
server {
listen 80;
grpc_socket_keepalive on;
location /myservice {
grpc_pass grpc://backend;
}
}Ensure that your operating system's TCP keepalive settings are configured appropriately, as NGINX relies on them to manage keepalive packets.
Do not enable keepalive on short-lived connections, as it might lead to performance overhead without significant benefits.