N+1 query problem

A performance bug where code runs one query for a list and then one more query per item, so N items cost N+1 queries.

In more detail

Each query may be fast, but the round trips add up, so latency grows with the size of the list. For example, a page of ten tasks that each look up their owner becomes eleven database calls. Fix it by fetching the related rows in one query, with a join or by batching the lookups together.

Example

In the APIs course: The response body looks correct, so the course service reports a query count header and the contract suite fails the 06-n-plus-one fault.

Related terms

Taught in

References