Parent (root) argument in GraphQL - Time & Space Complexity
When using GraphQL, the parent (or root) argument helps pass data between resolver functions. Understanding how this affects time complexity helps us see how the work grows as data grows.
We want to know: how does the number of operations change when the parent argument is used in nested queries?
Analyze the time complexity of the following GraphQL resolver snippet using the parent argument.
type Query {
users: [User]
}
type User {
posts: [Post]
}
resolver Query {
users() { return getAllUsers(); }
}
resolver User {
posts(parent) { return getPostsByUser(parent.id); }
}
This code fetches all users, then for each user fetches their posts using the parent user id.
Look for repeated work in the code.
- Primary operation: For each user, fetching posts by user id.
- How many times: Once per user, so as many times as there are users.
As the number of users grows, the number of post-fetch operations grows too.
| Input Size (n users) | Approx. Operations |
|---|---|
| 10 | 10 post fetches |
| 100 | 100 post fetches |
| 1000 | 1000 post fetches |
Pattern observation: The work grows directly with the number of users.
Time Complexity: O(n)
This means the total work grows in a straight line as the number of users increases.
[X] Wrong: "Using the parent argument means all data is fetched at once, so time stays the same."
[OK] Correct: Actually, each user triggers a separate fetch for posts, so the total work adds up with more users.
Understanding how parent arguments affect query performance shows you can reason about nested data fetching. This skill helps you write efficient GraphQL queries and explain your choices clearly.
"What if the posts resolver cached results instead of fetching each time? How would the time complexity change?"