CH-J Toolsserver management over SSH
Menu
All guides and articles →

NGINX 504 Gateway Timeout: Diagnosis and Fix

Find out at which layer and on which operation the limit expired. Distinguish between worker queue, slow application, database and proxy timeout without blindly extending the wait.

504 says the gateway did not receive the required response in time

HTTP 504 indicates a situation where a server acting as a gateway or proxy did not receive a timely response from another server needed to fulfill the request. Unlike the number itself, the operation that was being waited for is important for the fix. It could be establishing a connection, waiting for headers, or another part of the response. The same page can also be created by a upstream proxy whose limit is shorter than your NGINX limit.

Write down the exact time, path, and type of request. Determine if a single export, all dynamic pages, or a random chunk of traffic is failing under load. When only one function is slow and static files are working, the search will be different than when the application is unavailable for all requests. Don't just base your decision on the same error page size.

Do not retry an operation that could have changed something without checking. A proxy timeout does not confirm that the backend did not perform the write, order, or send email. After losing the response, the application may still be working or may have already completed the operation. For diagnostics, choose safe read requests and verify the actual state for change operations.

Map out all the time limits in the journey

A path can include a browser, CDN, public proxy, NGINX, PHP-FPM, application, database, and external API. Each layer can have its own limit and different wait definition. Changing the innermost limit will not increase the wait of the layer before it. Therefore, you need a time budget for the entire operation, not just one directive with a large number.

  • Proxy connect timeout: waiting for a connection to the upstream to be established.
  • Proxy read timeout: the gap between reads from upstream as defined by the module, not the universal total request length.
  • Application deadline: the time after which the application should stop working or return a controlled response.
  • Database or API timeout: the limit of a specific dependency that a worker can hold.

Additionally, PHP limits and request_terminate_timeout pool may differ for PHP-FPM. The way PHP accounts for time is environment-dependent, and it is not correct to output all time parameters as the same wall time. Find out which layer actually terminates a particular job, and which layers just stop waiting for its response.

Error log will determine the phase, timing will help find the queue

Start with the relevant error log for the given vhost and time window. An upstream timed out message usually adds context, such as when connecting or reading a header. This is more important than assuming that all 504s mean the same slow database. Add a related application log if you can match it to the same request.

sudo tail -n 100 /var/log/nginx/error.log
sudo journalctl -u APLIKACE.service --since "-15 min" --no-pager
sudo nginx -T

The last command prints the effective configuration and may reveal non-public data; read it in a privileged environment and do not share it in its entirety without review. Find the corresponding location and the chosen upstream. The global limit may be overridden in a particular branch, so an estimate from a single master file may not describe the actual request being served.

If upstream timing is already in place in the access log, compare request_time, upstream_connect_time, upstream_header_time, and upstream_response_time. The definitions are not interchangeable and multiple attempts may result in multiple values. The total request_time includes additional work and client transfer. You must explain a dashed or missing upstream value based on your specific process.

Test the backend the right way and without causing another incident

Perform a limited direct test of a known HTTP backend from a correct network location. Preserve the host, secure path, and TLS name as needed. A localhost response from another container does not validate the original backend. Likewise, a fast general health page is not a complete test of a slow report.

# Ilustrační čtecí HTTP požadavek na známý backend:
curl --max-time 10 -sS -o /dev/null \
  -H 'Host: aplikace.example' \
  -w 'HTTP=%{http_code} connect=%{time_connect} first_byte=%{time_starttransfer} total=%{time_total}\n' \
  http://127.0.0.1:8080/health

The max-time here is limited by the diagnostic client itself, not by changing the production configuration. Measure several suitable samples without an unlimited loop and compare them to normal traffic. A mass test on an overloaded server can amplify the problem. If the endpoint under test requires login, do not transmit secret tokens in the public command sample or the resulting report.

Do not try a FastCGI pool as a regular HTTP server. For FPM, use the established secure restricted status and application path. In case of a TLS or incorrect protocol issue, first fix the communication contract; extending the wait will not produce valid headers from the wrong backend type.

Worker queue, memory, and slow dependencies

A request can spend most of the time waiting for a free worker to come out. Each worker can block on the database or remote API. As a result, even simple pages that would otherwise require little CPU will suffer. Find out the number of active workers, the queue, and their normal memory consumption; high CPU is not a necessary condition for this failure.

