Schema-first development in GraphQL - Time & Space Complexity
When building GraphQL APIs using schema-first development, it's important to understand how the time to process queries grows as the data size increases.
We want to know how the execution time changes when the input data or query size grows.
Analyze the time complexity of the following GraphQL schema and resolver setup.
type Query {
books: [Book]
}
type Book {
id: ID
title: String
author: Author
}
type Author {
id: ID
name: String
}
# Resolver for books returns a list of all books
# Resolver for author fetches author details for each book
This schema defines a query to get all books, each with its author details.
Look at what repeats when the query runs.
- Primary operation: Fetching all books (once) and then fetching each book's author separately.
- How many times: Books resolver runs once; author resolver runs once per book.
As the number of books grows, the total operations increase because each book triggers an author fetch.
| Input Size (n books) | Approx. Operations |
|---|---|
| 10 | 1 books fetch + 10 author fetches = 11 |
| 100 | 1 books fetch + 100 author fetches = 101 |
| 1000 | 1 books fetch + 1000 author fetches = 1001 |
Pattern observation: The operations grow linearly with the number of books.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of books requested.
[X] Wrong: "Fetching authors for all books happens instantly or in constant time regardless of book count."
[OK] Correct: Each book requires a separate author fetch, so the total time grows with the number of books.
Understanding how schema design affects query time helps you build efficient APIs and explain your choices clearly in interviews.
What if the author data was included inside each book record to avoid separate fetches? How would the time complexity change?