N+1 on an article page: find extra queries before premature optimization

Compare N+1 with a card projection on MySQL 8.4: define the SELECT-count boundary, preserve equal DTOs, and measure timing separately.

A conceptual illustration of individual reads and an assembled list.
A conceptual illustration of individual reads and an assembled list.

A slow article list makes adding a cache tempting. First, however, it helps to understand which work the page repeats. One query for twenty cards followed by twenty queries for author names creates N+1: the number of calls grows with the number of displayed items. Even individually fast queries can create unnecessary work at the application and database boundary.

This article compares two ways to read article titles and author names in one Symfony Demo. The example uses MySQL 8.4 and InnoDB through native PDO MySQL. We check successful SELECT counts and equal cards; results from the old SQLite measurement are not measurements of this implementation.

Start with the card contract

“How can we speed up the repository?” is too broad a question. For this list, define the output as ordered id, title, and author_name fields. The complete article, revision history, and comment collection are unnecessary for this card. A narrow read projection helps us compare the same useful work.

The contract also includes selection. The example reads only published Ukrainian articles belonging to the journal site. Ordering is published_at DESC, id DESC, and the limit stays within the teaching dataset. The second key removes ambiguity when publication times match. A different language or a disappearing card makes an optimization incorrect, even if the query becomes shorter.

The card contract requires one author for each article. The author identifier is the primary key of the author table, so joining that row should not multiply article rows. This is an essential assumption: applying the same technique to a comment collection changes row cardinality and can break a limited page.

Make repetition visible

The baseline path is deliberately simple. One SELECT first reads the list and its author_id values. A loop then executes a separate SELECT name for each returned article using that identifier. Preparing a statement can be reused, but executing the query for every author remains separate work.

The PDO prepared statements documentation explains preparation, execution, and parameter binding. A prepared statement helps pass values safely; it does not combine twenty execute() calls into one database call. This is why the example places its counter at the actual execution boundary.

After a successful execute(), the wrapper records the SQL in an executed-query array. An error propagates to the caller and stops the comparison. A successful-execution counter is not an attempted-execution counter, so a failed run cannot enter a table of successful results. The failed run’s error and its reason must be recorded separately.

Freeze the measurement boundary

Only the SELECT statements needed to obtain cards through the selected path enter the counter. Running the example requires the guarded disposable MySQL fixture introduced earlier: the App\Infrastructure\MysqlLab helper supplies a test schema, a separate migrator explicitly creates InnoDB tables and FK/CHECK constraints, and data preparation finishes before measurement. DDL runs before business transactions; in MySQL it can cause an implicit commit. The runtime read path does not create, alter, or drop tables. This is neither an atomic schema upgrade nor an automatic transfer of old SQLite data. There is no total-article-count query: if the page needs a total, add it as a separate declared operation to both paths.

Application-level result caching is disabled in this experiment. For each path, QueryCountCommand separately calls CardReader::fixtureLab($n), creating a fresh owned disposable MySQL schema and a separate native PDO runtime connection. The prepared datasets have identical contents, but the two paths do not share a schema. There is no ORM identity map, entity cache, or complete-response cache. A new connection does not imply a cold InnoDB buffer pool: we compare the source-reading topology, not guarantee the absence of server-side caching.

Four datasets were frozen before implementation: 0, 1, 20, and 100 articles, each with a distinct author. An empty page is a useful control: the initial list query still executes, while the author-reading loop does not. The boundary case checks the explanation of the formula as well as the typical list.

Cards Expected baseline SELECTs Expected projection SELECTs
0 1 1
1 2 1
20 21 1
100 101 1

The invariant to check for 0, 1, 20, and 100 cards is respectively 1/1, 2/1, 21/1, and 101/1 successful SELECTs for the baseline and projection. Reducing executions is acceptable only with identical ordered identifiers and DTOs. This is a read-correctness criterion, not a new series of 40 timed MySQL reads.

Shape the read around the page

The second path returns a.id, a.title, and u.name AS author_name in one query. The filters, ordering, and limit remain the same. What changes is how the required author field is obtained. The MySQL 8.4 SELECT reference explains sources, joins, filtering, ordering, and limits; these parts define the teaching query's contract.

