N+1 problem
Проблема N+1
This performance problem happens when an app fetches a list in one database query, then runs a separate query for each item to get related data. A list of N items results in N+1 queries.
One query for the list, one more per item
Say an endpoint returns 40 articles with their authors' names. It first fetches the articles. Then, as it builds the response, it looks up each article's author. If the authors are distinct and none is already loaded, that's 41 queries: one for the articles and 40 for the authors. The endpoint can return the correct result in development and still slow down as page sizes grow.
Object-relational mappers (ORMs) can make this pattern hard to see. With lazy loading, article.author.name looks like an ordinary property access, but accessing an unloaded author can trigger a database query. The access might happen in a serializer or template rather than in the code that fetches the articles. The same issue can occur without an ORM if the application runs a separate query for every item in a loop.
Fetch related data for the whole page
One option is to fetch the page first, collect its distinct author IDs, and load those authors in one batch. A second option is to fetch the page and its author names together. For example, if authors.id is unique:
SELECT a.id, a.title, u.name AS author_name
FROM articles AS a
LEFT JOIN authors AS u ON u.id = a.author_id
ORDER BY a.id
LIMIT 40;
Because each article matches at most one author, the join does not multiply article rows. The LEFT JOIN keeps articles without a matching author. For a collection, such as comments on an article, the trade-off changes: a join returns a row per matching comment and repeats the article columns. A LIMIT on that joined result limits rows, not articles. Page the articles before joining, or fetch comments in a separate batch keyed by article ID.
Loading relationships up front is useful only when the response needs them. If the page displays a comment count rather than comment text, compute the counts in a grouped query instead of fetching every comment. An index can speed up each lookup but doesn't eliminate the extra database calls.
Diagnose it and discuss it in interviews
Inspect the SQL log or trace for one endpoint request. Look for the same query shape repeated with different IDs, then vary the page size and see whether the query count grows with it. Some ORMs reuse already-loaded objects, so test with distinct related IDs and a fresh session to avoid hiding the pattern.
When an interviewer shows you a loop, identify the exact operation that triggers SQL and count the queries under stated assumptions. Then explain how your fix changes both the number of database calls and the shape of the result. Fewer queries are useful, but one query that transfers many repeated rows is not always the best choice.