Finding the real performance problem in a Laravel app · Part 3 of 6
The database on a million rows
The slow query log and pt-query-digest, EXPLAIN on the queries behind the baseline, two rounds of indexes, keyset pagination, full-text search and the bound parameter that made it five times slower, a chunked export, and a buffer pool measured before and after.
By Abhishek Fouzdar · Updated
Part 2 left the application layer clean and pointed at the database for everything that was still slow: a dashboard at seven seconds, a search at fifteen, an inbox whose every page sorts thirteen thousand rows, deep pages that throw away a hundred thousand, and an export that stops at thirty seconds of CPU. This part is the database, on the million-row tables the seeder built, with the three instruments MySQL gives away: the slow query log, EXPLAIN, and the status counters. Every index below is here because one of them asked for it.
Turn on the slow log before you need it
MySQL will write every query over a threshold to a file, with its time, its rows examined and its rows sent, and a tool from Percona will group that file into a ranked list. Both cost almost nothing and most servers run with neither. Four lines in a config file mounted into the container:
[mysqld]
slow_query_log = 1
slow_query_log_file = /var/lib/mysql/slow.log
long_query_time = 0.1
log_queries_not_using_indexes = 1
A hundred milliseconds is low for production and right for finding things; the last line also logs fast queries that scanned a table, which is how a query that is fast today and slow at ten times the data gets caught today. Then a few minutes of ordinary traffic and:
bin/dev digest # pt-query-digest /var/lib/mysql/slow.log, in the percona-toolkit container
# Overall: 96 total, 15 unique, 2 QPS, 0.84x concurrency
# Attribute total min max avg 95% stddev median
# Exec time 41s 58us 9s 422ms 501ms 1s 110ms
# Rows examine 18.02M 5 1.41M 192.20k 257.47k 217.98k 192.13k
# Profile
# Rank Query ID Response time Calls R/Call V/M
# 1 0x6EEBAD3F56792605315BE97CB6590A5B 14.9927 37.0% 2 7.4964 0.52 SELECT messages tickets messages
# 2 0x1D3C9DA79B08BAB25DA63977B62D8774 14.7769 36.5% 2 7.3885 0.98 SELECT tickets messages
# 3 0xFBEF876AB4F7ADB552C6AFF3B00F94A3 6.0848 15.0% 53 0.1148 0.00 SELECT tickets
# 4 0x4AE404C007E2836D0CB523785691F61E 1.3022 3.2% 8 0.1628 0.00 SELECT tickets
# 5 0x2B568668889BB8A9FA1E98F9089F10FA 1.0919 2.7% 2 0.5460 0.00 SELECT tickets tag_ticket tags
# 6 0x9335546D98E0587C075B914AF821C7B5 0.9329 2.3% 2 0.4664 0.00 SELECT messages tickets
# 7 0x290C7B5776D6C55DDFF23EBEDC835800 0.6485 1.6% 2 0.3243 0.00 SELECT tickets
Forty-eight seconds of traffic (two dashboards, two searches, three inbox pages, a month's export, a ticket, the SLA check), ninety-six slow queries, eighteen million rows examined to send eighteen thousand. Under each rank the digest prints the query itself with its distribution; the first two are the search page's results query and its pagination count, both scanning the same 1.4 million rows, and the third is the dashboard's tickets-per-day count, 53 calls at 115 ms each, which is one full scan per bar of the chart.
That is the whole investigation, ranked. A digest says which queries cost the most in total, not which are slowest once, and that ordering is the one that matters: a 40 ms query that runs thirty times per page beats a 400 ms query that runs once.
Reading EXPLAIN
EXPLAIN is the plan MySQL intends to use, and three of its columns answer most questions: type (how rows are found: ALL is a full scan, ref and range use an index), rows (how many it expects to examine), and Extra (Using filesort means a sort that no index provided, Using index means it never read the table). The queries behind the digest, before any change:
| Query | type | key | rows | Extra |
|---|---|---|---|---|
Inbox, first page (status = 'open' ORDER BY last_message_at) |
ref | status | 24,960 | Using filesort |
Inbox, page 4000 (status = 'closed' … OFFSET 99975) |
ref | status | 92,969 | Using filesort |
Dashboard, tickets per day (DATE(created_at) = ?) |
ALL | 185,938 | Using where | |
Dashboard, agent counts (assignee_id = ? AND status = ?) |
index_merge | assignee_id, status | 2,121 | Using intersect |
Search (subject LIKE '%x%' OR EXISTS (… body LIKE '%x%')) |
ALL | 185,938 | Using where; Using filesort | |
Export (created_at BETWEEN ? AND ?) |
ALL | 185,938 | Using where; Using filesort | |
SLA check (status IN (…) AND first_response_at IS NULL …) |
ALL | 185,938 | Using where |
Two patterns account for every row. The inbox finds the open tickets through the status index and then sorts them, every page, because the index knows nothing about last_message_at. Everything else is a full scan: DATE(created_at) wraps the column in a function, so no index on created_at could serve it even if one existed, and none did; the export and the SLA check filter on columns with no index at all; and LIKE '%term%' cannot use a B-tree index by definition, since the term can be anywhere in the string.
The agent counts are the interesting one. MySQL merged two single-column indexes to answer assignee_id = ? AND status = ?, which works, and cost about 18 ms per count against 1.3 ms through one index on both columns, measured with SET profiling = 1 in the client. It ran sixty times per dashboard.
The first round: indexes for what the pages read
Schema::table('tickets', function (Blueprint $table) {
$table->index(['status', 'last_message_at']);
$table->index(['status', 'created_at']);
$table->index(['assignee_id', 'status']);
$table->index('created_at');
$table->fullText('subject');
});
Schema::table('messages', function (Blueprint $table) {
$table->fullText('body');
});
Column order in a composite index follows the query: the equality first, the sort or range second, so (status, last_message_at) lets MySQL walk straight to the open tickets and read them already in order. The migration took 2 minutes 53 seconds on this laptop, nearly all of it the full-text index over a million message bodies. That one is not an online operation: MySQL builds a FULLTEXT index in place but permits no concurrent writes while it does, and the first full-text index on a table rebuilds the table, so on a production messages table it is a maintenance window or a copy of the table, not a deploy step.
The inbox after, from EXPLAIN:
type: ref key: tickets_status_last_message_at_index rows: 24942 Extra: Backward index scan
No filesort. The 32 ms query is 2 ms, and the page is at 95 ms, which is now mostly PHP rendering twenty-five rows.
The deep pages are a different problem and an index does not solve it. OFFSET 99975 still reads a hundred thousand index entries to discard them, and it gets slower the deeper it goes, which is why the baseline's 99th percentile was the deep page. The answer is keyset pagination: instead of "skip N rows", the next page asks for "rows after the last one I saw", which the same index answers in constant time:
$tickets = Ticket::query()
->with(['customer', 'assignee', 'tags', 'latestMessage'])
->withCount('messages')
->when(…)
->orderByDesc('last_message_at')
->orderByDesc('id');
return view('inbox.index', [
'total' => $tickets->clone()->count(),
'tickets' => $tickets->cursorPaginate(25)->withQueryString(),
]);
cursorPaginate encodes the last row's sort columns in the URL, and the second orderBy on id is required because last_message_at alone is not unique and a cursor has to be. What it gives up is page numbers, which agents do not use, and the total, which a cursor paginator cannot know. The count is a separate query: 4 ms for the open tickets through the index, and about 100 ms for status = 'closed', because counting 171,000 index entries is reading 171,000 index entries. Every closed-tickets page now costs 110 ms of database time, and the count is most of it; part 4 keeps that number somewhere cheaper.
The dashboard stopped running thirty queries for its chart and sixty for its agents table. Each card is one grouped query over a range an index can serve:
$from = now()->subDays(29)->startOfDay();
$counted = Ticket::query()
->where('created_at', '>=', $from)
->select(DB::raw('date(created_at) as day'), DB::raw('count(*) as n'))
->groupBy('day')
->pluck('n', 'day');
The DATE() is still there, but on the select side where it costs nothing; the WHERE is a plain range on an indexed column. The agents table became one query grouped by assignee_id, status, the average first-response time became AVG(TIMESTAMPDIFF(…)) computed by the database instead of a thousand models and Carbon, and the week's top tags became a join from the pivot to the week's tickets instead of a correlated count per tag over the whole table. 104 queries became 11; 7.4 seconds became 1.6.
The second round: what the digest said next
The method says to measure again, and the second desk:queries on the dashboard ranked what was left:
| 1 | 892.7 | select `assignee_id`, count(*) as n from `tickets` where `resolved_at` >= ? and `assignee_id` is not null group by `assignee_id`
| 1 | 252.3 | select `priority`, count(*) as n from `tickets` where `status` in (…) group by `priority`
| 1 | 203.2 | select count(*) as `aggregate` from `tickets` where `status` in (…) and `sla_breached_at` is not null
Three aggregates, each finding its rows through an index and then reading the table for a column the index does not have. Three more indexes, each chosen so its query finishes inside the index:
$table->index('resolved_at');
$table->index(['status', 'priority']);
$table->index(['status', 'sla_breached_at']);
Six seconds of migration, and the dashboard is at 600 to 700 ms:
| 1 | 172.9 | select `assignee_id`, `status`, count(*) as n from `tickets` where `status` in (…) … group by `assignee_id`, `status`
| 1 | 142.8 | select `tags`.*, count(*) as tickets_count from `tags` inner join `tag_ticket` … where `tickets`.`created_at` >= ?
| 1 | 115.0 | select `status`, count(*) as n from `tickets` group by `status`
What remains is honest work: counting every ticket by status means visiting two hundred thousand index entries, and no index makes that free. A page that aggregates a whole table on every load is asking the wrong layer, and part 4 moves these numbers into a cache with a short life, which is where numbers that change by the minute and are read by the second belong. Seven seconds to seven hundred milliseconds is the database's share of the fix; the next ten times is not the database's to give.
Search: three wrong versions and the right one
LIKE '%invoice%' over a million bodies was a fifteen-second table scan, and the full-text index is the replacement: InnoDB tokenises the text once at index time and a MATCH … AGAINST looks the term up. Laravel has whereFullText() for it. The first version was the obvious one, the old query with the operators swapped:
Ticket::whereFullText('subject', $term)
->orWhereIn('id', Message::whereFullText('body', $term)->select('ticket_id'))
->orderByDesc('last_message_at')
->paginate(25);
Fifteen seconds became 3.3 for "invoice" and 0.6 for "okta". EXPLAIN showed why the common word was still slow: the OR between a full-text condition and an IN (subquery) made MySQL scan the whole tickets table and test each row. The second version replaced the OR with a UNION of the two id sets joined back to tickets, and got slower for common words, 5.7 seconds, because withCount('messages') and the pagination COUNT(*) were now evaluated for all 81,000 tickets that mention invoices before the sort could keep twenty-five. The third version split the work in two queries, one to pick and page the ids and one to hydrate the page, and ordered by relevance with a LIMIT inside each full-text branch, which MySQL can serve from the index without scoring every match. In the MySQL client that query took 0.36 seconds for "invoice". From Laravel it took 1.8.
That gap was the afternoon's real lesson. The same SQL, the same server, five times slower from the application, and the difference was the ?:
literal, natural mode both 376 ms
bound, natural mode both 1786 ms
Laravel sends queries as server-side prepared statements (PDO::ATTR_EMULATE_PREPARES is false), and with the search term arriving as a bound parameter rather than a literal, MySQL does not apply the full-text sorted-limit optimisation and scores every matching message before taking the top rows. The fix is to inline the term as a literal, quoted by the driver so it is still safe:
$quoted = DB::connection()->getPdo()->quote($term);
$scores = Ticket::query()
->selectRaw("id, match(subject) against ({$quoted} in natural language mode) as score")
->whereRaw("match(subject) against ({$quoted} in natural language mode)")
->orderByDesc('score')
->limit(300)
->pluck('score', 'id');
Message::query()
->selectRaw("ticket_id, match(body) against ({$quoted} in natural language mode) as score")
->whereRaw("match(body) against ({$quoted} in natural language mode)")
->orderByDesc('score')
->limit(300)
->get()
->each(function (Message $hit) use ($scores) {
$scores[$hit->ticket_id] = max($hit->score, $scores[$hit->ticket_id] ?? 0);
});
Two more details that each cost a measurement. The MATCH in the select list is spelled exactly like the one in the WHERE, including the mode, so MySQL evaluates the index once; a different spelling is a different expression. And there is no GROUP BY ticket_id on the message side, because grouping forced MySQL to score every matching message before it could take the top 300; duplicate tickets among the top messages are merged in PHP instead, where 300 rows cost nothing. The merged list is paged in PHP and only one page of tickets is hydrated with its relations. The page has a "next" link and no total, since counting 81,000 matches is as expensive as finding them and nobody reads past the three hundred most relevant.
/search?q=invoice db;dur=433.2;desc="8 queries", total;dur=537.9 (was 14,485)
/search?q=refund db;dur=200.4;desc="8 queries", total;dur=284.1
/search?q=okta db;dur=25.4;desc="8 queries", total;dur=89.6 (was 637 after the first version)
A term with quotes in it (o'brien "test) comes back as an empty result in 31 ms, which is the test that PDO::quote is doing its job.
The export and the SLA check
The export loaded a quarter of the table into memory with get() and then touched four relations per row until PHP's time limit stopped it. Now it reads a thousand tickets at a time with their relations, by id, and never holds more than that:
$tickets = Ticket::whereBetween('created_at', [$data['from'].' 00:00:00', $data['to'].' 23:59:59'])
->with(['customer', 'assignee', 'tags'])
->withCount('messages')
->lazyById(1000);
return response()->streamDownload(function () use ($tickets) {
set_time_limit(0);
…
lazyById orders by id rather than by date, so the CSV's row order changed, and the set_time_limit(0) is there because a streamed response has already sent its 200 by the time PHP would otherwise kill it, and a complete file after forty seconds beats a truncated one after thirty. The quarter export that stopped at 11,873 rows now returns all 43,223 in 27 seconds. It is still a 27-second HTTP request that ties up one of five PHP-FPM workers, which is why part 5 makes it a job that writes a file.
The SLA command loaded every unanswered open ticket to compare dates in PHP. The database can compare dates:
foreach (Ticket::SLA_HOURS as $priority => $hours) {
$breached += Ticket::whereIn('status', ['open', 'pending'])
->whereNull('first_response_at')
->whereNull('sla_breached_at')
->where('priority', $priority)
->where('created_at', '<', now()->subHours($hours))
->update(['sla_breached_at' => DB::raw("DATE_ADD(created_at, INTERVAL {$hours} HOUR)")]);
}
Four UPDATEs, no models, and the rows that do not qualify are never sent to PHP. It runs every minute in production, which is the kind of job whose cost is invisible until a request lands during it.
The buffer pool
One number from part 1 was waiting: innodb_buffer_pool_size at 128 MB, the MySQL default, against 515 MB of data. The pool is the memory InnoDB caches pages in, and a table that does not fit is read from disk every time it is scanned. Measured before the indexes, with the scans still there, raising it to 1 GB took the fifteen-second search to eleven and the ten-second dashboard to eight, and dropped Innodb_buffer_pool_reads (pages fetched from disk) from 31,392 to 6,600 for the same work. Twenty percent, for a line in a config file, and the reason it was not the first change in this part is that twenty percent of a table scan is still a table scan. Memory makes the wrong query less slow; the index makes it a different query. The setting stays at 1 GB because the data fits, and on a real server it is the first thing to size, to about three quarters of the memory MySQL is allowed.
The scenarios again
Ten users, sixty seconds, the four scenarios whose pages this part changed, against the part 1 baseline and part 2 where it touched the same page:
| Scenario | p50 before | p50 after | p95 before | p95 after | req/s before | req/s after |
|---|---|---|---|---|---|---|
| dashboard | 1.4 s | 1.8 s | 53.1 s | 2.3 s | 0.4 | 5.6 |
| inbox (part 2: 555 ms, 2.1 s) | 1.07 s | 264 ms | 2.8 s | 421 ms | 6.4 | 35.3 |
| search | 20.2 s | 154 ms | 32.5 s | 623 ms | 0.2 | 12.4 |
| export (one user, three ranges) | 42.0 s, truncated | 3.7 s | 48.2 s, truncated | 18.5 s |
The dashboard's median looks worse and is not: at the baseline, ten users shared five workers for ten-second pages, so most requests waited in the queue and the few that were served quickly between stalls set a misleading median, while the 95th percentile told the truth at fifty-three seconds. Now every request is served in about two seconds and the tail is 2.3. Fourteen times more dashboards per second is the number to read, and 700 ms of it is still the database counting a whole table on every load, which part 4 takes away.
The inbox is five and a half times faster at the 95th percentile than part 2 left it and its tail is gone: the deep pages that made the baseline's 99th percentile twelve seconds are now the same price as the first page. Search went from a request that took twenty seconds and blocked a worker to one that takes a sixth of a second, a hundred and thirty times more of them per minute. The export, which returned a truncated file in 48 seconds, returns a complete one: a week in 3.7, a month in 7.9, the quarter in 20.7, every row present and checked against the count.
What went wrong
The full-text index cannot see a test's own rows. The search test failed after the migration with the page rendering and the results missing. InnoDB's full-text index is updated on commit, and RefreshDatabase runs every test inside a transaction that is rolled back, so the tickets the test created were invisible to MATCH … AGAINST for the whole test. That one file uses DatabaseTruncation instead, which commits and truncates after each test, and the rest keep the faster transactions.
The slow log came back empty, twice, and the log was fine. pt-query-digest said "No events processed" with 469 lines in the file. The first time it was hidden behind an image pull; the second time, a look at stderr: the log is written by MySQL as mysql:mysql with mode 640, and the toolkit container runs as a different user. The toolkit service now runs as uid 999, the mysql user in the official image, and the digest above came out on the next run. The real mistake was 2>/dev/null on the first attempt, which turned an error into a silence.
MySQL dropped an index it had created, and the rollback failed. Rolling the migration back to capture the baseline digest stopped at Cannot drop index 'tickets_assignee_id_status_index': needed in a foreign key constraint. The assignee_id foreign key had been served by an index Laravel created with the constraint; when the composite (assignee_id, status) index arrived, InnoDB silently dropped the single-column one as redundant, and from then on the composite was the constraint's only index. The down() method now recreates the foreign key's index before dropping the composite. The failed rollback had already removed four other indexes, which were put back by hand while the migrations table still claimed they existed; a migration that fails halfway leaves a schema no migration describes, and the fix is to read information_schema.statistics rather than trust the table.
A GROUP BY undid a LIMIT. The relevance query at 0.36 seconds became 2.9 the moment it grouped by ticket, because the group has to see every scored row before it can order the groups. Deduplication moved to PHP, over three hundred rows.
The export's row order changed. lazyById has to order by id to page safely, and the old export was ordered by date. Nobody had asked for either order; it is in the post so that nobody is surprised by the diff.
Part 4 is caching: the dashboard's aggregates and the inbox's counts into Redis with a short life, Cache::flexible so a stale value is served while a fresh one is computed, locks against the stampede when the cache is empty and ten users ask at once, invalidation on the events that matter, HTTP caching for the assets and the export, and the cases where a cache is the wrong answer, including one that looked right.
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
3 / 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