Count across the whole request
The N+1 pattern starts with one query for a collection and then performs another query for each item’s related data. The number of database round trips grows with the collection size. Each individual query can be fast while their accumulated latency makes the request slow.
This is not a problem exclusive to an ORM. Explicit SQL inside a loop can create the same shape. Count queries across the complete page or API request, rather than examining only the slowest individual statement. Request-level amplification can be missed by a statement-only investigation.
A list of one hundred orders
Suppose a request fetches one hundred orders and then separately loads each customer name. In the simplest case, it performs 101 queries. A ten-item test might hide the cost that becomes significant as the page grows. The repeated waiting can dominate even when indexes make each lookup efficient.
Possible changes include fetching related fields with a join or collecting customer identifiers for a batched lookup. Repeated customers can also make duplicate fetching unnecessary. First identify the fields and rows the screen really needs, so the repair does not simply fetch every possible relationship.
One query is not the only objective
Joining one-to-many relationships can duplicate parent fields across result rows. Joining several such relationships may amplify the row count substantially. Minimizing query count alone is therefore not a sufficient performance objective; measure rows returned, bytes transferred and application reconstruction cost.
Batching also needs bounds. Very large identifier sets and interactions with pagination can change the cost profile. Test skewed relationship sizes instead of assuming every parent has the average number of children. A request with one unusually large relationship can behave differently from a uniformly small sample.
Validate the request shape
Compare query count, total database time and end-to-end request latency using the same data and item count before and after the change. Inspect the resulting execution plans as well; a batched statement can introduce a different scan or join cost that deserves attention.
Caching can temporarily hide repeated work. Include cold or newly encountered relationships and vary collection size. Checking how query count grows with input size makes the structural issue visible and helps catch regressions when another related field is later added to the screen.