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
- batching — Doing many similar pieces of work together in one operation, such as loading all needed owners with one query instead of one query each.
- embedding — Including a small copy of a related resource inside a representation, instead of only linking to it.
- bottleneck — The single most constrained part of a system or process, which limits how fast the whole thing can go.
- GraphQL resolver — The function a GraphQL server runs to produce the value of one field in a query.
- ORM — A library that lets code read and write database rows as ordinary objects, generating the SQL for you.
- join — Combining rows from two tables into one result by pairing rows according to a rule, usually matching keys.
- round trip — One journey of a request to a server and its response back, whose time adds directly to how long the caller waits.
- lazy loading — Loading related data from the database only when code first accesses it, instead of together with the object that refers to it.
- set-based query — A single query that works on a whole set of rows at once, instead of code that loops and queries row by row.
- latency — The time between asking for something and getting the answer back.
Taught in
- Partial Responses — Modern API Architecture: REST, GraphQL & gRPC
- Performance Optimization — Modern API Architecture: REST, GraphQL & gRPC
- When Each Wins: REST, GraphQL, gRPC And SOAP — Modern API Architecture: REST, GraphQL & gRPC
- Database Access & Migrations: ORM & Data Layers — Production Full-Stack Engineering
- Spring Data Repositories — Modern Java: Virtual Threads & High-Throughput Services
- The N Plus One Problem — PostgreSQL, Indexing & Relational Data Modeling