0
0
GraphQLquery~5 mins

DataLoader for batching in GraphQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: DataLoader for batching
O(n)
Understanding Time Complexity

When using DataLoader for batching in GraphQL, we want to understand how the number of database calls changes as we request more data.

We ask: How does batching affect the total work done when fetching many items?

Scenario Under Consideration

Analyze the time complexity of this DataLoader batch function.


const userLoader = new DataLoader(async (userIds) => {
  const users = await db.users.findMany({
    where: { id: { in: userIds } }
  });
  const userMap = new Map(users.map(user => [user.id, user]));
  return userIds.map(id => userMap.get(id));
});

// Later in resolvers:
const user1 = await userLoader.load(1);
const user2 = await userLoader.load(2);

This code batches multiple user ID requests into one database query.

Identify Repeating Operations

Look for repeated work inside the batch function.

  • Primary operation: One database query fetching all requested users at once.
  • How many times: Once per batch of user IDs, not once per user ID.
How Execution Grows With Input

As the number of user IDs requested grows, the database query fetches all at once.

Input Size (n)Approx. Operations
101 database query fetching 10 users
1001 database query fetching 100 users
10001 database query fetching 1000 users

Pattern observation: The number of database queries stays the same (one per batch), but the query size grows with n.

Final Time Complexity

Time Complexity: O(n)

This means the work grows linearly with the number of user IDs requested, but the number of database calls stays minimal.

Common Mistake

[X] Wrong: "DataLoader makes each user request a separate database call."

[OK] Correct: DataLoader batches all requests in a short time window into one query, reducing calls significantly.

Interview Connect

Understanding how batching reduces repeated work is a valuable skill that shows you can write efficient data fetching logic in real projects.

Self-Check

What if the batch function made separate database calls for each user ID instead of one query? How would the time complexity change?