Context setup in GraphQL - Time & Space Complexity
When using context setup in GraphQL, we want to know how the time to prepare data changes as the amount of input grows.
We ask: How does the work to set up context scale when many requests or data items are involved?
Analyze the time complexity of the following code snippet.
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
const user = await getUserFromToken(req.headers.authorization);
const permissions = await getPermissions(user.id);
return { user, permissions };
}
});
This code sets up context for each request by fetching user info and permissions before running resolvers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Fetching user and permissions data for each request.
- How many times: Once per incoming request, sequentially.
Each request triggers two data fetches: user info and permissions.
| Input Size (requests) | Approx. Operations |
|---|---|
| 10 | 20 fetches (10 users + 10 permissions) |
| 100 | 200 fetches (100 users + 100 permissions) |
| 1000 | 2000 fetches (1000 users + 1000 permissions) |
Pattern observation: Operations grow directly with the number of requests, doubling the fetches per request.
Time Complexity: O(n)
This means the time to set up context grows linearly with the number of requests.
[X] Wrong: "Context setup happens once and is reused for all requests."
[OK] Correct: Each request needs fresh context data, so setup runs every time, making the cost grow with requests.
Understanding how context setup scales helps you explain backend performance and design efficient APIs.
"What if we cached user permissions in context? How would the time complexity change?"