Finding the real performance problem in a Laravel app · Part 1 of 6

Performance14 min read

The app, the data, a load test and a baseline

A helpdesk written the usual way, eighteen months of tickets, ten k6 users and a baseline: a ten-second dashboard, a twenty-second search, an export that returns 200 and is wrong, and the method the rest of the series follows.

By Abhishek Fouzdar

This part builds nothing clever. It builds a helpdesk the way helpdesks get built, fills it with eighteen months of tickets, puts ten simulated agents on it with k6, and writes down what it measures. The rest of the series fixes what this part finds, one layer at a time, and every fix is checked against the numbers recorded here. The method comes first, because the method is the point: a slow app is not a mystery, it is a measurement that has not been taken yet.

The DeskMini dashboard: counts by status, a thirty-day bar chart of new tickets, open work by priority, an agents table and the top tags

The method

Every performance investigation that goes well has the same shape, and every one that goes badly skipped a step.

  1. Name the symptom as a number. Not "the dashboard is slow" but "the dashboard's 95th percentile is ten seconds for one user and the page times out for ten." A symptom with a number can be reproduced and can be declared fixed.
  2. Reproduce it on data that looks like production. A query that is instant on 200 rows and takes nine seconds on 200,000 is the normal case, not the exception. If the production data cannot be copied, generate data with the same shape: the same table sizes, the same skew, the same share of old rows.
  3. Measure at the layer, with the tool for that layer. The table below. The common mistake is to reach for the tool one already knows: an EXPLAIN when the time is in Blade, a cache when the time is in a query that should not exist, a bigger server when one function is called a million times.
  4. Change one thing, measure again, keep the log. A change that is not measured is a guess, and two changes measured together cannot be told apart. The log is the numbers before and after, with the conditions, and bench/results/ in the repository is that log for this series.
  5. Stop when the number is met, not when the code is beautiful. There is always another millisecond.

The layers and their tools, from the browser inward:

Layer Question Tool used in this series
Load How does it behave with many users, and where does it fall over? k6, with the summary exported per scenario
Request Which requests are slow, how often, for whom? nginx and PHP-FPM logs with timings, then Pulse and OpenTelemetry in part 6
Application Where inside one request does the time go? php-spx (sampling profiler with flame graphs), Xdebug for the cases that need every call
Query Which queries, how many, how long, reading how many rows? MySQL's slow query log, pt-query-digest, EXPLAIN and EXPLAIN ANALYZE
Cache and queue What is cached, what is hit, what waits? Redis INFO and MONITOR, Horizon's metrics, the queue's own timing
Server Is PHP-FPM out of workers, is OPcache full, is MySQL's buffer pool too small? FPM's status page, opcache_get_status(), SHOW ENGINE INNODB STATUS
Host Is the machine itself the limit? docker stats, vmstat, and the honesty to say so

Two rules about the numbers themselves. Report percentiles, not averages: an average of 300 ms hides a 95th percentile of 4 s, and the 95th percentile is what a tenth of the agents see on every click. And state the conditions next to every number. All of this series runs in Docker on a laptop with eight virtual cores, eleven gigabytes of memory and an eight-year-old SATA SSD, which makes the absolute numbers meaningless anywhere else and the relative ones, before and after on the same machine with the same data, the only ones worth reading.

The app

DeskMini is a helpdesk: customers send email, the email provider posts it to a webhook, a ticket opens, an agent replies, the ticket closes. It exists because a helpdesk has every slow shape an application can have, in a domain nobody needs explained.

Page or job What it does What it will turn out to be
Inbox Open tickets, newest activity first, with filters for status, priority, agent, tag and subject, paginated An N+1 per row, a sort that cannot use its index, pages that get slower the deeper they go
Ticket The thread of messages and events, the customer's other tickets, a reply form N+1 again, per message this time, and a sidebar that loads a customer's whole history to count it
Dashboard Counts by status and priority, tickets per day for thirty days, average first-response time, per-agent counts, top tags Thirty full-table scans for one chart, a seven-day average computed in PHP, and a table that runs sixty queries
Search Subject and message bodies containing a term LIKE '%term%' across a million rows
Export Every ticket in a date range as CSV get() on a quarter of the table, then relations per row
Inbound webhook Finds or creates the customer, opens or appends to the ticket, tags it from its text, assigns the least loaded agent, emails the agent All of that in the request, including the email
SLA check Every minute: open tickets past their first-response deadline are marked breached Loads every unanswered open ticket to compare dates in PHP
Agent digest Every morning: each agent's open tickets by email One query per agent that loads everything

The schema is seven tables: customers, tickets (with a status index, because that is the one everybody adds), messages with a polymorphic author (a customer or an agent), tags and the tag_ticket pivot, attachments (metadata only) and ticket_events for assignments and status changes. Nothing is denormalised: no message counts on tickets, no last-message text, no per-agent counters. That is deliberate, because the question of what to denormalise is a part 3 question and the answer should come from a measurement.

