Timeouts, Buffers, Retries & Keepalive
A proxy's defaults are tuned for "a typical website". APIs with slow reports, streaming endpoints, uploads and flaky backends each need different settings, and the wrong ones show up as 502/504 errors, doubled payments or truncated streams. This lesson goes through the four groups of proxy_* settings that matter most.
Timeouts: who gives up first
| Directive | Default | Limits |
|---|---|---|
proxy_connect_timeout |
60s | establishing the TCP connection to the backend (keep it short: 1–5 s) |
proxy_send_timeout |
60s | time between two successive writes to the backend |
proxy_read_timeout |
60s | time between two successive reads from the backend (not the whole response!) |
client_body_timeout / client_header_timeout |
60s | the client sending its request |
send_timeout |
60s | between two writes to the client |
keepalive_timeout |
75s | idle client keep-alive connections |
When the backend is slower than proxy_read_timeout, Nginx answers 504 Gateway Timeout; when it can't connect or the backend closes the connection, 502 Bad Gateway. Timeouts must also be ordered along the chain: if a cloud load balancer in front of Nginx times out at 60 s and Nginx waits 120 s, the client sees the load balancer's error, and Nginx and the app keep working on a request nobody is waiting for. Set each layer's timeout slightly shorter than the layer in front of it.
Retries: proxy_next_upstream
When a request fails, Nginx can try the next server. proxy_next_upstream says which failures count:
| Value | Retry when |
|---|---|
error (default) |
connecting, sending or reading the header failed |
timeout (default) |
a timeout happened while connecting, sending or reading the header |
http_500, http_502, http_503, http_504, http_429 |
the backend answered with that status |
non_idempotent |
also retry POST, LOCK, PATCH (off by default: a retried payment may be charged twice) |
off |
never retry |
Bound retries with proxy_next_upstream_tries 2; and proxy_next_upstream_timeout 5s;, or a dead tier turns every request into N attempts × the timeout. Here one backend is broken (returns 500 on everything) and one healthy, with a slow endpoint thrown in:
cat > app.py <<'EOF'
import sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/slow": time.sleep(3)
code = 500 if sys.argv[2] == "broken" else 200
self.send_response(code); self.end_headers(); self.wfile.write(f"{sys.argv[2]} {code}\n".encode())
do_POST = do_GET
def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 broken &
python3 app.py 9002 healthy &
for p in 9001 9002; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
access_log off;
upstream app { server 127.0.0.1:9001 max_fails=0; server 127.0.0.1:9002 max_fails=0; }
server {
listen 127.0.0.1:8080;
location /plain/ { proxy_pass http://app/; }
location /retry/ {
proxy_pass http://app/;
proxy_next_upstream error timeout http_500;
proxy_next_upstream_tries 2;
}
location /timeout/ { proxy_pass http://127.0.0.1:9002/; proxy_read_timeout 1s; }
}
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "plain GET: $(for i in 1 2 3 4; do curl -s 127.0.0.1:8080/plain/; done | tr '\n' ' ')"
echo "retry GET: $(for i in 1 2 3 4; do curl -s 127.0.0.1:8080/retry/; done | tr '\n' ' ')"
echo "retry POST: $(for i in 1 2 3 4; do curl -s -X POST 127.0.0.1:8080/retry/; done | tr '\n' ' ')"
curl -s -o /dev/null -w "slow backend: %{http_code}\n" 127.0.0.1:8080/timeout/slow
grep -o 'upstream timed out[^,]*' error.log
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1 %2plain GET: broken 500 healthy 200 broken 500 healthy 200
retry GET: healthy 200 healthy 200 healthy 200 healthy 200
retry POST: broken 500 healthy 200 broken 500 healthy 200
slow backend: 504
upstream timed out (110: Connection timed out) while reading response header from upstream
Without retries, every second client got the broken server's 500. With http_500 in proxy_next_upstream, GETs were retried on the healthy server and all succeeded. POSTs were not retried, which is the safe default: Nginx can't know whether the broken server already performed the action. Retrying on http_500 is only reasonable for idempotent reads; for most APIs, error timeout (the default) plus real health checks is the better design.
(max_fails=0 disables passive failure marking here so the round-robin pattern stays visible; in production, leave it on.)
Buffering
By default Nginx buffers the backend's response: it reads it as fast as the backend sends it (into memory buffers, then a temp file), frees the backend, and feeds the client at the client's speed. That protects app workers from slow clients and is right for almost everything. Turn it off where data must flow immediately:
location /events/ { # Server-Sent Events, long polling, streaming LLM tokens
proxy_pass http://app;
proxy_buffering off; # or have the app send "X-Accel-Buffering: no"
proxy_read_timeout 1h;
}
location /upload/ {
client_max_body_size 200m;
proxy_request_buffering off; # stream the upload to the backend as it arrives
}proxy_buffers 8 4k; and proxy_buffer_size 4k; (the header buffer) are per connection; a backend that sends huge headers (big cookies, long JWTs) causes upstream sent too big header and a 502 until proxy_buffer_size is raised.
Keepalive to the backends
Without configuration, Nginx opens a new TCP connection to the backend for every request and closes it afterwards (it speaks HTTP/1.0 upstream by default). At a few thousand requests per second that is thousands of handshakes and TIME_WAIT sockets per second. The fix is three lines; the backend below counts the distinct TCP connections it saw:
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
conns = set()
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1" # allows persistent connections
def do_GET(self):
if self.path == "/reset": conns.clear()
else: conns.add(self.client_address)
body = f"{len(conns)}\n".encode()
self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
for i in $(seq 50); do curl -s 127.0.0.1:9000/reset > /dev/null && break; sleep 0.1; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
access_log off;
upstream plain { server 127.0.0.1:9000; }
upstream pooled { server 127.0.0.1:9000; keepalive 8; }
server {
listen 127.0.0.1:8080;
location /plain/ { proxy_pass http://plain/; }
location /pooled/ {
proxy_pass http://pooled/;
proxy_http_version 1.1; # keep-alive needs HTTP/1.1 upstream
proxy_set_header Connection ""; # and no "Connection: close" from Nginx
}
}
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
for path in plain pooled; do
curl -s 127.0.0.1:9000/reset > /dev/null
for i in $(seq 20); do last=$(curl -s 127.0.0.1:8080/$path/x); done
echo "$path: 20 requests used $last backend connection(s)"
done
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1plain: 20 requests used 20 backend connection(s)
pooled: 20 requests used 1 backend connection(s)
keepalive 8 is the number of idle connections each worker keeps per upstream, not a limit on active ones. Make sure the backend's own idle timeout is longer than Nginx's (keepalive_timeout inside upstream, default 60 s), or the backend closes a connection just as Nginx reuses it and the request fails with a 502 (this race is a well-known cause of rare, random 502s behind app servers with short idle timeouts; check your framework's default).
Test yourself
A backend takes 90 s to produce a report. Nginx returns an error after 60 s. Which error, and which directive?
- 502, proxy_connect_timeout
- 504, proxy_read_timeout
- 500, send_timeout
- 413, client_max_body_size
Why doesn't Nginx retry a failed POST on the next server by default?
- POST bodies are too big
- The first server may already have performed the action; repeating it could, for example, charge a payment twice
- HTTP forbids it
- It does
What three settings make Nginx reuse connections to an upstream?
keepalive Nin the upstream,proxy_http_version 1.1, andproxy_set_header Connection ""keepalive_timeout 0proxy_buffering offworker_connections