Finding the real performance problem in a Laravel app · Part 2 of 6
The application layer: a profiler, flame graphs and the N+1s
Two instruments that stay in production, a tracing profiler on the inbox and the ticket page, the N+1s and what is left when they are gone, a change the profiler liked and the clock could not confirm, and the three recommended PHP settings measured against the machine's own noise.
By Abhishek Fouzdar · Updated
Part 1 left a baseline: an inbox at a second, a ticket page at a third of one, a dashboard at ten and a search at twenty, with a method that says to measure at the layer before touching anything. This part is the application layer. It adds two instruments that cost almost nothing and stay in production, opens a profiler on the two pages agents use all day, fixes what the profile shows, and then measures the PHP-side settings everyone recommends, to find out which of them do anything.

Two instruments first
Before a profiler, two cheaper things, because most of the time they are enough.
A Server-Timing header. The browser's Network panel renders it as a bar chart per request, curl prints it, k6 can read it, and it answers the first half of "where did the time go" for every request in production at the cost of one event listener:
class ServerTiming
{
public function handle(Request $request, Closure $next): Response
{
$queries = 0;
$queryMs = 0.0;
DB::listen(function (QueryExecuted $query) use (&$queries, &$queryMs) {
$queries++;
$queryMs += $query->time;
});
$response = $next($request);
$totalMs = (microtime(true) - $request->server('REQUEST_TIME_FLOAT')) * 1000;
$response->headers->set('Server-Timing', implode(', ', [
sprintf('db;dur=%.1f;desc="%d queries"', $queryMs, $queries),
sprintf('app;dur=%.1f;desc="php"', $totalMs - $queryMs),
sprintf('total;dur=%.1f;desc="%s MB peak"', $totalMs, number_format(memory_get_peak_usage() / 1048576, 1)),
]));
return $response;
}
}
One request to each page, read from the header:
/inbox db;dur=73.7;desc="100 queries", app;dur=65.6, total;dur=139.2
/inbox?status=closed&page=4000 db;dur=489.1;desc="103 queries", app;dur=53.3, total;dur=542.3
/tickets/120070 db;dur=237.5;desc="329 queries", app;dur=315.9, total;dur=553.5
/tickets/5 db;dur=25.1;desc="27 queries", app;dur=47.0, total;dur=72.1
/ db;dur=5707.5;desc="105 queries", app;dur=228.5, total;dur=5936.0
/search?q=invoice db;dur=14409.4;desc="101 queries", app;dur=75.5, total;dur=14485.0
That one listing sorts the series. The dashboard and search are database time, 96% and 99% of the request, and they are part 3. The inbox and the ticket page are something else: a hundred and three hundred queries that together take less time than the PHP around them. Query count is the symptom, and the cause is on this side of the connection.
A command that replays a request and groups its queries. DB::listen again, this time collecting every statement, normalising the bindings and counting:
Auth::login(User::where('role', 'admin')->firstOrFail());
$groups = [];
DB::listen(function (QueryExecuted $query) use (&$groups) {
$sql = preg_replace('/\s+/', ' ', $query->sql);
$sql = preg_replace('/in \((\?, )*\?\)/', 'in (…)', $sql);
$groups[$sql] ??= ['count' => 0, 'ms' => 0.0];
$groups[$sql]['count']++;
$groups[$sql]['ms'] += $query->time;
});
$response = $kernel->handle(Request::create($this->argument('path')));
bin/dev artisan desk:queries /inbox
| Runs | ms | Query |
| 1 | 33.4 | select * from `tickets` where `status` = ? order by `last_message_at` desc limit 25 offset 0 |
| 25 | 11.2 | select * from `messages` where `messages`.`ticket_id` = ? ... order by `created_at` asc |
| 25 | 10.5 | select `tags`.*, ... from `tags` inner join `tag_ticket` ... where `tag_ticket`.`ticket_id` = ? |
| 25 | 8.8 | select * from `customers` where `customers`.`id` = ? limit 1 |
| 20 | 7.8 | select * from `users` where `users`.`id` = ? limit 1 |
| 1 | 4.3 | select count(*) as `aggregate` from `tickets` where `status` = ? |
/inbox: HTTP 200, 100 queries in 79.2 ms, 9 distinct
Four queries per row, twenty-five rows, and the messages one is not a count: it loads every message of every ticket on the page so that Blade can call ->count() and ->last() on the collection. The ticket page is the same shape, bigger:
bin/dev artisan desk:queries /tickets/120070
| 160 | 50.7 | select * from `attachments` where `attachments`.`message_id` = ? ... |
| 86 | 26.3 | select * from `users` where `users`.`id` = ? limit 1 |
| 76 | 22.8 | select * from `customers` where `customers`.`id` = ? limit 1 |
/tickets/120070: HTTP 200, 329 queries in 105.6 ms, 10 distinct
One query per message for its attachments and one per message for its author, which is a morphTo: Eloquent resolves a polymorphic parent one row at a time unless told otherwise. Both tables say what to fix and roughly what it will save. What they cannot say is what the other 60% of the ticket page's time is, the app;dur=315.9 that is not queries. That needs the profiler.
The profiler
php-spx is a tracing profiler built into the image in part 1. It does nothing until a request carries two cookies, SPX_ENABLED=1 and SPX_KEY, and then it records every function call with wall time and memory and writes a report to /tmp/spx. The control panel at /?SPX_KEY=dev&SPX_UI_URI=/ lists the reports; each opens as a flame graph over a flat profile. For a page behind a login the simplest trigger is curl with both cookie jars:
curl -b jar.txt -b 'SPX_ENABLED=1; SPX_KEY=dev' http://localhost:8070/tickets/120070
Two things to know before reading one. A traced request is slower than an untraced one, here about twice: the ticket page took 1,008 ms under the profiler against 553 ms without, so the percentages are what to read, not the milliseconds. And the inclusive column counts a function and everything it called, which is why the compiled Blade view sits at 97%: it is where the lazy loads fire. The exclusive column is a function's own time, and that is where the surprises are.
The flat profile of the ticket page, sorted by exclusive time, before any fix:
| Function | Called | Inclusive | Exclusive |
|---|---|---|---|
Connection::select |
329 | 28.4% | 27.0% |
Model::resolveClassAttribute |
16,250 | 2.8% | 2.8% |
Model::__construct |
1,040 | 11.1% | 2.5% |
Model::mergeDefaultAttributes |
1,040 | 2.1% | 2.1% |
Model::getCasts |
5,080 | 2.4% | 1.7% |
Dispatcher::dispatch |
1,070 | 1.9% | 1.5% |
compiled tickets/show.blade.php |
1 | 97.3% | 1.2% |
Model::transformModelValue |
2,530 | 12.2% | 1.2% |
IdentityTranslator::trans |
973 | 1.1% | 1.0% |
CarbonInterval::forHumans |
163 | 7.9% | 0.8% |
Model::getAttribute |
3,040 | 80.5% | 0.7% |
The queries are 28% and the rest is spread thin across Eloquent doing Eloquent things: a thousand models constructed, sixteen thousand attribute resolutions, three thousand getAttribute calls that between them cover 80% of the request inclusively because every $message->body and $message->created_at in the view goes through casting. And one line that is not Eloquent at all: forHumans, 163 calls, 8% of the page. That is diffForHumans() on every message's timestamp, each one building a CarbonInterval and asking the translator for "3 months ago".
The fixes
The inbox gets its relations in four queries for the page instead of four per row, a count instead of a collection, and the newest message through a latestOfMany relation, which is one query with a MAX(id) subquery:
public function latestMessage(): HasOne
{
return $this->hasOne(Message::class)->latestOfMany();
}
$tickets = Ticket::query()
->with(['customer', 'assignee', 'tags', 'latestMessage'])
->withCount('messages')
->when(…)
->orderByDesc('last_message_at')
->paginate(25)
->withQueryString();
· {{ $ticket->messages_count }} {{ Str::plural('message', $ticket->messages_count) }}
· {{ Str::limit($ticket->latestMessage?->body, 90) }}
The ticket page loads the thread's relations up front, and the sidebar stops loading the customer's whole history to count it:
$ticket->load(['customer', 'tags', 'messages.author', 'messages.attachments', 'events.user']);
return view('tickets.show', [
'ticket' => $ticket,
'agents' => User::where('role', 'agent')->orderBy('name')->get(),
'customerTicketCount' => $ticket->customer->tickets()->count(),
'recentTickets' => $ticket->customer->tickets()->latest('last_message_at')->limit(5)->get(),
]);
messages.author is the polymorphic one, and eager loading handles it with one query per parent type: one IN list for the customers, one for the users, however many messages there are.
The guard. The difference between fixing an N+1 and keeping it fixed is one line in AppServiceProvider:
Model::preventLazyLoading(! $this->app->isProduction());
Outside production, a relation that was not eager loaded throws instead of quietly querying, so the next partial that adds $ticket->somethingNew->name fails its test instead of shipping a query per row. In production it stays a silent extra query, which is the right failure mode there. The sixteen tests from part 1 render every page, and they passed with the guard on at the first run, which is the proof that no lazy load is left on the paths they cover; the customer page and the search results got the same with() list as the inbox so that they would.
The same two instruments after:
/inbox db;dur=40.2;desc="9 queries", app;dur=39.7, total;dur=79.9 (was 100 queries, 139.2)
/tickets/120070 db;dur=7.1;desc="13 queries", app;dur=55.1, total;dur=62.2 (was 329 queries, 553.5)
/tickets/5 db;dur=8.4;desc="13 queries", app;dur=18.5, total;dur=26.9 (was 27 queries, 72.1)
/customers/32463 db;dur=10.7;desc="8 queries", app;dur=21.6, total;dur=32.2
The ticket page is nine times faster for one user and its database time is seven milliseconds. The inbox is only 40% faster, and desk:queries says why: of its 40 ms of database time, 32 are the one query that was always there, select … from tickets where status = ? order by last_message_at desc limit 25, sorting thirteen thousand open tickets to return twenty-five. That is a missing index, and indexes are part 3.
What the profile shows after

