DEV Community

Daniele Michelin
Daniele Michelin

Posted on Originally published at daniele-michelin.com

HTTP 504 Gateway Timeout (nginx): causes & fix

nginx reached the backend but did not get a response within the configured timeout (60 seconds by default).

Common causes

  • Long-running requests: large uploads, exports, reports, image processing.
  • The PHP-FPM pool is full (pm.max_children reached) and new requests wait in line.
  • Slow or locked database queries.
  • fastcgi_read_timeout or proxy_read_timeout too low for the use case.
  • Backend on another host unreachable through network or firewall (connect runs into the timeout).

How to check it

Find timeouts in the nginx log

grep 'upstream timed out' /var/log/nginx/error.log | tail -n 20
Enter fullscreen mode Exit fullscreen mode

Check whether PHP-FPM hits its limit

grep -i 'max_children' /var/log/php8.3-fpm.log
Enter fullscreen mode Exit fullscreen mode

Measure response time precisely

curl -s -o /dev/null -w 'connect=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n' https://cloud.example.com/status.php
Enter fullscreen mode Exit fullscreen mode

What actually helps

  1. Fix the cause first: optimise slow queries, add indexes, move long jobs to cron or a queue.
  2. Raise pm.max_children according to RAM (RAM for PHP divided by memory per worker).
  3. Raise timeouts together: fastcgi_read_timeout 300s; in nginx plus max_execution_time and request_terminate_timeout in PHP-FPM.

FAQ

Should I just set the timeout to 3600 seconds?

No. It hides the problem and ties up workers. Raise timeouts only for specific locations such as upload or export paths.

Why do I get a 504 while PHP keeps running?

nginx only drops the connection to the client. The PHP script continues until max_execution_time or request_terminate_timeout kicks in.


Full page with every command and the German/Italian version: daniele-michelin.com/en/errors/http-504-gateway-timeout/

First published at daniele-michelin.com. The error lexicon covers HTTP, DNS, TLS, mail, database, PHP, nginx, systemd and Nextcloud, in German, English and Italian.

Top comments (1)

Collapse
 
lycore profile image
Lycore Development •

Helpful checklist, and the point about raising timeouts only per location is the one people tend to skip. One thing worth adding to the diagnosis is that nginx's error log line shows whether it timed out while connecting or while reading the response ('upstream timed out ... while connecting' vs 'while reading response header'), which immediately separates a network or firewall problem from a slow backend. Logging $upstream_response_time in the access log also lets you see which endpoints are the slow ones before touching any timeout.