Nginx upstream keepalive with PHP-FPM: worth configuring
Found this in some performance guide:
upstream phpfpm {
server unix:/run/php/php8.2-fpm.sock;
keepalive 32;
}
And in the location block:
fastcgi_keep_conn on;
Has anyone benchmarked this? The docs say it keeps TCP connections alive but FPM uses Unix sockets here anyway.
With Unix sockets the keepalive benefit is smaller than with TCP because you are not paying TCP handshake cost. But you still save the socket open/close syscall overhead and the FastCGI connection setup. On high-traffic sites the aggregate saving is measurable.
We benchmarked this: on a 1000 req/s server, keepalive 32 dropped p99 latency by about 8ms and reduced CPU by 3%. Not dramatic but free.
The keepalive value should be roughly equal to the number of Nginx worker connections that hit FPM concurrently. Too low and you create new connections anyway. Too high and you hold idle connections that waste FPM slots.
Make sure pm.max_children is higher than your keepalive value, otherwise the pool runs out of workers serving idle keepalive connections instead of real requests.