Gathering detailed insights and metrics for dataloader
Gathering detailed insights and metrics for dataloader
Gathering detailed insights and metrics for dataloader
Gathering detailed insights and metrics for dataloader
@opentelemetry/instrumentation-dataloader
OpenTelemetry instrumentation for `dataloader` data fetching layer
redis-dataloader
DataLoader Using Redis as a Cache
@pothos/plugin-dataloader
A Pothos plugin for attaching dataloader to object types
dataloader-sequelize
Batching and simplification of Sequelize with facebook/dataloader
DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a consistent API over various backends and reduce requests to those backends via batching and caching.
npm install dataloader
99.6
Supply Chain
100
Quality
78.1
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
12,905 Stars
218 Commits
515 Forks
143 Watching
5 Branches
82 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (98.96%)
Shell (1.04%)
Cumulative downloads
Total Downloads
Last day
-0.7%
1,035,266
Compared to previous day
Last week
6.1%
5,418,019
Compared to previous week
Last month
10.6%
22,114,721
Compared to previous month
Last year
15.9%
232,444,763
Compared to previous year
DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.
A port of the "Loader" API originally developed by @schrockn at Facebook in 2010 as a simplifying force to coalesce the sundry key-value store back-end APIs which existed at the time. At Facebook, "Loader" became one of the implementation details of the "Ent" framework, a privacy-aware data entity loading and caching layer within web server product code. This ultimately became the underpinning for Facebook's GraphQL server implementation and type definitions.
DataLoader is a simplified version of this original idea implemented in JavaScript for Node.js services. DataLoader is often used when implementing a graphql-js service, though it is also broadly useful in other situations.
This mechanism of batching and caching data requests is certainly not unique to Node.js or JavaScript, it is also the primary motivation for Haxl, Facebook's data loading library for Haskell. More about how Haxl works can be read in this blog post.
DataLoader is provided so that it may be useful not just to build GraphQL services for Node.js but also as a publicly available reference implementation of this concept in the hopes that it can be ported to other languages. If you port DataLoader to another language, please open an issue to include a link from this repository.
First, install DataLoader using npm.
1npm install --save dataloader
To get started, create a DataLoader
. Each DataLoader
instance represents a
unique cache. Typically instances are created per request when used within a
web-server like express if different users can see different things.
Note: DataLoader assumes a JavaScript environment with global ES6
Promise
andMap
classes, available in all supported versions of Node.js.
Batching is not an advanced feature, it's DataLoader's primary feature. Create loaders by providing a batch loading function.
1const DataLoader = require('dataloader'); 2 3const userLoader = new DataLoader(keys => myBatchGetUsers(keys));
A batch loading function accepts an Array of keys, and returns a Promise which resolves to an Array of values*.
Then load individual values from the loader. DataLoader will coalesce all individual loads which occur within a single frame of execution (a single tick of the event loop) and then call your batch function with all requested keys.
1const user = await userLoader.load(1); 2const invitedBy = await userLoader.load(user.invitedByID); 3console.log(`User 1 was invited by ${invitedBy}`); 4 5// Elsewhere in your application 6const user = await userLoader.load(2); 7const lastInvited = await userLoader.load(user.lastInvitedID); 8console.log(`User 2 last invited ${lastInvited}`);
A naive application may have issued four round-trips to a backend for the required information, but with DataLoader this application will make at most two.
DataLoader allows you to decouple unrelated parts of your application without sacrificing the performance of batch data-loading. While the loader presents an API that loads individual values, all concurrent requests will be coalesced and presented to your batch loading function. This allows your application to safely distribute data fetching requirements throughout your application and maintain minimal outgoing data requests.
A batch loading function accepts an Array of keys, and returns a Promise which
resolves to an Array of values or Error instances. The loader itself is provided
as the this
context.
1async function batchFunction(keys) { 2 const results = await db.fetchAllKeys(keys); 3 return keys.map(key => results[key] || new Error(`No result for ${key}`)); 4} 5 6const loader = new DataLoader(batchFunction);
There are a few constraints this function must uphold:
For example, if your batch function was provided the Array of keys: [ 2, 9, 6, 1 ]
,
and loading from a back-end service returned the values:
1{ id: 9, name: 'Chicago' } 2{ id: 1, name: 'New York' } 3{ id: 2, name: 'San Francisco' }
Our back-end service returned results in a different order than we requested, likely
because it was more efficient for it to do so. Also, it omitted a result for key 6
,
which we can interpret as no value existing for that key.
To uphold the constraints of the batch function, it must return an Array of values
the same length as the Array of keys, and re-order them to ensure each index aligns
with the original keys [ 2, 9, 6, 1 ]
:
1[ 2 { id: 2, name: 'San Francisco' }, 3 { id: 9, name: 'Chicago' }, 4 null, // or perhaps `new Error()` 5 { id: 1, name: 'New York' }, 6];
By default DataLoader will coalesce all individual loads which occur within a
single frame of execution before calling your batch function with all requested
keys. This ensures no additional latency while capturing many related requests
into a single batch. In fact, this is the same behavior used in Facebook's
original PHP implementation in 2010. See enqueuePostPromiseJob
in the
source code for more details about how this works.
However sometimes this behavior is not desirable or optimal. Perhaps you expect
requests to be spread out over a few subsequent ticks because of an existing use
of setTimeout
, or you just want manual control over dispatching regardless of
the run loop. DataLoader allows providing a custom batch scheduler to provide
these or any other behaviors.
A custom scheduler is provided as batchScheduleFn
in options. It must be a
function which is passed a callback and is expected to call that callback in the
immediate future to execute the batch request.
As an example, here is a batch scheduler which collects all requests over a 100ms window of time (and as a consequence, adds 100ms of latency):
1const myLoader = new DataLoader(myBatchFn, {
2 batchScheduleFn: callback => setTimeout(callback, 100),
3});
As another example, here is a manually dispatched batch scheduler:
1function createScheduler() { 2 let callbacks = []; 3 return { 4 schedule(callback) { 5 callbacks.push(callback); 6 }, 7 dispatch() { 8 callbacks.forEach(callback => callback()); 9 callbacks = []; 10 }, 11 }; 12} 13 14const { schedule, dispatch } = createScheduler(); 15const myLoader = new DataLoader(myBatchFn, { batchScheduleFn: schedule }); 16 17myLoader.load(1); 18myLoader.load(2); 19dispatch();
DataLoader provides a memoization cache for all loads which occur in a single
request to your application. After .load()
is called once with a given key,
the resulting value is cached to eliminate redundant loads.
DataLoader caching does not replace Redis, Memcache, or any other shared
application-level cache. DataLoader is first and foremost a data loading mechanism,
and its cache only serves the purpose of not repeatedly loading the same data in
the context of a single request to your Application. To do this, it maintains a
simple in-memory memoization cache (more accurately: .load()
is a memoized function).
Avoid multiple requests from different users using the DataLoader instance, which could result in cached data incorrectly appearing in each request. Typically, DataLoader instances are created when a Request begins, and are not used once the Request ends.
For example, when using with express:
1function createLoaders(authToken) {
2 return {
3 users: new DataLoader(ids => genUsers(authToken, ids)),
4 };
5}
6
7const app = express();
8
9app.get('/', function (req, res) {
10 const authToken = authenticateUser(req);
11 const loaders = createLoaders(authToken);
12 res.send(renderPage(req, loaders));
13});
14
15app.listen();
Subsequent calls to .load()
with the same key will result in that key not
appearing in the keys provided to your batch function. However, the resulting
Promise will still wait on the current batch to complete. This way both cached
and uncached requests will resolve at the same time, allowing DataLoader
optimizations for subsequent dependent loads.
In the example below, User 1
happens to be cached. However, because User 1
and 2
are loaded in the same tick, they will resolve at the same time. This
means both user.bestFriendID
loads will also happen in the same tick which
results in two total requests (the same as if User 1
had not been cached).
1userLoader.prime(1, { bestFriend: 3 }); 2 3async function getBestFriend(userID) { 4 const user = await userLoader.load(userID); 5 return await userLoader.load(user.bestFriendID); 6} 7 8// In one part of your application 9getBestFriend(1); 10 11// Elsewhere 12getBestFriend(2);
Without this optimization, if the cached User 1
resolved immediately, this
could result in three total requests since each user.bestFriendID
load would
happen at different times.
In certain uncommon cases, clearing the request cache may be necessary.
The most common example when clearing the loader's cache is necessary is after a mutation or update within the same request, when a cached value could be out of date and future loads should not use any possibly cached value.
Here's a simple example using SQL UPDATE to illustrate.
1// Request begins... 2const userLoader = new DataLoader(...); 3 4// And a value happens to be loaded (and cached). 5const user = await userLoader.load(4); 6 7// A mutation occurs, invalidating what might be in cache. 8await sqlRun('UPDATE users WHERE id=4 SET username="zuck"'); 9userLoader.clear(4); 10 11// Later the value load is loaded again so the mutated data appears. 12const user = await userLoader.load(4); 13 14// Request completes.
If a batch load fails (that is, a batch function throws or returns a rejected
Promise), then the requested values will not be cached. However if a batch
function returns an Error
instance for an individual value, that Error
will
be cached to avoid frequently loading the same Error
.
In some circumstances you may wish to clear the cache for these individual Errors:
1try { 2 const user = await userLoader.load(1); 3} catch (error) { 4 if (/* determine if the error should not be cached */) { 5 userLoader.clear(1); 6 } 7 throw error 8}
In certain uncommon cases, a DataLoader which does not cache may be desirable.
Calling new DataLoader(myBatchFn, { cache: false })
will ensure that every
call to .load()
will produce a new Promise, and requested keys will not be
saved in memory.
However, when the memoization cache is disabled, your batch function will
receive an array of keys which may contain duplicates! Each key will be
associated with each call to .load()
. Your batch loader should provide a value
for each instance of the requested key.
For example:
1const myLoader = new DataLoader( 2 keys => { 3 console.log(keys); 4 return someBatchLoadFn(keys); 5 }, 6 { cache: false }, 7); 8 9myLoader.load('A'); 10myLoader.load('B'); 11myLoader.load('A'); 12 13// > [ 'A', 'B', 'A' ]
More complex cache behavior can be achieved by calling .clear()
or .clearAll()
rather than disabling the cache completely. For example, this DataLoader will
provide unique keys to a batch function due to the memoization cache being
enabled, but will immediately clear its cache when the batch function is called
so later requests will load new values.
1const myLoader = new DataLoader(keys => {
2 myLoader.clearAll();
3 return someBatchLoadFn(keys);
4});
As mentioned above, DataLoader is intended to be used as a per-request cache. Since requests are short-lived, DataLoader uses an infinitely growing Map as a memoization cache. This should not pose a problem as most requests are short-lived and the entire cache can be discarded after the request completes.
However this memoization caching strategy isn't safe when using a long-lived DataLoader, since it could consume too much memory. If using DataLoader in this way, you can provide a custom Cache instance with whatever behavior you prefer, as long as it follows the same API as Map.
The example below uses an LRU (least recently used) cache to limit total memory to hold at most 100 cached values via the lru_map npm package.
1import { LRUMap } from 'lru_map'; 2 3const myLoader = new DataLoader(someBatchLoadFn, { 4 cacheMap: new LRUMap(100), 5});
More specifically, any object that implements the methods get()
, set()
,
delete()
and clear()
methods can be provided. This allows for custom Maps
which implement various cache algorithms to be provided.
DataLoader creates a public API for loading data from a particular
data back-end with unique keys such as the id
column of a SQL table or
document name in a MongoDB database, given a batch loading function.
Each DataLoader
instance contains a unique memoized cache. Use caution when
used in long-lived applications or those which serve many users with different
access permissions and consider creating a new instance per web request.
new DataLoader(batchLoadFn [, options])
Create a new DataLoader
given a batch loading function and options.
batchLoadFn: A function which accepts an Array of keys, and returns a Promise which resolves to an Array of values.
options: An optional object of options:
Option Key | Type | Default | Description |
---|---|---|---|
batch | Boolean | true | Set to false to disable batching, invoking batchLoadFn with a single load key. This is equivalent to setting maxBatchSize to 1 . |
maxBatchSize | Number | Infinity | Limits the number of items that get passed in to the batchLoadFn . May be set to 1 to disable batching. |
batchScheduleFn | Function | See Batch scheduling | A function to schedule the later execution of a batch. The function is expected to call the provided callback in the immediate future. |
cache | Boolean | true | Set to false to disable memoization caching, creating a new Promise and new key in the batchLoadFn for every load of the same key. This is equivalent to setting cacheMap to null . |
cacheKeyFn | Function | key => key | Produces cache key for a given load key. Useful when objects are keys and two objects should be considered equivalent. |
cacheMap | Object | new Map() | Instance of Map (or an object with a similar API) to be used as cache. May be set to null to disable caching. |
name | String | null | The name given to this DataLoader instance. Useful for APM tools. |
load(key)
Loads a key, returning a Promise
for the value represented by that key.
loadMany(keys)
Loads multiple keys, promising an array of values:
1const [a, b] = await myLoader.loadMany(['a', 'b']);
This is similar to the more verbose:
1const [a, b] = await Promise.all([myLoader.load('a'), myLoader.load('b')]);
However it is different in the case where any load fails. Where Promise.all() would reject, loadMany() always resolves, however each result is either a value or an Error instance.
1var [a, b, c] = await myLoader.loadMany(['a', 'b', 'badkey']); 2// c instanceof Error
clear(key)
Clears the value at key
from the cache, if it exists. Returns itself for
method chaining.
clearAll()
Clears the entire cache. To be used when some event results in unknown
invalidations across this particular DataLoader
. Returns itself for
method chaining.
prime(key, value)
Primes the cache with the provided key and value. If the key already exists, no
change is made. (To forcefully prime the cache, clear the key first with
loader.clear(key).prime(key, value)
.) Returns itself for method chaining.
To prime the cache with an error at a key, provide an Error instance.
DataLoader pairs nicely well with GraphQL. GraphQL fields are designed to be stand-alone functions. Without a caching or batching mechanism, it's easy for a naive GraphQL server to issue new database requests each time a field is resolved.
Consider the following GraphQL request:
{
me {
name
bestFriend {
name
}
friends(first: 5) {
name
bestFriend {
name
}
}
}
}
Naively, if me
, bestFriend
and friends
each need to request the backend,
there could be at most 13 database requests!
When using DataLoader, we could define the User
type using the
SQLite example with clearer code and at most 4 database requests,
and possibly fewer if there are cache hits.
1const UserType = new GraphQLObjectType({ 2 name: 'User', 3 fields: () => ({ 4 name: { type: GraphQLString }, 5 bestFriend: { 6 type: UserType, 7 resolve: user => userLoader.load(user.bestFriendID), 8 }, 9 friends: { 10 args: { 11 first: { type: GraphQLInt }, 12 }, 13 type: new GraphQLList(UserType), 14 resolve: async (user, { first }) => { 15 const rows = await queryLoader.load([ 16 'SELECT toID FROM friends WHERE fromID=? LIMIT ?', 17 user.id, 18 first, 19 ]); 20 return rows.map(row => userLoader.load(row.toID)); 21 }, 22 }, 23 }), 24});
In many applications, a web server using DataLoader serves requests to many different users with different access permissions. It may be dangerous to use one cache across many users, and is encouraged to create a new DataLoader per request:
1function createLoaders(authToken) {
2 return {
3 users: new DataLoader(ids => genUsers(authToken, ids)),
4 cdnUrls: new DataLoader(rawUrls => genCdnUrls(authToken, rawUrls)),
5 stories: new DataLoader(keys => genStories(authToken, keys)),
6 };
7}
8
9// When handling an incoming web request:
10const loaders = createLoaders(request.query.authToken);
11
12// Then, within application logic:
13const user = await loaders.users.load(4);
14const pic = await loaders.cdnUrls.load(user.rawPicUrl);
Creating an object where each key is a DataLoader
is one common pattern which
provides a single value to pass around to code which needs to perform
data loading, such as part of the rootValue
in a graphql-js request.
Occasionally, some kind of value can be accessed in multiple ways. For example, perhaps a "User" type can be loaded not only by an "id" but also by a "username" value. If the same user is loaded by both keys, then it may be useful to fill both caches when a user is loaded from either source:
1const userByIDLoader = new DataLoader(async ids => {
2 const users = await genUsersByID(ids);
3 for (let user of users) {
4 usernameLoader.prime(user.username, user);
5 }
6 return users;
7});
8
9const usernameLoader = new DataLoader(async names => {
10 const users = await genUsernames(names);
11 for (let user of users) {
12 userByIDLoader.prime(user.id, user);
13 }
14 return users;
15});
Since DataLoader caches values, it's typically assumed these values will be treated as if they were immutable. While DataLoader itself doesn't enforce this, you can create a higher-order function to enforce immutability with Object.freeze():
1function freezeResults(batchLoader) { 2 return keys => batchLoader(keys).then(values => values.map(Object.freeze)); 3} 4 5const myLoader = new DataLoader(freezeResults(myBatchLoader));
DataLoader expects batch functions which return an Array of the same length as
the provided keys. However this is not always a common return format from other
libraries. A DataLoader higher-order function can convert from one format to another. The example below converts a { key: value }
result to the format
DataLoader expects.
1function objResults(batchLoader) {
2 return keys =>
3 batchLoader(keys).then(objValues =>
4 keys.map(key => objValues[key] || new Error(`No value for ${key}`)),
5 );
6}
7
8const myLoader = new DataLoader(objResults(myBatchLoader));
Looking to get started with a specific back-end? Try the loaders in the examples directory.
Listed in alphabetical order
DataLoader Source Code Walkthrough (YouTube):
A walkthrough of the DataLoader v1 source code. While the source has changed since this video was made, it is still a good overview of the rationale of DataLoader and how it works.
This repository is managed by EasyCLA. Project participants must sign the free (GraphQL Specification Membership agreement before making a contribution. You only need to do this one time, and it can be signed by individual contributors or their employers.
To initiate the signature process please open a PR against this repo. The EasyCLA bot will block the merge if we still need a membership agreement from you.
You can find detailed information here. If you have issues, please email operations@graphql.org.
If your company benefits from GraphQL and you would like to provide essential financial support for the systems and people that power our community, please also consider membership in the GraphQL Foundation.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 17/24 approved changesets -- score normalized to 7
Reason
1 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
19 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More