N+1 problem and solutions in GraphQL - Time & Space Complexity
When fetching related data in GraphQL, some queries can cause many repeated database calls.
We want to understand how the number of calls grows as we ask for more items.
Analyze the time complexity of the following GraphQL query pattern.
query {
users {
id
name
posts {
id
title
}
}
}
This query fetches a list of users and for each user, fetches their posts.
Look for repeated database calls caused by nested fetching.
- Primary operation: Fetching posts for each user separately.
- How many times: Once for users, then once per user for posts.
As the number of users grows, the number of post-fetch calls grows too.
| Input Size (users) | Approx. Operations (DB calls) |
|---|---|
| 10 | 1 (users) + 10 (posts) = 11 |
| 100 | 1 + 100 = 101 |
| 1000 | 1 + 1000 = 1001 |
Pattern observation: The number of operations grows linearly with the number of users.
Time Complexity: O(n)
This means the number of database calls increases directly with the number of users requested.
[X] Wrong: "Fetching nested data always costs the same no matter how many users there are."
[OK] Correct: Because fetching posts separately for each user causes many extra calls, so cost grows with user count.
Understanding this problem shows you can spot inefficient data fetching and explain how to improve it.
What if we batch fetch all posts for all users in one call? How would the time complexity change?