PHP FPM Max Children Sizing on Linux
Three Mondays in a row, at 09:04 local time, a 16 GB Ubuntu 24.04 server hosting a regional B2B parts portal fell off the network. Nginx threw 502 Bad Gateway errors, SSH took forty seconds to accept a key, and by 09:06 the kernel had killed mysqld to claw back memory. After a restart, the box ran cleanly all week—under 45% RAM on Thursday afternoon, zero leaks overnight. Then Monday arrived and it crashed on schedule.
If you've run PHP stacks for long enough, you know where I looked first. Inside /etc/php/8.3/fpm/pool.d/www.conf sat a classic guess:
pm = dynamic
pm.max_children = 250
Whoever provisioned the VM did napkin math: 16 GB divided by roughly 60 MB per worker, rounded down to 250. That guess ignored every other daemon on the box, ignored how worker memory swells under load, and turned a normal Monday login wave into a weekly outage.
Why an Oversized pm.max_children Hides Until Peak Load
Bad FPM limits stay invisible during quiet hours. On a normal Tuesday, this portal served about 18 dynamic requests per second at 110 ms average execution time, rarely keeping more than 10 workers busy. Setting pm.max_children to 50 or 500 behaved identically.
Monday at 09:00 AM was different. Roughly 350 warehouse staff and reps logged in at once to pull stock sheets, pricing tables, and CSV exports. Dynamic traffic jumped to 45 requests per second, and two unindexed reporting queries stretched average PHP execution time from 110 ms to 950 ms.
While workers sat blocked on MySQL, new requests kept arriving. PHP-FPM obeyed its config and forked past 60, 100, and 150 children. Two failures hit together:
- Physical RAM ran dry. Once the page cache collapsed,
kswapd0pegged all four vCPUs and the OOM killer shot MySQL first because it held the largest anonymous footprint. I walked through why Linux targets databases under pressure in our earlier postmortem on fixing the Linux OOM killer on web nodes. - Every extra PHP worker opened its own database connection. With MySQL's
max_connectionsstill at the default 151, the pool exhausted connection slots before memory even hit zero, repeating the failure chain from our breakdown of solving MySQL 1040 too many clients errors.
Systemd's kernel journal confirmed the kill right away:
sudo journalctl -k -g "Out of memory" --since "2026-11-02 09:00:00"
Nov 02 09:06:14 b2b-web-01 kernel: Out of memory: Killed process 1842 (mysqld) total-vm:8124912kB, anon-rss:6412380kB, file-rss:0kB, shmem-rss:0kB, UID:112 pgtables:13840kB oom_score_adj:0
Fixing this permanently took two measurements instead of guesses: true physical RAM per warmed worker via PSS, and actual concurrency demand via queueing math.
Step 1: Budget Everything Else Before Sizing PHP
A 16 GB cloud VM doesn't hand Linux 16,384 MiB once firmware and kernel reservations take their cut; free -m on this Ubuntu 24.04 box showed 15,980 MiB usable. Because MySQL 8.0, Redis 7, and Nginx shared the host, I measured every non-PHP component first:
- Usable RAM from
free -m: 15,980 MiB - MySQL 8.0 (
innodb_buffer_pool_size = 6Gplus connection buffers): 6,750 MiB - Redis 7 (
maxmemory 1024mbplus allocator overhead): 1,120 MiB - Nginx, OS base, systemd, kernel slabs, Prometheus exporter: 1,350 MiB
- Headroom buffer for Linux page cache and spikes (~15%): 2,400 MiB
Non-PHP allocations plus headroom total 11,620 MiB. Subtract that from 15,980 MiB and PHP-FPM gets 4,360 MiB—barely 4.26 GiB, not 16 GB. Never cut that 15% OS buffer; once page cache shrinks near zero, a routine backup or logrotate job pushes the box into swap thrashing.
Step 2: Measure Warmed Workers with smem and ps_mem
Reading RSS from top or ps breaks worker sizing in two ways. First, RSS double-counts shared pages—every worker maps the same php-fpm8.3 binary, C libraries like libicu, and our 256 MiB OPcache segment, inflating summed RSS by gigabytes. Second, measuring right after a reload fools you: a cold worker sits near 28 MiB, while a warmed worker that has hydrated Laravel models and built a Monday PhpSpreadsheet export retains a much larger Zend heap until it recycles.
What you need is PSS (Proportional Set Size) alongside USS (Unique Set Size, strictly private RAM). PSS divides shared pages evenly across mapping processes, so summing PSS equals true physical RAM. On Ubuntu 24.04, smem (via apt install smem) and ps_mem (via pipx install ps-mem) read /proc/<pid>/smaps_rollup directly.
Mid-morning on Monday, with 42 warmed workers active, I captured both:
sudo smem -t -k -P "php-fpm: pool www" -c "pid uss pss rss command"
PID USS PSS RSS Command
24108 64.2M 71.8M 118.4M php-fpm: pool www
24112 71.5M 79.1M 125.9M php-fpm: pool www
24119 83.8M 91.4M 138.1M php-fpm: pool www
... (39 more warmed workers) ...
-----------------------------------------------------------------
42 2.79G 3.10G 4.92G
Cross-checking only the pool PIDs with ps_mem showed the same split:
sudo ps_mem -p $(pgrep -d, -f "php-fpm: pool www")
Private + Shared = RAM used Program
2.8 GiB + 320.0 MiB = 3.1 GiB php-fpm8.3 (42)
---------------------------------
3.1 GiB
=================================
Notice the trap: summed RSS claimed 4.92 GiB, overstating physical RAM by 1.8 GiB. Actual pool usage was 3,176 MiB—320 MiB fixed shared memory plus 2,856 MiB private USS, averaging 68.0 MiB private RAM and 75.6 MiB PSS per worker.
Separating fixed shared overhead from per-worker USS gives a sharp RAM ceiling:
max_children = (4,360 MiB - 320 MiB) / 68 MiB = 59.4
Dividing by average PSS gives 4,360 / 75.6 = 57.6. Because a few export workers spiked to 84 MiB USS before recycling, I rounded conservatively to 55. Compare that to 250: 320 + (250 × 68) = 17,320 MiB—more RAM than the VM had installed. Once you have measured USS and PSS off your server, plugging them into an interactive PHP worker calculator is a quick way to verify your headroom math before editing production configs.
Step 3: Check Real Traffic Demand with Little's Law
RAM tells you how many workers the server can survive, not how many your traffic needs. For demand, use Little's Law from queueing theory:
L = λ × W
L is average concurrent active workers, λ is dynamic PHP requests per second, and W is mean execution time in seconds. Static files served by Nginx never touch PHP-FPM. Since our Nginx log writes $upstream_response_time in column 11 (or - for static files), one awk scan over Monday 09:00–09:10 pulled both inputs:
awk '$4 >= "[02/Nov/2026:09:00:00" && $4 <= "[02/Nov/2026:09:10:00" && $11 != "-" {n++; sum+=$11} END {printf "lambda=%.1f req/s avg_W=%.3fs\n", n/600, sum/n}' /var/log/nginx/portal-access.log
lambda=45.2 req/s avg_W=0.950s
Running the numbers explained the outage:
- Typical Tuesday:
L = 18.0 × 0.110 = 1.98concurrent workers. - Monday 09:05 AM (unindexed queries):
L = 45.2 × 0.950 = 42.9concurrent workers.
An average of 43 workers under a 55-worker ceiling leaves thin burst margin. Yet allowing 250 workers made everything worse. Crowding 140 workers onto 4 vCPUs and a lock-contended database pushed W from 0.95 s to 4.20 s. Feeding 4.20 s back into Little's Law yields L = 190 workers—a death spiral straight into OOM.
Capping pm.max_children = 55 breaks that loop. Because Nginx speaks the FastCGI protocol over a Unix socket, brief spikes past 55 concurrent requests queue cleanly in the kernel listen backlog until an active worker frees up. Waiting 200 ms in kernel space beats losing MySQL.
Little's Law also pointed to the real fix: lower W. Adding two composite indexes on the inventory tables dropped Monday peak W from 0.950 s to 0.310 s. Now L = 45.2 × 0.310 = 14.0 workers, leaving generous margin for 3x bursts inside our 55-worker cap.
The Final www.conf That Ended the Crashes
With RAM and queueing math aligned, I rewrote /etc/php/8.3/fpm/pool.d/www.conf and verified net.core.somaxconn sat above listen.backlog so the kernel wouldn't silently clamp the socket queue:
[www]
user = www-data
group = www-data
listen = /run/php/php8.3-fpm.sock
listen.backlog = 511
pm = dynamic
pm.max_children = 55
pm.start_servers = 16
pm.min_spare_servers = 12
pm.max_spare_servers = 24
pm.max_requests = 500
request_terminate_timeout = 30s
request_slowlog_timeout = 5s
slowlog = /var/log/php8.3-fpm-slow.log
pm.status_path = /fpm-status
Three companion directives matter alongside pm.max_children:
pm = dynamickeeps 12 warm spares ready for morning bursts while returning RAM overnight for backups and cron jobs. On a dedicated PHP-only box with flat load, static pools behave differently—I covered the benchmarks when comparing dynamic vs static PHP-FPM pool modes.pm.max_requests = 500recycles workers cleanly so heap memory retained after heavy CSV exports never lingers forever.request_terminate_timeout = 30sandrequest_slowlog_timeout = 5sstop stuck scripts from holding slots and catch N+1 regressions early.
We also left MySQL's max_connections at 151, leaving comfortable room for all 55 workers plus scheduled CLI jobs and admin access. Over the next four Mondays, active workers peaked at 29, memory stayed below 71%, and checking FPM logs for saturation returned zero:
sudo grep -c "server reached pm.max_children" /var/log/php8.3-fpm.log
A Five-Point Sizing Checklist Before You Reload FPM
Before editing pm.max_children on any Linux web box, run these five checks:
- Subtract resident memory of MySQL, Redis, Nginx, OS services, and a 15% buffer from
free -mtotal RAM. - Measure warmed workers under real traffic with
smemorps_memusingUSSandPSS, neverRSS. - Keep
pm.max_childrenstrictly below MySQLmax_connectionsminus cron jobs, replication, and admin slots. - Check peak concurrency with
L = λ × W; if demand exceeds your RAM ceiling, fix slow queries or scale out instead of risking OOM. - Expose
pm.status_pathinternally and alert onmax children reachedandlisten queuespikes early.
Guessing worker limits works right up until traffic and query latency collide. Ten minutes with smem and an awk scan gives you numbers that hold up on Monday morning.
Comments
Post a Comment