TExcelTAD
Home › GraphQL › Batching with DataLoader

Batching with DataLoader

DataLoader is a tiny utility, originally from Facebook, that solves N+1 while letting every resolver stay simple. A resolver calls loader.load(id) and gets a Promise. The loader doesn't query right away: it collects all the ids requested in the same tick of the event loop, then calls your batch function once with all of them. It also caches results, so the same id is never loaded twice in a request.

The real package is npm install dataloader, used like this:

js
import DataLoader from 'dataloader';

const userLoader = new DataLoader(async (ids) => {
  const rows = await db.query('SELECT * FROM users WHERE id = ANY($1)', [ids]);
  return ids.map((id) => rows.find((r) => r.id === id) ?? null);
});

const user = await userLoader.load(42);

To really understand it, let's build our own.

A DataLoader in 25 lines

js · try it yourself
class TinyLoader {
  constructor(batchFn) {
    this.batchFn = batchFn;
    this.cache = new Map();   // key -> Promise
    this.queue = [];          // pending { key, resolve, reject }
  }

  load(key) {
    if (this.cache.has(key)) return this.cache.get(key);
    const promise = new Promise((resolve, reject) => {
      this.queue.push({ key, resolve, reject });
      // First load in this tick: schedule one dispatch after the current work.
      if (this.queue.length === 1) queueMicrotask(() => this.dispatch());
    });
    this.cache.set(key, promise);
    return promise;
  }

  async dispatch() {
    const batch = this.queue;
    this.queue = [];
    try {
      const values = await this.batchFn(batch.map((item) => item.key));
      batch.forEach((item, i) => item.resolve(values[i]));
    } catch (error) {
      batch.forEach((item) => item.reject(error));
    }
  }
}

const loader = new TinyLoader(async (keys) => {
  console.log('batch called with', keys);
  return keys.map((k) => k * 10);
});

// Four loads, made "at the same time"...
const results = await Promise.all([loader.load(1), loader.load(2), loader.load(1), loader.load(3)]);
console.log(results);

// ...a later load of a cached key doesn't call the batch function.
console.log(await loader.load(2));
batch called with [ 1, 2, 3 ]
[ 10, 20, 10, 30 ]
20

Two rules make a batch function correct, and the real DataLoader enforces both:

  1. It returns an array the same length as keys.
  2. Item i of the result belongs to key i. Databases return rows in any order, so always map the results back to the keys.

Using it in resolvers

Now the N+1 example from the previous lesson, with the author resolver going through a loader. The loader lives in the context, so a fresh one (with a fresh cache) is created for every request:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

class TinyLoader {
  constructor(batchFn) { this.batchFn = batchFn; this.cache = new Map(); this.queue = []; }
  load(key) {
    if (this.cache.has(key)) return this.cache.get(key);
    const promise = new Promise((resolve, reject) => {
      this.queue.push({ key, resolve, reject });
      if (this.queue.length === 1) queueMicrotask(() => this.dispatch());
    });
    this.cache.set(key, promise);
    return promise;
  }
  async dispatch() {
    const batch = this.queue;
    this.queue = [];
    try {
      const values = await this.batchFn(batch.map((b) => b.key));
      batch.forEach((b, i) => b.resolve(values[i]));
    } catch (error) {
      batch.forEach((b) => b.reject(error));
    }
  }
}

const tables = {
  users: [{ id: 1, name: 'Ana' }, { id: 2, name: 'Ben' }, { id: 3, name: 'Chloé' }],
  posts: [
    { id: 1, title: 'Hello', authorId: 1 },
    { id: 2, title: 'GraphQL tips', authorId: 2 },
    { id: 3, title: 'On caching', authorId: 1 },
    { id: 4, title: 'Batching', authorId: 3 },
    { id: 5, title: 'Wrap-up', authorId: 2 },
  ],
};

const queryLog = [];
const db = {
  allPosts: async () => { queryLog.push('SELECT * FROM posts'); return tables.posts; },
  usersByIds: async (ids) => {
    queryLog.push(`SELECT * FROM users WHERE id IN (${ids.join(', ')})`);
    // Pretend the database returns rows in a different order.
    return tables.users.filter((u) => ids.includes(u.id)).reverse();
  },
};

const createLoaders = () => ({
  user: new TinyLoader(async (ids) => {
    const rows = await db.usersByIds(ids);
    return ids.map((id) => rows.find((r) => r.id === id) ?? null);   // keep key order!
  }),
});

const schema = buildSchema(`
  type User { id: ID!, name: String! }
  type Post { id: ID!, title: String!, author: User! }
  type Query { posts: [Post!]! }
`);

const rootValue = {
  posts: async () =>
    (await db.allPosts()).map((row) => ({
      ...row,
      author: (_args, context) => context.loaders.user.load(row.authorId),
    })),
};

const result = await graphql({
  schema,
  rootValue,
  contextValue: { loaders: createLoaders() },   // one set of loaders per request
  source: '{ posts { title author { name } } }',
});
console.log(result.data.posts.map((p) => `${p.title} by ${p.author.name}`).join('; '));
console.log(queryLog);
Hello by Ana; GraphQL tips by Ben; On caching by Ana; Batching by Chloé; Wrap-up by Ben
[ 'SELECT * FROM posts', 'SELECT * FROM users WHERE id IN (1, 2, 3)' ]

Two queries, regardless of how many posts there are, and every resolver still only knows about its own post.

How the timing works

graphql-js resolves the author field of every post in the list before it awaits any of them. Each load() only pushes to the queue; the scheduled microtask runs after all of them, so the batch contains every id from that level. Deeper levels (authors' posts, their comments, …) form their own batches. The number of queries grows with the depth of the query, not with the number of items.

Per-request, not global

Warning: Don't create a loader once at server start and share it. Its cache would serve stale data forever and, worse, could hand one user's data to another if authorization depends on the requester. Create loaders in the function that builds the context for each request.

Beyond "by id"

Loaders work for any lookup with a batchable key:

Loader Key Batch query
userById user id WHERE id IN (…)
postsByAuthor author id WHERE author_id IN (…), then group rows per author (each value is an array)
priceBySku SKU one call to a pricing microservice with all SKUs

Test yourself

When does a DataLoader call its batch function?

  1. Immediately on every load()
  2. Once per tick, with all keys collected so far
  3. Only when the cache is full
  4. When the server starts

The batch function receives keys [3, 1, 2]. What must it return?

  1. Rows in database order
  2. An array of 3 values where index i belongs to key i
  3. A Map from key to value
  4. A single value

Why create loaders per request?

  1. They can't be reused at all
  2. A shared cache would leak stale or other users' data
  3. graphql-js requires it
  4. To make batching slower