Skip to main content
Web DevDatabases & CachingDiagramBeginner

N+1 Query Problem

KO: N+1 쿼리 문제·EN: N+1 Query Problem·JA: N+1クエリ問題

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

DB Queries Executed vs Item Count: N+1 vs Batched/JOIN
Pool Exhaustion & LatencyConstant 1–2 Round-TripsParent Records Fetched (N) →Total
(50, 52)N+1 Queries (1 + N) #3
Quick Answer

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 (JOIN or IN batching): Fetch relations upfront via Prisma include, JPA JOIN FETCH, or Django select_related/prefetch_related. For multiple 1-to-many relations, prefer batched WHERE 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_related or BatchSize often 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.