uptime
free -h
ps -eo pid,ppid,comm,pcpu,pmem --sort=-pcpu | head -20
sudo journalctl -u php8.3-fpm.service --since "-30 min" --no-pager

Replace the FPM version with the actual one. For example, look for pm.max_children being reached and the connection to slow requests. Increasing the number of processes requires memory and database capacity. Without a budget, you can cause OOMs, restarts, and 502s instead of waiting. First, differentiate the lack of workers from the reason why they stay busy for so long.

For a specific slow query, use approved database diagnostics and application metrics. Check locks, connection time, and external call retries. Do not add random indexes or turn off transaction protections just for the sake of a general article. The fix must be specific to the actual query and its operational impact.

When does increasing the timeout make sense?

A longer limit may be justified if the application demonstrably needs a longer synchronous operation, the user expects it, and the resources are designed for such concurrency. Then change the limit specifically for the given branch and align it with other layers. It is not advisable to blindly extend the wait for all URLs just for one export.

# Pouze ilustrace zvolených intervalů uvnitř odpovídající location:
proxy_connect_timeout 5s;
proxy_read_timeout 90s;

# Pro FastCGI se používají direktivy příslušného modulu, například:
fastcgi_read_timeout 90s;

The sample does not specify universally correct values or a complete location block. Do not add proxy and FastCGI as interchangeable parts of one unknown configuration. In particular, proxy_read_timeout and fastcgi_read_timeout limit the interval between reads, according to the documentation. A continuously sent response may therefore take longer than the specified number; it is not automatically a total deadline.

Longer waits can also increase worker occupancy and queue growth. Consider the number of concurrent slow requests, capacity, and how to handle them. For very long reports or calculations, a background job with progress and later download of the result may be more appropriate. This is an application design, not a single NGINX switch.

Request repetition and change operations

The proxy may have set up retries for the next upstream. Retrying a safe read has a different impact than retrying a payment or state change. Verify proxy_next_upstream or fastcgi_next_upstream and application protections for your specific traffic. Shortening or lengthening the timeout must not cause uncontrolled multiplication of expensive operations.

If the client resubmits the form after a 504, the first request may have succeeded. For operations where duplication is a concern, the application needs to design idempotence and result retrieval accordingly. A network error cannot be relied upon to automatically roll back the database to its previous state. This property depends on the transactions and the actual point in time of completion.

Diagnostics should record these circumstances. In particular, distinguish between "user did not receive a response" and "operation was not performed". The support manager may then not trigger further work just because the monitoring panel sees an error status. In addition, for a partially sent response, the status may be different from the expected 504, so also check the completeness of the transmission.

Confirm the repair on the original public road

Backup the specific change, check the syntax, and use a managed reload. Then repeat the safe scenario through the same upstream layers where the problem occurred. The direct backend may work, while the upstream proxy will still finish waiting early. Therefore, after changing the timeout, just local curl is not enough.

sudo nginx -t
# Po úspěšné kontrole a schválené změně:
sudo systemctl reload nginx.service
  • It is documented which layer and at what waiting time the limit was reached.
  • The slow path has a measured course and a known dependency or queue.
  • The change is of reasonable scope and did not extend the limits to all requests without reason.
  • Response, concurrency, and error rate after correction are on target.
  • Important operations have a verified outcome and controlled repetition.

In CH-J Tools you can read logs and check server status, but a true explanation of a 504 requires a proxy-to-application relationship. Consider a fix complete when the confirmed cause has been removed or a documented and safe new time budget has been reached. Simply pushing the same failure back another minute is not a permanent solution.

Frequently asked questions

Is proxy_read_timeout the maximum request length?

Not generally. The documentation defines it as the interval between reads from upstream. The overall operation may have different time limits.

Will a 504 stop a running application?

Not necessarily. The proxy can stop waiting while the backend continues or has already completed the change.

Should I set it to a few minutes everywhere?

No. First, determine the cause and time budget for the entire journey. Longer limits can worsen queues and resource consumption.

Why didn't changing NGINX help over CDN?

The upstream layer may have its own shorter limit. Verify all gateways and perform a test over the original public path.

Detailed documentation

NGINX: HTTP proxy timeouts →

NGINX: FastCGI timeouts →

NGINX: upstream timing →

PHP: FPM and pool limits →

IETF RFC 9110: 504 Gateway Timeout →

Biometric unlock and security →

All tutorials by category →