Fix 504 Gateway Timeout on Nginx and PHP-FPM: Runbook

Resolve HTTP 504 Gateway Timeout errors on Nginx and PHP-FPM. Diagnostic runbook for fastcgi_read_timeout, request_terminate_timeout, and worker pools.

Fix 504 Gateway Timeout on Nginx and PHP-FPM: Runbook
Linux Server Diagnostic Runbook

To fix 504 gateway timeout on Nginx and PHP-FPM: Synchronize the timeout thresholds across your stack by adding fastcgi_read_timeout 300s; to your Nginx location ~ \.php$ block, updating request_terminate_timeout = 300s in your PHP-FPM pool configuration (www.conf), and matching max_execution_time = 300 in php.ini before executing nginx -t && systemctl reload nginx php*-fpm.[1][2]

Follow this production server runbook to isolate upstream FastCGI latency bottlenecks, inspect worker process exhaustion, and configure slow query tracing across Ubuntu, Debian, AlmaLinux, and Rocky Linux environments.[1][3]


Understanding the 504 Gateway Timeout on Nginx and PHP-FPM

In a modern web architecture, Nginx functions as a high-performance reverse proxy and web server, while PHP-FPM (FastCGI Process Manager) serves as the upstream dynamic application backend.[1]

An HTTP 504 Gateway Timeout indicates that Nginx successfully accepted the client HTTP request, forwarded it to the PHP-FPM Unix domain socket or TCP port (e.g., 127.0.0.1:9000), but PHP-FPM failed to return a complete response before Nginx’s internal wait timer expired.[1][2]

+----------------+          +---------------+          +---------------+
|     Client     |          |  Nginx Proxy  |          |    PHP-FPM    |
+-------+--------+          +-------+-------+          +-------+-------+
        |                           |                          |
        | 1. HTTP GET /report ----->|                          |
        |                           | 2. FastCGI Request ----->|
        |                           |    (Socket / TCP 9000)   | (Worker executing
        |                           |                          |  slow SQL query
        |                           |    [Wait Timer: 60s]     |  or external cURL)
        |                           |    ... Timer Expired!    |
        |                           |                          |
        |<--- 3. HTTP 504 Timeout --+                          |
        |                           |                          |

This differs fundamentally from an HTTP 502 Bad Gateway:

  • 502 Bad Gateway: The upstream backend crashed, was offline, or returned an invalid or malformed packet header.[3]
  • 504 Gateway Timeout: The upstream backend is actively alive, but the script is executing too slowly, blocking on disk I/O, or stuck behind an exhausted worker process queue.[1]

For enterprises hosting resource-heavy WooCommerce stores or corporate ERP systems on Pakistan dedicated bare metal or high-throughput international enterprise servers, eliminating 504 errors requires harmonizing timeout thresholds and auditing upstream application execution.[4]


The Timeout Triangle: Harmonizing Execution Limits

A common administrative pitfall is modifying max_execution_time in php.ini without adjusting upstream FastCGI directives.[2] To ensure scripts execute to completion, three configuration layers must be synchronized:[2]

               +---------------------------------------+
               |        Nginx (fastcgi_read_timeout)   |
               +-------------------+-------------------+
                                   |
                                   v
+----------------------------------+----------------------------------+
| PHP-FPM (request_terminate_timeout) | PHP Runtime (max_execution_time) |
+-------------------------------------+----------------------------------+
  1. Nginx Layer (fastcgi_read_timeout): Determines how long Nginx will wait for a response from the FastCGI server before dropping the connection and returning a 504.[1] Default: 60s.
  2. PHP-FPM Pool Layer (request_terminate_timeout): A watchdog timeout that forcefully kills a worker process serving a single request.[2] Default: 0 (disabled) or set by hosting control panels.
  3. PHP Runtime Layer (max_execution_time): The internal PHP interpreter execution limit.[3] Default: 30s.

Rule of thumb: fastcgi_read_timeout must always be equal to or greater than request_terminate_timeout, which in turn should match max_execution_time.[2]


Diagnostic Matrix: 504 Timeout Root Causes and Log Signatures