The example uses a LEFT JOIN followed by an explicit missing-author check. Both paths can therefore fail if the author required by the contract is absent, including after an ordinary author deletion. An ordinary INNER JOIN could silently remove that article, making fewer cards look like cheaper reading. The teaching result must preserve the author requirement rather than conceal the problem.

Both paths normalize their DTOs identically: a numeric identifier, a title, and an author name. Equal row counts are insufficient for comparison. Check exact order, field values, and the SHA-256 of the serialized ordered output. The hash provides a compact equality receipt, while readable identifiers help investigate a mismatch.

Check that optimization preserved meaning

The executed tests check expected counts at all four sizes, identical DTOs, and descending identifiers when publication times are equal. A separate negative control adds an article from another site, one in another language, and an unpublished article. None of those rows should appear in either path's result.

A missing required author must cause an explicit error rather than an empty name or an incomplete page. In the InnoDB schema created by CardReader::fixtureLab, author_id is nullable and its foreign key uses ON DELETE SET NULL. An ordinary author deletion can therefore leave an article without an author: the schema permits this state, but explicit checks in both read paths reject it as a violation of the card contract. This state is prepared separately as a negative fixture before reading begins; a missing table is likewise a source error, not a runtime action. A quick failure does not become a successful performance result: comparison requires the complete page under the agreed contract.

The example remains in the one existing Symfony Demo without a new skeleton. Database tests run through the guarded MySQL fixture, with a separate migrator for setup and only DML in runtime code. The important checks are exact counts, DTOs and order, filters, and explicit propagation of source errors; a failed SELECT does not increment the successful-execution counter. The old 4 tests / 26 assertions are not presented as a separate result for this MySQL port.

Timing answers a different question

Fewer queries mean fewer executions inside the defined boundary. They do not yet guarantee a shorter page duration. For MySQL, duration depends on network exchanges with the server, the query plan, indexes, InnoDB buffer-pool state, row transfer, and data conversion. Measure these conditions with a suitable dataset; a database connection is not an external HTTP-service call.

For a new MySQL measurement, repeat each size several times, alternating the two paths. Use monotonic hrtime(true) to measure reading and DTO construction, excluding fixture creation and subsequent hashing. Retain SQL, counts, elapsed nanoseconds, order, and DTO hashes for every pair. The old SQLite medians are not reported here as MySQL results; without a new series, there is no basis for a speedup magnitude or a production-latency prediction.

Analysis needs every duration, rather than only the best run. If the projection is equally fast or slower on a small dataset, that is still a valid observation. Artificially delaying every query to produce an attractive chart would obscure the question. Explain the conditions and repeat the experiment where they match the task.

Decide where optimization ends

Once one read produces the correct page, there is no reason to automatically join every possible relationship. A long query with multiple collections can transfer more repeated data and change pagination. Sometimes two batched queries with explicit result assembly are simpler than a universal join across the domain.

Likewise, caching author names should begin with a freshness and invalidation policy. A cache can remove repeated reads on a warm path, while the cold path remains part of the system. Establish correct selection and an understandable operation count first, then decide which results can safely be reused.

For a working page, the next step is to locate the specific call producing repetition, freeze its boundary, and compare identical output before and after the change. The name N+1 alone cannot diagnose an entire platform. This teaching example shows how to ask a testable question: how many executions does this particular page need, and does reducing the work preserve its meaning?

The team should separately agree on what one query means in its report. Here it means one successful SQL statement execution through the wrapper. Internal MySQL query-plan steps, InnoDB page access, or row fetching do not become additional queries. That agreement makes the count reproducible and prevents the two paths from being compared under different definitions.

The limit must also apply to returned articles. If the list later gains additional sorting, permits a missing author in a card, or gains a new access rule, revise the contract and checks before changing SQL. Keeping the empty dataset and equal publication times as permanent regression cases is particularly useful: they quickly expose an assumption that no longer holds. After changing the query, repeat the complete matrix rather than only the hundred-card dataset where execution savings look largest. Correctness at every size remains an acceptance condition regardless of future durations.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/QueryCount
  1. Symfony Core Entity or DTO: which data should a page receive from storage?
  2. API Testing an API without a live database: what a fixture proves and what it does not
  3. Architecture Profile a fast page: TTFB, images, and browser rendering

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article