A 504 Gateway Timeout is not a WordPress error. It is the process in front of WordPress giving up. Nginx, Apache with mod_proxy, a load balancer or a CDN opened a connection, PHP did not answer inside the window it allows, and the proxy closed the request. To fix a 504 gateway timeout on WordPress you either make the slow request finish sooner or raise the timeout at the layer that gave up. The checks below tell you which of those you need, in an order that avoids wasted work.
Two symptoms point in different directions. A 504 on one URL, every time, is a code problem: a loop, an unbounded query, a call to a payment API with no timeout. A 504 that lands on random pages, gets worse in the afternoon and clears after a restart is a capacity problem: PHP workers exhausted, a cron backlog, or a database that cannot keep up.
What the status code tells you about the layer that failed
The request passes through several processes, each with its own patience. The browser waits. The CDN waits. The web server waits for PHP-FPM. PHP-FPM waits for a worker, and the worker waits for MySQL or an external API. Whichever of those runs out first writes the error you see, and the status code narrows it down.
A 502 means the proxy reached the backend and got an invalid or empty reply, which usually points at a crashed or restarted PHP-FPM pool. A 504 means the proxy reached the backend and heard nothing at all before its own clock expired. That distinction matters because raising a timeout on a 502 does nothing, while raising it on a 504 buys you time you may not need if the real problem is a plugin waiting on a dead socket.
1. Take a snapshot of limits and queues with one WP-CLI command
Before you edit a single config file, collect the numbers. The mu-plugin below adds wp tut504 audit, which prints the PHP limits, whether WP-Cron is disabled, how many events are queued and which fire next, the size of autoloaded options, and the active plugin list. Those five numbers explain most 504s on an ordinary site, and they take ten seconds to gather.
<?php
/**
* Plugin Name: Tuts Hub 504 Audit
* Description: Prints the limits and queues behind most gateway timeouts.
*/
defined( 'ABSPATH' ) || exit;
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command(
'tut504 audit',
static function () {
$limits = array(
'max_execution_time' => ini_get( 'max_execution_time' ),
'max_input_time' => ini_get( 'max_input_time' ),
'default_socket_timeout' => ini_get( 'default_socket_timeout' ),
'memory_limit' => ini_get( 'memory_limit' ),
);
WP_CLI::line( 'PHP limits' );
foreach ( $limits as $name => $value ) {
WP_CLI::line( sprintf( ' %-24s %s', $name, $value ) );
}
WP_CLI::line( '' );
WP_CLI::line( 'Cron' );
WP_CLI::line( ' DISABLE_WP_CRON ' . ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ? 'true' : 'false' ) );
$total = 0;
$next = array();
foreach ( (array) _get_cron_array() as $timestamp => $hooks ) {
foreach ( (array) $hooks as $hook => $queue ) {
foreach ( (array) $queue as $event ) {
++$total;
$next[ $hook ] = $timestamp;
}
}
}
WP_CLI::line( ' scheduled events ' . $total );
asort( $next );
foreach ( array_slice( $next, 0, 5, true ) as $hook => $timestamp ) {
WP_CLI::line( sprintf( ' %s %s', gmdate( 'Y-m-d H:i', $timestamp ), $hook ) );
}
global $wpdb;
$autoload = (int) $wpdb->get_var(
"SELECT SUM(LENGTH(option_name) + LENGTH(option_value)) FROM {$wpdb->options} WHERE autoload IN ('yes','on','auto','auto-on')"
);
WP_CLI::line( '' );
WP_CLI::line( 'Autoloaded options: ' . size_format( $autoload ) );
$plugins = get_option( 'active_plugins', array() );
WP_CLI::line( 'Active plugins: ' . count( $plugins ) );
foreach ( $plugins as $plugin ) {
WP_CLI::line( ' ' . $plugin );
}
}
);
Drop that in wp-content/mu-plugins/ and run wp tut504 audit. Read the output against three thresholds. A max_execution_time of 30 with a proxy timeout of 60 means PHP dies first and you get a 500 rather than a 504, which is worth knowing before you blame the host. A cron event count in the hundreds with DISABLE_WP_CRON set to false means jobs are running inside visitor requests. Autoloaded options above roughly 1 MB slow every single request on the site.
The audit command prints PHP limits, the cron backlog, autoload size and the active plugin list in one pass (test site: WordPress 7.1.3, PHP 8.2):
PHP limits
max_execution_time 0
max_input_time -1
default_socket_timeout 60
memory_limit -1
Cron
DISABLE_WP_CRON true
scheduled events 12
2026-11-11 01:56 recovery_mode_clean_expired_keys
2026-11-11 01:56 wp_privacy_delete_old_export_files
2026-11-11 01:56 wp_privacy_personal_data_cleanup_requests
2026-11-11 02:56 wp_version_check
2026-11-11 03:26 wp_update_plugins
Autoloaded options: 40 KB
Active plugins: 0
2. Find the request that actually hangs
Guessing which plugin is slow wastes an afternoon. The access log already knows. Both Nginx and Apache record the status code and the path, so a single grep gives you the URLs that timed out and how often.
# Nginx: which paths returned 504, most frequent first
sudo grep -h ' 504 ' /var/log/nginx/access.log /var/log/nginx/access.log.1 \
| awk '{print $7}' | sort | uniq -c | sort -rn | head -20
# Apache: same question, different log format
sudo grep -h ' 504 ' /var/log/apache2/*access*.log | cut -d'"' -f2 | sort | uniq -c | sort -rn
# Time a suspect URL from the server itself so the proxy is the only variable left
curl -sS -o /dev/null -w 'connect %{time_connect} ttfb %{time_starttransfer} total %{time_total} code %{http_code}\n' \
https://example.com/wp-admin/admin-ajax.php
If the log shows admin-ajax.php, a REST route, or a WooCommerce admin screen, the problem is in PHP and you can reproduce it. If it shows static files or the home page, the problem is upstream of WordPress and no plugin change will help. Enable the PHP-FPM slow log as well, because it names the script and the function stack that was still running when the clock ran out, which the access log never does.
3. Line up PHP, PHP-FPM and the proxy on the same number
There are three separate clocks and they do not measure the same thing. max_execution_time counts CPU time only, so on Unix a request blocked on a socket to a payment gateway can outlive a 30 second limit by minutes. request_terminate_timeout in the FPM pool is a hard kill measured in wall time. fastcgi_read_timeout in Nginx is the proxy’s patience. Set them in ascending order so the innermost layer fails first and writes the useful log line.
; php.ini
max_execution_time = 120
max_input_time = 120
default_socket_timeout = 20
; /etc/php/8.2/fpm/pool.d/www.conf
; hard kill slightly above max_execution_time so PHP logs its own error first
request_terminate_timeout = 130s
request_slowlog_timeout = 10s
slowlog = /var/log/php-fpm/slow.log
Then the proxy, which must sit above the FPM kill so it never gives up before PHP has had the chance to write a stack trace.
# /etc/nginx/conf.d/timeouts.conf
# fastcgi_read_timeout must be larger than request_terminate_timeout
fastcgi_read_timeout 150s;
fastcgi_send_timeout 150s;
proxy_read_timeout 150s;
# Apache httpd.conf or the vhost block
# ProxyTimeout 150
# Timeout 150
# .htaccess, shared hosting with mod_php only
# php_value max_execution_time 120
# php_value max_input_time 120
Those php_value lines are a trap on modern hosting. Under PHP-FPM, .htaccess is not read by PHP at all, and putting php_value in it returns a 500 for the whole site. If your host runs FPM, change the limit in the control panel or a local php.ini instead. Tools, then Site Health, then the Info tab lists the value PHP is actually running with, which is the number that matters rather than the one in the file you edited.

4. Bisect the plugin or hook that never returns
Once the log points at a PHP request, halve the problem instead of reading code. Deactivate everything, confirm the URL answers, then switch plugins back on in groups. WP-CLI makes this fast enough to do while the site is in maintenance mode.
wp plugin list --status=active --field=name
wp plugin deactivate --all
# reload the failing URL, then bring groups back
wp plugin activate woocommerce
wp plugin activate woocommerce-gateway-stripe
# a plugin that is active but broken will still fatal on load
wp plugin verify-checksums --all
The classic offender is an external HTTP call inside a loop. wp_remote_get() defaults to a 5 second timeout, but plenty of code passes 'timeout' => 30, or omits the argument entirely while looping over 200 products. Twenty calls at 30 seconds each is a 504 no matter what you set in php.ini. If the slow request is a scheduled job rather than a page, the debugging approach is different and covered in WP-Cron Part 2: Single Events, Arguments and Debugging.
5. Clear the cron and Action Scheduler backlog
WooCommerce does not run subscriptions, webhooks and imports on its own scheduler. It queues them in Action Scheduler, which stores jobs in the database and drains them through WP-Cron. A backlog of a few thousand pending actions means every page load tries to claim and run a batch, and the visitor’s request pays for it. That is how a shop ends up with 504s on pages that do almost nothing.
wp cron event list --fields=hook,next_run_relative,recurrence
wp cron event run --due-now
# WooCommerce queue: run four batches of 25 actions, then stop
wp action-scheduler run --batch-size=25 --batches=4
# then keep cron out of page loads entirely
# wp-config.php: define( 'DISABLE_WP_CRON', true );
# crontab: */5 * * * * cd /var/www/html && wp cron event run --due-now >/dev/null 2>&1
Disabling WP-Cron without adding the system cron line is worse than leaving it alone, because nothing runs at all. Set both at the same time. The scheduling side of this is covered in WP-Cron Part 1: Schedule Recurring Events in WordPress if you need the event API rather than the cleanup commands.
WP-Cron lists the same queue with relative times, which is how you spot a backlog that never drains (test site: WordPress 7.1.3, PHP 8.2):
hook next_run_relative recurrence
recovery_mode_clean_expired_keys now 1 day
wp_privacy_delete_old_export_files now 1 hour
wp_privacy_personal_data_cleanup_requests now 1 day
wp_version_check now 12 hours
wp_update_plugins now 12 hours
wp_update_themes now 12 hours
wp_site_health_scheduled_check now 1 week
wp_scheduled_delete now 1 day
delete_expired_transients now 1 day
wp_update_user_counts now 12 hours
wp_scheduled_auto_draft_delete now 1 day
wp_update_comment_type_batch 59 seconds Non-repeating
6. Batch WooCommerce work so it finishes inside the window
When a WooCommerce admin screen or an import times out, the fix is usually to stop doing the work in a web request. Move it to WP-CLI, page through the records, and give the loop a time budget so it can be resumed instead of dying halfway. The loop below recalculates totals in chunks of 50 and stops after 20 seconds, then tells you which page to continue from.
<?php
// Start page: pass it as an argument, for example: wp eval-file batch.php 5
$page = isset( $args[0] ) ? max( 1, (int) $args[0] ) : 1;
$start = time();
while ( true ) {
$orders = wc_get_orders(
array(
'limit' => 50,
'page' => $page,
'status' => 'processing',
'orderby' => 'ID',
'order' => 'ASC',
)
);
if ( empty( $orders ) ) {
WP_CLI::success( 'Finished at page ' . $page );
break;
}
foreach ( $orders as $order ) {
$order->calculate_totals( false );
$order->save();
}
WP_CLI::log( 'Processed page ' . $page );
++$page;
if ( ( time() - $start ) > 20 ) {
WP_CLI::warning( 'Time budget reached. Continue with: wp eval-file batch.php ' . $page );
break;
}
}
Run it with wp eval-file batch.php. When it stops on its time budget, pass the page it reports as an argument to carry on, for example wp eval-file batch.php 5. Two details keep this honest. wc_get_orders() with no limit loads every matching order into memory, which is its own route to a timeout on a large shop. And if you are mid-migration to custom order tables, the sync between posts and orders adds work to each save, so keep batches small; the order meta side of that is covered in WooCommerce HPOS migration.
7. Shrink autoloaded options and slow queries
Autoloaded options load on every request, including REST calls and admin-ajax. A plugin that stores a serialised array of product IDs in an option marked autoload turns a 200 ms request into a 900 ms one, and a request that was already close to the proxy limit tips over. Find the offenders with a direct query.
SELECT option_name, LENGTH(option_value) AS bytes
FROM wp_options
WHERE autoload IN ('yes','on','auto','auto-on')
ORDER BY bytes DESC
LIMIT 20;
Anything over about 100 KB deserves a look. Switch autoload off for options that are only read on their own admin screen, with wp option set-autoload option_name off, and clear expired transients with wp transient delete --expired. If the slow log shows queries rather than PHP, check the database itself before blaming the code, since a table that needs repair produces exactly this symptom and is covered in fixing the WordPress database connection error.
Prove the fix with a timed request, not a page refresh
After changing a timeout, measure. The curl -w line from check 2 prints time to first byte and total time, so you can see whether the request now finishes in 4 seconds or still crawls to 140. If it finishes in 4 seconds, the timeout change was cosmetic and the real fix was the batching or the plugin. If it still crawls, you raised a limit without removing the cause and the 504 will return the moment traffic picks up.
A useful next step is to log slow requests yourself rather than waiting for the host to notice. Start a timer in a mu-plugin on init, compare it against the current time on shutdown, and append anything over five seconds to a file with the URL and the current user. That log catches the request that is about to become a 504 while it is still a 200, which is the only window where you can fix it quietly.