Batched Queries with query.batch()
Using query.batch()
to solve the n+1 problem by
batching multiple simultaneous queries into single server calls.
Users
User alice
getUserById('alice')
Email: alice@example.com
Role: User
User bob
getUserById('bob')
Email: bob@example.com
Role: User
User charlie
getUserById('charlie')
Email: charlie@example.com
Role: User
Posts by User
alice's Posts
getPostsByUserId('alice')
- First Post by alice
- Second Post by alice
- Third Post by alice
bob's Posts
getPostsByUserId('bob')
- First Post by bob
- Second Post by bob
- Third Post by bob
charlie's Posts
getPostsByUserId('charlie')
- First Post by charlie
- Second Post by charlie
- Third Post by charlie
How query.batch() works:
- 6 queries are called (3 users + 3 posts), but only 2 server functions are executed
- All
getUserById()
calls are batched together - All
getPostsByUserId()
calls are batched together - Each batch function receives an array of all arguments (e.g., ['alice', 'bob', 'charlie'])
- The batch function fetches all data in one go, then returns a resolver function for individual queries
- Check your server console logs to see batching in action!