Fixing 504 Request Timeout Errors on Nginx

Posted on

I came across this problem the other day and thought I would write down my findings.

In short a 504 request means that the script has taken too long to execute and the server or browser has given up waiting for it.

There are two possible reasons why this could occur;

PHP is tired of waiting for you!

The script is taking longer to execute than what is allowed in the PHP max_execution_time and max_input_time variables.

The best fix for this depends on the scenario. If you require this (and only this) request to take longer I recommend setting the variable from whatever script is being called for this request

php_ini('max_execution_time', 300);
$somethingLongRunning->go();

This is ensure that before the

$somethingLongRunning->go();

is hit the request time that php will wait for this peice of logic to compute will increase to 300 seconds or 5 minutes.

This 5 minutes will begin as soon as the php_ini() function is hit, so if your request has already been running for 3 seconds, the total time it can take will be 5 minutes and 3 seconds

This is a complete hack and I would recommend that you look into optimising your code or move heavy, long processing logic into a worker. But if you are stuck for time or a plethera of other reasons. max_execution_time is your friend.

Are You uploading data?

If you are uploading data you may also want to set the max_input_time the same way as above;

php_ini('max_input_time', 300);
$somethingLongRunning->go();

Max input time is the maximum amount of time that PHP will spend processing input data.

public function foo()

{
    ini_set('max_execution_time', 1200);
    ini_set('max_input_time', 6000);
    // do long running stuff
}

If you would like to change the above variables globally mine where located in /etc/php/7.1/fpm/php.ini

Nginx is tired of waiting for you

Wow aren’t they aren’t very patience these machine friends of ours.

Sometimes extending PHPs max input and timeout threshold may not be enough. Nginx is also at play and the web server will only try and serve a request for so long. if the above chancge to PHP has no effect try updating your request_terminate_timeout variable in Nginx. This can be found in your php-fpm worker config, mine was at /etc/php5/fpm/pool.d/www.conf I increased it to 300