Skip to content

Nginx upstream keepalive — tuning the connection pool between proxy and backend

Most Nginx reverse proxies leave the upstream keepalive pool at zero by default. A short run-through of what to set, why, and how the math actually works.

A reverse-proxy Nginx in front of three upstream PHP-FPM nodes was burning 8000 TCP connects per second to the backends — even though it was only serving 1200 requests per second to clients. The difference was the missing keepalive directive in the upstream block. This article is the walkthrough we use when a proxy that should be cheap is somehow consuming an entire CPU core on socket setup, and what to set for an HTTP/1.1 upstream pool.

How to verify

Confirm whether your current proxy is reusing connections at all:

# Connections from Nginx to a specific upstream IP, by state
ss -ntop "( dst 10.0.1.21 )" | awk '{print $1}' | sort | uniq -c

# Per-second new-connection rate to the upstream port
sar -n TCP 1 5 | awk 'NR>3 {print $3}'

# nginx-vts or stub_status shows reuse if keepalive is configured
curl -s http://127.0.0.1:8080/status | grep -E 'reading|writing|waiting'

# Quick proof: tail upstream_response_time vs request_time
tail -F /var/log/nginx/access.log | awk '{print $NF, $(NF-1)}'

If ss shows hundreds of TIME-WAIT sockets to backend IPs and the upstream port jumps with every request, the pool isn’t being used. A healthy pool shows a small, mostly-stable count of ESTAB connections per worker.

What’s happening

By default an Nginx proxy_pass opens a fresh TCP connection (and a fresh TLS handshake, if https://) for each request and closes it after the upstream response. That’s fine at 50 requests per second per worker. It’s expensive at 5000.

The keepalive directive inside an upstream block tells Nginx to keep a pool of idle, already-open connections to each backend, ready to be reused. The pool is per-worker, per-upstream-server. A worker with keepalive 32; and three backend servers in the pool may hold up to 96 idle connections at peak.

Three settings work together:

  • keepalive N — maximum idle connections per worker per upstream server. Not a target, a ceiling. Sized to your concurrency, not your RPS.
  • keepalive_requests N — how many requests a single pooled connection can serve before being closed. Default is 1000. Raising it lets you amortize the connection cost over more requests but lets a stuck connection (mismatched timeouts, server-side state leak) persist longer.
  • keepalive_timeout T — how long an idle pooled connection survives before Nginx closes it. Default 60s. Make sure it’s shorter than the backend’s own idle timeout, or the backend will close first and your next request will see a connection-reset error.

The other half is the proxy_http_version and Connection header. HTTP/1.0 connections don’t keep-alive by default, and proxy_set_header Connection "" is what clears the inbound Connection: close so the upstream connection can be reused. Without these two lines, the keepalive directive does nothing.

The procedure

  1. Add a keepalive pool to your upstream block. Size N to roughly the per-worker concurrency you expect to a given backend at peak:

    upstream app_backend {
        server 10.0.1.21:8080 max_fails=2 fail_timeout=10s;
        server 10.0.1.22:8080 max_fails=2 fail_timeout=10s;
        server 10.0.1.23:8080 max_fails=2 fail_timeout=10s;
    
        keepalive 32;
        keepalive_requests 10000;
        keepalive_timeout 60s;
    }

    A worker handling 200 concurrent requests spread across 3 backends needs roughly 200/3 ~= 67 connections in flight; a pool of 32 idle on top of those reuses well. Pool size of 8 starves the reuse, pool size of 512 wastes file descriptors.

  2. Force HTTP/1.1 and clear the inbound Connection header in the location block:

    location / {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    These two lines (proxy_http_version 1.1; and proxy_set_header Connection "";) are non-negotiable. Without them, every reused connection is closed by the backend after one request because the request still says “Connection: close” downstream.

  3. Align the backend’s idle timeout to be longer than Nginx’s. If Nginx holds connections for 60s and the backend closes after 30s, you’ll see intermittent 502s under low load (the connection was already half-closed when Nginx tried to reuse it). On a PHP-FPM backend behind another Nginx, set the backend’s keepalive_timeout to 75 seconds. On Tomcat, connectionTimeout="75000". On a Node/Express upstream, server.keepAliveTimeout = 75000 and server.headersTimeout = 76000.

  4. Reload and watch the connection rate drop. Use nginx -t && nginx -s reload, then watch ss -s to confirm the established count to upstream IPs stabilizes around the pool size rather than spiking with each request:

    watch -n1 'ss -ntp state established "( dport = :8080 )" | wc -l'

    A correctly-sized pool sits at a near-constant number even as RPS doubles. The TIME-WAIT count to upstream IPs drops to near zero — TIME-WAIT only happens on the side that initiated the close, and a reused connection doesn’t close.

  5. Wire metrics. The two numbers worth alerting on are upstream_connect_time (should be near-zero microseconds for pooled requests) and the per-upstream reuse rate. With nginx-vts or nginx_prometheus_exporter, plot nginx_upstream_response_time vs nginx_upstream_request_time — the gap is your connection-setup overhead. If the gap grows, your pool is exhausted.

Operational notes

  • The pool is per-worker, not per-process. With worker_processes 8;, the effective max is 8 * keepalive * upstream-server-count. Don’t multiply your way into upstream file-descriptor exhaustion — count it.
  • keepalive_requests defaults to 1000. Raise to 10000 for stable PHP-FPM or Java backends; keep at 1000 for backends that leak state per connection (some legacy app servers).
  • HTTPS upstreams (server backend.internal:443; with proxy_pass https://...) amplify the win — TLS handshakes are the expensive part. The pool also caches the TLS session, so reused connections skip the handshake entirely.
  • Connection pools don’t help health checks. A backend marked unhealthy is removed from the pool but its sockets are kept until the next idle scan. Set fail_timeout and max_fails for fast eviction.
  • A pool sized larger than the backend’s max concurrency just gives you slow refusals. If the backend caps at 100 concurrent and you hold 200 idle on the proxy side, the next 100 requests will see EAGAIN-style backpressure once the pool is fully active.

Stack Harbor tunes Nginx pools as part of how we operate proxy fleets — sized to the workload, monitored end-to-end, with the upstream and the downstream timeouts kept in sync so deploys don’t introduce 502s. If you’re seeing connection-storm symptoms in front of an otherwise healthy backend, we cover this on the managed operations side of the house.