Sub topic 11
Tuning proxy timeouts and buffering
This chapter covers the timeout and buffering directives that decide how long Nginx waits on a backend and where response data is held while it moves to the client. It assumes you can write a basic proxy_pass configuration, you know what an upstream group is, and you can read HTTP status codes. If you can't yet, review the earlier chapters on reverse proxy fundamentals and upstream groups.
Why these settings matter
The defaults work for typical web pages. They fail in three common cases:
- A backend that takes longer than 60 seconds to answer, such as a report export. Nginx gives up and returns 504.
- A long-lived stream, such as server-sent events. Buffering holds the data back and the client sees nothing.
- A large response sent to a slow client. A backend worker stays busy until the response is delivered, unless Nginx buffers it.
Buffering and timeouts are two sides of one idea. Nginx sits between two connections: the client connection and the upstream connection. They run at different speeds, and these directives control how Nginx copes with the mismatch.
The three proxy timeouts
Nginx applies three separate timeouts on the upstream connection. Each one measures something different.
| Directive | Default | What it limits |
|---|---|---|
| `proxy_connect_timeout` | 60s | Time to establish the TCP connection to the backend |
| `proxy_send_timeout` | 60s | Time between two successive write operations when sending the request to the backend |
| `proxy_read_timeout` | 60s | Time between two successive read operations when receiving the response from the backend |
Two points are easy to miss.
First, proxy_send_timeout and proxy_read_timeout are not totals. They measure the gap between two consecutive operations. A backend that sends one byte every 59 seconds never triggers proxy_read_timeout, even if the response takes an hour. Conversely, a backend that computes for 61 seconds before sending the first byte does trigger it.
Second, proxy_connect_timeout cannot usefully exceed 75 seconds, because the operating system's TCP connection attempt gives up at about that point. In practice, set it low. A backend that cannot accept a connection within a few seconds is unhealthy, and a short timeout lets proxy_next_upstream move on to another server quickly.
location / {
proxy_pass http://app_backend;
proxy_connect_timeout 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}Which status code you get
The failure mode tells you which timeout fired.
| Symptom | Likely cause |
|---|---|
| 502 Bad Gateway quickly | Connection refused or reset. The backend is down or crashed |
| 504 Gateway Timeout after about `proxy_connect_timeout` | The backend host is unreachable or its accept queue is full |
| 504 Gateway Timeout after about `proxy_read_timeout` | The backend accepted the request but did not answer in time |
For a slow endpoint, raise the timeout only for that location instead of globally. A global increase lets every hung request hold resources for longer.
location /reports/ {
proxy_pass http://app_backend;
proxy_read_timeout 300s;
}Timeouts and retries
When proxy_next_upstream includes timeout, a timeout on one server makes Nginx try the next one. Be careful here. A request that times out after 60 seconds, then retries on a second server for another 60 seconds, takes two minutes to fail. Two directives cap this behavior:
proxy_next_upstream_trieslimits the number of servers tried.proxy_next_upstream_timeoutlimits the total time spent on retries.
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 10s;By default Nginx does not retry non-idempotent requests (POST, LOCK, PATCH) once they have been sent to a server. Adding non_idempotent to proxy_next_upstream overrides that. Do it only if your application tolerates duplicate requests.
How buffering works
With buffering on (the default), Nginx reads the response from the backend as fast as the backend sends it, stores it in memory buffers, and sends it to the client at the client's pace. The backend is released as soon as Nginx has the whole response, even if the client is still downloading.
The diagram below shows the flow.
Without buffering, the backend worker stays tied to the slow client for the whole transfer. For applications with a small worker pool, buffering is a large protection against slow-client problems.
Buffer directives
| Directive | Default | Purpose |
|---|---|---|
| `proxy_buffering` | on | Turns response buffering on or off |
| `proxy_buffer_size` | 4k or 8k (one memory page) | Buffer for the first part of the response, which holds the headers |
| `proxy_buffers` | 8 4k or 8 8k | Number and size of buffers for the body, per connection |
| `proxy_busy_buffers_size` | 2 × buffer size | Amount that can be busy sending to the client while the rest is still being read |
| `proxy_max_temp_file_size` | 1024m | Upper limit for spilling the response to a temporary file on disk |
| `proxy_temp_file_write_size` | 2 × buffer size | Amount written to the temp file at once |
When a response does not fit in the configured buffers, Nginx writes the excess to a temporary file. Disk spill is not an error, but it costs I/O. If you see this warning in the error log, your buffers are smaller than your typical response:
[warn] an upstream response is buffered to a temporary file /var/cache/nginx/proxy_temp/3/00/0000000003 while reading upstreamRaising proxy_buffers costs memory per active connection. The figure to watch is buffers × size × concurrent connections. With proxy_buffers 16 16k, each connection can use up to 256 KB. With 2,000 concurrent proxied connections, that is up to about 500 MB.
Large headers: the "upstream sent too big header" error
The first buffer, set by proxy_buffer_size, must hold the entire response header block. Applications that set many or large cookies, or long Set-Cookie and Location values, can overflow it. The symptom is a 502 and this line in the error log:
upstream sent too big header while reading response header from upstreamThe fix is to enlarge the header buffer, and usually the busy buffer limit with it:
proxy_buffer_size 16k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;Nginx requires proxy_busy_buffers_size to be at least as large as proxy_buffer_size and smaller than the total of all buffers minus one buffer. If you break that rule, nginx -t reports an error, which is one more reason to always test before reloading.
Disabling buffering
Buffering is wrong for responses that must reach the client incrementally:
- Server-sent events
- Streaming or chunked progress output
- Long polling where partial data matters
Turn it off for those locations only:
location /events/ {
proxy_pass http://app_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_read_timeout 1h;
}A backend can also request this itself by sending the response header X-Accel-Buffering: no. Nginx honors that header unless you tell it to ignore it with proxy_ignore_headers X-Accel-Buffering. This is convenient because the application decides per response, but it means the application can bypass your tuning.
With buffering off, Nginx passes data to the client synchronously as it arrives, using only proxy_buffer_size. A slow client then holds the backend connection open. Use this only where you need it.
Request buffering
Buffering also applies in the other direction. By default (proxy_request_buffering on), Nginx reads the entire client request body before it opens the upstream connection, spooling large bodies to a temporary file. This protects the backend from slow uploads, because it only sees the request once it is complete.
| Directive | Default | Purpose |
|---|---|---|
| `client_body_buffer_size` | 8k or 16k | Memory buffer for the request body before spilling to disk |
| `client_max_body_size` | 1m | Largest accepted request body. Larger requests get 413 |
| `proxy_request_buffering` | on | Read the whole body first, then forward |
The default client_max_body_size of 1 MB is a frequent surprise. File uploads fail with 413 Request Entity Too Large, and the cause is Nginx, not the application. Raise it for the upload location:
location /upload/ {
proxy_pass http://app_backend;
client_max_body_size 200m;
proxy_request_buffering off;
}Setting proxy_request_buffering off streams the body to the backend as it arrives. This suits large uploads that the application processes incrementally, and it avoids a full disk copy. The cost is that Nginx can no longer retry the request on another server once body transfer has started, because the body is not stored.
Putting it together
This configuration combines the settings for a typical application with a normal API, a slow report endpoint and a streaming endpoint. It assumes the app_backend upstream from the earlier chapter.
server {
listen 80;
server_name example.com;
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;
location / {
proxy_pass http://app_backend;
proxy_connect_timeout 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 10s;
proxy_buffer_size 8k;
proxy_buffers 16 8k;
}
location /reports/ {
proxy_pass http://app_backend;
proxy_connect_timeout 5s;
proxy_read_timeout 300s;
}
location /events/ {
proxy_pass http://app_backend;
proxy_buffering off;
proxy_read_timeout 1h;
}
location /upload/ {
proxy_pass http://app_backend;
client_max_body_size 200m;
proxy_request_buffering off;
proxy_send_timeout 120s;
}
}Directives set at the server level are inherited by each location only if the location sets none of the same kind. The proxy_set_header lines above are inherited because none of the locations defines its own proxy_set_header. If you add one proxy_set_header to a location, you must repeat all the others there.
Apply the change with the check-then-reload command:
sudo nginx -t && sudo systemctl reload nginxVerifying timeout behavior
You can test a timeout without a real slow application. This small Python server sleeps before answering:
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
class Slow(BaseHTTPRequestHandler):
def do_GET(self):
time.sleep(40)
self.send_response(200)
self.send_header("Content-Length", "2")
self.end_headers()
self.wfile.write(b"ok")
HTTPServer(("127.0.0.1", 3000), Slow).serve_forever()With proxy_read_timeout 30s, a request fails after 30 seconds:
curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" http://example.com/The output is a 504 at about 30 seconds. Check /var/log/nginx/error.log for the matching line:
upstream timed out (110: Connection timed out) while reading response header from upstreamChange the timeout to 60 seconds, reload, and repeat. The request now succeeds after about 40 seconds. The wording of the error line, "while connecting", "while reading response header" or "while sending request", names which timeout fired.
Common mistakes
- Raising
proxy_read_timeoutglobally to hide a slow endpoint. Fix the slow endpoint, or raise the value only in its location. - Leaving the connect timeout at 60 seconds in a multi-server group. A dead server delays every request that lands on it by a minute before failover.
- Disabling
proxy_bufferingeverywhere "for speed". Unbuffered proxying exposes backend workers to slow clients and rarely improves throughput. - Forgetting
client_max_body_size. The 413 appears in Nginx's error log and has nothing to do with the application. - Confusing the timeout with a total deadline. The read and send timeouts reset on every successful operation.
Exercises
Exercise
A backend sends a 20 MB export by writing one chunk every 20 seconds, for 10 minutes in total. proxy_read_timeout is 30s. Does Nginx return a 504? Explain.
Show answer
No. proxy_read_timeout measures the gap between two successive reads, not the total time. Each chunk arrives within 30 seconds of the previous one, so the timer resets every time and the transfer completes. A 504 would occur only if the backend stayed silent for more than 30 seconds, including before the first byte of the response.
Exercise
Users report that uploading a 5 MB image returns 413, but the application logs show no request. What is the cause, and what change fixes it for the /upload/ location only?
Show answer
Nginx rejects the request itself because the body exceeds client_max_body_size, which defaults to 1m. The request never reaches the application. Add client_max_body_size 10m; (or larger) inside location /upload/, run sudo nginx -t && sudo systemctl reload nginx, and retry.
Exercise
The error log contains "upstream sent too big header while reading response header from upstream" and clients get 502. Which directive do you raise first, and which related directive must stay consistent with it?
Show answer
Raise proxy_buffer_size, because the first buffer must hold the whole response header block. Keep proxy_busy_buffers_size at least as large as proxy_buffer_size, and smaller than the total size of proxy_buffers minus one buffer, or nginx -t fails.