Failure Scenario Log Signature Primary Diagnostic Command Resolution Action
FastCGI Read Exceeded upstream timed out (110: Connection timed out) while reading response header from upstream tail -n 100 /var/log/nginx/error.log Increase fastcgi_read_timeout 300s; in Nginx.[1]
FPM Worker Exhaustion server reached pm.max_children setting (X), consider raising it tail -n 100 /var/log/php*-fpm.log Increase pm.max_children and tune FPM pool memory.[3]
Unindexed Slow SQL MySQL processlist shows queries in Sending data or Copying to tmp table mysqladmin processlist Enable MySQL slow query log; add composite indexes.[4]
External API Deadlock PHP-FPM slow log traces hanging inside curl_exec() or file_get_contents() Inspect /var/log/php-fpm/slow.log Implement explicit cURL timeouts (CURLOPT_TIMEOUT, 15).[2]
Proxy Buffer Overflow upstream sent too big header while reading response header from upstream Inspect Nginx error log for buffer warnings Increase fastcgi_buffer_size 128k; and fastcgi_buffers 4 256k;.[1]

Step-by-Step Action Plan: Fix 504 Gateway Timeout on Nginx and PHP-FPM

Step 1: Trace the Timeout Signature in Server Logs

Connect via SSH and verify the exact point of failure:

# Inspect Nginx error log for upstream timeout signatures
sudo tail -n 50 /var/log/nginx/error.log | grep -E "timed out|upstream"

Expected Error Log Output:

2026/11/27 14:45:10 [error] 18420#18420: *1204 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 198.51.100.4, server: example.com, request: "POST /wp-admin/admin-ajax.php HTTP/2.0", upstream: "fastcgi://unix:/run/php/php8.2-fpm.sock:", host: "example.com"

Examine the corresponding PHP-FPM pool log:

# Ubuntu / Debian
sudo tail -n 50 /var/log/php8.2-fpm.log

# AlmaLinux / RHEL
sudo tail -n 50 /var/log/php-fpm/www-error.log

Step 2: Configure Nginx FastCGI Timeout Directives

Open your site’s virtual host configuration file (e.g., /etc/nginx/sites-available/example.com or /etc/nginx/conf.d/example.conf):

server {
    listen 443 ssl http2;
    server_name example.com;

    root /var/www/html;
    index index.php index.html;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf; # or fastcgi_params
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;

        # Increase timeout thresholds to 300 seconds
        fastcgi_connect_timeout 300s;
        fastcgi_send_timeout 300s;
        fastcgi_read_timeout 300s;

        # Prevent large response header buffer truncation
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}

Step 3: Align PHP-FPM Pool Watchdog and Worker Scaling

Open your active PHP-FPM pool configuration file:

  • Ubuntu/Debian: /etc/php/8.2/fpm/pool.d/www.conf
  • RHEL/AlmaLinux: /etc/php-fpm.d/www.conf
; Terminate scripts that exceed 300 seconds
request_terminate_timeout = 300s

; Scale worker concurrency to prevent queuing deadlocks
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 1000

Calculation Formula for pm.max_children:[3] $$\text{pm.max_children} = \frac{\text{Total Available RAM} - \text{Buffer for OS & MySQL}}{\text{Average Memory per PHP Process (60 MB)}}$$ For a server with 8 GB RAM dedicated to PHP: $\frac{6000\text{ MB}}{60\text{ MB}} = 100\text{ children}$.


Step 4: Increase Execution Limits in php.ini

Open your PHP-FPM php.ini file:

  • /etc/php/8.2/fpm/php.ini (Ubuntu/Debian)
  • /etc/php.ini (RHEL/AlmaLinux)

Update execution and input duration directives:[2]

max_execution_time = 300
max_input_time = 300
memory_limit = 512M
post_max_size = 64M
upload_max_filesize = 64M

Step 5: Test Configuration and Reload Daemons

Validate syntax before reloading processes to avoid unexpected web downtime:[1]

# Verify Nginx configuration syntax
sudo nginx -t

# Verify PHP-FPM configuration syntax
sudo php-fpm8.2 -t   # On Ubuntu/Debian
sudo php-fpm -t      # On RHEL/AlmaLinux

# Reload services gracefully without dropping active connections
sudo systemctl reload nginx
sudo systemctl restart php8.2-fpm

Step 6: Identify Long-Running Code via PHP-FPM Slow Log

