All posts

PHP-FPM Processes: pm Modes and How to Set max_children

The difference between static, dynamic and ondemand mode, and a simple way to calculate pm.max_children from the server's memory.

Marijan Kopčić••2 min read
PHP-FPM Processes: pm Modes and How to Set max_children

One PHP-FPM worker handles one request at a time. The number of workers therefore decides how many requests the server can handle in parallel, and also how much memory PHP can use.

Three modes

  • static: always runs exactly pm.max_children processes. No startup cost, but the memory is always taken. Good for a server that runs a single application.
  • dynamic: the number of processes moves between pm.min_spare_servers and pm.max_children. A sensible choice for most cases.
  • ondemand: processes start only when a request arrives and stop after pm.process_idle_timeout. Saves memory on servers with many low-traffic sites, at the cost of a slower first request.

Calculating max_children

First measure how much memory one worker uses (the process name depends on the version):

ps -o rss= -C php-fpm8.3 | awk '{s+=$1; n++} END {print s/n/1024 " MB"}'

Then:

max_children = memory reserved for PHP / average per process

Example: the server has 4 GB, the database and the system take 1.5 GB, which leaves 2.5 GB. With an average of 60 MB per process that is about 40 workers.

pm = dynamic
pm.max_children = 40
pm.start_servers = 8
pm.min_spare_servers = 4
pm.max_spare_servers = 12
pm.max_requests = 500

pm.max_requests recycles a worker after the given number of requests, which limits the damage from memory leaks.

How to tell it is too low

The FPM log shows a warning that pm.max_children has been reached. At that point requests wait in a queue. Before raising the number, check that there is memory for it: a max_children that is too high pushes the server into swap, and that is worse than waiting.

Keep reading