Slow WordPress Backend? Find Slow PHP Functions with phpspy

Waiting or computing, the plugin and function behind it, and how you prove the fix made the backend faster.

  • Good ≤ 0.8 s
  • Needs improvement ≤ 1.8 s
  • Poor > 1.8 s
Arjen Karel
Updated · 12 min read
Share

A slow WordPress backend in short

A slow WordPress backend shows on pages a page cache can't serve: logged-in members, wp-admin, search. PHP builds them per request. A slow one waits on the database or an outside service, or runs PHP code. On our test site three plugins slowed a member's course page from 32 to 793 ms; phpspy, a PHP profiler for live servers, named each one.

Why is the WordPress backend slow when cached pages are fast?

Cached WordPress pages are fast because the page cache hands logged-out visitors a copy it stored earlier. Logged-in members, wp-admin, search results and carts skip that copy: PHP builds their page for that one request, so every slow plugin runs every time.

The test site is Acme Academy, an online woodworking school on WordPress, running on an Ubuntu VM on a Mac mini with nginx, PHP-FPM 8.4 and OPcache, and measured with curl from the Mac. Its course page comes from the page cache in 15 ms. Past the cache, the same page takes 683 ms for a logged-out visitor and 793 ms for a member.

The WordPress admin (wp-admin) is slow because its pages are never cached: every plugin's admin code runs on each load. The instructor's dashboard on the test site took 398 ms, and 355 ms of that was one dashboard widget asking an outside service for the next live session.

In field data this is the request part of TTFB, and it stands out once you split it by logged-in status: finding and fixing a slow TTFB shows how, and the request duration guide has the page cache and the Server-Timing code.

What makes a PHP request slow?

A slow PHP request is either waiting or computing. Waiting is PHP sitting idle on a database query or an outside HTTP call. Computing is PHP running code, or compiling it first when OPcache is off. A wait points to the code that asked for it, computing to the function itself. A PHP profiler shows which: on the test site's course page, phpspy found 45% of the samples waiting on an outside call, 47% on the database and 9% running PHP code.

The test site has five slow parts, each from a cause the WordPress docs, core Trac or the PHP manual describe. The savings are medians on the member's course page over 30 rounds with and without each fix.

  • The outside call. A "Next live session" box calls a scheduling API on every view, and the API takes 350 ms to answer, which adds 401 ms to the course page, 393 ms to the lesson page and 355 ms to the dashboard. In the profile that is a wait in curl_exec under acme_fetch_sessions, and the fix keeps the answer in a transient that WP-Cron refreshes.
  • The meta_value lookup. "More courses by this instructor" searches meta_value, a column without an index, in a postmeta table of 903,362 rows, and adds 277 ms while PHP waits in mysqli_query under acme_more_by_instructor. An instructor taxonomy and a tax_query fix it.
  • The progress box. "Your progress" parses and renders 600 lessons with parse_blocks() and render_block() on every request, which adds 125 ms (104 ms on the lesson page). The profile shows PHP frames under acme_build_progress with no wait on top; store the summary in user meta and rebuild it when a lesson is done.
  • The autoloaded option. A 2.6 MB autoloaded option made no measurable difference, 54 against 53 ms, and doesn't show in the profile. The fix is wp option set-autoload <name> off.
  • OPcache off. With OPcache off, the fixed page went from 54 to 124 ms. I didn't profile this one: check the setting, and set opcache.enable=1 for PHP-FPM.

WordPress core flags large autoloaded options: Site Health warns when they pass 800 KB together. Fix it, but without a persistent object cache, as on this site, don't expect a faster page.

Stacked bars per page from phpspy: waiting on an outside service, waiting on the database, running PHP code. Course page 45, 47 and 9%, lesson page 79, 8 and 14%, dashboard 90, 4 and 6%

What PHP was doing on each page, from phpspy's samples on the test site.

How do you find the slow plugin without server access?

Without server access, find the slow WordPress plugin with Query Monitor: it shows the database queries and outside HTTP calls of one page, grouped per plugin. The Code Profiler plugin adds the time in a plugin's own code.

  • Query Monitor. Shows the database queries per plugin with their time, the slow and duplicate ones, and every outside HTTP call with its caller and plugin. It is the first look, one page at a time while you are logged in, and needs only the plugin and an admin login.
  • Code Profiler. Times each plugin and the theme on a page you pick, front end or admin, plus file I/O, so you see which plugin's own PHP code is slow. It needs a plugin and an admin login, and the database and remote calls are in the Pro version.
  • Server-Timing (Performance Lab). A plugin that adds the time before the template and in the template to every response, so you read it for one request in DevTools and in field data through RUM.
  • A host's APM. Lists PHP, database queries and outside calls per transaction, the slowest transactions first, on live traffic. It works on hosts that offer it, once the host switches it on.
  • PHP-FPM slowlog. Keeps a PHP backtrace of every request slower than a timeout you set, which catches slow requests on live traffic for days. It needs access to the pool config, so your host sets it up, or you with root.

