Skip to content

Why does a single page fire 101 database queries?

IntermediateAsked very oftenConcept roundDebuggingDatabases
Asked atShopifyStripeAtlassian
#orm#n+1#sql#dataloader#performance

Company tags are compiled from public interview reports and are signals, not guarantees.

What interviewers are testing

N+1 is the most common production performance bug in web backends, and interviewers treat it as a fluency test: do you read what the ORM actually sends instead of trusting its API? Strong answers point at the query log as the source of truth, distinguish a join from a batched IN query, and know why GraphQL makes the pattern worse — one resolver runs per field, per object.

Mental model

The ORM is waitstaff that fetches one dish per trip: ask for 100 posts and you get the list, but each post.author is a separate walk to the kitchen. Eager loading orders everything in a single join; batching queues all the orders together and sends one combined request. The bill is measured in round trips, not rows.

Step-by-step solution

  1. Step 1: The loop that hides a hundred round trips

    Nothing in this handler looks wrong. It fetches a list, loops over it, and attaches an author to each row — idiomatic code in almost every ORM. The problem is invisible at the call site and obvious in the query log: line 1 fires one SELECT for the list, and the loop body fires one more SELECT per row. With 100 posts that is 101 queries, and with 10,000 posts it is 10,001. The page still renders correctly, which is exactly why the bug survives code review and ships to production. If there were a query-count assertion on this endpoint's tests, the number would read as "grows with row count" — the signature interviewers want you to recognize on sight.

  2. Step 2: Why lazy loading keeps it silent

    The ORM did not lie to you: it returned proxies, not data. When the first query loads 100 posts, relation fields like post.author are placeholders that promise to fetch later — the moment any code reads one, the ORM issues a query behind the scenes. That laziness is a feature at small scale, which is why it is the default; it becomes a trap when the access happens inside a loop, a serializer, or a template. Notice where the loop actually runs: sometimes it is a visible for-loop, but just as often it is toJSON(), a presenter layer, or GraphQL resolving each author field separately. Watch the animation — the trigger is not your query call, it is the innocent property access, which is why grepping for find() calls never finds this bug.

  3. Step 3: The waterfall: why N round trips compound

    A single query against a local database feels free — fractions of a millisecond — so the loop looks harmless in development. Production changes the arithmetic: every query crosses a network, checks out a connection, parses and plans, and the awaits are strictly serialized, so each round trip waits for the one before it. At only 1 ms per trip, 100 rows add 100 ms of pure waiting before rendering starts; under load, connection polling and lock waits make it far worse, and p99 latency sails past the timeouts. The animation shows the shape that should be burned into memory: a staircase of round trips instead of one step. N+1 is not a SQL problem — the queries are individually fast — it is a round-trip multiplication problem, which is why batching survives even when a join is inconvenient.

  4. Step 4: Fix one: eager loading with a join

    The smallest change with the biggest payoff: tell the ORM upfront that you will need the authors, so it plans a single query instead of a discovery sequence. In most ORMs that is an include, with, or populate option that compiles to a JOIN, and the query count drops from 101 to 1 regardless of row count. The trade-off to name out loud: a join to a belongs-to relation is safe, but joining a has-many relation multiplies parent rows — 100 posts with 10 comments each return 1000 rows with the post payload duplicated, which is often worse than a second query. Compare the panels: the left column is the same code with one line removed, the right column is the same intent expressed as one statement. Interviewers are listening for whether you know the join's row-multiplication caveat, not just the incantation.

  5. Step 5: Fix two: batch the lookups (DataLoader)

    Joins do not cover every case — GraphQL resolvers run per field per object by design, and has-many relations multiply rows under a join — so the second cure is batching. The hairdresser trick: instead of each resolver querying immediately, it hands its key to a loader that waits until the next tick, collects every key requested so far, and fires one WHERE id IN (…) query for the whole set, then distributes rows back to the callers that asked. DataLoader is the canonical implementation, and its per-request cache means a repeated key costs nothing extra. Watch the animation: 100 individual asks become one batched question at the database. Two limits to respect — chunk huge ID lists to stay under parameter limits, and scope the cache per request so stale rows never leak between users.

Edge cases & traps

  • Joins multiply rows for has-many relations: 100 posts × 10 comments returns 1000 rows with duplicated post payloads — a separate batched IN query usually costs less than the fan-out.
  • The guilty loop often hides in the serialization layer: toJSON(), presenters, or template rendering can touch relations per row, so grep for property access, not just for query calls.
  • Batching has a ceiling: WHERE id IN (…) with tens of thousands of keys hits bind-parameter and packet limits — chunk the ids (a few hundred to a thousand per batch) and paginate the parent list itself.
  • Development data hides it completely: ten rows in a local database never show the problem, so assert query counts in tests and watch per-request query metrics in production.
  • The DataLoader cache must be scoped to the request: a module-level cache leaks rows across users and upgrades a performance bug into a correctness and privacy bug.

Follow-up questions

Go deeper: Explore the SQL Cosmos visualizer