The code is written the way application code is usually written, which is to say with Eloquent doing what it does when nobody has asked it to do otherwise. The inbox:

$tickets = Ticket::query()
    ->when($filters['status'] ?? 'open', fn ($q, $status) => $status === 'all' ? $q : $q->where('status', $status))
    ->when($filters['priority'] ?? null, fn ($q, $priority) => $q->where('priority', $priority))
    ->when($filters['assignee'] ?? null, fn ($q, $assignee) => $assignee === 'none' ? $q->whereNull('assignee_id') : $q->where('assignee_id', $assignee))
    ->when($filters['tag'] ?? null, fn ($q, $tag) => $q->whereHas('tags', fn ($t) => $t->where('name', $tag)))
    ->when($filters['q'] ?? null, fn ($q, $term) => $q->where('subject', 'like', "%{$term}%"))
    ->orderByDesc('last_message_at')
    ->paginate(25)
    ->withQueryString();

and the row partial it renders, which is where the real work happens:

<span class="avatar">{{ $ticket->customer->initials() }}</span>
…
{{ $ticket->customer->name }}@if ($ticket->customer->company) · {{ $ticket->customer->company }}@endif
· {{ $ticket->messages->count() }} {{ Str::plural('message', $ticket->messages->count()) }}
· {{ Str::limit($ticket->messages->last()?->body, 90) }}
…
@include('partials.tags', ['tags' => $ticket->tags])
…
@if ($ticket->assignee)<span class="avatar">{{ $ticket->assignee->initials() }}</span>@endif

Each of customer, messages, tags and assignee is a query per row, and messages is not a count, it is every message of the ticket loaded to count them and take the last one. Twenty-five rows is a hundred queries and however many messages those tickets have. This is not a strawman; it is what a row partial looks like when the relations are added one at a time over a year.

The dashboard's chart is the other classic:

$perDay = [];
for ($i = 29; $i >= 0; $i--) {
    $day = now()->subDays($i)->toDateString();
    $perDay[$day] = Ticket::whereDate('created_at', $day)->count();
}

Thirty queries, and whereDate wraps the column in DATE(), which means no index can serve it and every one of the thirty reads the whole table. The agents table runs three counts per agent for twenty agents, and the average first-response time loads a week of tickets as models to average a Carbon difference in PHP.

The export calls get() on everything in the range and touches four relations per row inside the stream. The webhook does its tagging by loading every tag and running str_contains for each, finds the least loaded agent with a withCount over open tickets, and sends the assignment email before responding. The SLA command loads every unanswered open ticket to compare dates in PHP. None of this is wrong in the sense of producing wrong answers, and all of it passes the sixteen Pest tests in the repository. It is wrong in the sense that will show up below.

The data

Measuring on a hundred seeded rows would make every page instant and the series pointless, so the seeder builds eighteen months of a real desk. It is deterministic for a given hour: mt_srand(2026), no Faker on the big tables, and a timeline anchored to the start of the current hour rather than to the second, so two runs in the same hour produce identical rows and a run next month has the same shape with the recent end moved along. It goes through the query builder in chunks of a thousand rather than through models, and it predicts ids rather than reading them back, because the tables are empty and nothing else is writing:

$messageId++;
$messages[] = ['ticket_id' => $ticketId, 'author_type' => …, 'body' => $body, 'created_at' => $at, …];
if ($fromCustomer && mt_rand(1, 100) <= 15) {
    $attachments[] = ['message_id' => $messageId, 'filename' => $file, …];
}
…
if (DB::table('messages')->max('id') !== $messageId) {
    throw new RuntimeException('Message ids did not come out sequential; attachments point at the wrong rows.');
}

The shape matters more than the size. Tickets are denser in recent months and lighter at weekends; thread length is skewed, with 30% of tickets a single message, most under six, 2% between twenty and a hundred and sixty; 88% are assigned, unevenly, to twenty agents; priority follows the subject, so outages are urgent; status follows age, so a year-old ticket is closed and last week's is still moving; first-response times depend on priority and sometimes miss the SLA. The dashboard's thirty-day chart and the inbox's "open" filter only mean something if recent tickets behave differently from old ones.

bin/dev seed
Seeding at scale 1
Seeded 200,000 tickets, 1,300,120 messages, 101,968 attachments, 362,328 events.

Four minutes on this laptop, 515 MB on disk, and the status mix on the day it was seeded: 171,707 closed, 13,583 open, 6,672 pending, 8,038 resolved, 7,656 open or pending with no first response yet. SEED_SCALE=0.01 in .env gives a two-thousand-ticket version for a quick look; the numbers in this series are all at scale 1.

