How Adjusting PHP‑FPM max_requests Stabilizes CPU and Memory Usage
This article explains how tuning the PHP‑FPM max_requests setting and modifying its source code can eliminate periodic CPU_IDLE and MEM_USED fluctuations in high‑traffic web services, resulting in smoother resource utilization and more reliable performance.
Abstract
By optimizing the PHP‑FPM process restart mechanism, the fluctuations of
CPU_IDLEand
MEM_USEDon production servers become smoother and more reliable.
Background
The delivery transaction service cluster showed severe
CPU_IDLEswings on monitoring charts. Historically both
CPU_IDLEand
MEM_USEDexhibit periodic drops and recoveries, prompting a deeper look at the PHP‑FPM manager.
Principle
Since PHP 5.3.3, PHP‑FPM is an official FastCGI manager supporting smooth start/stop, slow‑log, dynamic processes, and status reporting. It can operate in three modes:
static,
dynamic, and
ondemand. The article uses the
staticmode, which creates a fixed number of FastCGI processes to avoid the overhead of frequent process creation.
The periodic
CPU_IDLEand
MEM_USEDfluctuations were traced to the
max_requestsparameter. A too‑small value (1000) caused FastCGI processes to restart frequently during traffic peaks, increasing CPU load.
Optimization
Increasing
max_requeststo 10000 reduced the immediate
CPU_IDLEspikes, as shown in the first improvement graph.
However, the periodic fluctuations persisted because the FastCGI restart mechanism still counted requests per process. When the count reached
max_requests, the child process executed
fcgi_finish_request, terminated, and the master process received a SIGCHLD signal, triggering
fpm_children_buryto fork a new child.
In large‑scale production, hundreds of FastCGI processes can simultaneously hit the
max_requestslimit, causing the observed resource oscillations.
To keep the benefits of
max_requestswhile smoothing resource usage, the article proposes a small modification to the PHP‑FPM source: assign different
max_requestsvalues to each child process by randomizing the limit.
<code>php_mt_srand(GENERATE_SEED());
*max_requests = fpm_globals.max_requests + php_mt_rand() & 8191;</code>Result
After deploying the patched code, the final monitoring graphs show that both
CPU_IDLEand
MEM_USEDhave stopped their periodic swings, leading to stable CPU consumption and more accurate memory usage reporting.
This case demonstrates that fine‑grained tuning of PHP‑FPM in production environments can significantly improve backend performance stability.
Efficient Ops
This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.