A PHP site slows down. The first instinct is to raise memory_limit, add more PHP-FPM workers or install a bigger cache. Sometimes that works. Often it masks the real problem: the application does too much work per request, and no amount of server tuning will fix that. This article explains how to tell a configuration bottleneck from an architecture bottleneck, what to look for in each case, and when the honest answer is to redesign part of the system.
Configuration problems vs. architecture problems
A configuration problem is a mismatch between the server's settings and the application's actual workload. The code is fine; the environment is not tuned for it. Typical examples:
memory_limitset to 128 MB when the CMS import job needs 256 MB.max_execution_timetoo low for a report that legitimately takes 45 seconds.- OPcache disabled or sized too small to hold the framework's compiled files.
- PHP-FPM running
pm = dynamicwithpm.max_childrenset to 5 on a site that regularly handles 30 concurrent visitors.
An architecture problem is in the application itself. It does too much synchronous work, queries the database too often, or holds shared resources longer than it should. Raising limits lets it finish, but every request still does unnecessary work. Typical examples:
- A product listing page that runs one SQL query per product to fetch its category — an N+1 query pattern.
- A checkout flow that calls a payment gateway, a shipping API and an inventory service in sequence, blocking the PHP worker for the sum of all three response times.
- A dashboard that recalculates aggregate statistics on every page load instead of reading a cached result.
The practical test is simple: after you tune the server to its reasonable ceiling, does the problem stay? If yes, the code or its design needs to change.
Worker exhaustion: the clearest signal
PHP-FPM keeps a pool of worker processes. Each worker handles one request at a time. When all workers are busy, new requests queue. If the queue fills, Nginx or Apache returns a 502 or 504.
Check the pool status. With pm.status_path enabled in www.conf, a request to that path reports active, idle and total processes, plus the listen queue length:
curl -s http://127.0.0.1/status?full | grep -E 'active|idle|listen queue'
If active processes equals max_children and listen queue is growing, workers are exhausted. The question is why.
Configuration cause: max_children is set too low for the traffic. Each request finishes in 50–200 ms, but there are not enough workers to serve concurrent visitors. The fix is to raise pm.max_children within the server's RAM budget. A worker running a typical WordPress or Laravel request uses 30–60 MB. On a 4 GB server, 50–80 workers is a reasonable ceiling. The PHP-FPM configuration reference documents every pool directive.
Architecture cause: each request holds a worker for 2–10 seconds because it waits on a slow query, a remote API call or a synchronous file operation. Even 50 workers cannot keep up when every one of them is blocked. Adding more workers consumes RAM without reducing wait time. The fix is in the application: move slow work off the request path.
Slow queries and the N+1 pattern
Enable the MySQL slow query log (long_query_time = 1) and watch what appears. A single expensive query is a tuning problem — add an index, rewrite the join. A hundred fast queries that do the same thing is an architecture problem.
The N+1 pattern is the most common. A controller loads a list of 50 products, then loops through them and runs a separate query for each product's category, brand and stock count. The page works, but it fires 150+ queries. Each one is fast; together they add 500 ms to the response.
-- N+1: one query per product category
SELECT name FROM categories WHERE id = 12;
SELECT name FROM categories WHERE id = 7;
SELECT name FROM categories WHERE id = 12; -- same category, queried again
...
-- Fixed: one query for all needed categories
SELECT id, name FROM categories WHERE id IN (12, 7, 34, 5);
Frameworks offer eager loading (with() in Laravel/Eloquent, joinedload() in SQLAlchemy) to solve this in application code. If the codebase has grown organically and nobody owns the query layer, this is not a quick server-side fix — it is custom software development work: someone needs to trace the data-access paths and restructure them.
Synchronous external calls
A PHP request that calls a payment API, waits for the response, then calls a shipping API, then sends a notification email, blocks the worker for the total time of all three operations. If the payment API takes 800 ms, the shipping API takes 400 ms and the email relay takes 300 ms, the page response is at least 1.5 seconds — plus the application's own work.
No PHP-FPM setting shortens that chain. The fix is architectural:
- Parallelise where possible. If the shipping quote does not depend on the payment result, request both at once. PHP 8.1+ Fibers or libraries like Guzzle's async requests can overlap independent calls.
- Defer what the user does not need to see. The confirmation email, the analytics event, the inventory sync — push them to a queue (Redis, RabbitMQ, a database job table) and let a background worker handle them after the response is sent.
- Set timeouts on every outbound call. A missing timeout on a third-party API turns a slow partner into a site outage. Five seconds is generous for most payment gateways.
Queue-based processing is a design change. It introduces a worker process, a retry strategy and a failure mode (what happens when the queue backs up). That is application architecture, not server configuration.
Sessions, shared state and horizontal scaling
PHP stores sessions on disk by default (session.save_handler = files). On a single server this works. The moment traffic justifies a second web server behind a load balancer, file-based sessions break: a user authenticated on server A gets a fresh, empty session on server B.
Quick fixes include sticky sessions at the load balancer (binds a user to one server, defeating the purpose of load balancing for failover) or copying session files between servers (fragile, slow). The durable fix is a shared session store — Redis or Memcached — configured in php.ini:
session.save_handler = redis
session.save_path = "tcp://redis.internal:6379"
This is a small configuration change with a large architectural implication: the application now depends on a network service for every authenticated request. Redis must be monitored, backed up and sized for the session volume. If the application also caches data in local files, those caches become stale across nodes too.
Horizontal scaling works when the application is stateless by design — when it reads shared state from a service, not from the filesystem. Reaching this point often means rethinking how the application handles uploads, caches, locks and temporary files. Understanding how PHP-FPM manages pools and processes is part of the picture, but the pool configuration only decides how many workers exist — not whether the application is ready to run on more than one machine.
Caching: when it hides the problem
Caching is the most effective performance tool and the most common way to avoid fixing the real issue.
OPcache eliminates the cost of compiling PHP files on every request. It is a configuration concern: enable it, size it to hold the full codebase, and validate timestamps in production. The OPcache configuration reference explains each directive. If the site is still slow with OPcache enabled and properly sized, the bottleneck is not compilation.
Application-level caching (page cache, object cache, query result cache) reduces repeated work. But a cache that is necessary for the site to function at acceptable speed is a warning sign. What happens when the cache is cold — after a deployment, a restart, or when a new product page is requested for the first time? If the uncached response takes 8 seconds, the architecture is relying on the cache to paper over an expensive code path.
A healthy caching strategy has two properties: the uncached path is tolerable (slow, but not broken), and the cache invalidation is deliberate (not "restart Memcached and hope"). When neither is true, the next step is to reduce the work the uncached path does — which means changing application code, not cache settings.
Profiling: separating fact from instinct
Server metrics (CPU, RAM, disk I/O, network) tell you that something is wrong. A profiler tells you where.
Xdebug's profiler mode generates cachegrind files that show time spent in each function. For production, Xdebug is too heavy; use a sampling profiler like Tideways, Datadog's PHP tracer, or the SPX extension. The goal is to find the function or query that dominates wall-clock time.
Common findings:
- A single function takes 60% of the time — usually a database call or an API request. Fix that one path.
- Time is spread across hundreds of small calls — the framework itself is doing too much per request. Consider whether the page needs server-side rendering at all, or whether a static cache or a CDN edge page would serve it.
- Autoloading is expensive — Composer's
classmapoptimisation (composer dump-autoload -o) is a configuration fix. If the application loads 400 classes per request, the loading cost is a symptom of a monolith that initialises everything for every route.
Profiling turns a vague "the site is slow" into a specific "this query in this controller on this route takes 1.2 seconds." That specificity is what separates a server tuning task from a software architecture services engagement — the first adjusts settings around existing code; the second restructures the code itself.
A safe remediation plan
When a site is slow in production, the pressure is to change something fast. A disciplined sequence reduces the risk of making it worse:
- Measure before changing. Record the current response time (p50, p95, p99), error rate and resource usage. Without a baseline, you cannot tell whether a change helped.
- Fix configuration first. Enable OPcache, size the FPM pool, raise limits that are provably too low. These changes are low-risk and often buy time for deeper work. A performance review can identify the quick wins.
- Identify the top offender. Profile the slowest route. If it is a query, explain it (
EXPLAIN SELECT ...). If it is an API call, measure its latency independently. - Decide: tune or redesign. If the top offender is a missing index, add it. If it is an N+1 loop across 12 models, that is a code change with a test plan, a staging step and a rollback strategy.
- Test the fix under load. A change that helps at 10 requests per second may fail at 100. Use a load-testing tool (k6, Locust, siege) against staging before promoting to production.
- Monitor after deployment. Watch the same metrics from step 1. If the p95 drops but errors rise, the fix introduced a regression.
Steps 1–3 are server audit work. Steps 4–6, when redesign is involved, are engineering work that benefits from someone who can read the codebase, understand its data model and propose a change that does not break adjacent features.
When to call it an architecture problem
A few honest questions help draw the line:
- Does the slowest page run more than 20 database queries? → Likely an N+1 or a missing aggregate.
- Does the page call two or more external services in sequence? → The request is bound by network latency, not by PHP speed.
- Does the site break or become unusable when the cache is cold? → The cache is compensating for an expensive default path.
- Has
max_childrenbeen raised three times and workers are still exhausted? → Requests hold workers too long; the pool size is not the constraint. - Does adding a second server require application changes (sessions, file storage, cron jobs)? → The application was not designed for horizontal scaling.
None of these are failures. Most PHP applications were built for the traffic they had when they launched. Growth exposes assumptions that were reasonable at the time. Recognising the boundary between "this server needs tuning" and "this application needs restructuring" saves both time and money — and prevents the cycle of raising limits, watching them fill up, and raising them again.
If you are unsure which side of the line your site falls on, start with a free server check. A quick diagnostic often reveals whether the next step is a configuration change you can apply today or a structural conversation that needs a broader plan.