One number from the database container worth writing down now: innodb_buffer_pool_size is 128 MB, the MySQL default, against a 515 MB dataset. Part 3 comes back to it.

The stack

The Compose stack is the one from the Docker series with two changes. There is no Vite dev server, because the app exists to be measured and the stylesheet is built once and served as it would be in production. And the PHP image carries two profilers: php-spx, compiled in and idle until a request carries its cookie, and Xdebug as a build-time option, because Xdebug slows everything it touches even when it is not profiling.

RUN apk add --no-cache icu-libs mysql-client git bash zlib \
    && apk add --no-cache --virtual .build-deps $PHPIZE_DEPS linux-headers icu-dev zlib-dev \
    && docker-php-ext-install -j"$(nproc)" pdo_mysql intl bcmath pcntl \
    && pecl install redis \
    && docker-php-ext-enable redis \
    && git clone https://github.com/NoiseByNorthwest/php-spx.git /tmp/php-spx \
    && cd /tmp/php-spx && git checkout -q 015c221 && phpize && ./configure && make -j"$(nproc)" && make install \
    && cd / && rm -rf /tmp/php-spx \
    && apk del .build-deps

OPcache is not in that list, and the reason is in the first entry of "What went wrong". The SPX control panel is at /?SPX_KEY=dev&SPX_UI_URI=/ once the stack is up; part 2 uses it.

The queue worker and the scheduler run throughout, because they run in production too. The SLA command fires every minute during every benchmark below, loading its 7,648 tickets each time, and that is part of the baseline rather than noise to be removed: a production server has its cron jobs during peak hours as well.

The load test

k6 runs from a container in the same Compose network, so the requests go through nginx and PHP-FPM exactly as a browser's would. Every virtual user signs in once, with the CSRF token read from the login page, and k6 keeps the session cookie per user:

export function login() {
  const page = http.get(`${BASE}/login`);
  const token = page.html().find('input[name=_token]').attr('value');
  const res = http.post(`${BASE}/login`, { _token: token, email: '[email protected]', password: 'password' }, { redirects: 0 });
  if (res.status !== 302) fail(`login failed: ${res.status}`);
}

Six scenarios, one per shape of work, each tagged so the summary can be read per request type:

// inbox.js: what agents do all day
if (r < 0.5) get(`${BASE}/inbox`, 'inbox page 1');
else if (r < 0.8) get(`${BASE}/inbox?page=${rand(2, 20)}`, 'inbox pages 2-20');
else if (r < 0.9) get(`${BASE}/inbox?priority=high&assignee=none`, 'inbox filtered');
else get(`${BASE}/inbox?status=closed&page=${rand(2000, 5000)}`, 'inbox deep page');

ticket.js opens random tickets across the whole table, with one request in five going to one of the eight longest threads (160 messages each, their ids passed in as LONG_IDS). dashboard.js loads the dashboard. search.js runs three users through eight common terms. export.js is one user exporting a week, a month and a quarter. inbound.js is the email provider: five users posting signed webhooks, 40% new tickets and 60% replies, and it runs last because it writes. Ten virtual users for sixty seconds is the default, which is a small desk at a busy moment, and small is right for a baseline: the purpose is to see which pages are slow at a load the app should handle, not to find the breaking point. Part 5 ramps it.

