What is a worker?
PHP is a single-threaded interpreter by design at the core language level, though using threads is made possible by the "pthreads" PECL extension.
Suppose that you have 5 requests that come to your site at the exact same time. Will requests wait in a queue until the previous script completes its work due single-threaded php interpreter?
As everyone noticed, this does not happen. The fact is that when the server starts, the N number of processes (so-called workers) are launched in parallel, which in turn process all requests sequentially.
PHP workers determine how many simultaneous requests server can execute at a given time. Requests are executing almost instantly and even a small number of workers can handle a large number of requests.
How many php workers do I need?
In most cases, the number of workers is chosen equal to the number of processor cores. But this scenario only works well if there are no long database queries, heavy file manipulation, etc. In this case, the number of workers can be increased. Try to change the number of workers and measure performance as described in the article "How to test web server performance".
You can see the number of cpu with the command:
What if workers are not enough?
If workers do not have time to quickly process requests, requests begin to form a queue which could result in 504 errors after a timeout.
The accumulation of requests in a queue can be caused by:
- Longtime queries to the database
- Heavy processing scripts
- Blocking web calls to external services like s3 buckets, twitter streams, and other services.
So, before increasing the number of the workers you need to optimize code, cache the database queries whenever possible, use a CDN to offload serving static assets and so on. But in some cases, the more PHP workers the better, because of dynamic content or unique architecture of the application.