DataN+1 queriesn+1 problemn plus one

N+1 query problem

Definition

The N+1 query problem is fetching N parent rows with one query and their related data with N separate queries, instead of one join or one batched query.

In practice

Each query is cheap, but every one costs a network round trip and holds a pooled connection for the whole sequence. ORMs produce the pattern by lazily loading associations inside a loop. The fix is a join, a batched WHERE id = ANY(...) query, or the ORM's eager loading, which turns N+1 round trips into one or two.

It hides in development, where lists are short and the database is local, and appears in production with long lists and real network latency. Traces make it obvious as a ladder of identical spans. Not to be confused with N+1 redundancy, which is about spare capacity.

Example

A page lists 100 orders and loads each customer separately: 101 queries at 1 ms round trip each hold a connection for over 100 ms; one join returns the same data in about 3 ms.