Batching and testing
Local baseline: Node.js 22.16.0, ECMAScript modules, synthetic data. Run each complete example independently as node main.mjs in a disposable directory. Static ByteMind blocks do not imply live Node execution. SQLite is experimental in this baseline. Third-party integrations below are staged candidates, not installed or validated dependencies.
Compare individual and batched lookups
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);Expected output:
["Owen","Mira","Owen",null] 4["Owen","Mira","Owen",null] 1This explicit model reduces four logical data calls to one while preserving order.
How it works
A DataLoader batch function receives keys and must produce an array aligned with those keys, including missing values or errors. Create loaders per request or another correctly isolated lifetime; shared memoization can mix users or stale authorization decisions. Dispatch timing determines which calls can share a batch: sequential awaits may prevent coalescing. A batch size bound protects the data source. Pagination is separate: use deterministic ordering and capped page sizes; a cursor represents a position, not authorization. Tests should verify values, key order, missing entries, repeated keys and backend call count.
Keep memoization within each request
function loader(rows){ const cache=new Map(); return id=>{if(!cache.has(id)) cache.set(id,rows.get(id)??null); return cache.get(id);};}const a=loader(new Map([['1','Tenant A']]));const b=loader(new Map([['1','Tenant B']]));console.log(a('1'),b('1'),a('missing'));Expected output:
Tenant A Tenant B nullTwo independent caches can safely hold different synthetic values for the same key. Real access control is still needed.
DataLoader batch alignment
NOT RUN — dataloader (2.x candidate; not installed). This integration requires reviewed pinned dependencies and a disposable fixture. Do not execute against shared services.
import DataLoader from 'dataloader';const authors=new Map([['a1','Mira'],['a2','Owen']]);let calls=0;const loader=new DataLoader(async keys=>{calls++;return keys.map(k=>authors.get(k)??null);},{maxBatchSize:20});console.log(JSON.stringify(await Promise.all(['a2','a1','a2','missing'].map(k=>loader.load(k)))),calls);Intended result (not observed): ["Owen","Mira","Owen",null] 1
Common mistakes
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.
Practice and next steps
Given book IDs b2, b1, b2 and missing, reconstruct ordered results including null, then count how many unique keys reach the backend. Add a test proving a different request cannot reuse the first request cache.
Further reading: https://github.com/graphql/dataloader. Related staged reference: node-batching-and-testing-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Batching and testing — knowledge check
Apply the lesson to a fresh scenario and identify the failure boundary.
Batch keys are [b,a,b]. How should results be ordered?
Why create a loader per request?
Which metric establishes the N+1 improvement in this fixture?