DataLoader batching: handle batch contracts, cache, and errors safely
DataLoader is a JavaScript library that combines multiple .load(key) calls into one batch function and, by default, memoizes repeated keys within a request. Use it safely by returning one result per input key in the same order and by creating loaders per request. Cache-off mode, custom dispatch timing, and per-key errors change the defaults; adjust them deliberately.
DataLoader is a JavaScript library that combines multiple .load(key) calls into one batch function and, by default, memoizes repeated keys within a request. Use it safely by returning one result per input key in the same order and by creating loaders per request. Cache-off mode, custom dispatch timing, and per-key errors change the defaults; adjust them deliberately.
Preserve the batch-function contract
const userLoader = new DataLoader(async (ids) => {
const rows = await getUsersByIds(ids);
const byId = new Map(rows.map((user) => [user.id, user]));
return ids.map((id) => byId.get(id) ?? null);
});The returned array must have the same length and positional order as the input keys. A backend may reorder rows or omit missing records, so map by key and restore the input order. Represent missing values as null or Error according to policy. If a backend returns a map/object, adapt it to the required array. Keep each loader focused on one access pattern, such as lookup by ID versus username.
Default batching and custom scheduling
By default, DataLoader coalesces loads in one execution frame before calling the batch function. Usually there is no need for a custom scheduler. batchScheduleFn can defer or manually dispatch a batch, but waiting longer increases request latency; a 100 ms collection window adds that delay. Measure first and customize only when there is a concrete need.
maxBatchSize limits keys per batch, which can accommodate database parameter or downstream API limits. Too small a value creates more batches. Batch size is separate from memoization: disabling cache can allow duplicate keys into a batch.
Cache scope and mutations
The default memoization cache is request-local, not a shared cache like Redis. Create loaders per request when users have different data permissions, then discard them. After a mutation changes a cached value, clear the key or clear and prime it with the updated value so later loads do not return stale data.
With cache: false, repeated .load() calls can produce duplicate keys in the batch input. The batch function still needs one result for each position. Prefer targeted clear/clearAll when possible instead of disabling memoization wholesale.
Handle errors deliberately
If the batch function throws or rejects, the batch values are not cached. If it returns an Error for one key, that individual error may be cached. Clear that key before retrying when the failure is transient and policy allows it.
loadMany(keys) resolves an array that can contain Error values, unlike Promise.all(loader.load(...)), which rejects when one load rejects. Inspect each result and decide consistently which cases become GraphQL errors versus null.
Verification checklist
Is each loader created per request and isolated by authorization?
Does the batch return exactly one positionally aligned result per key?
With cache disabled, are duplicate keys handled at every position?
Does the caller inspect individual `Error` results from `loadMany`?
Are cached values cleared or refreshed after mutations?
Have scheduling and batch-size changes been measured for latency and call count?
The JavaScript examples are explanatory and were not run or benchmarked. Do not assume other-language loaders have identical behavior.
Sources
[DataLoader README: batching, cache, scheduling, and errors](https://github.com/graphql/dataloader)
[GraphQL.js: DataLoader batch contract](https://github.com/graphql/graphql-js/blob/17.x.x/website/pages/docs/n1-dataloader.mdx)
[Official GraphQL performance guide](https://graphql.org/learn/performance/)
[Apollo GraphQL overview: performance and DataLoader](https://www.apollographql.com/docs/graphos/resources/concepts/graphql)
[Apollo Server resolver docs](https://www.apollographql.com/docs/apollo-server/data/resolvers)