Apollo Server setup in GraphQL - Time & Space Complexity
When setting up Apollo Server, it's important to understand how the server handles requests as the number of queries grows.
We want to know how the work the server does changes when more data or queries come in.
Analyze the time complexity of this Apollo Server setup code.
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Query {
books: [Book]
}
type Book {
title: String
author: String
}
`;
const books = [
{ title: 'Book 1', author: 'Author A' },
{ title: 'Book 2', author: 'Author B' }
];
const resolvers = {
Query: {
books: () => books
}
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen();
This code sets up a simple Apollo Server that returns a list of books when queried.
Look for parts that repeat work as input grows.
- Primary operation: Returning the list of books from the resolver.
- How many times: The resolver runs once per query request, and returns all books in the array.
As the number of books increases, the server returns more items each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Returns 10 books |
| 100 | Returns 100 books |
| 1000 | Returns 1000 books |
Pattern observation: The work grows directly with the number of books to return.
Time Complexity: O(n)
This means the time to respond grows linearly with the number of books requested.
[X] Wrong: "Apollo Server setup always runs in constant time regardless of data size."
[OK] Correct: The server work depends on how much data it sends back; more data means more work.
Understanding how server response time grows with data size helps you design efficient APIs and explain your choices clearly.
What if the resolver fetched books from a database with a filter? How would that affect the time complexity?