To see a member's page in Query Monitor, log in as a test member with the view_query_monitor capability, or set the Query Monitor authentication cookie in its Settings panel first. On the test site's course page its overview said 0.89 s for the page, 88 queries in 0.28 s and one HTTP API call in 0.36 s, and two panels named the plugins:

Query Monitor, Queries by Component on the course page: acme-courses with 5 queries in 0.25 s on top, acme-progress with 47 queries in 0.006 s, WordPress core with 31 queries in 0.003 s

Query Monitor, Queries by Component, on the test site's course page as a member.

Query Monitor, HTTP API Calls on the course page: one GET to the scheduling API, caller acme_fetch_sessions(), component Plugin: acme-live-sessions

Query Monitor, HTTP API Calls: the caller and the plugin of the outside call.

Query Monitor puts the 47 queries of the "Your progress" box at 6 ms, and that is right: the 104 to 125 ms it adds is PHP code, the time Code Profiler and a sampling profiler show.

The PHP-FPM slowlog writes a backtrace of every request that runs longer than request_slowlog_timeout, and it takes that timeout in whole seconds. On the test site, 300ms was read as 300 seconds, so check the value with sudo php-fpm8.4 -tt after you set it. At 1s, with the scheduling API slowed to 1.5 s for this test only, every slow request left a backtrace from curl_exec() through wp_remote_get() to acme_fetch_sessions() and acme_next_session() in acme-live-sessions.php.

I start with Query Monitor on the slow page, and go to a profiler on the server once I have root. Without root, ask your host or a developer with root to profile the slow pages. Send them the URLs, whether you were logged in and as which role, the times you see, and the Query Monitor screenshot.

How do you profile PHP on a live server with phpspy?

phpspy is a sampling profiler that reads the stacks of running PHP-FPM workers from outside, with no change to PHP or the site. On live traffic it shows what PHP was doing at each sample and which plugin called it, including the time in PHP code. It needs Linux and root on the server.

1. Build it from master. The last tagged release, v0.7.0 of July 2024, lists PHP up to 8.3; for PHP 8.4 and newer, build from master (checked on 20 November 2026).

git clone --recursive https://github.com/adsr/phpspy.git
cd phpspy
make

On arm64 the README calls support experimental, for PHP 8.3 and up; it worked on the test site with PHP 8.4.

2. Attach it to the pool's workers. Run it as root, outside the webroot.

sudo ./phpspy -H 99 -b 131072 -T 4 -r u -P "-x php-fpm8.4" -o run.txt

-P passes its argument to pgrep, so phpspy follows every process with that exact name: the master and the workers of every pool. Use the process name of your PHP version. phpspy uses one thread per process, so -T 4 covers the master and three workers; under real traffic set it to the pool's pm.max_children plus one. -H 99 is the sample rate in Hz, and -r u adds the request URI to each sample. -b 131072 raises the bytes per trace from the default 4,096, so a deep WordPress stack stays one trace.

3. Load the slow pages. Logged in as the user who sees them slow, 30 times. This loop prints each TTFB, logged out and as a member. The first line logs in once and keeps the member's cookie in member.jar; cb makes every URL new, so every request reaches PHP.

curl -s -o /dev/null -c member.jar -d 'log=USERNAME&pwd=PASSWORD' https://example.com/wp-login.php
URL=https://example.com/course/dovetail-joints-1/
for i in $(seq 30); do
  curl -s -o /dev/null -w "logged out %{time_starttransfer}\n" "$URL?cb=$RANDOM$RANDOM"
  curl -s -o /dev/null -w "member %{time_starttransfer}\n" -b member.jar "$URL?cb=$RANDOM$RANDOM"
done

On PHP-FPM every front-end page has the URI /index.php, so profile one page at a time.

4. Stop it and draw the flame graph. Ctrl-C stops it, or add -i 30000 to stop after 30 seconds. Then:

./stackcollapse-phpspy.pl <run.txt | ./vendor/flamegraph.pl >flame.svg

