PHP-FPM looks like a single service from the outside: a socket, a process, a stream of responses. Inside, it is a process-based concurrency system with a small number of moving parts, each of which fails in a specific, predictable way. Most production incidents trace back to a misunderstanding of one of those parts.
The single most important fact about PHP-FPM: each worker process handles exactly one request at a time. There is no in-process concurrency. Your maximum concurrent request capacity equals your number of active worker processes. Everything else in the system exists to feed, queue, recycle, or protect those workers.
What it is and why it matters
PHP-FPM (FastCGI Process Manager) is a master-worker process architecture. A single master process manages one or more pools of worker processes. Each pool has its own socket, its own worker limits, its own user context, and its own configuration. The master forks workers, reaps them when they die, maintains a shared-memory scoreboard of their state, and implements the process manager strategy that decides when to spawn or kill.
PHP itself is share-nothing and request-scoped. A worker boots the PHP runtime, executes one request, returns the response, and goes idle. There is no event loop, no async I/O, no thread pool inside the worker. When a worker blocks on a database query or an external API call, it blocks completely. It holds its slot and uses no CPU while it waits. This is why PHP-FPM can hit saturation with CPU at 10%: all workers are parked on I/O, none are computing, and there are no spare slots for new requests.
How it works
The request lifecycle
A request flows through PHP-FPM in the following stages:
- A web server (nginx, Apache, Caddy) receives an HTTP request that requires PHP processing.
- The web server opens a FastCGI connection to PHP-FPM via a Unix domain socket or a TCP socket.
- If a worker is currently blocking on
accept(), it picks up the connection immediately. If all workers are busy, the connection waits in the kernel-managed socket backlog queue. - The worker initializes the PHP runtime for that request, executes the script, sends the response, and returns to idle (back to
accept()on the shared listening socket). - If
pm.max_requestsis set, the worker tracks its completed request count and self-terminates after finishing the current request and delivering the response. The master spawns a replacement.
A critical consequence of step 3: the master does not dispatch requests to workers. Workers call accept() on the shared listening socket themselves. The master is pure control plane; it manages worker lifecycle, not request routing.
The master process
The master does no per-request work. Its responsibilities are control-plane only:
- Maintain the scoreboard: a shared memory segment tracking each worker’s state, PID, current request URI, and request duration.
- Fork new workers and reap dead ones via SIGCHLD.
- Implement the process manager strategy (static, dynamic, or ondemand).
- Handle emergency restart: if too many children die from SIGSEGV or SIGBUS within a configured interval, the master calls
execvp()on itself to fully restart. This is disabled by default (emergency_restart_threshold = 0). - Expose the status page and ping endpoint when configured via
pm.status_pathandping.path.
Signal handling is specific and worth remembering: SIGUSR1 reopens logs only; SIGUSR2 is a graceful reload that re-reads config and replaces workers; SIGQUIT is a graceful stop; SIGTERM and SIGINT are immediate stops; SIGHUP is not handled and terminates the process.
A critical detail about SIGUSR2: unlike nginx, PHP-FPM does not spawn new workers before draining old ones. Old workers are drained first, then the master re-execs and spawns replacements. There is a brief window with reduced or zero worker capacity. Brief 502 errors and listen queue spikes during a reload are expected, not incidents.
The FastCGI socket and kernel listen backlog
Between the web server and the workers sits the socket backlog. This is a kernel-managed queue sized by listen.backlog in the pool configuration. When all workers are busy, new connections queue here. When the backlog is full, the kernel drops new connections with no notification to PHP-FPM. The web server sees connection refused or timeout and returns 502.
The backlog default changed across PHP versions. On Linux, PHP versions before 8.2 default to 511. PHP 8.2 and later default to -1, which maps to the kernel’s net.core.somaxconn (typically 4096 on modern Linux, historically 128). The kernel clamps the effective backlog to somaxconn regardless of what listen.backlog requests, so both values must be raised together. Raising listen.backlog alone does nothing if somaxconn is lower.
This queue is invisible to PHP-FPM’s own instrumentation. The status page reports current backlog depth, but it cannot report dropped connections. When the backlog overflows, the status page shows listen queue at its maximum and nothing more. Detecting drops requires kernel-level counters such as TcpExtListenOverflows in /proc/net/netstat:
# Cumulative listen socket overflows since boot
nstat -az TcpExtListenOverflows
# If nstat is unavailable, the raw counter lives in the TcpExt line of /proc/net/netstat
Process manager modes
The process manager decides how many workers exist at any time. Three modes are supported:
| Mode | Behavior | Monitoring implications |
|---|---|---|
| static | Fixed number of workers, always running, set by pm.max_children | Predictable memory. Active/idle ratio is the only variable. max children reached is always 0. |
| dynamic | Scales between pm.min_spare_servers and pm.max_children based on demand | Most common mode. Monitor total process count for scaling behavior. max children reached counter is meaningful. |
| ondemand | Spawns workers only when requests arrive, kills idle workers after pm.process_idle_timeout | Zero workers at idle is normal. Cold-start latency on first request. max children reached counter is meaningful. |
The scaling in dynamic mode is reactive, not predictive. The master checks spare server counts on a timer and forks one worker at a time. Under a sudden burst, this is slower than the traffic arriving. Static mode eliminates this latency at the cost of constant memory usage. Many experienced operators prefer static in production for exactly this reason.
The shared OPcache segment
OPcache is a single shared memory segment, allocated via mmap(MAP_SHARED), used by all workers under the same FPM master to cache compiled PHP bytecode. The default opcache.memory_consumption is 128 MB. Workers share the compiled bytecode pages, but tools like ps count those shared pages in each worker’s VmRSS (in the RssShmem component), which overstates unique memory usage by 30 to 50%. Use PSS via smem or /proc/<pid>/smaps_rollup for accurate per-process accounting:
# Accurate per-worker memory using proportional set size (PSS)
smem -P php-fpm -k
# Without smem: read PSS from smaps_rollup for any worker PID
awk '/^Pss:/{print $2}' /proc/$(pgrep -f 'php-fpm: pool' | head -1)/smaps_rollup
When OPcache fills up, PHP evicts cached scripts and recompiles them on the next request. This is a silent performance cliff: CPU spikes across all workers, latency increases uniformly, and nothing in the FPM status page shows it. The signal lives in opcache_get_status(), specifically the free_memory and wasted_memory fields in the memory_usage array.
flowchart LR
WS[Web server] -- FastCGI --> SQ[Socket backlog
kernel-managed]
SQ -- accept --> W1[Worker 1]
SQ -- accept --> W2[Worker 2]
SQ -- accept --> Wn[Worker N]
M[Master process] -. fork/reap .-> W1
M -. fork/reap .-> W2
M -. fork/reap .-> Wn
W1 -- read/write --> OC[(OPcache
shared memory)]
W2 -- read/write --> OC
Wn -- read/write --> OC
M -. scoreboard .-> SB[(Shared memory
scoreboard)]The diagram shows the core data flow. Requests enter from the left and queue in the kernel backlog. Workers call accept() on the shared listening socket to pick up connections. The master manages worker lifecycle separately, fork/reaping workers and maintaining the scoreboard. Workers share the OPcache segment for compiled bytecode.
Where it shows up in production
The mental model predicts six characteristic failure archetypes.
Worker exhaustion. All
pm.max_childrenslots are occupied. New requests queue in the backlog. Once the backlog fills, connections are refused. Users see 502 or 504. The most common PHP-FPM failure mode.Slow request cascade. A subset of requests block on a slow backend (database, external API). Those workers hold slots for extended periods while using no CPU. Effective concurrency drops. Throughput collapses even though CPU is low. This is the most common cause of archetype 1.
Memory leak spiral. Workers accumulate memory over time, especially when
pm.max_requestsis 0. Eventually the OOM killer fires, taking out workers or the master. Restarting fixes it temporarily, but it recurs. The defaultpm.max_requestsof 0 (never recycle) is the enabling condition.Socket backlog overflow. Even with free workers, if the connection arrival rate exceeds the rate at which workers can accept, the kernel backlog fills. Rare in normal operation, but happens during SYN floods or massive bursts. Invisible to PHP-FPM; detectable only via kernel counters.
Session lock serialization. With file-based sessions, concurrent requests from the same user block on
flock(LOCK_EX)atsession_start(). AJAX-heavy pages or parallel API calls from the same session ID serialize completely, appearing as slowness. The lock is exclusive, so even read-only session access blocks.Cold start penalty. After a restart or in ondemand mode, OPcache is empty. Every request compiles PHP from source, causing high CPU and slow responses until the cache warms. A full restart with simultaneous worker replacement turns a brief warmup into a throughput collapse if traffic is high.
Tradeoffs and common misuses
Static versus dynamic versus ondemand. Static wastes memory during idle periods but provides instant burst capacity and eliminates fork latency. Dynamic scales with demand but reacts too slowly for sharp bursts. Ondemand saves memory at idle but imposes cold-start latency on every traffic return. For most steady-traffic production workloads, static or a well-tuned dynamic pool with high pm.min_spare_servers outperforms ondemand.
pm.max_requests = 0. This is the default in many distributions. Workers never recycle, which allows memory leaks to accumulate without bound. Setting it to 500 or 1000 is near-zero cost (a fork every 500 requests adds negligible overhead) and provides a safety net against unbounded growth. The risk of leaving it at 0 is unjustifiable for any production deployment.
max_children based on CPU. The most common capacity mistake. PHP-FPM workers spend most of their time waiting on I/O, not computing. You can run 50 to 200 workers on a 4-core machine if memory allows. The binding constraint is memory: max_children = (available_RAM * 0.7 - OS_overhead) / avg_worker_RSS. Setting it based on CPU cores wastes capacity and invites premature exhaustion.
Listen backlog without somaxconn. Raising listen.backlog to 65535 does nothing if net.core.somaxconn remains at its default. The kernel clamps the effective backlog to the lower of the two. Both must be raised together. Note that changing listen.backlog requires recreating the socket, which means a full restart, not just a reload.
Ignoring OPcache in capacity planning. OPcache is shared memory, separate from per-worker RSS. It degrades performance across all workers simultaneously when it fills. Capacity math that accounts only for worker RSS misses this shared resource entirely.
Signals to watch in production
| Signal | Why it matters | Warning sign |
|---|---|---|
| Active processes / max_children | Primary saturation ratio. When active equals max_children, the next request queues. | Sustained above 80% during normal traffic. |
| Listen queue depth | Earliest direct signal of user-facing degradation. Non-zero means requests are waiting. | Any sustained non-zero value. |
| Idle processes | Headroom buffer. Near-zero means one burst away from queuing. | Sustained near zero in dynamic or static mode. |
| Max children reached counter | How often the process manager wanted to spawn but could not. Meaningful only in dynamic and ondemand. | Incrementing during normal traffic. |
| Per-worker RSS | Memory leak detection. Growth between recycles indicates a leak. | Monotonic increase over hours or days. |
| Slow requests counter | Application performance degradation. Requires request_slowlog_timeout to be set. | Rate of change above baseline. |
| OPcache hit rate | Cache effectiveness. Below 99% after warmup means recompilation overhead. | Below 95% sustained with uptime over 30 minutes. |
| OPcache free memory | Cache saturation. When full, eviction and recompilation begin. | Free memory below 10% of total. |
How Netdata helps
Netdata’s PHP-FPM collector pulls the status page metrics at per-second resolution. PHP-FPM saturation events unfold in seconds, so coarser polling misses transient queue buildups and the first moments of a dependency-induced worker drain.
- Active, idle, and total process counts are collected per pool, so multi-pool deployments show independent saturation rather than misleading aggregates.
- Listen queue depth and the max children reached counter are tracked as both instantaneous values and rates of change, separating brief bursts from sustained saturation.
- Per-worker RSS from the process table is correlated with FPM status metrics, so memory leak trends appear alongside worker count and saturation signals.
- OPcache memory usage and hit rate are collected alongside FPM metrics, making the shared-cache failure mode visible without separate instrumentation.
- Web server 502 and 504 rates from nginx or Apache logs correlate with FPM saturation, confirming whether queuing has reached user-visible errors.
- ML anomaly detection flags unusual shifts in active worker ratios, listen queue depth, and OPcache hit rate without requiring static thresholds.
Related guides
- PHP-FPM monitoring checklist: the signals every production pool needs
- PHP-FPM monitoring maturity model: from survival to expert
- PHP-FPM worker exhaustion: all workers busy and requests piling into the backlog
- PHP-FPM “server reached pm.max_children setting (N), consider raising it”
- PHP-FPM active processes near max_children: reading pool utilization
- PHP-FPM idle processes at zero: no burst headroom left
- PHP-FPM listen queue growing: the earliest signal of saturation
- PHP-FPM sizing pm.max_children: by memory, not by CPU cores
- PHP-FPM slow request cascade: one slow dependency drains the whole pool
- PHP-FPM 504 Gateway Timeout: requests accepted but never finishing in time
- PHP-FPM slow log: turning on request_slowlog_timeout to see what is slow
- PHP-FPM request duration climbing: spotting stuck and outlier workers






