DEV Community

Cover image for The php-fpm Tuning Cheat Sheet: 5 Settings That Decide Your p99
Gabriel Anhaia
Gabriel Anhaia

Posted on

The php-fpm Tuning Cheat Sheet: 5 Settings That Decide Your p99


Your Laravel app is slow under load. CPU sits at 30%. Memory is fine. The database isn't sweating. And p99 still spikes to 8 seconds during the Tuesday-morning rush.

You open Grafana. You look at the queries. You look at the cache hit ratio. You add another Redis node. Nothing changes.

The problem isn't your code. It's php-fpm. Specifically, five lines in www.conf that ship with values picked for a Raspberry Pi.

The pool model in 60 seconds

php-fpm runs a pool of worker processes. A web request comes into Nginx, Nginx forwards it through FastCGI to the pool, a worker picks it up, the worker runs your PHP code, sends the response back, then waits for the next request.

The whole game is: how many workers, when to spawn them, when to recycle them.

You pick one of three process managers in www.conf:

; /etc/php/8.4/fpm/pool.d/www.conf
pm = dynamic
Enter fullscreen mode Exit fullscreen mode
  • pm = static: fixed number of workers, always alive. Predictable memory. No spawn latency. Wastes RAM when traffic dips.
  • pm = dynamic: a min/max range, scales up and down based on demand. The default in most distros. Has spawn latency at the boundaries.
  • pm = ondemand: workers spawn only when a request arrives, die after idle timeout. Lowest memory floor. Adds 5-50ms to cold requests.

For a single-purpose API server serving real traffic, static is almost always the right answer. Spawn cost during a burst is the worst latency outlier you can hand a user. We'll come back to this.

Setting 1: pm.max_children (the one most teams get wrong)

This is the cap. It's how many PHP processes can run at once on this box. Set it too low, requests queue. Set it too high, the kernel OOM-kills your workers and your Redis sidecar.

The formula every distro doc skips:

pm.max_children = (total_RAM - reserved_for_OS_and_sidecars) / avg_worker_memory
Enter fullscreen mode Exit fullscreen mode

The two values you need to measure, not guess:

  1. avg_worker_memory: actual RSS of a settled worker after handling a few requests. Not the boot value. Workers grow as autoloaders load classes, opcache warms, and Laravel hydrates service containers. Measure after a real warmup.
# settled RSS per worker, in MB
ps -ylC php-fpm8.4 --sort:rss \
  | awk 'NR>1 { sum+=$8; n++ } END { printf "avg=%.1f MB\n", sum/n/1024 }'
Enter fullscreen mode Exit fullscreen mode

A bare Laravel 12 worker is usually 50-80 MB. A monolith with 200 routes, Telescope and a few Filament resources sits at 120-180 MB. A worker doing heavy image transforms can balloon past 400 MB transiently.

  1. reserved RAM: the OS itself, Nginx, Redis if it's local, OPcache shared memory (defaults to 128 MB), the APM agent if you've got one. On a 4 GB box you're usually looking at 700 MB to 1 GB reserved before php-fpm gets a slice.

Worked example. c5.large EC2: 4 GB RAM, 2 vCPUs, Ubuntu, Nginx + php-fpm + a local Redis.

  • Total: 4096 MB
  • Reserved (OS + Nginx + Redis + OPcache + buffers): ~900 MB
  • Available for php-fpm: ~3200 MB
  • Measured avg worker RSS: 140 MB
  • pm.max_children = 3200 / 140 = ~22
pm = static
pm.max_children = 22
Enter fullscreen mode Exit fullscreen mode

A common shape on this exact box: someone ships pm.max_children = 50 because that's what some Stack Overflow answer from 2014 said. Traffic comes in, the 23rd worker pushes them into swap, latency goes vertical, and the on-call engineer adds more workers thinking it'll help. It doesn't. It makes it worse.

The CPU side check. If your average request is CPU-bound and short (under 50ms), there's no point having more workers than vCPU * 2-4. They'll just thrash the scheduler. On the c5.large that's 4-8 workers max if you're CPU-bound. Pick whichever bound is smaller, RAM or CPU.

Setting 2: pm.max_requests (memory-leak insurance)

