A. Add a delay before each comment fetch to reduce load.
B. Fetch comments inside the client instead of server.
C. Remove the comments field from the schema.
D. Replace with a batch loader that fetches comments for many post IDs at once.
Solution
Step 1: Identify the N+1 cause
Calling getCommentsByPostId for each post causes many queries.
Step 2: Apply batching fix
Using a batch loader to fetch comments for all post IDs in one query solves N+1.
Final Answer:
Replace with a batch loader that fetches comments for many post IDs at once. -> Option D
Quick Check:
Batch loading fixes N+1 [OK]
Hint: Batch fetch related data to fix N+1 [OK]
Common Mistakes:
Adding delays does not fix query count
Removing fields breaks schema
Fetching on client doesn't reduce server queries
5. You have a GraphQL query fetching users and their posts:
{
users {
id
posts {
id
title
}
}
}
Your current resolver fetches posts inside each user resolver causing N+1 queries. How can you optimize this with DataLoader and SQL to reduce queries?
hard
A. Create a batch loader that fetches posts for all user IDs in one SQL query using WHERE user_id IN (...).
B. Fetch posts one by one inside each user resolver without batching.
C. Remove posts from the query to avoid N+1.
D. Use a separate query for each post title.
Solution
Step 1: Identify the N+1 cause in nested posts
Fetching posts inside each user resolver causes many queries, one per user.
Step 2: Use DataLoader with SQL batching
Create a batch loader that runs one SQL query with WHERE user_id IN (list of user IDs) to get all posts at once.
Final Answer:
Create a batch loader that fetches posts for all user IDs in one SQL query using WHERE user_id IN (...). -> Option A
Quick Check:
Batch SQL query with DataLoader fixes N+1 [OK]
Hint: Batch SQL with WHERE IN for all IDs [OK]
Common Mistakes:
Fetching posts one by one
Removing needed fields
Querying posts separately per post
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.