Guides
DataLoader
One well-known challenge of GraphQL, compared with REST, is the "N+1 problem".
The N+1 problem is a performance issue that arises when a GraphQL server resolves a query that includes a list of items. GraphQL servers are written as decoupled resolver functions, so for each item in the list, the server may make a separate call to the database. The overhead of these calls can make the server slow to respond.
In a traditional REST server, where the query's shape is hard-coded, you can hand-write a query that fetches all the data in a single request. That degree of optimization is not possible in GraphQL (unless you tightly couple your database and your schema), but there is a simple mitigation that solves the N+1 problem in a general way: DataLoader.
DataLoader is a simple pattern for batching and caching data that originated inside Facebook, and was later shared with the community as a pattern with a reference implementation in JavaScript (much like GraphQL itself).
The basic idea: whenever you want to fetch a single record from the database, instead of calling the database directly, add the record's key to a queue. Then wait one turn of the event loop, batch up all the keys in the queue, and fetch all the records at once. You fetch all the records you need in a single query, and avoid the N+1 problem.
type BatchLoader<K, V> = (keys: readonly K[]) => Promise<readonly V[]>;
type Pending<V> = { resolve: (value: V) => void; reject: (error: unknown) => void };
class DataLoader<K, V> {
_batchLoadFn: BatchLoader<K, V>;
_queue: { key: K; pending: Pending<V> }[] = [];
constructor(batchLoadFn: BatchLoader<K, V>) {
this._batchLoadFn = batchLoadFn;
}
load(key: K): Promise<V> {
if (this._queue.length === 0) {
process.nextTick(() => this._dispatchQueue());
}
return new Promise((resolve, reject) => {
this._queue.push({ key, pending: { resolve, reject } });
});
}
_dispatchQueue() {
const queue = this._queue;
this._queue = [];
// Promise.try turns a batch function that throws into a rejection, so every load settles.
Promise.try(() => this._batchLoadFn(queue.map((item) => item.key))).then(
(values) => queue.forEach((item, i) => item.pending.resolve(values[i] as V)),
(error) => queue.forEach((item) => item.pending.reject(error)),
);
}
}For more, see Lee Byron's walkthrough of DataLoader's source: DataLoader v2.