Data source integration in GraphQL - Time & Space Complexity
When connecting GraphQL to a data source, it is important to understand how the time to get data grows as the data size increases.
We want to know how the work done changes when the data source has more records.
Analyze the time complexity of the following GraphQL resolver fetching data from a database.
query GetUsers {
users {
id
name
posts {
id
title
}
}
}
This query fetches all users and their posts from the data source.
Look for repeated data fetching or loops in the resolver process.
- Primary operation: Fetching each user and then fetching their posts.
- How many times: Once for all users, plus once per user for posts.
As the number of users grows, the number of operations grows because we fetch posts for each user.
| Input Size (n users) | Approx. Operations |
|---|---|
| 10 | Fetch users once + 10 fetches for posts |
| 100 | Fetch users once + 100 fetches for posts |
| 1000 | Fetch users once + 1000 fetches for posts |
Pattern observation: The work grows roughly in proportion to the number of users.
Time Complexity: O(n)
This means the time to get all users and their posts grows linearly with the number of users.
[X] Wrong: "Fetching all users and their posts happens in constant time regardless of user count."
[OK] Correct: Each user's posts require separate fetching, so more users mean more work.
Understanding how data fetching scales helps you design efficient GraphQL queries and resolvers, a key skill in real projects.
"What if we batch fetch posts for all users in one query? How would the time complexity change?"