N+1 Query Problem
A classic database performance anti-pattern where fetching N parent rows triggers 1 initial query followed by N extra round-trip queries to load related children
Table of Contents
Structure Diagram
What is N+1 Query Problem?
A classic database performance anti-pattern where fetching N parent rows triggers 1 initial query followed by N extra round-trip queries to load related children. It is a core concept in Databases & Caching within Web Dev.
Core Principles
The N+1 query problem is the most common performance pitfall when using ORMs or GraphQL resolvers. An application executes 1 query to fetch N parent records (e.g., 50 blog posts), then loops through them accessing a lazy-loaded relation (post.author), firing N additional queries to the database.
It hides easily during local development with tiny datasets, but explodes in production into hundreds of sequential network round-trips that spike latency and starve the connection pool.
Practical Takeaways
- Use Eager Loading (
JOINorINbatching): Fetch relations upfront via Prismainclude, JPAJOIN FETCH, or Djangoselect_related/prefetch_related. For multiple 1-to-many relations, prefer batchedWHERE id IN (...)queries over massive joins to avoid Cartesian row multiplication. - Batch GraphQL resolvers with DataLoader: Coalesce per-item lookups within a single event-loop tick into one batched SQL query.
- Assert query counts in tests: Enable SQL query logging in dev and add query-budget assertions in CI tests so N+1 regressions never ship silently.
Notable Examples
- ORM relation loading: Switching lazy loops to
prefetch_relatedorBatchSizeoften reduces endpoint queries from 100+ down to 2–3. - Social feeds & order history APIs: Cutting P95 latency from >1s to <50ms simply by eliminating hidden N+1 loops.