GraphQL

Request-scoped batching

The N+1 problem occurs when a list lookup is followed by a separate related-record lookup for each item. Batching combines keys into fewer backend calls; request-local memoization avoids fetching the same key repeatedly within one request. Measure the actual number of backend calls rather than assuming a speedup. Do not return database rows in arbitrary order as the batch result. Do not share a user-sensitive loader globally. A local call-count reduction is not measured latency or evidence of DataLoader execution. Source: https://github.com/graphql/dataloader Local examples do not establish third-party integration support.

Formal Syntax & Structure

nodejs syntaxnodejs
new DataLoader(batchLoadFn); loader.load(key)

Working Example

Example Snippetnodejs
const authors=new Map([['a1','Mira'],['a2','Owen']]);const keys=['a2','a1','a2','missing'];let calls=0;function one(id){calls++;return authors.get(id)??null;}console.log(JSON.stringify(keys.map(one)),calls);calls=0;function batch(ids){calls++;return new Map(ids.map(id=>[id,authors.get(id)??null]));}const rows=batch([...new Set(keys)]);console.log(JSON.stringify(keys.map(id=>rows.get(id))),calls);
Node.js Reference