A WordPress page that sends its first byte in 60 ms and one that takes 900 ms are usually the same code on the same hardware. The difference is whether the request touched PHP at all. Everything else here — pool sizing, OPcache, Redis, indexes — only changes what happens on a cache miss, and a miss is the expensive path by definition. So the order of work is fixed: push the anonymous page-cache hit ratio as high as the site honestly allows, then shorten the miss path for requests that genuinely must run PHP. Doing it the other way round is how a team spends a week tuning pm.max_children on a site whose cache never hit because every ad click carried a tracking parameter. If you have not split your TTFB into phases yet, do that first: measuring WordPress TTFB across the full request lifecycle covers measurement and is not repeated here.
What you’ll accomplish
- A measured page-cache hit ratio for anonymous traffic, plus a written list of every cookie and query parameter allowed to bypass the cache.
- Connection cost removed where it is removable: TLS session resumption, origin keep-alive, HTTP/2, and an origin that is not on the wrong continent.
- A PHP-FPM pool sized from measured worker memory rather than a copied number, with
max children reachedat zero under real traffic. - OPcache holding the whole codebase without restarts, and a deploy procedure that stays correct with
opcache.validate_timestamps=0. - A persistent object cache, an autoload payload small enough to stop hurting, and a slow-query list with an index or a plugin decision against each entry.
Prerequisites
PHP 8.1 or newer under PHP-FPM, WordPress 6.x, and nginx, Apache or LiteSpeed in front of it. Root or sudo on the origin, WP-CLI 2.x for the site user, and curl on a machine outside the server. MySQL 8.0 or MariaDB 10.6 with access to the slow query log. A staging copy that mirrors production data volume, because index decisions made against a 200-row table are worthless. And a measurement you trust before you change anything — a single browser reload is not it.
How it works
TTFB on WordPress is a sum of layers, each with its own cost profile and its own fix. The structural fact that matters is that one layer can end the request early.
On a page-cache hit, the web server reads a file or a memory entry and writes it to the socket. PHP never starts, WordPress never bootstraps, no plugin runs, no query executes. The remaining cost is the connection: DNS, TCP, TLS, and the distance between visitor and whichever machine holds the entry. That small, mostly fixed budget is the floor for the whole site.
On a miss, the request falls through every layer beneath. It queues for a PHP-FPM worker. The worker retrieves or compiles the bytecode of several thousand PHP files through OPcache. WordPress loads its options — one cheap read if a persistent object cache is warm, one query plus a large unserialize if it is not. Then plugin and theme code runs on init, WP_Query executes, and the template renders. Any of those steps can dominate, and which one does differs between sites.
This is why the layers get worked top-down. A 40 % hit ratio means 60 % of traffic pays the full miss path, so the highest-value change is the one that moves traffic from the second column into the first.
Step-by-step
- Measure the current hit ratio before touching anything. Expose the cache status so you can read it from outside. On nginx with
fastcgi_cache, add the header and log the status:
add_header X-FastCGI-Cache $upstream_cache_status always;
log_format cachelog '$remote_addr $status $upstream_cache_status $request_time "$request"';
access_log /var/log/nginx/access.log cachelog;
Reload, wait for real traffic, then count:
awk '{print $3}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
Expected output is dominated by HIT:
84213 HIT
9127 MISS
2044 BYPASS
61 EXPIRED
If BYPASS or MISS dominates, fix that before anything else. On LiteSpeed the equivalent header is x-litespeed-cache; behind Cloudflare it is cf-cache-status.
- Find what is busting the cache. Two things do it in almost every case: query strings and cookies. Check one anonymous request:
curl -sI https://example.com/ | grep -iE '^(x-fastcgi-cache|cf-cache-status|age|cache-control|vary|set-cookie):'
The success signal is a cache status of HIT and no set-cookie line at all. A plugin that starts a PHP session or sets an analytics cookie on every anonymous response makes that response private, and most caches refuse to store it. Find the plugin and stop it setting the cookie for anonymous visitors.
For query strings, the usual configuration is a blanket bypass — the single most damaging line in a typical WordPress nginx config:
if ($query_string != "") { set $skip_cache 1; }
Every visitor arriving from an ad, a newsletter or a social share carries utm_source, fbclid or gclid, and every one of them misses. Replace it with an allowlist of the parameters that actually change the response, and key the cache on the path only:
map $arg_s$arg_p$arg_preview$arg_add_to_cart $skip_query {
"" 0;
default 1;
}
set $skip_cache $skip_query;
if ($request_method = POST) { set $skip_cache 1; }
if ($http_cookie ~* "wordpress_logged_in|wp-postpass|comment_author|woocommerce_items_in_cart|wp_woocommerce_session") { set $skip_cache 1; }
fastcgi_cache_key "$scheme$request_method$host$uri";
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
Dropping the query string from fastcgi_cache_key is only safe because everything that changes the response is in the bypass map — audit your own parameters before copying this. Test and reload:
nginx -t && systemctl reload nginx
Expected: syntax is ok followed by test is successful.
- Take the connection cost out of the hit path. Once hits are the majority, TLS and distance set the floor. Confirm the protocol and where the time goes:
curl -sI -o /dev/null -w 'http %{http_version} tls %{time_appconnect}s ttfb %{time_starttransfer}s\n' https://example.com/
Then confirm session resumption works, which removes a full round trip for repeat visitors:
openssl s_client -connect example.com:443 -reconnect < /dev/null 2>&1 | grep -E 'New, |Reused'
Expected: one New, line followed by several Reused lines. All-New means resumption is off. On nginx:
http2 on;
keepalive_timeout 65s;
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 1d;
ssl_session_tickets on;
If a CDN sits in front, keep the origin connection alive rather than reconnecting per request. And if the edge is in Montréal while the origin is in Frankfurt, every miss pays that round trip — moving the origin closer to the audience is often worth more than any PHP change.
- Size the PHP-FPM pool from measured memory. The number that matters is average resident memory per worker under real load:
ps --no-headers -o rss,cmd -C php-fpm8.3 | awk '{s+=$1; n++} END {printf "%d processes, avg %d MB\n", n, s/n/1024}'
Expected output resembles 12 processes, avg 96 MB. Take total RAM, subtract what MySQL, Redis, nginx and the OS need, and divide the remainder by that average. A 16 GB box giving 8 GB to PHP with 96 MB workers supports roughly 85 children — if the current config says 200, the box is one traffic spike away from swapping.
Turn on the status page in the pool config, usually /etc/php/8.3/fpm/pool.d/www.conf:
pm = dynamic
pm.max_children = 85
pm.start_servers = 12
pm.min_spare_servers = 8
pm.max_spare_servers = 24
pm.max_requests = 500
pm.status_path = /fpm-status
Validate and reload:
php-fpm8.3 -t && systemctl reload php8.3-fpm
Expected: configuration file /etc/php/8.3/fpm/php-fpm.conf test is successful. Then read the pool under load:
curl -s http://127.0.0.1/fpm-status | grep -E 'active processes|listen queue|max children reached|slow requests'
The success signal is max children reached: 0 and listen queue: 0. A non-zero listen queue is time added to TTFB before PHP has done anything.
- Make OPcache actually cache. The CLI SAPI has its own OPcache, so
php -ifrom a shell says nothing about the pool serving traffic. Read it through the web server with a temporary file:
cat > /var/www/example.com/opcache-check.php <<'PHP'
<?php
header('Content-Type: text/plain');
$s = opcache_get_status(false);
print_r($s['opcache_statistics']);
print_r($s['memory_usage']);
var_dump($s['cache_full']);
PHP
curl -s https://example.com/opcache-check.php | grep -E 'hit_rate|misses|oom_restarts|hash_restarts|num_cached_keys|bool'
rm /var/www/example.com/opcache-check.php
Expected: a hit rate above 99, zeros for oom_restarts and hash_restarts:
[opcache_hit_rate] => 99.62
[misses] => 812
[oom_restarts] => 0
[hash_restarts] => 0
[num_cached_keys] => 14208
bool(false)
If num_cached_keys is near max_cached_keys, or restarts are climbing, the cache is thrashing and affected requests recompile PHP on the way through. Count the files and size the settings above that number:
find /var/www/example.com -name '*.php' | wc -l
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=50000
opcache.validate_timestamps=0
opcache.validate_timestamps=0 removes a stat call per included file per request — thousands of syscalls on a plugin-heavy site. The cost is that PHP no longer notices edited files, so every deploy has to end with systemctl reload php8.3-fpm. If you cannot change deploys yet, keep validate_timestamps=1 with opcache.revalidate_freq=60. Full parameter reference: the PHP manual on OPcache.
- Add a persistent object cache, then fix what it carries. Without one, WordPress rebuilds every option, term and meta lookup from MySQL on every request:
wp cache type
Default means no persistent object cache; Redis or Memcached means a drop-in is active. With the Redis Object Cache plugin, confirm the connection and hit ratio:
wp redis status
redis-cli info stats | grep -E 'keyspace_hits|keyspace_misses'
redis-cli info memory | grep -E 'used_memory_human|maxmemory_policy'
Expected: Status: Connected, hits far exceeding misses, and maxmemory_policy:allkeys-lru so Redis evicts instead of erroring when full. An object cache does not fix the autoloaded-options problem — it moves a large unserialize off MySQL onto every worker, and a 6 MB alloptions entry still costs on every request. Measure it:
wp db query "SELECT ROUND(SUM(LENGTH(option_value))/1048576,2) AS mb, COUNT(*) AS n FROM wp_options WHERE autoload IN ('yes','on','auto','auto-on');" --skip-column-names
Expected output is two numbers, for example 0.42 318. Above roughly 1 MB or 1,500 rows this is a live problem — the autoloaded options audit covers finding the offenders, and cleaning up transient bloat covers their most common source.
- Work the query layer last. Turn on the slow log with a threshold low enough for WordPress reality:
mysql -e "SET GLOBAL slow_query_log = 'ON'; SET GLOBAL long_query_time = 0.2; SET GLOBAL log_queries_not_using_indexes = 'ON';"
Let it collect through a normal traffic period, then rank by total time rather than worst single execution — a 40 ms query running 900 times a minute costs more than a 2-second report nobody loads:
mysqldumpslow -s t -t 10 /var/log/mysql/mysql-slow.log
Expected: ten normalized queries with Count and Time columns. For each repeat offender, check the plan:
wp db query "EXPLAIN SELECT post_id FROM wp_postmeta WHERE meta_key = '_stock_status' AND meta_value = 'instock';"
A type: ALL row with a large rows count is a full scan. The default wp_postmeta schema indexes meta_key and post_id but not the pair, so filtered meta lookups scan. When one pair is proven hot, add a composite index:
ALTER TABLE wp_postmeta ADD INDEX meta_key_value (meta_key(32), meta_value(64));
This costs write throughput and disk, so add it against a measured query, never preemptively. Queries from plugin code hooked on init run on every uncached request including AJAX and REST — attribute them before you index around them, which is what query optimization with Query Monitor is for.
Validate it works
A TTFB claim is only meaningful with cache state and session state both stated. Measure warm and anonymous first, twenty samples, reported as percentiles rather than a single reading:
for i in $(seq 1 20); do curl -s -o /dev/null -w '%{time_starttransfer}\n' https://example.com/; done \
| sort -n | awk '{a[NR]=$1} END {print "p50", a[int(NR*0.5)], "p95", a[int(NR*0.95)]}'
Then cold, purging the page cache and taking the very next request:
find /var/cache/nginx -type f -delete
curl -s -o /dev/null -w 'cold %{time_starttransfer}s\n' https://example.com/
curl -s -o /dev/null -w 'warm %{time_starttransfer}s\n' https://example.com/
The gap between those two numbers is the true miss path, and it is what steps 4 through 7 move. If cold and warm are identical, the cache is serving nothing and step 2 is unfinished.
Then logged-in, using a cookie jar exported from a browser session rather than putting a password in your shell history:
curl -s -o /dev/null -b /tmp/wp-cookies.txt -w 'logged-in %{time_starttransfer}s\n' https://example.com/wp-admin/
Logged-in requests bypass the page cache by design, so this reflects the miss path alone. Track it separately; never average it with anonymous traffic. Finally, confirm the pool held: max children reached and oom_restarts should both still read 0. A single curl is a latency check, not a capacity check — for that use a load generator and watch those two counters while it runs.
Troubleshooting
The hit ratio barely moved after the cache config change. Check Set-Cookie on anonymous responses again, then check Vary. A response carrying Vary: Cookie or Vary: User-Agent fragments the cache into near-useless slices. Also verify the bypass map matches what you think: add add_header X-Skip-Cache $skip_cache always; temporarily and request a URL with a tracking parameter to confirm it returns 0.
Raising pm.max_children made everything worse. The pool now allows more concurrent workers than RAM supports, so the kernel swaps and every request waits on disk. Watch vmstat 1 5 and free -m: non-zero si and so columns while PHP is busy is the signature. Lower pm.max_children back to the measured figure — a request queued for 200 ms is far cheaper than one running against swap.
OPcache hit rate looks fine but restarts keep climbing. oom_restarts means opcache.memory_consumption is too small for the codebase; hash_restarts means opcache.max_accelerated_files is below the file count. Both flush the whole cache, and requests immediately after a flush recompile everything — a periodic TTFB spike with no traffic explanation is usually this.
Redis was added and TTFB went up. Either the instance is on another host, so a request doing 400 lookups now pays 400 network round trips — check redis-cli --latency and move it to a local socket — or maxmemory_policy is noeviction, so once full Redis returns errors and the drop-in silently falls back to MySQL on every read. Set allkeys-lru.
Anonymous pages are fast, /wp-admin/ is unbearable. That is the miss path with no cache to hide it, and it is normal for it to be slower — but seconds-slow usually means a large autoload payload, no object cache, or the heartbeat API firing against a busy wp_postmeta. Work steps 6 and 7; the page cache will never help here.
When this is the wrong approach
If TTFB is already around 100 ms and the complaint is that the site “feels slow”, the problem is front-end render. Largest Contentful Paint driven by render-blocking JavaScript, unoptimized hero images or a late-arriving font will not improve by one millisecond from anything here. Measure LCP and Total Blocking Time before spending another hour on the server.
Some sites are genuinely uncacheable at the page level: a members’ dashboard, per-customer pricing, a cart rendered in the header of every page. There, every request is a miss, the whole budget lives in steps 4 through 7, and edge-side fragment caching or moving the dynamic part into an authenticated API call is a design change rather than a tuning change. Say that out loud before promising a hit ratio that cannot exist.
Tuning inside a throttled container is also wrong. If the host caps CPU or IOPS below what the workload needs, a well-sized pool just queues more politely — check whether the plan is the constraint first. And if bots drive your misses, the fix is filtering at the edge, not a faster miss path for scrapers. The WordPress optimization documentation is a reasonable second opinion on scope.
Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.