Finding the real performance problem in a Laravel app · Part 5 of 6
Queues, workers and the server: the number that shaped every table
The ramp that shows five PHP-FPM workers for what they were, the webhook, the export and the digest moved to the queue with Horizon, sixteen workers measured against the host's own ceiling, the keepalive that pinned every worker, and a production php.ini and nginx config with reasons.
By Abhishek Fouzdar
Every table in this series has had the same number hiding in it. Part 1's dashboard took ten seconds for one user and fifty-three for ten; part 2's ticket page got nine times cheaper and under twice as fast under load; part 4's cold cache was computed five times by ten users, not ten. The number is five: pm.max_children = 5, the PHP-FPM default in the official image, which means five requests in flight and everyone else waiting in nginx. This part is the layer outside the application: the work that should never have been in a request, the worker count that sets the shape of every latency curve, the production settings for PHP and nginx, and a load test ramped until something gives, before and after.
The ramp, before
The scenarios so far held ten users steady. This one ramps, thirty seconds per stage, through 5, 10, 20, 40 and 60 users on the agents' mix of inbox, ticket, dashboard and search, and k6's JSON stream is bucketed per stage afterwards, because the summary of a ramp is a meaningless average of its stages:
| Users | req/s | p50 | p95 | p99 |
|---|---|---|---|---|
| 5 | 54.3 | 37 ms | 91 ms | 105 ms |
| 10 | 76.9 | 83 ms | 162 ms | 188 ms |
| 20 | 73.3 | 187 ms | 318 ms | 383 ms |
| 40 | 69.7 | 412 ms | 662 ms | 755 ms |
| 60 | 108.4 | 635 ms | 960 ms | 1,023 ms |
Read the second column first. From ten users on, the server does about 75 requests a second whatever the load, and from then on every added user adds their share of waiting to everyone's latency: twenty users, 187 ms median; forty, 412; sixty, 635. That is a queue, and its length is the only thing changing. Nothing failed; nothing was slow in the application sense, since each request still took its 40 ms once a worker picked it up. The five workers were simply all busy, and /fpm-status, which the next section turns on, would have shown the queue; at the baseline it was not on, which is itself the finding.
Work that was never a request
Three things in DeskMini ran inside an HTTP request that had no business there, and each held one of the five workers for the duration.
The webhook created the ticket and the message, then loaded every tag to match against the text, ran a withCount over all open tickets to find the least loaded agent, and sent that agent an email over SMTP, and only then answered the email provider. Providers retry a webhook that does not answer fast enough, and a retry of a handler that has already created the ticket is a second ticket. Now the handler saves the ticket and the message, dispatches a job, and answers:
if ($isNew) {
ProcessInboundTicket::dispatch($ticket);
}
class ProcessInboundTicket implements ShouldBeUnique, ShouldQueue
{
public int $tries = 3;
public function uniqueId(): string
{
return (string) $this->ticket->id;
}
…
ShouldBeUnique with the ticket id as the key means the provider can resend as often as it likes and the tagging and assignment happen once. The agent's email and the customer's reply email both implement ShouldQueue now, so Mail::to(…)->send() queues them without the calling code changing; the tests changed from assertSent to assertQueued, which is the whole diff on that side.
The export was a twenty-second request after part 3 fixed its queries, which is a complete file and still one of five workers gone for twenty seconds. It is a job now that writes the CSV under storage/app/exports in chunks of a thousand, and the request that asks for it redirects to a reports page where the file appears when it is done:
ExportTickets::dispatch($data['from'], $data['to'], $name);
return redirect()->route('reports.index')->with('status', "Export {$name}.csv is being prepared; it will appear below.");
The job has $timeout = 600, and the time limit that part 3 removed from the request is back where it belongs, on a worker that is not serving pages.
The digest loaded every open ticket an agent owned, with every message of each, to put ten subjects and a count in an email. It counts and takes ten now, with the customer and a message count joined in, which is the kind of query the mail view was always going to need.
Horizon runs the workers instead of queue:work, because a queue nobody can see is a queue nobody trusts: it balances the worker processes across queues, restarts them after a set number of jobs so a leak cannot grow for a week, and keeps the throughput, runtime and failure counts the dashboard at /horizon shows, behind a gate that admits the admin role.

That screenshot was taken a minute after the webhook scenario below, and the 131 failed jobs on it are real and worth reading before the numbers: they are assignment emails whose ticket's customer no longer existed when the mail rendered, because the benchmark's reset command deleted its customers while four thousand jobs were still queued. A job runs later than the request that queued it, and "later" can be after the data it needs is gone; the failed-jobs table keeps the exception and Horizon keeps the payload, which is how the cause took one query to find.
Sixteen workers
The worker count is arithmetic, and the inputs are in part 1 and part 2. Each worker is about 38 MB resident (ps inside the container), the pages are CPU-bound once the queries are fixed, and the host has eight cores. Two workers per core is the usual starting point for CPU-bound PHP, sixteen, which is about 600 MB:
[www]
pm = static
pm.max_children = 16
pm.status_path = /fpm-status
request_terminate_timeout = 60s
static forks all sixteen at start rather than under the first busy minute; request_terminate_timeout kills a request that runs past a minute, which nothing on the web side should now; and the status path is the instrument for this layer, exposed by nginx on the Compose network only:
curl http://web/fpm-status
pool: www
process manager: static
total processes: 16
active processes: 3
idle processes: 13
listen queue: 0
max listen queue: 44
listen queue is the number of requests waiting for a worker right now and max listen queue the most that ever waited since the last restart. A non-zero max is the earliest sign a server has that it is too small, long before any page is slow enough to notice, and it is a number that belongs on a graph.
The ramp, after
The same ramp, sixteen workers, nothing else changed:
| Users | req/s before | req/s after | p50 before | p50 after | p95 before | p95 after |
|---|---|---|---|---|---|---|
| 5 | 54.3 | 52.9 | 37 ms | 37 ms | 91 ms | 95 ms |
| 10 | 76.9 | 82.7 | 83 ms | 77 ms | 162 ms | 149 ms |
| 20 | 73.3 | 84.1 | 187 ms | 156 ms | 318 ms | 333 ms |
| 40 | 69.7 | 83.3 | 412 ms | 350 ms | 662 ms | 578 ms |
| 60 | 108.4 | 122.1 | 635 ms | 566 ms | 960 ms | 863 ms |
Ten to fifteen percent more throughput and the same shape: a plateau from ten users on, and latency growing with the queue behind it. Sixteen workers did not make this host three times faster because the host does not have three times the CPU: eight virtual cores shared with MySQL, Redis, nginx, Horizon and k6 itself, and at 83 requests a second of pages that each cost 40 ms of PHP, the cores are the ceiling. The worker count was never the bottleneck on this machine, which is the honest end of a series that kept blaming it; it was the bottleneck's shape. With five workers the queue formed in nginx and /fpm-status could see it; with sixteen it forms in the kernel's run queue and only vmstat can. On a server with cores to spare the same change is the three-times, and the arithmetic above is how to know which server one has before changing the number.
max listen queue: 44 after the run: at sixty users, forty-four requests were waiting for a worker at the worst moment, with sixty users and sixteen workers. The status page was not on for the five-worker run, so there is no before for this number, and that is the point of turning it on today: the next change has one.
The webhook, after
The webhook scenario from part 1, five users posting signed webhooks for sixty seconds, before and after the follow-up work moved to the queue:
| inbound | p50 | p95 | p99 | max | req/s |
|---|---|---|---|---|---|
| Part 1, everything in the request | 54 ms | 1.37 s | 1.46 s | 2.76 s | 10.0 |
| Part 5, ticket saved, job queued | 61 ms | 91 ms | 105 ms | 175 ms | 79.8 |
The median barely moved, because a reply was always cheap; the tail is what the new-ticket path was, and it is gone. Eight times the throughput, and the provider gets its 201 in under a tenth of a second on the slowest request of the minute, which is what makes retries stop being duplicates. Horizon processed the 4,794 jobs the run produced at about 3,700 a minute on one worker process, which says how little each of them was once the SMTP round trip and the withCount were off the request path and on their own.
PHP and nginx in production
The production php.ini turns off what the development one needed on. display_errors off and log_errors on, because an error page on a production site is a leak. opcache.validate_timestamps = 0, because a release never changes a file in place, so OPcache can stop checking every file's modification time; part 2 measured that check at nothing visible, and the setting is here for correctness rather than speed, with the consequence that a deploy must restart PHP-FPM. opcache.memory_consumption = 192 and max_accelerated_files = 20000, which the status in part 2 showed to be more than twice what the app needs; the room is for the next year's vendor directory.
nginx got three lines that cost nothing. gzip on for text, at level 5, which takes the inbox from 48 KB to about 8 on the wire; gzip_vary so a cache in front knows the response differs by encoding; and fastcgi_keep_conn with an upstream keepalive, so nginx reuses its connections to PHP-FPM rather than opening one per request. None of these moves a latency number on a Compose network, and all of them do on a real one, where the bytes cross a wire.
curl -H 'Accept-Encoding: gzip' -D - http://localhost:8070/inbox
Vary: Accept-Encoding
Content-Encoding: gzip
inbox: 36,009 bytes plain, 5,008 bytes gzipped
app-BV8WrX4k.css: 17,136 bytes plain, 4,152 bytes gzipped
What went wrong
nginx was restarted before its config changed. The gzip and keepalive lines went into default.conf while the rebuild chain was already recreating the web container, so the first check showed the inbox at 36,009 bytes with and without Accept-Encoding. A config file is read when the process starts; docker compose restart web and the second check compressed it seven times over. The validation step was its own small lesson: nginx -t in a container outside the Compose network fails with "host not found in upstream app", which is not a syntax error.
The tests changed shape before the code did. Queueing the mails broke Mail::assertSent in three tests, because a queued mailable is asserted with assertQueued, and moving the export to a job broke the test that read the CSV out of the response, because there is no CSV in the response any more. Both are the right failures: the tests described a synchronous app, and the app is not one now. The export test now fakes the storage disk, asks for the export, and reads the file the job wrote, which under QUEUE_CONNECTION=sync in phpunit.xml happens inside the request.
The download's content type gained a charset. Storage::download with text/csv sends text/csv; charset=utf-8, and an exact header assertion failed on the suffix. The assertion matches the full value now; the header was never wrong.
FastCGI keepalive pinned the workers. The first sixteen-worker ramp had 24 failures, all of them k6's sixty-second timeout, 23 of them on the login request of users joining in the sixty-user stage, and /fpm-status reported max active processes: 176 for a pool of sixteen. The cause was two lines added for nginx: fastcgi_keep_conn on with a keepalive upstream. PHP-FPM does not multiplex: a kept-alive connection occupies a worker while it waits for its next request, so sixteen idle connections from nginx were sixteen busy workers, and new connections sat in the backlog until nginx happened to close one. That run's lower latencies were not a gain either: the stalled users stopped generating load, and the rest got a quieter server. The two lines came out, the ramp was run again, and the table above is from that run.
Horizon crashed on its own config. Two supervisors were defined with new names and Horizon restarted ten times with "Undefined array key connection", because it merges each environment's supervisor with the entry of the same name under defaults, and defaults only knew supervisor-1. Every supervisor name an environment uses needs its own defaults entry; the comment in config/horizon.php now says so.
The export waited behind four thousand jobs. The first queued quarter export took 84 seconds to appear, against 20 for the same work as a request, because it was dispatched during the webhook scenario and the default queue had 4,794 assignment jobs ahead of it, in order. A queue is FIFO, and a long job on the same queue as short ones delays whichever arrives second. Exports have their own queue and their own Horizon supervisor now, one process with a ten-minute timeout, and the same export dispatched into the same webhook flood took 43 seconds to appear instead of 84: longer than the 20 it takes on an idle machine, because the flood and the export share the host's cores, and nothing in front of it any more. The webhook's own numbers during that minute were unchanged, 66 ms median and 100 ms at the 95th, which is what the separation was for.
Part 6 is observability, which is the layer that would have made every part of this series a shorter investigation: Laravel Pulse on the live app, Telescope in development, OpenTelemetry tracing a request through nginx, PHP, MySQL, Redis and a queued job, the honest comparison with Nightwatch, and three investigations from the dashboards: a slow request, a failing job and a worker whose memory grows.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
5 / 6- OverviewFinding the real performance problem in a Laravel app
- Part 1The app, the data, a load test and a baseline
- Part 2The application layer: a profiler, flame graphs and the N+1s
- Part 3The database on a million rows
- Part 4Caching: what to cache, the stampede, and the cache that looked right
- Part 5Queues, workers and the server: the number that shaped every table
- Part 6Observability: Pulse, Telescope and OpenTelemetry, and what each one costs