How to Batch Requests in GraphQL for Efficient Data Fetching
To batch requests in
GraphQL, you can use query batching by sending multiple queries in a single HTTP request or implement a DataLoader to batch and cache database calls within resolvers. Both methods reduce network overhead and improve performance by grouping multiple operations together.Syntax
Batching in GraphQL can be done by sending an array of query objects in one HTTP request or by using a DataLoader inside resolvers to batch database calls.
For query batching, the request body is an array of GraphQL queries:
query: The GraphQL query string.variables: Optional variables for the query.
For DataLoader, you create a loader that collects keys and batches them into a single database call.
json
[
{ "query": "{ user(id: \"1\") { name } }" },
{ "query": "{ post(id: \"2\") { title } }" }
]Example
This example shows how to batch database requests inside GraphQL resolvers using DataLoader. It batches multiple user ID requests into one database call.
javascript
const DataLoader = require('dataloader'); // Simulated database call that fetches users by IDs async function batchGetUsers(ids) { console.log('Batching DB call for IDs:', ids); // Simulate DB response return ids.map(id => ({ id, name: `User${id}` })); } // Create a DataLoader instance const userLoader = new DataLoader(batchGetUsers); // Resolver function example async function resolveUser(parent, args) { // Load user by ID using DataLoader return await userLoader.load(args.id); } // Simulate multiple resolver calls async function run() { const user1 = resolveUser(null, { id: '1' }); const user2 = resolveUser(null, { id: '2' }); const user3 = resolveUser(null, { id: '1' }); // Cached const results = await Promise.all([user1, user2, user3]); console.log(results); } run();
Output
Batching DB call for IDs: [ '1', '2' ]
[ { id: '1', name: 'User1' }, { id: '2', name: 'User2' }, { id: '1', name: 'User1' } ]
Common Pitfalls
Common mistakes when batching GraphQL requests include:
- Sending multiple queries without enabling query batching on the server, causing errors.
- Not using
DataLoaderor similar batching inside resolvers, leading to N+1 query problems. - Forgetting to cache results in
DataLoader, which reduces batching benefits.
Always ensure your GraphQL server supports query batching if you send multiple queries in one request.
javascript
/* Wrong: Sending multiple queries as separate requests (inefficient) */ fetch('/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: '{ user(id: "1") { name } }' }) }); fetch('/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: '{ post(id: "2") { title } }' }) }); /* Right: Send queries batched in one request if server supports it */ fetch('/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify([ { query: '{ user(id: "1") { name } }' }, { query: '{ post(id: "2") { title } }' } ]) });
Quick Reference
| Method | Description | When to Use |
|---|---|---|
| Query Batching | Send multiple queries in one HTTP request as an array | When server supports batching and you want to reduce network calls |
| DataLoader | Batch and cache database calls inside resolvers | To solve N+1 query problems and optimize DB access |
| Persisted Queries | Pre-define queries to reduce request size | When you want to optimize network usage further |
Key Takeaways
Use query batching to send multiple GraphQL queries in a single HTTP request if your server supports it.
Implement DataLoader inside resolvers to batch and cache database calls, avoiding N+1 query issues.
Always check that your GraphQL server is configured to accept batched queries to prevent errors.
Caching results in DataLoader improves performance by avoiding repeated database calls for the same keys.
Batching reduces network overhead and improves overall GraphQL API efficiency.