DataLoader and batching

Intermediate · 1 min

Fix N+1 with DataLoader: batch keys from one tick into one query, cache per request, and build loaders in context. 11 queries become 2.

Before thisThe N+1 problemContext and resolver arguments

Warren Day · 12 min · from 1:41:34

DataLoader and batching

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Warren DayReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A DataLoader takes a batch function from an array of keys to an array of values, in the same order and the same length, and calls it once for all the `load(key)` calls made in the same tick.
  • On the 10-post server, `{ posts { title author { name } } }` dropped from 11 queries to 2, and the nested `posts { author { posts } }` shape from 21 to 3.
  • Keys requested in the same tick are batched and deduplicated; awaiting one `load` before the next call makes three separate batches.
  • Create the loaders in the context factory, one set per request. A module-level loader caches across requests and serves stale or another user's data.
  • Return an `Error` instance in a key's slot to fail only that key; return an array of the wrong length and the whole batch throws.

The idea: wait one tick, then ask once

The N+1 problem happens because each Post.author runs its query immediately. DataLoader changes one thing: load(key) does not run a query, it returns a promise and remembers the key. When the current tick ends, after all the sibling resolvers have had their turn and called load, DataLoader calls your batch function once with every key collected.

Think of a bus stop. Instead of sending a taxi per passenger, the loader waits at the stop, takes everyone who showed up for this run, and makes one trip.

The batch function

import DataLoader from 'dataloader';

const authorById = new DataLoader(async (ids) => {
  const rows = db
    .prepare(`SELECT * FROM authors WHERE id IN (${ids.map(() => '?').join(',')})`)
    .all(...ids);
  const byId = new Map(rows.map((r) => [r.id, r]));
  return ids.map((id) => byId.get(id) ?? new Error(`No author ${id}`));
});

Two rules, enforced by the library:

  1. It must return a promise of an array the same length as ids.
  2. The value at index i must belong to ids[i].

The database does not return rows in the order you asked or include a row for a missing id, so you reshape. A Map keyed by id and a .map over ids gives you the right order. A missing row becomes an Error instance in that slot, which rejects only that one load call. I tried a batch function that returned one value for two keys and DataLoader threw: it must “return a Promise of an Array of the same length as the Array of keys.”

Wiring into resolvers

Loaders go in the context so every resolver reaches them. Create them in the factory, once per request:

const createLoaders = (db) => ({
  authorById: new DataLoader(/* as above */),
  postsByAuthorId: new DataLoader(async (ids) => {
    const rows = db
      .prepare(`SELECT * FROM posts WHERE author_id IN (${ids.map(() => '?').join(',')})`)
      .all(...ids);
    return ids.map((id) => rows.filter((r) => r.author_id === id));
  }),
});

const yoga = createYoga({
  schema,
  context: () => ({ db, loaders: createLoaders(db) }),
});

const resolvers = {
  Post: { author: (post, _args, { loaders }) => loaders.authorById.load(post.author_id) },
  Author: { posts: (author, _args, { loaders }) => loaders.postsByAuthorId.load(author.id) },
};

The one-to-many loader returns an array per key, so each value is itself a list. For a missing key, an empty array is the right answer.

The count, after

With DataLoader 2.2.3, graphql-yoga 6.1.0 and the same SQLite data as the last lesson:

{ posts { title author { name } } }                 2 queries (was 11)
  SELECT * FROM posts LIMIT ?
  SELECT * FROM authors WHERE id IN (?,?,?,?,?)
{ posts { author { name posts { title } } } }       3 queries (was 21)
{ posts(limit: 100) { title author { name } } }     2 queries (was 101)

Ten posts and five authors produced one query with five ids, because the loader deduplicates keys as well as batching them. The count no longer depends on the length of the list, which is the property you want.

When batching does not happen

Batching depends on calls arriving in the same tick. I checked three patterns, logging each batch:

Promise.all([load(1), load(2), load(1), load(3)])      [[1,2,3]]
await load(1); await load(2); await load(3)            [[1],[2],[3]]
three loads, each after the same number of awaits      [[1,2,3]]

Parallel calls batch, with duplicates removed. Calls separated by await do not, because each resolves before the next is made. In GraphQL that works out: the executor starts sibling resolvers together, so their load calls land in the same tick. If you write a resolver that awaits load and then calls load again for something different, the second call is a separate batch. That is correct, since its key depended on the first result. This is an event-loop behaviour; the event loop and the call stack explains the mechanics.

For large lists, maxBatchSize splits a batch: with maxBatchSize: 2 and five keys I saw [[1,2],[3,4],[5]]. That keeps an IN (...) list from growing beyond what the database allows.

Per request, not per process

DataLoader also caches: load(1) twice returns the same object, and the batch function is not called again. Calling loader.clear(1) forgets a key, which you do after a mutation changes it. That cache lives as long as the loader. A loader created at module scope would keep serving it forever, so one request could read what a previous request cached. I verified that a module-level loader returned the identical cached value 20 ms later. Per-request creation also keeps one user’s authorization-filtered rows away from another user. That is why the loaders sit in the context factory.

What the video covers

The clip is the chapter “Part 20: Dataloaders”, the last of the “GraphQL Fundamentals” section of Warren Day’s 2025 full course, from 1:41:34 to 1:54:00 where “GraphQL Mastery” begins. From the chapter title alone, it introduces dataloaders for the course’s server; I could not read a transcript, so the details of its library choice may differ from this lesson’s. The link below adds Jamie Barton’s focused DataLoader video.

Where this fits

Fields now fetch efficiently. When something goes wrong in a resolver, though, the response has to say so without throwing away the parts that worked. Next: errors and partial responses.

Check yourself

  1. 01What are the two rules for a DataLoader batch function?

    It receives an array of keys and must return a promise of an array of the same length, with the result for each key in the same position.

  2. 02Why did ten posts with five distinct authors produce one query with five ids?

    The ten `load(author_id)` calls happened in the same tick, so DataLoader collected them, removed the duplicates and called the batch function once with the five unique ids.

  3. 03Why must you create new DataLoaders for each request?

    A loader caches results for its lifetime. A module-level loader would keep serving cached rows across requests, which is stale at best and a data leak between users at worst.

  4. 04You call `await loader.load(1); await loader.load(2);` in a row. How many batch calls happen?

    Two. The first load resolves before the second begins, so nothing is waiting to be batched. Batching needs calls queued in the same tick, as when many resolvers run in parallel.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark