Sub topic 16
Choosing worker counts and basic tuning
This chapter assumes you have a working Nginx, PHP-FPM, Gunicorn and systemd setup from the earlier chapters. You should be comfortable with systemctl, reading logs and editing config files. Tuning is the last step. Measure first, change one setting at a time, and measure again.
What a worker is and why the count matters
A worker is one process (or one thread inside a process) that handles one request at a time. PHP-FPM calls its workers "children". Gunicorn calls them "workers". Nginx has its own worker processes, but each one handles thousands of connections at once.
The worker count sets how many requests your application can run in parallel. Two failure modes sit on either side of the right number.
- Too few workers. Requests wait in a queue. Latency rises, and clients eventually see timeouts (504) or refused connections (502).
- Too many workers. Each worker holds memory. When the total exceeds RAM, the kernel swaps, or the out-of-memory (OOM) killer ends a process. Too many CPU-bound workers also waste time switching between each other.
Nginx workers
Nginx rarely needs tuning. Its workers use an event loop, so one worker serves many connections. Two settings in /etc/nginx/nginx.conf matter.
worker_processes auto;
worker_rlimit_nofile 4096;
events {
worker_connections 1024;
}worker_processes autostarts one worker per CPU core. This is the right value in almost every case.worker_connectionsis the maximum number of simultaneous connections per worker. A proxied request uses two connections: one to the client and one to the application. The theoretical limit isworker_processes × worker_connections, and proxying roughly halves the number of clients you can serve.worker_rlimit_nofileraises the open-file limit, because every connection is a file descriptor. Keep it at least twiceworker_connections.
If you see worker_connections are not enough in error.log, raise the value and worker_rlimit_nofile together. Reload with sudo nginx -t && sudo systemctl reload nginx.
PHP-FPM: choosing a process manager mode
The pm setting in the pool file (/etc/php/8.3/fpm/pool.d/www.conf on Debian/Ubuntu) controls how children are created.
| Mode | Behaviour | Good for |
|---|---|---|
| `static` | Always runs exactly `pm.max_children` children | Busy servers with predictable memory |
| `dynamic` | Keeps a spare range of idle children and grows up to `pm.max_children` | General use, and the default |
| `ondemand` | Starts children only when requests arrive and stops idle ones | Many small, rarely used sites |
ondemand saves memory but adds a startup delay to the first request after idle time. static removes that delay and makes memory use predictable, but you pay for every child all the time.
Working out pm.max_children
The upper bound comes from memory, not from CPU. Measure how much memory a child uses while the application is under realistic load:
ps --no-headers -o rss -C php-fpm8.3 | awk '{sum+=$1; n++} END {printf "processes=%d average=%.1f MB\n", n, sum/n/1024}'rss is resident memory in kilobytes. It counts shared pages for each process, so the result slightly overestimates real use. That error is on the safe side. The count includes the small master process, which pulls the average down a little.
Then apply this formula:
max_children = (RAM available to PHP) ÷ (average memory per child)
"RAM available to PHP" is total RAM minus the operating system, Nginx, the database if it runs on the same host, and some headroom. On a 4 GB server with a local database, 2 GB for PHP-FPM is a realistic budget. With 50 MB per child, that gives 40.
[www]
user = www-data
group = www-data
listen = /run/php/php8.3-fpm.sock
listen.owner = www-data
listen.group = www-data
pm = dynamic
pm.max_children = 40
pm.start_servers = 8
pm.min_spare_servers = 5
pm.max_spare_servers = 12
pm.max_requests = 500
request_terminate_timeout = 30s
pm.status_path = /fpm-statuspm.start_serversmust lie betweenpm.min_spare_serversandpm.max_spare_servers. FPM refuses to start, or warns, if the values are inconsistent.pm.max_requestsrecycles a child after that many requests. It contains slow memory leaks in extensions or application code.request_terminate_timeoutkills a request that runs too long, so a stuck script cannot hold a child forever. It is separate from PHP'smax_execution_time, which does not count time spent waiting on I/O such as database calls.
When FPM runs out of children it logs server reached pm.max_children setting in its log (/var/log/php8.3-fpm.log). That line means requests are queuing. It tells you to check the memory budget before raising the number.
To watch the pool live, expose the status page to localhost only:
location = /fpm-status {
allow 127.0.0.1;
deny all;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}Then run curl http://127.0.0.1/fpm-status on the server. The listen queue and max children reached fields show whether the pool is too small.
Gunicorn: workers, threads and worker classes
Gunicorn's documentation suggests (2 × CPU cores) + 1 workers as a starting point. The rule assumes a synchronous worker that spends part of each request waiting on I/O. Treat it as a first guess, not a target.
The worker class changes the arithmetic:
sync(default). One request per worker at a time. Concurrency equals the worker count. A slow upstream call blocks the whole worker.gthread. Each worker runs several threads. Concurrency isworkers × threads. This suits apps that wait on databases or APIs, and threads share memory, so it costs less RAM than more processes.- Async or ASGI workers. For ASGI applications, use
uvicorn.workers.UvicornWorker, which needs theuvicornpackage. Each worker handles many requests concurrently on an event loop, so you need only about one worker per core.
Putting the settings in a file keeps the systemd unit short. Save this as /srv/myapp/gunicorn.conf.py:
import multiprocessing
bind = "unix:/run/gunicorn/app.sock"
workers = multiprocessing.cpu_count() * 2 + 1
threads = 1
timeout = 30
graceful_timeout = 30
max_requests = 1000
max_requests_jitter = 100Gunicorn reads gunicorn.conf.py from the working directory automatically. The unit's ExecStart can then be /srv/myapp/venv/bin/gunicorn app:application, with WorkingDirectory=/srv/myapp.
timeoutis how long a worker may stay silent before the master kills and replaces it. It is not a limit on response time for async workers.max_requestsrestarts a worker after that many requests.max_requests_jitteradds a random offset so all workers do not restart at the same moment.
The same memory formula applies here. Measure a worker's RSS, multiply by the worker count and compare the total with your RAM budget. A Python worker often uses 60 to 200 MB, depending on the framework and loaded data.
Keeping Nginx and the application server in step
Nginx's timeouts must agree with the application's limits. Otherwise one side gives up while the other keeps working.
location / {
proxy_pass http://unix:/run/gunicorn/app.sock;
proxy_connect_timeout 5s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
}proxy_read_timeout defaults to 60 seconds. If it is shorter than the Gunicorn timeout, Nginx returns 504 while the worker is still busy. For PHP, the matching directive is fastcgi_read_timeout.
The two error codes point in different directions:
- 502 Bad Gateway: Nginx could not talk to the application. Check whether the socket exists, whether the service is running, and whether a worker was killed by a timeout or the OOM killer.
- 504 Gateway Timeout: The application accepted the request but did not answer in time. The usual causes are too few workers, a slow query, or a long timeout mismatch.
To check for OOM kills, run sudo journalctl -k | grep -i "out of memory".
Basic tuning checklist
- Measure the memory per worker under real traffic, not at idle.
- Compute the worker count from the memory budget, and keep headroom for traffic spikes.
- Use
gthreador ASGI workers if the application mostly waits on I/O. - Enable
max_requests(Gunicorn) orpm.max_requests(PHP-FPM) to limit leaks. - Align
proxy_read_timeoutorfastcgi_read_timeoutwith the application's own timeouts. - Change one setting, reload, and compare the results before changing another.
Exercise
A server has 8 GB of RAM. The operating system, Nginx and a local database need about 5 GB. Each PHP-FPM child averages 60 MB. What is the largest sensible pm.max_children, and why might you choose a lower number?
Show answer
PHP-FPM gets about 3 GB, which is 3072 MB. Dividing by 60 MB gives about 51 children, so 51 is the ceiling. A lower value such as 40 leaves headroom for memory spikes, for children that grow between recycles, and for other processes. If FPM then logs "reached pm.max_children", measure again before raising it.
Exercise
Users see 504 errors on a Gunicorn site under load. Nginx has proxyreadtimeout 60s, and Gunicorn has timeout 30 and 3 sync workers. Gunicorn logs show no worker kills. Name two likely causes and one first step.
Show answer
With only 3 sync workers, each request holds a worker until it finishes. Under load, requests queue until Nginx's 60-second read timeout expires, which produces a 504. Slow application code, such as a long database query, could be the second cause. A good first step is to measure worker memory and CPU use and check request durations in the logs. If there is free RAM and CPU, raise the workers or add threads with gthread.