Increasing timeout values prevents premature 504 errors, but it does not fix poorly written code or slow database queries.[2] Enable the PHP-FPM slow log to identify the exact file and line number causing the delay.[2]

In /etc/php/8.2/fpm/pool.d/www.conf:

slowlog = /var/log/php-fpm/www-slow.log
request_slowlog_timeout = 5s
request_slowlog_trace_depth = 20

Restart PHP-FPM and monitor the log:

sudo tail -f /var/log/php-fpm/www-slow.log

Example Output Identifying a Problematic Plugin:

[27-Nov-2026 14:48:22]  [pool www] pid 19230
script_filename = /var/www/html/wp-admin/admin-ajax.php
[0x00007f9c2d415b30] curl_exec() /var/www/html/wp-content/plugins/slow-sync/sync.php:142
[0x00007f9c2d415a10] process_sync() /var/www/html/wp-content/plugins/slow-sync/sync.php:48

This pinpoint trace proves the script timed out while waiting for an external cURL call to complete.[2]


Pro Tips and Common Pitfalls

Pro Tip: If your Nginx server is placed behind Cloudflare, remember that Cloudflare's enterprise edge enforces a strict 100-second HTTP response timeout on Free and Pro tiers. If an export or batch process takes 180 seconds, Cloudflare will return a Cloudflare 524 error even if Nginx is configured with fastcgi_read_timeout 300s. For long-running administrative tasks, bypass Cloudflare via a direct origin IP or offload the processing to an asynchronous background worker using WP-CLI or Redis queues.[1][4]

Critical Pitfall: Never set pm.max_children higher than your available physical RAM can accommodate. If 100 PHP-FPM workers spawn simultaneously and each consumes 80 MB of RAM on a 4 GB server, the Linux kernel Out-of-Memory (OOM) killer will trigger immediately, killing MySQL or Nginx and causing catastrophic server-wide crashes instead of graceful request throttling.[3]


Frequently Asked Questions (PAA)

What is the default fastcgi_read_timeout in Nginx?

The default value for fastcgi_read_timeout in standard Nginx distributions is 60s.[1] If an upstream PHP-FPM script takes longer than 60 seconds to compute database queries or process image uploads, Nginx closes the connection and emits a 504 Gateway Timeout.[1]

Does increasing fastcgi_read_timeout slow down my server?

No. Increasing the timeout value does not slow down normal requests that finish quickly.[1] However, if multiple requests hang on unoptimized code simultaneously, they will tie up PHP-FPM worker processes for the full duration of the timeout, reducing available worker concurrency for incoming visitors.[3]

Why does a 504 error occur during WooCommerce CSV imports?

WooCommerce product or customer CSV imports require heavy database writes, image downloading, and SKU lookups.[4] Large batch imports frequently exceed the 60-second default threshold, triggering Error 110 in Nginx.[1] Raising FastCGI timeouts to 300s or executing imports via wp wc product import via WP-CLI resolves the issue.[4]


Eliminate Gateway Bottlenecks with Nextgen Hosting

Deploy mission-critical web applications on high-performance cloud infrastructure from Nextgen Hosting. Experience dedicated CPU cores, NVMe SSD storage, and pre-tuned Nginx and LiteSpeed server architectures.

Pakistan Bare Metal Servers • Global Dedicated Infrastructure • High-Speed Cloud VPS

Disclaimer: This post is for informational and educational purposes only, accurate to the best of our knowledge at publication. Modifying production web server and PHP-FPM configurations carries operational risks. Nextgen Hosting accepts no liability for server downtime or resource exhaustion resulting from reliance on this content.

Sources & Official References
  1. Nginx Official Documentation - Module ngx_http_fastcgi_module: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html
  2. PHP Official Documentation - FastCGI Process Manager (FPM) Configuration: https://www.php.net/manual/en/install.fpm.configuration.php
  3. Ubuntu Server Guide - Web Servers and PHP-FPM Process Management: https://ubuntu.com/server/docs/web-servers
  4. WooCommerce Developer Documentation - Server Resource Recommendations and Timeouts: https://woocommerce.com/document/server-requirements/

Disclaimer: This post is for informational and educational purposes only, accurate to the best of our knowledge at publication. It does not constitute advice. We do not guarantee accuracy or completeness and accept no liability for any decisions or losses resulting from reliance on this content.