PHP doesn't leak the way C does, but php-fpm workers absolutely do grow. Composer autoloading, opcache, hydrated containers, accidental static caches in your own code. After 50,000 requests the same worker that started at 80 MB might be sitting at 220 MB and not giving it back.

pm.max_requests recycles workers after N requests. They exit cleanly, php-fpm spawns a fresh replacement.

pm.max_requests = 500
Enter fullscreen mode Exit fullscreen mode

The right value is "high enough that recycling cost is invisible, low enough that leaks don't matter." For most apps that's 500-1000. Library code that allocates aggressively (PDF generation, image processing, HTTP clients with caching layers) wants the lower end. Lean API workers can run at 2000+.

The gotcha: pm.max_requests = 0 (the default in some distros) means workers never recycle. If you've got it set to 0 and you've never explicitly tuned it, you have memory growth you don't know about. Set it to something. Even 2000 is safer than 0.

Setting 3: request_terminate_timeout (the timeout that actually fires)

This is the timeout that wins.

PHP has max_execution_time in php.ini. Nginx has fastcgi_read_timeout in its server block. php-fpm has request_terminate_timeout in www.conf. They are three different timeouts that kill the same request, and the shortest one wins.

request_terminate_timeout = 30s
Enter fullscreen mode Exit fullscreen mode

What goes wrong: a slow query takes 60 seconds. fastcgi_read_timeout is 60s. max_execution_time is 30s but it's inside a sleep() or a blocked socket call, so it can't fire (PHP only checks the timer at opcode boundaries). The request hangs the worker for the full 60s. Repeat 22 times and your whole pool is wedged on the same broken upstream.

request_terminate_timeout is enforced by the php-fpm master with a signal, so it fires regardless of what the worker is doing. It's the only timeout that reliably frees a wedged worker.

Set all three. Keep request_terminate_timeout slightly higher than max_execution_time so PHP gets a chance to throw Maximum execution time exceeded and log a stack trace before the master nukes the worker:

; www.conf
request_terminate_timeout = 35s
Enter fullscreen mode Exit fullscreen mode
; php.ini
max_execution_time = 30
Enter fullscreen mode Exit fullscreen mode
# Nginx server block
fastcgi_read_timeout = 40s;
Enter fullscreen mode Exit fullscreen mode

The order: PHP throws at 30s (you get a stack trace), php-fpm kills at 35s (worker is freed), Nginx closes the connection at 40s (request returns 504). Each layer is a backstop for the previous one failing.

Setting 4: pm.process_idle_timeout (only relevant for ondemand)

If you're on pm = dynamic or pm = static, skip this section. It's a no-op.

For pm = ondemand, workers spawn on the first request and die after pm.process_idle_timeout seconds of doing nothing.

pm = ondemand
pm.max_children = 22
pm.process_idle_timeout = 60s
pm.max_requests = 500
Enter fullscreen mode Exit fullscreen mode

The trap: a too-short process_idle_timeout thrashes spawn/kill, which is the most expensive thing php-fpm does. A 60-second timeout is reasonable for low-traffic services where you genuinely want to release RAM during quiet periods. Going below 10s is almost always wrong.

When to actually use ondemand. Multi-tenant hosting where you've got 50 pools on one box and most of them are dormant. Background workers that handle bursty cron-driven traffic. A staging environment where memory matters more than latency.