Each line of the collapsed profile is one stack, from the outside in, with the number of samples at the end. This is the biggest one from the test site's course page, cut to its last frames:

{closure:/var/www/acme/wp-content/plugins/acme-live-sessions/acme-live-sessions.php:33};acme_next_session;acme_fetch_sessions;wp_remote_get;WP_Http::get;WP_Http::request;WpOrg\Requests\Requests::request;WpOrg\Requests\Transport\Curl::request;curl_exec 782

Read it from the end. The last frame is what PHP was doing: curl_exec is waiting on an outside call, mysqli_query on the database, anything else is PHP code. The file path names the plugin, here acme-live-sessions. Just before WordPress's HTTP functions you find the code that asked for the wait, acme_fetch_sessions: the function you fix.

the phpspy flame graph of the course page, 1,751 samples over 30 requests: a wide tower for mysqli_query under acme_more_by_instructor, one as wide for curl_exec under acme_fetch_sessions, and a narrow one for acme_build_progress

phpspy flame graph of the course page: 1,751 samples over 30 requests.

Read the profile as shares, and expect PHP code to come out low. On the test site phpspy caught 67 to 75% of the samples its rate predicts per request, and logged 1,090 read errors for 9,106 stacks, mostly stacks that changed while it read them. A stack changes while PHP runs code, so the lost samples are mostly PHP code: the progress box got 9% of the course page's samples, while its fix saved 125 of 793 ms.

Is it safe to profile a production server?

Yes, with limits. phpspy reads the PHP-FPM workers without pausing them and changes nothing; on the test site it added no measurable time to a request. It stops on Ctrl-C or a time limit, and PHP-FPM keeps running.

  • What it records. With -r u only the URI. Leave out q and c: a query string can hold an email address or a token (on the test site, the secret key that turns a fix on for one request), and cookies hold login sessions.
  • The load. The course page took 792 ms with phpspy attached and 793 ms without. phpspy itself used 0.7% CPU and 1.9 MB of memory.
  • How long. A few minutes while you load the slow pages is enough. The output grows by about 3 MB a minute at one request at a time, and faster with real traffic.
  • Where the output goes. Outside the webroot, and deleted when you are done: it holds URIs and file paths of your site.

Never add -S on a live server: it pauses the PHP process while phpspy reads it.

How do you fix the slow plugin functions?

Moving the wait or the repeated work out of the visitor's request is what makes a slow plugin function fast. The three fixes below do that on the test site, shortened from its plugins.

For the outside call, keep the answer in a transient and let WP-Cron fetch it in its own request. While the transient is empty, the box shows nothing.

function acme_next_session() {
	$data = get_transient( 'acme_next_session' );
	if ( false === $data && ! wp_next_scheduled( 'acme_refresh_sessions' ) ) {
		wp_schedule_single_event( time(), 'acme_refresh_sessions' );
	}
	if ( ! $data ) {
		return '';
	}
	return '<p class="acme-next">Next live session: ' . esc_html( $data['title'] ) . ', ' . esc_html( $data['when'] ) . '</p>';
}

add_action( 'acme_refresh_sessions', function () {
	set_transient( 'acme_next_session', acme_fetch_sessions(), 15 * MINUTE_IN_SECONDS );
} );

For the meta_value lookup, give every course its instructor as a term once, then find the other courses with a tax_query. The term tables are indexed; meta_value is not.

add_action( 'init', function () {
	register_taxonomy( 'instructor', array( 'course' ), array( 'public' => true, 'label' => 'Instructors' ) );
} );

// Once, for every course: the instructor's name as a term.
wp_set_object_terms( $course_id, get_post_meta( $course_id, 'instructor_name', true ), 'instructor' );

// On the course page: the other courses with the same term.
$terms = wp_get_post_terms( $course_id, 'instructor', array( 'fields' => 'ids' ) );
$q     = new WP_Query( array(
	'post_type'      => 'course',
	'tax_query'      => array( array( 'taxonomy' => 'instructor', 'terms' => $terms ) ),
	'post__not_in'   => array( $course_id ),
	'posts_per_page' => 4,
	'no_found_rows'  => true,
) );

The progress summary stays the same until the member finishes a lesson. Build it then, keep it in user meta, and read it from there on every other page.

function acme_progress_summary( $user_id ) {
	$rows = get_user_meta( $user_id, 'acme_progress_cache', true );
	if ( ! is_array( $rows ) ) {
		$rows = acme_build_progress( $user_id );
		update_user_meta( $user_id, 'acme_progress_cache', $rows );
	}
	return $rows;
}

