Migration from REST to GraphQL - Time & Space Complexity
When moving from REST to GraphQL, it's important to understand how the time to get data changes.
We want to know how the number of operations grows as we ask for more or different data.
Analyze the time complexity of this GraphQL query fetching user data and their posts.
query GetUserAndPosts($userId: ID!) {
user(id: $userId) {
id
name
posts {
id
title
}
}
}
This query fetches one user and all their posts with basic details.
Look for repeated work inside the query.
- Primary operation: Fetching each post of the user.
- How many times: Once for each post the user has.
As the number of posts grows, the work grows too.
| Input Size (posts) | Approx. Operations |
|---|---|
| 10 | Fetching 1 user + 10 posts |
| 100 | Fetching 1 user + 100 posts |
| 1000 | Fetching 1 user + 1000 posts |
Pattern observation: The work grows roughly in direct proportion to the number of posts requested.
Time Complexity: O(n)
This means the time to get data grows linearly with the number of posts requested.
[X] Wrong: "GraphQL always reduces the time to get data compared to REST."
[OK] Correct: GraphQL lets you ask for exactly what you want, but if you ask for many items, the time still grows with how much data you request.
Understanding how data fetching time grows helps you explain trade-offs when moving from REST to GraphQL in real projects.
"What if we added pagination to limit posts per request? How would that affect the time complexity?"