Sub topic 9
Reusing upstream connections with keepalive
This chapter explains why Nginx opens a new TCP connection to a backend for every request by default, how the keepalive directive changes that, and which settings you need for it to work. It assumes you can read an upstream block, you know what proxy_pass does, and you understand the HTTP/1.1 Connection header. It builds on the upstream group example from the earlier chapters.
Why connection reuse matters
Nginx handles two separate connections for each proxied request:
- The client connection, from the browser to Nginx.
- The upstream connection, from Nginx to your application.
Client-side keepalive is on by default and is controlled by keepalive_timeout. The upstream side behaves differently. By default Nginx opens a new TCP connection to the backend for each request and closes it when the response ends. This has three costs:
- Every request pays for a TCP handshake, which is at least one round trip. If the backend link is also TLS, the TLS handshake adds more.
- Closed connections leave sockets in the
TIME_WAITstate on the Nginx host. Under heavy traffic to a few backends, you can run out of ephemeral ports. - The backend spends CPU on accepting and closing connections instead of serving requests.
On a local loopback or fast LAN the handshake is cheap, so you may not notice. The problem shows up under high request rates, with backends in another zone, or with TLS to the backend.
Two requirements for reuse
Two things must be true before Nginx can keep an upstream connection open:
- The
upstreamblock must have akeepalivedirective. It sets how many idle connections each worker process keeps cached. - The request to the backend must use HTTP/1.1 and must not send
Connection: close.
Nginx talks to backends over HTTP/1.0 by default. HTTP/1.0 has no persistent connections by default. Also, when proxy_pass is used, Nginx sets Connection: close on the upstream request unless you override it. So you need three lines, not one.
The upstream group from this tutorial already contains the first piece:
upstream app_backend {
least_conn;
server 10.0.0.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.13:8080 backup;
keepalive 32;
}
server {
listen 80;
server_name example.com;
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;
proxy_next_upstream error timeout http_502 http_503;
}
}Here is what each part does:
keepalive 32;keeps up to 32 idle connections per worker process in a cache.proxy_http_version 1.1;makes Nginx speak HTTP/1.1 to the backend.proxy_set_header Connection "";removes theConnection: closeheader that Nginx would otherwise send. An empty value means the header is not sent at all.
If you leave out either of the last two, the keepalive line has no effect. Nginx does not warn you. The configuration passes nginx -t and the proxy works, just without reuse.
How the connection cache works
The cache is a pool of idle connections. When a request needs an upstream server, Nginx first picks a server using the load-balancing method. It then looks in the cache for an idle connection to that server. If one exists, it uses it. If not, it opens a new one.
When the response is finished and the backend allows reuse, the connection goes back into the cache. If the cache is already full, Nginx closes the least recently used idle connection to make room.
Three details are easy to get wrong.
The number is per worker, not global
The keepalive value applies to each worker process separately. With worker_processes 4; and keepalive 32;, Nginx can hold up to 128 idle connections across the pool. Each backend must be able to accept these on top of its active connections. If a backend limits connections (for example, a small max_connections or a file descriptor limit), count workers times keepalive when you size it.
It limits idle connections, not total connections
The keepalive directive does not cap how many connections Nginx opens to a backend. If 500 requests arrive at once and the cache is empty, Nginx opens 500 connections. Only the idle ones that remain after the burst are limited to the cache size. To cap total connections to a server, use the max_conns parameter on the server line (see the note below). Without max_conns, a traffic spike can still exceed your backend's capacity.
The load-balancing method must come before keepalive
For methods other than round robin, the method directive (least_conn, ip_hash, hash) must appear in the upstream block before keepalive. The example above follows this order. Placing it after keepalive is a configuration error in older versions. Keeping the method first is the safe convention.
Choosing a keepalive size
A reasonable starting point is a small number compared to peak concurrency. You want enough idle connections to absorb ordinary request rates, not enough to hold a connection for every possible client.
A common rule of thumb:
- Estimate the number of concurrent upstream requests per worker at normal load.
- Set
keepaliveto about that value, often between 16 and 64. - Watch connection counts on the backend and adjust.
If the number is too low, bursts cause connections to be opened and closed repeatedly, which loses the benefit. If it is too high, you hold idle sockets on the backend that it could use elsewhere, and a backend with a small connection limit may refuse new clients.
Tuning idle lifetime
Nginx 1.15.3 added two more directives in the upstream block. They bound how long a connection may live.
| Directive | Default | Meaning |
|---|---|---|
| `keepalive_timeout` | 60s | How long an idle connection stays in the cache before Nginx closes it. |
| `keepalive_requests` | 1000 (100 before 1.19.10) | Maximum number of requests served over one connection before it is closed. |
| `keepalive_time` | 1h | Maximum total lifetime of a connection, added in 1.19.10. |
These are separate from the same-named directives for client connections. Inside upstream they affect only the Nginx-to-backend side.
The idle timeout should be shorter than the backend's own idle timeout. If the backend closes an idle connection at 5 seconds and Nginx tries to reuse it at 6 seconds, the request fails or is retried. For example, many application servers close idle connections after a short time. Set the Nginx value below that:
upstream app_backend {
least_conn;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
keepalive 32;
keepalive_timeout 4s;
keepalive_requests 1000;
}A failure mode: race with backend close
Even with a shorter timeout, a race exists. The backend can close an idle connection at the same moment Nginx sends a request on it. Nginx sees a reset or an empty reply. For idempotent requests such as GET, Nginx can retry on another connection through proxy_next_upstream. For a POST, Nginx does not retry by default because the backend may have processed it.
Signs of this problem in the error log are messages like upstream prematurely closed connection while reading response header or recv() failed (104: Connection reset by peer), appearing at a low, steady rate rather than in bursts. The fix is to lower the Nginx keepalive_timeout below the backend's idle timeout, or raise the backend's.
Verifying that reuse works
After changing the configuration, validate and reload it:
sudo nginx -t && sudo systemctl reload nginxThen check the sockets from the Nginx host while you send traffic. This command counts established connections to one backend:
ss -tn state established '( dport = :8080 )' dst 10.0.0.11 | wc -lWith keepalive working, the count stays near a stable small number and the sockets keep the same source ports between checks. Without it, ss -tn state time-wait dst 10.0.0.11 | wc -l grows quickly while you send load.
You can also see the effect in the access log. Add $upstream_connect_time to the log format from the logging chapter. Reused connections report a connect time of 0.000, while new ones show the handshake time.
log_format upstream_log '$remote_addr [$time_local] "$request" $status '
'upstream=$upstream_addr '
'upstream_status=$upstream_status '
'uct=$upstream_connect_time '
'urt=$upstream_response_time rt=$request_time';
access_log /var/log/nginx/proxy_access.log upstream_log;Common mistakes
| Symptom | Likely cause |
|---|---|
| `TIME_WAIT` sockets keep growing | Missing `proxy_http_version 1.1` or `Connection ""`, or `keepalive` not set. |
| Occasional 502 with "prematurely closed connection" | Backend idle timeout shorter than Nginx's `keepalive_timeout`. |
| Backend hits its connection limit | `keepalive` times worker count is larger than the backend allows, or no `max_conns` on bursts. |
| `nginx -t` rejects the config | `keepalive` placed outside an `upstream` block, or method directive after it. |
| No effect with WebSockets | Upgrade requests need their own `Connection` header, covered in the WebSocket chapter. |
Keepalive with a single backend
You can use keepalive with an upstream that has only one server. If you proxy to a single application, define an upstream with one server line and a keepalive value. A bare proxy_pass http://127.0.0.1:3000; does not use the connection cache, because the cache belongs to upstream groups.
upstream single_app {
server 127.0.0.1:3000;
keepalive 16;
}Point proxy_pass at http://single_app and keep the two proxy_http_version and Connection lines in the location.
Exercise
A location proxies to upstream app_backend, which contains keepalive 32;. After a load test you still see thousands of TIME_WAIT sockets on the Nginx host, and nginx -t reports no errors. The location contains only proxy_pass http://app_backend; and the Host header line. What is missing, and why does Nginx not report an error?
Show answer
The location needs proxy_http_version 1.1; and proxy_set_header Connection "";. By default Nginx speaks HTTP/1.0 to the backend and sends Connection: close, so every upstream connection is closed after one request and nothing is returned to the cache. nginx -t only checks syntax and directive placement, and the configuration is valid, so the missing reuse produces no error.
Exercise
Your backend closes idle connections after 5 seconds. You see a low, steady rate of 502 errors with "upstream prematurely closed connection". What change fixes it, and which directive do you edit?
Show answer
Set keepalive_timeout inside the upstream block to a value below 5 seconds, such as 4s, so Nginx discards idle connections before the backend closes them. Alternatively, raise the backend's idle timeout above Nginx's value.