bin/dev bench inbox runs a scenario and writes bench/results/inbox.json; node bench/report.mjs bench/results/*.json turns the files into one table.

The baseline

A single logged-in request to each page first, with curl, because one number per page is the fastest way to know where to look:

200 10.06s  18784B  /
200  0.44s  48056B  /inbox
200  1.55s  48813B  /inbox?page=3000&status=closed
200  0.68s 152026B  /tickets/17440
200  0.11s  16055B  /tickets/5
200 19.81s  44522B  /search?q=invoice

Ten seconds for the dashboard and twenty for a search, for one user with nothing else happening. Then the scenarios, ten users each, sixty seconds, in the order listed:

Scenario Users Requests req/s p50 p95 p99 max
dashboard 10 35 0.4 1.4 s 53.1 s 53.4 s 53.4 s
inbox 10 393 6.4 1.07 s 2.8 s 12.4 s 12.5 s
ticket 10 1,426 23.5 300 ms 1.0 s 1.23 s 1.57 s
search 3 15 0.2 20.2 s 32.5 s 32.6 s 32.6 s
export 1 3 0.05 42.0 s 48.2 s 48.4 s 48.4 s
inbound 5 606 10.0 54 ms 1.37 s 1.46 s 2.76 s

Reading down the table:

The dashboard served thirty-five requests in a minute to ten users, and the 95th percentile is fifty-three seconds against ten for a single user. The difference is queueing, and the queue is PHP-FPM's: the official image ships pm.max_children = 5, so five dashboards hold the five workers for ten seconds each and the other five users wait in nginx for a worker, then wait again for their own ten seconds. A page that is slow for one user is slower than itself for ten, and the multiplier is the worker count. Part 5 is about that number; part 3 is about the ten seconds.

The inbox has a median of a second and a 99th percentile of twelve, which is the deep page in the mix: ?status=closed&page=4000 is an OFFSET 100000 over a sort that has no index to use, so MySQL sorts the closed tickets and then throws away a hundred thousand rows. The first pages pay for a hundred queries per page, the deep pages pay for the sort. Both are part 3; the hundred queries are part 2 first, because the profiler finds them in a minute.

The ticket page is the healthiest page, at 300 ms median and a second at the 95th, and it is still an N+1 per message with a sidebar that loads the customer's whole history to count it. The eight 160-message threads are what the tail is made of.

Search managed fifteen requests from three users in a minute, at twenty seconds each. LIKE '%term%' on a million message bodies cannot use an index, so every search reads every row, and three searches at once are three full scans at once.

The export is the one that lies. All three came back with a 200 and a CSV. The week's 6,656 rows took twenty-six seconds and were complete; the month came back with 13,013 of its 16,006 rows and the quarter with 11,873 of 43,223, checked against SELECT COUNT(*) for the same ranges, and both stopped at about forty-eight seconds of wall time. That is PHP's max_execution_time of thirty seconds, which on Linux counts the script's own CPU time and not the time it spends waiting for MySQL. So the export is not slow; for any range much over a week it is broken, and nobody gets an error.

The inbound webhook has a 54 ms median and a 1.4 s 95th percentile, and those are two different code paths: a reply is an insert, a new ticket is a withCount over every open ticket to find the least loaded agent, thirty str_contains over the text, and an email sent before the provider gets its 201. Email providers retry on slow responses, which is how a slow webhook becomes a duplicated ticket; part 5.

That is the baseline, and the only conclusion this part draws from it is where to look first. The inbox and the ticket page are what agents open hundreds of times a day, and both are under a second for one user and in trouble for ten; part 2 takes the profiler to them. The dashboard and search are the slow pages a user notices, and their problem is in the database; part 3. The export and the webhook are the request-shaped things that should not be requests at all; part 5.

What went wrong

docker-php-ext-install opcache fails on PHP 8.5. The build stopped with cp: can't stat 'modules/*' after OPcache's configure step, because PHP 8.5 made OPcache a permanent part of the engine: it cannot be left out of a build any more, so there is no module to compile and the helper has nothing to install. php -m in the base image already lists Zend OPcache, and it is enabled. The line came out of the Dockerfile. If a Dockerfile from the 8.4 era is upgraded, this is the first thing that breaks.

php-spx's last release predates PHP 8.5. Tag v0.4.22 is from October 2025 and does not compile against the 8.5 engine; master does. The Dockerfile pins the commit rather than a tag, and the pin is the kind of thing to re-check when the next release lands.

The pivot table was named ticket_tag. Laravel names a pivot from the two models in alphabetical order, tag_ticket, and the first test that rendered tags failed with a missing table. The migration follows the convention now; the alternative was naming the table in both belongsToMany calls for the life of the project.

The quarter export returned 200 and was wrong. k6 marked all three exports as successes, and the log said otherwise for two of them: Maximum execution time of 30 seconds exceeded in the controller, followed by Cannot modify header information - headers already sent. The export streams, so the 200 and the headers had gone out before PHP's max_execution_time (30 s, the default the official image ships with no php.ini at all) killed the process mid-file. The row counts are in the table's notes above. A status code is not a result; the row count is. The scenario checks the status and the content type, which is the baseline's own blind spot: a load test cannot know how many rows there should have been. Part 3 fixes the export's queries, and part 5 moves it off the request altogether.

k6 empties the cookie jar between iterations. The first full run reported the inbox at 170 requests per second with a 53 ms median, which would have been wonderful and was the login page: a virtual user signs in once, and k6 resets its cookies at the start of every iteration unless noCookiesReset: true is set. Every page redirected to /login, which is a 200, which passed the check. The check now also looks for the "Sign out" link, and the scenario fails loudly instead of flattering the app. The dashboard scenario had been genuinely signed in, because its first iteration was slow enough to be its only one for most users.

The screenshot script waited three minutes for a button that was never there. Playwright's selector was button[type=submit]; the form's button has no type attribute and submits anyway, as buttons in forms do. Not a performance finding, but the kind of thing that costs a quarter of an hour and gets blamed on the app.

Part 2 opens the profiler on the inbox and the ticket page: what php-spx's flame graphs show, where the N+1s are and where they are not, what is left when the queries are gone, and what the PHP-side settings everyone recommends actually measure on this machine.

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.