Custom PHP

PHP Performance Profiling: Measure First, Optimize Second

PHP performance profiling is the practice of measuring where request time actually goes before you touch a line of code. In my builds it means setting a TTFB budget, capturing Xdebug or Tideways traces from the slowest routes, isolating slow queries with EXPLAIN ANALYZE, then changing one thing and re-measuring. Guesswork without a trace is how a "fix" makes the p95 worse.

By Saif Al Jahanwebdev-saif.com

What PHP performance profiling actually tells you

PHP performance profiling answers one question: where does the time between a request arriving and the first byte leaving go? That window — time to first byte, or TTFB — is the part a PHP developer can directly control. It includes PHP-FPM queueing, autoloading, framework boot, database calls, cache misses and template rendering, but not DNS, TLS or the browser rendering the response. I separate those deliberately. A page can have a 120 ms origin and still show a poor Largest Contentful Paint because of an uncompressed hero image. Profiling only earns its keep when it points at a specific function, query or wait state you can change. A flat list of average timings will not do that; you need call graphs, wall-clock spans and percentile distributions from the routes that real users hit.

  • Isolate origin TTFB from network and browser time
  • Capture the slowest routes, not the average homepage
  • Look at p95 and p99, not just the mean
  • Trace one request end to end before changing code

Set a TTFB budget before you optimize anything

A budget turns "this feels slow" into a number you can fail against. On the PHP applications I build, a practical origin target is under 200 ms at p95 for cached HTML and under 600 ms for a dynamic, database-backed page; anything past one second needs a trace before the next feature ships. I record the number with the same tooling that will later verify the fix — server access logs with $request_time, a real-user monitoring tag, or a synthetic check from a region close to the server. In Mymensingh I test from a local connection and from a Singapore node, because distance to the origin changes what TTFB means. Write the budget down beside the route name, not in a slide deck.

  • Under 200 ms origin TTFB at p95 for cached HTML
  • Under 600 ms at p95 for database-backed routes
  • Investigate anything over 1 s before adding features
  • Log $request_time and compare against real-user data

Reading Xdebug and Tideways traces without drowning in data

Xdebug and Tideways answer different questions, so I reach for different ones. Xdebug with xdebug.mode=profile and xdebug.start_with_request=trigger writes a cachegrind.out file only when a request carries the XDEBUG_TRIGGER cookie or query flag. I open that file in KCachegrind and sort by inclusive wall-clock time to find the call tree that dominates. It is accurate but heavy — never enable it on a busy production worker. Tideways, loaded as a PHP extension with tideways.api_key, runs continuously with low overhead and groups requests into named transactions with spans. That makes it the better tool for spotting a regression that started after a deploy. I use Xdebug for a deep, one-off look at a single request and Tideways for the trend line that tells me which request deserves the deep look.

  • xdebug.mode=profile with XDEBUG_TRIGGER for on-demand traces
  • Sort cachegrind output by inclusive time in KCachegrind
  • Tideways transactions and spans for continuous low-overhead data
  • Never leave the Xdebug profiler enabled on production workers

Hunting slow queries with EXPLAIN ANALYZE

Most PHP bottlenecks I find are database waits wearing a PHP costume. I start with the MySQL slow query log: long_query_time=0.5, min_examined_row_limit=1000, and log_queries_not_using_indexes enabled temporarily in staging. I run pt-query-digest from Percona Toolkit to group the noise into the few statements that account for most of the total time. For each candidate I run EXPLAIN ANALYZE — not plain EXPLAIN, because estimated rows often lie — and look for full table scans, filesort, and a large gap between estimated and actual rows. The fixes that usually follow are a composite index matching the WHERE and ORDER BY columns, removing an N+1 loop in the data layer, or caching a result that does not need to be recalculated on every request. I re-run the same digest afterwards to confirm the change.

  • long_query_time=0.5 and min_examined_row_limit=1000 in staging
  • Group slow log entries with pt-query-digest
  • Prefer EXPLAIN ANALYZE over estimated EXPLAIN plans
  • Watch for full scans, filesort and N+1 query loops

The measure, change, re-measure loop I use in production

Profiling is only useful if it changes what you ship. My loop is deliberately boring: capture a baseline trace on the target route, pick the single largest cost, change one thing, deploy behind OPcache, then capture the same route again under the same conditions. Comparing a cold, uncached request to a warm one is meaningless, so I warm the cache or preload scripts with opcache.preload first and note the state. I also check PHP-FPM slowlog with request_slowlog_timeout=2s to catch workers stuck in one function, and pm.max_children to rule out queueing that no amount of code optimisation will fix. If the p95 does not move, I revert. One change per measurement keeps the causal story honest; batching five fixes into one deploy tells you nothing.

Common profiling mistakes and trade-offs

The first mistake is optimising before measuring, which usually means speeding up a function that accounts for two percent of the request. The second is profiling in an environment that does not resemble production: no OPcache, a single dataset row instead of a million, and a development machine on the same LAN as the database. I keep a staging box with production-sized data and the same PHP version and extensions. The third mistake is chasing average latency while the p95 suffers — averages hide the slow requests users remember. There is also a real trade-off: deep tracing adds overhead, and Tideways or APM sampling always misses some requests. I sample deliberately, keep traces short, and accept that a trace is evidence, not a complete census. At webdev-saif.com I publish the budget and before/after numbers in the project notes so the next developer does not repeat the investigation.

  • Profile with production-sized data and the same PHP version
  • Do not leave Xdebug profiling on in production
  • Optimise for p95, not the average
  • Change one variable per deployment

Frequently asked questions

What is PHP performance profiling?

It is the process of recording where a PHP request spends its time so you can fix the real bottleneck. In practice I capture a trace with Xdebug or Tideways, read the call graph and spans, correlate them with the MySQL slow query log, and re-measure after each change. Without that evidence, optimisation is guesswork.

What is a good TTFB for a PHP site?

In my builds a practical target is under 200 ms at p95 for cached HTML and under 600 ms for dynamic, database-backed pages, measured at the origin. Anything consistently above one second deserves a trace. Treat those numbers as budgets to tune for your traffic and geography, not universal guarantees — distance and hosting change the baseline.

Should I use Xdebug or Tideways in production?

Tideways is designed for continuous production profiling with low overhead; the Xdebug profiler is heavier and I only enable it on demand with XDEBUG_TRIGGER on a single request or in staging. Running full Xdebug profiling on a busy production worker adds latency and large cachegrind files. Use Tideways for trends, Xdebug for a deep one-off trace.

How do I find slow MySQL queries behind a slow PHP page?

Enable the MySQL slow query log with a sensible long_query_time, group entries with pt-query-digest, then run EXPLAIN ANALYZE on the worst statements. Look for full table scans, filesort and a big gap between estimated and actual row counts. Then check the PHP data layer for N+1 loops before adding indexes.

Why is my PHP app slow even though every function looks fast?

Because the time is often spent waiting, not computing: database locks, an unindexed query, a saturated PHP-FPM pool, or a cache miss that triggers remote calls. Check pm.max_children and the FPM slowlog, then read the spans in a trace. A flat list of function timings can hide all of those waits.

When should I reach for OPcache?

OPcache should be on by default in production; it stores compiled script bytecode so PHP does not reparse files on every request. I set opcache.enable=1, give it enough memory, and use opcache.validate_timestamps=0 with a deliberate deploy reload. It fixes parse overhead, not slow queries — profile first to see which problem you have.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .