DataLoader batching and caching in GraphQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When using DataLoader in GraphQL, it helps group many requests into fewer ones and remembers past results.
We want to see how the time to get data changes as the number of requests grows.
Analyze the time complexity of the following code snippet.
const loader = new DataLoader(keys => batchLoadFunction(keys));
// Later in resolvers
const results = await Promise.all(
keys.map(key => loader.load(key))
);
This code batches multiple key requests into one batchLoadFunction call and caches results for reuse.
Look for repeated actions that affect performance.
- Primary operation: batchLoadFunction called once per batch with all keys.
- How many times: Once per batch, not once per key.
As more keys come in, DataLoader groups them to reduce calls.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 batch call with 10 keys |
| 100 | 1 batch call with 100 keys |
| 1000 | 1 batch call with 1000 keys |
Pattern observation: The number of batch calls stays the same (one), but each call handles more keys.
Time Complexity: O(n)
This means the time grows linearly with the number of keys because all keys are processed together in one batch.
[X] Wrong: "DataLoader makes each key load instantly, so time does not grow with more keys."
[OK] Correct: Even though DataLoader batches keys, the batchLoadFunction still processes all keys together, so time grows with the number of keys.
Understanding how batching and caching affect time helps you explain efficient data fetching in GraphQL APIs clearly and confidently.
What if the batchLoadFunction itself made multiple database calls instead of one? How would the time complexity change?
Practice
DataLoader in a GraphQL server?Solution
Step 1: Understand DataLoader's role in GraphQL
DataLoader groups many small data requests into fewer big ones to reduce database calls.Step 2: Identify caching behavior
It also caches results during one operation to avoid duplicate requests for the same data.Final Answer:
To batch multiple data requests into a single request and cache results during one operation -> Option AQuick Check:
Batching + caching = To batch multiple data requests into a single request and cache results during one operation [OK]
- Thinking DataLoader replaces the database
- Confusing DataLoader with schema generation tools
- Assuming it handles authentication
Solution
Step 1: Recall DataLoader instantiation syntax
DataLoader is a class and must be instantiated with thenewkeyword.Step 2: Check method usage
The constructor takes a batch loading function as argument, sonew DataLoader(batchLoadFn)is correct.Final Answer:
const loader = new DataLoader(batchLoadFn); -> Option BQuick Check:
Usenewwith DataLoader class [OK]
- Omitting 'new' keyword
- Using incorrect method calls like .new or .load
- Calling DataLoader as a function without 'new'
const DataLoader = require('dataloader');
const batchLoadFn = async keys => keys.map(key => key * 2);
const loader = new DataLoader(batchLoadFn);
(async () => {
const result1 = await loader.load(2);
const result2 = await loader.load(3);
console.log([result1, result2]);
})();Solution
Step 1: Understand batchLoadFn behavior
The batch function doubles each key: for key 2 returns 4, for key 3 returns 6.Step 2: Analyze loader.load calls
Callingloader.load(2)andloader.load(3)triggers batchLoadFn with keys [2,3], returning [4,6].Final Answer:
[4, 6] -> Option AQuick Check:
Keys doubled = [4, 6] [OK]
- Expecting original keys as output
- Confusing async behavior with undefined
- Ignoring batch function logic
const DataLoader = require('dataloader');
const batchLoadFn = async keys => {
return keys.map(key => fetchUserFromDB(key));
};
const loader = new DataLoader(batchLoadFn);
loader.load(1).then(user => console.log(user));
Assuming fetchUserFromDB returns a Promise resolving to user data.Solution
Step 1: Check batchLoadFn return type
batchLoadFn returns an array of Promises because fetchUserFromDB returns a Promise for each key.Step 2: Understand DataLoader batch function requirement
DataLoader expects batchLoadFn to return a single Promise resolving to an array of results, not an array of Promises.Final Answer:
batchLoadFn should return a Promise resolving to an array, but it returns an array of Promises -> Option DQuick Check:
Return a Promise of array, not array of Promises [OK]
- Returning array of Promises instead of Promise of array
- Misusing 'new' keyword with DataLoader
- Passing single key instead of array to batch function
Solution
Step 1: Understand DataLoader lifecycle
DataLoader instances should be created per request to cache data only during that request and avoid stale data.Step 2: Use DataLoader to batch and cache IDs
Usingloadfor each user or post ID lets DataLoader batch requests and cache results within the request.Final Answer:
Create one DataLoader instance per request for users and posts, and useloadfor each user or post ID -> Option CQuick Check:
Per-request DataLoader + load calls = Create one DataLoader instance per request for users and posts, and useloadfor each user or post ID [OK]
- Sharing DataLoader globally causing stale cache
- Creating new DataLoader per field causing no batching
- Skipping DataLoader and querying DB repeatedly
