📚 Encyclopedia

Databases · updated 2026-11-30

The missing index behind a slow list endpoint

mysqlmariadbindexsubqueryperformanceapiprofiling

A list endpoint that computes a count per row ((SELECT COUNT(*) FROM response WHERE post_id = p.id)) runs that subquery once for every row it returns. If the child table has no index on the column being matched, each of those runs is a full table scan, and the cost is rows times table size. It stays invisible while the tables are small and then grows quietly until "the app feels slow". This is the commonest cause of a slow list in a hand-written schema, because foreign-key columns only get an index automatically when a real FOREIGN KEY constraint is declared.

The concrete case

On the TLDR API (about 1,030 posts and 2,700 responses), GET /posts took 0.66 s for one page. Timing the PHP side showed 0.61 s of that was the per-post response-count subquery: the response table had no index on post_id, so the count scanned all 2,700 rows once per post. One statement fixed it:

ALTER TABLE response ADD INDEX idx_response_post (post_id, deleted);
Request Before After
One page of posts 656 ms 11 ms
Full list 968 ms 109 ms

The second column is there because the count skips soft-deleted rows: with (post_id, deleted) a count that filters on both is answered from the index alone, without touching the rows.

How to find it

Don't compute what the request doesn't use

The same endpoint computed a view count and a response count for every row only so that two rarely used sort orders could sort by them. Adding those subqueries only when the request asks for order=views or order=responses removes the work for every other call. An index makes a subquery cheap; not running it is cheaper.

Applying it safely

Adding an index is one of the lowest-risk schema changes (no data changes, and it is reversible with DROP INDEX), but treat it like any other production change: take a dump of the table first, keep the statement as a migration file in the repo, and apply it before the code that expects it. An index can go live ahead of the release, since old code benefits too. See Changing a production MariaDB safely (schema, data fixes, id generation).

Gotchas

See also

Linked from

Sources: tldr memory (perf-post-load), tldr post #1929, 2026-11-29