Field-level cost analysis in GraphQL - Time & Space Complexity
When we ask about field-level cost analysis in GraphQL, we want to know how the time to get data grows as we ask for more fields.
We are trying to see which parts of the query take more time as the request gets bigger.
Analyze the time complexity of the following GraphQL query.
query GetUserData {
user(id: "123") {
id
name
posts {
title
comments {
text
}
}
}
}
This query fetches a user with their posts and comments on each post.
Look for parts that repeat work as data grows.
- Primary operation: Fetching posts and then fetching comments for each post.
- How many times: For each post, we fetch all its comments, so comments fetching repeats for every post.
As the number of posts and comments grows, the work increases.
| Input Size (posts) | Approx. Operations (comments per post = 5) |
|---|---|
| 10 | 10 posts + 10 * 5 comments = 60 |
| 100 | 100 posts + 100 * 5 comments = 600 |
| 1000 | 1000 posts + 1000 * 5 comments = 6000 |
Pattern observation: The total work grows roughly in a straight line with the number of posts and comments combined.
Time Complexity: O(p + p * c)
This means the time grows with the number of posts plus the number of comments for all posts.
[X] Wrong: "Fetching nested fields like comments doesn't add much time because it's just one query."
[OK] Correct: Each nested field can cause extra work for every item above it, so more nested fields multiply the work.
Understanding how nested fields affect query time helps you design efficient APIs and answer questions about scaling data fetching.
"What if we added another nested field under comments, like likes? How would the time complexity change?"