Challenge 2: Count the Queries, Before and After — Possible Solution ==================================================================== SCENARIO: A query returns 25 posts, sharing only 4 distinct authors among them. NAIVE RESOLVER (NO BATCHING) ------------------------------- Query.posts's resolver runs once: 1 query, returning all 25 posts. Post.author's resolver then runs once PER POST — 25 times — regardless of the fact that many of those 25 calls are looking up the SAME 4 underlying author IDs over and over. Total: 1 + 25 = 26 queries DATALOADER-BATCHED RESOLVER ------------------------------ Query.posts's resolver still runs once: 1 query, returning all 25 posts. Post.author's resolver still runs 25 times (once per post) — BUT each call goes through context.userLoader.load(authorId) instead of hitting the database directly. DataLoader collects all 25 .load() calls made during that single tick, DEDUPLICATES them down to the underlying distinct keys, and issues exactly ONE batched db.users.findByIds(ids) call — needing to fetch only the 4 actual distinct author IDs, since that's all that were ever requested, however many times each was asked for. Total: 1 + 1 = 2 queries WHY THIS WORKS AS AN ANSWER ------------------------------ - The naive version's query count scales directly with the NUMBER OF POSTS (25), regardless of how many distinct authors those posts actually share — every single Post.author call triggers its own database round trip, even when it's asking for information that was already fetched moments earlier for a different post by the same author. - The DataLoader version's query count is completely independent of how many posts there are — it depends only on the number of DISTINCT author IDs actually referenced (4 in this case), because DataLoader's caching (not just batching) means the SAME id requested multiple times within one request only ever appears once in the batch function's input array. - This demonstrates precisely why the chapter distinguishes "batching" from "caching" as two separate mechanisms working together: batching alone would still merge 25 individual load() calls into one query, but it's the CACHING/deduplication behavior specifically that shrinks the batch function's actual input down to just 4 unique IDs rather than 25 (possibly repeated) ones.