Course contentsShow
← System Design
Lesson 1913 of 1,91945. API Design and VersioningFree lesson

The N+1 Query Problem in GraphQL

How nested GraphQL queries can trigger exponential database calls and why this is a critical scaling concern.

The N+1 Query Problem in GraphQL

What you'll learn: How nested GraphQL queries can trigger exponential database calls and turn an elegant API into a performance nightmare.

What Is the N+1 Problem?

The N+1 query problem occurs when fetching a collection of N items, then making an additional database query for each item to fetch related data. You end up with 1 query to fetch the list + N queries for related resources = N+1 total queries.

In GraphQL, this happens naturally because of how resolvers work. Each resolver independently fetches its data without knowing what other resolvers are doing. When you query a list of objects with nested fields, the parent resolver fetches the list (1 query), then each child resolver fires separately for every item in that list (N queries).

A Concrete Example

Imagine querying for 100 users and their posts:

query {
  users {
    name
    posts {
      title
    }
  }
}

Without optimization, this triggers:

  • 1 query to fetch 100 users
  • 100 queries to fetch posts for each user (one per user)

That's 101 database round-trips for what could be 2 queries (users, then all posts in one batch).

Why This Is Critical at Scale

At small scales, 101 queries might take 200ms. At large scales with thousands of users or deeply nested queries (users → posts → comments → authors), you face:

  • Database connection pool exhaustion
  • Linear-to-exponential latency growth
  • Server timeouts and cascading failures

Key Takeaway: GraphQL's resolver independence creates an N+1 trap by default—each nested field can multiply database calls, making query depth a critical scaling bottleneck that requires batching strategies to solve.