// A finished lesson rebuilds the summary.
add_action( 'acme_lesson_completed', function ( $user_id ) {
	update_user_meta( $user_id, 'acme_progress_cache', acme_build_progress( $user_id ) );
} );

How do you prove the fix made the backend faster?

Put the fix behind a switch that only you can trigger, load the page with and without it in random order in the same rounds, and compare the paired differences. On the test site the three fixes together took the member's course page from 793 to 32 ms.

  1. Build the switch. The fix runs only when the request carries a secret key, checked with hash_equals; a wrong key changes nothing. The request must also skip the page cache (on the test site, any query string did). Check both before the first measurement: the response header says which parts are off.
    <?php
    // wp-content/mu-plugins/acme-switch.php
    // ?acme_key=<key>&acme_off=s1,s2 turns those parts off for this request only.
    // The key is ACME_SWITCH_KEY in wp-config.php.
    function acme_off( $part ) {
    	static $off = null;
    	if ( null === $off ) {
    		$off = array();
    		if ( defined( 'ACME_SWITCH_KEY' ) && isset( $_GET['acme_key'], $_GET['acme_off'] )
    			&& hash_equals( ACME_SWITCH_KEY, (string) $_GET['acme_key'] ) ) {
    			$off = array_filter( explode( ',', (string) $_GET['acme_off'] ) );
    		}
    		header( 'X-Acme-Off: ' . ( $off ? implode( ',', $off ) : 'none' ) );
    	}
    	return in_array( $part, $off, true ) || in_array( 'all', $off, true );
    }
    
    // In the plugin, around the slow part:
    if ( acme_off( 's1' ) ) {
    	$data = get_transient( 'acme_next_session' ); // the fix
    } else {
    	$data = acme_fetch_sessions(); // the old code
    }
  2. Measure in rounds. Each round loads every variant once in random order, as the user who has the problem, with curl's time_starttransfer as TTFB.
    KEY=your-secret-key
    URL=https://example.com/course/dovetail-joints-1/
    for round in $(seq 30); do
      for off in $(printf '%s\n' none s1 s2 s3 all | sort -R); do
        t=$(curl -s -o /dev/null -b member.jar -w '%{time_starttransfer}' \
          "$URL?acme_key=$KEY&acme_off=$off&cb=$RANDOM$RANDOM")
        echo "$round $off $t"
      done
    done >rounds.txt
  3. Compare per round. Take the difference between the variants in each round, then the median and the spread of those differences. Server load that changes during the test hits both variants in the same round, so it drops out of the difference.
  4. Go live and watch the field data. The next day, the request part of TTFB for logged-in visitors in your RUM, such as CoreDash, shows the fix.

On the test site the outside call saved a median of 401 ms (95% interval 386 to 412), the meta query 277 (249 to 299) and the progress box 125 (94 to 144), each with the other slow parts still on. None of the three intervals comes near zero, so none of these savings is noise. On the lesson page, where the instructor box doesn't appear, the meta query fix saved just 4 ms, as it should.

TTFB per page with all slow parts on against all fixed: the member's course page 793 to 32 ms, the lesson page 515 to 34 ms, the wp-admin dashboard 398 to 45 ms, logged out past the cache 683 to 46 ms, and logged out from the page cache 15 ms

Median TTFB over 30 rounds on the test site, measured with curl.

Members waiting on every page, and a profile or Query Monitor screen you can't read yet? Bring it to an hour with me on your slow backend. We read it together, find the plugin and the function, and settle what your host or developer changes first.

About the author

Arjen Karel is a web performance consultant and the creator of CoreDash, a Real User Monitoring platform that tracks Core Web Vitals data across hundreds of sites. He also built the Core Web Vitals Visualizer Chrome extension. He has helped clients achieve passing Core Web Vitals scores on over 925,000 mobile URLs.

Arjen Karel

Need a faster site?

I'm Arjen, and I've been fixing slow sites for 17 years. If you're running into issues you can't fix yourself, send me your URL and let's have a chat.

Send me your URL
Arjen Karel
Arjen Karel, Web performance consultant since 2009

Why isn't our fix working?

Sometimes the CDN still serves the old HTML, or the fix went into the desktop template and mobile uses another one. Send me your URL and the problem, and I reply with a few times. I check your field data first, then we spend one hour on your site, and within a day you have my notes in writing. €350 excl. VAT.

Send me your URL

No developer to build the fix? I do the work myself, on a copy of your site.

Arjen KarelTTFB still red on mobile?Send me your URL