When to never use ondemand. Anything user-facing with real traffic. The spawn cost of a worker (autoloader, opcache hydration, framework bootstrap if you're not on Octane) is 50-200ms. That's an entire latency budget gone before your PHP code runs a single line. static with a tighter pm.max_children is a better trade.

Setting 5: listen.backlog (the SYN-queue knob nobody touches)

This is the one nobody knows about and it's the one that decides your behavior during traffic spikes.

listen.backlog is the size of the socket accept queue. When all your workers are busy and Nginx tries to hand off another request, the connection sits in this queue waiting for a worker to free up.

listen = /run/php/php8.4-fpm.sock
listen.backlog = 4096
Enter fullscreen mode Exit fullscreen mode

The default in many distros is 511. On a box that can take 22 concurrent workers handling 50ms requests, you can chew through 511 queued connections in roughly 1.2 seconds at full burst. After that, new connections get refused with connect() failed (11: Resource temporarily unavailable).

You've seen this in Nginx logs. It looks like php-fpm crashed. It didn't. The queue overflowed.

Bump listen.backlog to 4096 or 8192:

listen.backlog = 8192
Enter fullscreen mode Exit fullscreen mode

The kernel ceiling that bites. listen.backlog is silently capped at the smaller of itself and the kernel's net.core.somaxconn. On older Linux distros somaxconn defaults to 128. You can set listen.backlog = 65535 in www.conf and the actual queue size will be 128.

Check the kernel value:

sysctl net.core.somaxconn
Enter fullscreen mode Exit fullscreen mode

Raise it if it's lower than your php-fpm setting:

# /etc/sysctl.d/99-php-fpm.conf
net.core.somaxconn = 8192
net.ipv4.tcp_max_syn_backlog = 8192
Enter fullscreen mode Exit fullscreen mode
sudo sysctl -p /etc/sysctl.d/99-php-fpm.conf
Enter fullscreen mode Exit fullscreen mode

After this change, restart php-fpm so the listener picks up the new backlog. A reload isn't enough. The socket has to be recreated.

sudo systemctl restart php8.4-fpm
Enter fullscreen mode Exit fullscreen mode

Listen for the queue depth in production with ss:

# Recv-Q on the LISTEN socket = current queue depth
ss -lntp | grep php-fpm
Enter fullscreen mode Exit fullscreen mode

If Recv-Q is climbing during peak, your workers aren't keeping up. Backlog buys you time; it doesn't fix throughput. The fix is more workers, faster code, or Octane.

A real tuning walkthrough on c5.large, Laravel 12

Setup: c5.large, 2 vCPU, 4 GB RAM, Laravel 12 app with Telescope on, MySQL on a separate box, local Redis, Nginx + php-fpm 8.4.

Before:

pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 0
request_terminate_timeout = 0
listen.backlog = 511
Enter fullscreen mode Exit fullscreen mode

Load test with k6, 200 RPS for 5 minutes. p99 at 4800ms. Steady-state RAM at 92% with OOM-killer firing twice during the run.

After:

pm = static
pm.max_children = 20
pm.max_requests = 800
request_terminate_timeout = 35s
listen = /run/php/php8.4-fpm.sock
listen.backlog = 8192
Enter fullscreen mode Exit fullscreen mode
# /etc/sysctl.d/99-php-fpm.conf
net.core.somaxconn = 8192
Enter fullscreen mode Exit fullscreen mode

Same load test. p99 at 380ms. RAM steady at 78%. No OOMs. Throughput went up because the box stopped paging.

The lesson: pm.max_children = 50 on a 4 GB box wasn't "scaling," it was queuing requests inside swap. Cutting it to 20 made everything faster.

When to switch to Octane instead

Octane (Swoole or FrankenPHP backend) keeps the Laravel app booted in memory between requests. The autoloader doesn't re-run, the service container isn't rebuilt, the middleware stack stays intact. That 30-80ms framework boot cost goes to zero.

If your php-fpm worker spends 60ms in framework boot and 40ms in actual request work, Octane gives you a 2.5x throughput jump on the same hardware. That's not a tuning improvement; that's an architecture shift.

Octane needs your code to be more careful. Static state survives across requests, container singletons stay singleton across requests, anything that assumed a fresh process is now wrong. It's worth the work for high-traffic apps. For a CMS doing 10 RPS, php-fpm tuned correctly is fine.

The five settings above get you 80% of the way there before you change architecture. Octane gets you the last 20%. Tune first, then decide.

What's your current pm.max_children and how did you pick it? Drop your numbers (RAM, avg worker RSS, the value you settled on) in the comments. Curious how far off the defaults most folks are running.


If this was useful

php-fpm tuning gets you the box right, but the box is a small slice of why apps slow down at scale. The other slice (service boundaries, framework coupling, the layers that decide whether your team can scale the code itself) is what Decoupled PHP is about. It's the architectural layer your codebase reaches for once you've outgrown the framework defaults.

Decoupled PHP — Clean and Hexagonal Architecture for Applications That Outlive the Framework

Available on Kindle, Paperback, and Hardcover. English, German, and Japanese editions out now — Portuguese and Spanish coming soon.

Top comments (0)