| Function | Called | Inclusive | Exclusive |
|---|---|---|---|
Connection::select |
13 | 6.3% | 5.2% |
Model::getCasts |
5,340 | 4.5% | 3.3% |
Model::transformModelValue |
2,850 | 24.4% | 2.4% |
compiled tickets/show.blade.php |
1 | 60.3% | 2.3% |
IdentityTranslator::trans |
973 | 2.4% | 2.3% |
CarbonInterval::forHumans |
163 | 16.2% | 1.8% |
Carbon::createFromFormatAndTimezone |
652 | 1.7% | 1.7% |
Model::getAttribute |
3,350 | 32.0% | 1.4% |
The database is 6% of the ticket page now. A quarter of what is left is transformModelValue, which is the datetime casts: 652 Carbon instances built from strings, four per message, because created_at and updated_at are cast on every model the page touches, whether or not the view reads them. And 16% is forHumans, which was 8% before only because the page was twice as slow. Of the ticket page's 62 ms for one user, ten are the relative timestamps.
So the obvious change was made: relative times for messages from the last week, a plain date for anything older, which is what a "3 months ago" means to an agent anyway. Then it was measured, with nine requests per version and the two versions alternated three times, and the clock refused to confirm the profiler. The medians landed in two clusters, around 65 ms and around 100 ms, for both versions, in no pattern that followed the code; with the scheduler and the queue worker stopped, the same. The host has two speeds this afternoon and a ten-millisecond change cannot be seen between them. The change was reverted. Not because it is wrong, but because a change that cannot be measured cannot be defended, and the method from part 1 does not have an exception for changes that ought to work. The diff is three lines in the ticket view, for anyone whose machine is quieter than this one.
The PHP side
Every performance guide for Laravel ends with the same three commands, and this is where they get measured rather than recommended. The instrument is the ticket scenario from part 1 at ten users for thirty seconds, run after each change; the ticket page is the lightest page, which makes it the one where framework overhead shows.
First, what OPcache was already doing, read from opcache_get_status() through a one-line script dropped into public/ and removed again:
scripts cached 1,181 of max 10,000 · memory used 34 MB of 128 · hits 18,664,053 · misses 1,900
validate_timestamps 1, revalidate_freq 2 · JIT off
Healthy. Every file the app loads is compiled once and served from shared memory, the cache is a quarter full, and the miss count is the number of files, not a sign of churn. OPcache is on because PHP 8.5 builds it in and the default is enabled; the only question left is whether the two-second revalidation stat costs anything measurable.
Then the three commands, applied one after another with a thirty-second run of the ticket scenario after each, and everything reverted and measured once more at the end:
| Configuration | p50 | p95 | req/s |
|---|---|---|---|
| As fixed above, development settings | 152 ms | 315 ms | 60.0 |
+ php artisan optimize (config, events, routes, views cached) |
147 ms | 330 ms | 60.2 |
+ composer dump-autoload --classmap-authoritative |
191 ms | 353 ms | 46.9 |
+ opcache.validate_timestamps = 0 |
175 ms | 339 ms | 49.3 |
| Everything reverted, same code as the first row | 169 ms | 327 ms | 51.2 |
Read the last row before the middle ones. The same code and the same settings as the first row, four minutes later, came out 11% slower. Then three identical runs in a row, to find out what this machine's noise floor is:
| Run | p50 | p95 | req/s |
|---|---|---|---|
| A | 187 ms | 354 ms | 47.5 |
| A | 178 ms | 358 ms | 48.3 |
| A | 174 ms | 343 ms | 50.2 |
Seven percent between identical runs minutes apart, twenty percent across the afternoon. Every row in the settings table sits inside that, including the two that look like they made things worse. The conclusion is not that the three commands do nothing; it is that on this host, for this page, whatever they do is smaller than the drift, which the profile had already suggested: the autoloader's include closure was 1.7% of the request, config loading does not appear in the top thirty, and OPcache's revalidation is a stat per file every two seconds against a cache with a 99.99% hit rate. All three go into the production image in part 5 because they are correct there, config:cache above all, since it stops the app reading .env on every request. None of them is a performance fix for an app whose time is in Eloquent, and a guide that lists them next to "fix your N+1s" is listing a hundredfold difference as if it were a choice.
The method's own lesson from the afternoon: sequential before-and-after runs on a shared laptop can show a 20% change that is the laptop. Interleave the variants, repeat them, and measure the noise floor before measuring the change, or measure on a machine that is doing nothing else.
The scenarios again
Ten users, sixty seconds, the two scenarios whose pages this part changed, against part 1's baseline:
| Scenario | p50 before | p50 after | p95 before | p95 after | req/s before | req/s after |
|---|---|---|---|---|---|---|
| inbox | 1.07 s | 555 ms | 2.8 s | 2.1 s | 6.4 | 13.6 |
| ticket | 300 ms | 188 ms | 1.0 s | 352 ms | 23.5 | 47.5 |
Throughput doubled on both. The ticket page is nine times faster for one user and under a factor of two under load, and that gap is the next layer out: five PHP-FPM workers serving ten users means most of a request's time is spent waiting for a worker, and a page that got nine times cheaper only shortens the queue in front of it. Part 5 changes the worker count and the gap closes. The inbox's 99th percentile fell from 12.4 to 2.6 seconds because the deep pages no longer load every message of twenty-five closed tickets, and its 95th is still two seconds because the sort behind every page has no index to use. Part 3.
What went wrong
The middleware broke every test on its first run. It measured from LARAVEL_START, a constant that public/index.php defines and the test kernel does not, and sixteen tests failed with an undefined constant. REQUEST_TIME_FLOAT from the request's server bag is set in both places and is the right clock anyway.
The SPX control panel sat on "Initializing…" in the screenshot tool. The panel's own requests for report data carry no SPX_KEY query string, so with the key only in the first URL every one of them was refused and the page waited forever. The key has to be a cookie for the UI, and the panel sets it when opened in a browser; a headless browser needs it set beforehand.
desk:queries counted its own login query. Auth::login ran after DB::listen and select * from users where role = ? appeared in every table as a one-off. Listen after logging in.
Profiler overhead is not uniform. The ticket page took 1,008 ms traced against 553 ms untraced before the fixes and 141 ms against 62 ms after. Tracing costs per function call, so the pages with the most calls are the most distorted, and a function that is 8% of a traced request can be 10% or 6% of a real one. The order of the flat profile survives; the decimals do not.
Part 3 goes to the database with the pages that were never an application problem: the dashboard's thirty full scans, the search's LIKE over a million rows, the inbox's sort without an index, the deep pages, and the export that stops at thirty seconds of CPU; with the slow query log, EXPLAIN, and a buffer pool that is a quarter of the size of the data.
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
2 / 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