Skip to content

DataLoader Batching: Collapse N+1 Lookups Into One Call per Request

How per-request batching and caching turns hundreds of per-item lookups into a few bulk calls, with code, trade-offs and interview answers.

19 min readSystem pattern

Gather the individual key lookups made during one request, deduplicate them, and resolve them with a single bulk call per data source per tick. Memoize the results for the rest of that request so the same key is never fetched twice.

Any API that resolves a list and then fetches related data for each item has an N+1 problem waiting to happen. GraphQL makes it hard to miss, because every field resolver runs independently and has no view of its siblings. REST aggregators, background jobs and template renderers fall into the same trap. DataLoader batching handles this with one small object per request. It collects the keys that resolvers ask for during a single tick of the event loop, removes duplicates, sends one bulk request to the backing service, and caches the results until the request ends. This guide follows one invented production incident through the problem, the mechanism, working code in three languages, and the follow-up questions interviewers tend to ask.

The problem

A situation where the obvious design starts to hurt.

Cadenza is a marketplace for booking music lessons. Its mobile app's home screen sends one GraphQL query: upcomingLessons(first: 50) { startsAt teacher { name avatarUrl } student { name level } }. The gateway is a Node service. It loads the 50 lessons with one SQL query. Then the Lesson.teacher resolver calls teacher-service with GET /teachers/:id for each lesson, and Lesson.student does the same against student-service.

One screen therefore costs 101 downstream calls. On a typical page only about 7 distinct teachers appear, so most of those calls fetch the same records again. At normal load, about 150 home-screen requests per second, nobody noticed.

In the first week of the autumn term, traffic hit 900 requests per second, which meant roughly 90,000 calls per second to the two downstream services. Each gateway pod had an HTTP agent capped at 40 sockets for teacher-service, and every pod's pool saturated. Requests queued behind the socket limit. Gateway p99 went from 210 ms to 3.1 s, and the CDN started returning 504s after its 3 s origin timeout. Teacher-service, meanwhile, was handling 45,000 single-row lookups per second against a table with fewer than 4,000 active teachers.

Adding gateway pods made it worse, because each new pod opened another 40 connections to teacher-service. The waste was structural: the resolvers had no way to know their siblings needed the same thing.

The solution

What the pattern proposes.

Give each incoming request its own set of loaders: one TeacherLoader and one StudentLoader, created in the GraphQL context factory. Resolvers stop calling the HTTP clients directly and call loaders.teacher.load(lesson.teacherId) instead.

The loader does not fetch right away. It records the key, returns a promise, and schedules a dispatch for after the current tick. All 50 Lesson.teacher resolvers run during that tick, so by the time the dispatch fires, the queue holds 50 keys. A per-request map has already collapsed them to 7 unique ids, because asking for the same key a second time returns the existing promise.

The dispatch sends one GET /teachers?ids=3,9,14,... and hands the response back to each waiting promise by key. Keys the service did not return resolve to null. If the batch call fails, every promise in that batch is rejected and its cache entry is removed, so a later load in the same request can retry.

Teacher-service already had WHERE id = ANY($1), so the backend change was small. It got a bulk endpoint with a limit of 100 ids, and the loader splits larger queues into chunks of 100.

The home screen now costs 3 downstream calls: lessons, one teacher batch and one student batch. Nested fields add one batch per level of depth, not one call per item. The cache is discarded when the request finishes, so a teacher's renamed profile shows up on the next request, and one user's permission-filtered data can never reach another user.

An everyday analogy

The same idea, outside software.

Picture a school librarian on a busy morning. Thirty students come to the desk one at a time asking for books, and many want the same title for the same assignment. A librarian who walks to the stacks after every request makes thirty trips and fetches the same book nine times.

A better librarian writes each request on a slip until the line stops moving, crosses out duplicates, makes one trip with the shortened list, and hands each student the right book. Anyone who asks for that title again later in the same class period gets it from the cart at the desk.

When the class leaves, the cart goes back. The next class starts with an empty cart, because its students may be allowed different books.

Structure

The pieces and how they relate.

Cadenza gateway: per-request loaders collect keys from resolvers and send one bulk call per service per tick.Cadenza mobile app calls GraphQL gateway (POST /graphql). GraphQL gateway calls Lessons DB (list 50 lessons). GraphQL gateway calls Field resolvers (execute fields). GraphQL gateway creates TeacherLoader (new per request). GraphQL gateway creates StudentLoader (new per request). Field resolvers calls TeacherLoader (load(teacherId) x50). Field resolvers calls StudentLoader (load(studentId) x50). TeacherLoader calls teacher-service (1 call, 7 ids). StudentLoader calls student-service (1 call, unique ids). teacher-service sends to Teachers table (bulk select). student-service sends to Students table (bulk select).Cadenza mobileappupcomingLessons(first:50)GraphQL gatewayNode, builds contextper requestLessons DBPostgres, 1 query,50 rowsField resolversLesson.teacher,Lesson.studentTeacherLoaderper-request cache +queueStudentLoaderper-request cache +queueDispatch aftertickdedupe, chunk at 100idsteacher-serviceGET/teachers?ids=...student-servicePOST/students:batchGetTeachers tableWHERE id = ANY($1)Students tableWHERE id = ANY($1)POST /graphqllist 50 lessonsexecute fieldsnew per requestnew per requestload(teacherId) x50load(studentId) x501 call, 7 ids1 call, unique idsbulk selectbulk select
Cadenza gateway: per-request loaders collect keys from resolvers and send one bulk call per service per tick.

Participants

Field resolver
Code that needs one related record, such as Lesson.teacher. It calls load(key) and awaits the result. It never calls the downstream client directly and has no idea batching is happening.
Loader (TeacherLoader, StudentLoader)
One instance per data source per request. It holds a map from key to promise (the cache), a queue of keys not yet fetched, and a scheduled-dispatch flag. It turns many single-key calls into a few bulk calls.
Batch function
The only code that talks to the backend. It takes a list of keys and returns a map from key to value, issuing one IN/ANY query or one bulk HTTP request. It must tolerate missing keys and must not assume any order.
Request context factory
Creates fresh loaders at the start of each request and drops them at the end. This is what keeps the cache request-scoped and prevents data from leaking between users or going stale.
Bulk endpoint on the downstream service
For example GET /teachers?ids= with a hard limit of 100 ids. Without a bulk read on the other side, the loader can deduplicate keys but cannot batch them.

Pseudocode

The solution to the scenario, language-neutral.

class Loader:
  cache: map key -> promise
  queue: list of (key, resolve, reject)
  scheduled: bool

  load(key):
    if key in cache: return cache[key]          # dedupe within request
    promise, resolve, reject = new_promise()
    cache[key] = promise
    queue.append((key, resolve, reject))
    if not scheduled:
      scheduled = true
      run_after_current_tick(dispatch)          # setImmediate / call_soon / explicit flush
    return promise

  dispatch():
    batch = queue; queue = []; scheduled = false
    for chunk in split(batch, max_batch_size):  # e.g. 100, the backend limit
      run_chunk(chunk)

  run_chunk(chunk):
    try:
      found = batch_fn(keys of chunk)           # one bulk call, returns map key -> value
    except err:
      for (key, _, reject) in chunk:
        delete cache[key]                       # allow retry later in the request
        reject(err)
      return
    for (key, resolve, _) in chunk:
      resolve(found.get(key) or null)           # match by key, never by position

on_request_start:
  ctx.loaders = { teacher: Loader(fetch_teachers, 100), student: Loader(fetch_students, 100) }

resolve Lesson.teacher(lesson, ctx):
  return ctx.loaders.teacher.load(lesson.teacher_id)

The code

The same solution in TypeScript, Python and PHP.

type Key = string | number;
type BatchFn<V> = (keys: readonly Key[]) => Promise<Map<Key, V>>;

interface Pending<V> {
  key: Key;
  resolve: (value: V | null) => void;
  reject: (error: unknown) => void;
}

export class DataLoader<V> {
  private readonly cache = new Map<Key, Promise<V | null>>();
  private queue: Pending<V>[] = [];
  private scheduled = false;

  constructor(
    private readonly batchFn: BatchFn<V>,
    private readonly maxBatchSize = 100,
  ) {}

  load(key: Key): Promise<V | null> {
    const cached = this.cache.get(key);
    if (cached) return cached;

    const promise = new Promise<V | null>((resolve, reject) => {
      this.queue.push({ key, resolve, reject });
    });
    this.cache.set(key, promise);

    if (!this.scheduled) {
      this.scheduled = true;
      // setImmediate runs after all pending microtasks, so every resolver
      // at the current depth has called load() before we dispatch.
      setImmediate(() => this.dispatch());
    }
    return promise;
  }

  private dispatch(): void {
    const batch = this.queue;
    this.queue = [];
    this.scheduled = false;
    for (let i = 0; i < batch.length; i += this.maxBatchSize) {
      void this.runChunk(batch.slice(i, i + this.maxBatchSize));
    }
  }

  private async runChunk(chunk: Pending<V>[]): Promise<void> {
    let found: Map<Key, V>;
    try {
      found = await this.batchFn(chunk.map((p) => p.key));
    } catch (error) {
      for (const p of chunk) {
        this.cache.delete(p.key); // let a later load() retry
        p.reject(error);
      }
      return;
    }
    for (const p of chunk) p.resolve(found.get(p.key) ?? null);
  }
}

// Demo: 50 lessons pointing at 7 teachers -> one batch call with 7 ids.
interface Teacher {
  id: number;
  name: string;
}

let calls = 0;
const fetchTeachers: BatchFn<Teacher> = async (ids) => {
  calls += 1;
  return new Map(ids.map((id) => [id, { id: Number(id), name: `Teacher ${id}` }]));
};

async function main(): Promise<void> {
  const teachers = new DataLoader<Teacher>(fetchTeachers, 100); // one per request
  const lessons = Array.from({ length: 50 }, (_, i) => ({ id: i, teacherId: i % 7 }));
  const resolved = await Promise.all(lessons.map((l) => teachers.load(l.teacherId)));
  console.log(`${resolved.length} lessons, ${calls} batch call(s)`);
}

void main();

When to use it

Situations where it pays off.

  • GraphQL resolvers fetch a related entity per parent object, such as lesson.teacher, order.customer or comment.author.

    Resolvers execute independently, so without a shared collector each one makes its own call. A loader is the standard place to gather the keys for a whole level of the query.

  • A REST aggregator or BFF fans out per item after fetching a list, for example enriching 200 search hits with stock levels.

    The same N+1 shape appears outside GraphQL. Routing each per-item lookup through a loader turns 200 calls into 2 chunked calls without restructuring the enrichment code.

  • The same key is requested many times within one unit of work, such as a teacher who appears on 20 of 50 lessons.

    The per-request cache removes duplicates even when no bulk endpoint exists. A single-key backend still sees one call per distinct key instead of one per reference.

  • The downstream service or database supports a bulk read (WHERE id IN, batchGet, MGET) that costs about the same as a single read.

    Batching only saves time when one call for 100 keys is much cheaper than 100 calls for one key each. With a cheap bulk read, the round trips disappear almost entirely.

  • Connection pools or socket limits to a dependency are saturating under load while each individual request to it is small.

    Batching reduces how many requests are in flight, not just how much data moves, which is exactly what a pool limit of 40 sockets per pod constrains.

How to implement it

Steps to introduce it in existing code.

  1. Find the N+1: turn on per-request downstream call counting (a counter in the HTTP client, logged with the trace id) and look for requests whose call count grows with page size.

  2. Add a bulk read to the dependency: GET /teachers?ids= backed by WHERE id = ANY($1), with a documented maximum of 100 ids and a response keyed by id so callers can match results by key.

  3. Write a batch function that takes a list of keys and returns a map from key to value. Treat absent keys as null and never rely on response order.

  4. Create loaders in the per-request context factory, one per data source and per distinct query shape, and make sure they are garbage once the response is sent.

  5. Replace direct client calls in resolvers with ctx.loaders.x.load(id), starting with the fields that showed the highest call counts.

  6. Set maxBatchSize to the backend's limit and confirm, with the same counter, that a 50-item page now makes one call per data source per nesting level.

  7. Add a timeout and error handling inside the batch function, because one failed batch now affects every field that waits on it.

Pros and cons

What you gain and what you pay.

Pros

  • Downstream calls drop from linear in page size to roughly one per data source per nesting level; Cadenza's home screen went from 101 calls to 3.
  • Duplicate keys within a request are fetched once, which helps even against backends that have no bulk endpoint.
  • Resolvers stay simple and local; batching is invisible to the code that asks for data.
  • A request-scoped cache cannot serve stale data across requests and cannot leak one user's permission-filtered results to another.
  • Fewer in-flight requests relieve connection pools, so the gateway can scale out without multiplying connections to the dependency.

Cons

  • Every batched lookup waits until the end of the tick, which adds a small amount of latency to an isolated single-key fetch.
  • Each level of nesting is still a separate round trip, so a deep query (lessons, teacher, teacher.reviews, review.author) remains a waterfall of sequential batches.
  • A failed or slow batch fails or delays every field that depends on it, so one bad id or one timeout can blank a whole list.
  • It requires bulk endpoints on downstream services, which can mean cross-team API work before you see any gain.
  • Per-request caching does nothing for repeated reads across requests; you still need a shared cache for hot keys.

Trade-offs

Decisions you'll have to make, each with its price.

  • Dispatch after the full tick (setImmediate in Node, call_soon in asyncio) instead of on the next microtask

    You gainEvery resolver at the current depth has queued its key, so a 50-item page becomes one batch instead of the 2 or 3 partial batches you get when promise hops land after the microtask fires.

    You payI/O callbacks that are already waiting run before the dispatch, adding a fraction of a millisecond to a few milliseconds per level under load. A single-key lookup is never faster than calling the client directly.

  • maxBatchSize of 100, matching teacher-service's limit

    You gainRequests stay under URL length limits and keep ANY($1) plans on the primary key index; a 230-key queue becomes 3 parallel calls instead of one oversized request that fails.

    You payChunks run in parallel, so one request can open 3 connections at once. Larger pages trade fewer round trips for more concurrency against the pool.

  • Per-request cache lifetime instead of a shared TTL cache

    You gainNo invalidation logic, no cross-user leakage, and reads within one request stay consistent even if a teacher record changes partway through.

    You payEach request refetches the same 7 popular teachers; at 900 req/s that is still 900 teacher batches per second, which a shared cache could absorb.

  • Missing keys resolve to null rather than rejecting

    You gainA deleted student on one lesson nulls a single field, and the other 49 lessons still render.

    You paySchema fields must be nullable, and genuine data-integrity bugs show up as empty avatars instead of errors unless you log misses with the key.

  • Fail the whole chunk when the batch call throws

    You gainThe behaviour is simple to reason about and there is no partial-success parsing; errors appear on every affected field with the same cause.

    You payOne timeout empties up to 100 fields at once. Backends that can report per-key errors let you fail fewer fields, but the batch function then has to map each error back to its key.

How it fails

What goes wrong in production and how to prevent it.

  • Loader created once at module level, so the cache spans requests and returns one user's permission-filtered student data to another.

    What to doCreate loaders only in the request context factory and add a test that fires two requests with different auth and checks their results differ. A lint rule that bans new DataLoader outside the context module catches regressions.

  • Batch function returns rows in database order, and an index-based loader assigns teacher 14's name to lesson 3.

    What to doReturn a map keyed by id and look results up by key, as in the code above. Add a test that passes keys in descending order against a backend that returns ascending.

  • Dispatch fires too early because some resolvers await something else before calling load(), splitting one page into 4 to 6 small batches.

    What to doDispatch after the full tick rather than on a microtask, call load() before any other await in the resolver, and alert when a request's batch count per loader goes above 2.

  • An unbounded queue builds a 2,000-id request that exceeds the 8 KB URL limit at the load balancer and returns 414 for the whole page.

    What to doSet maxBatchSize to the documented backend limit, enforce first <= 100 in the schema, and switch the bulk endpoint to POST with a JSON body if pages need to be larger.

  • One slow teacher-service batch holds the entire response until the 3 s CDN timeout, because every lesson field waits on it.

    What to doGive the batch function an 800 ms timeout, resolve those fields to null with a GraphQL error entry, and put a circuit breaker on the bulk endpoint so later requests fail fast instead of piling up.

In a system design interview

When to bring it up and how to explain it.

Bring it up as soon as your design has a list endpoint or GraphQL query whose items reference other entities, or when the interviewer asks why p99 latency grows with page size. It also fits in a scaling discussion when connection pools to a downstream service saturate even though each call is cheap.

What you could say

The home screen lists 50 lessons, and each one needs its teacher and student. If every resolver fetches its own, that's 101 downstream calls per screen, and most of them are duplicates because a page usually has about 7 distinct teachers. I'd fix that with a per-request DataLoader for each data source. Resolvers call load(teacherId), which returns a promise and queues the key. After the current tick, the loader deduplicates the keys and sends one bulk call, something like GET /teachers?ids= backed by WHERE id = ANY, chunked at whatever limit the service allows, say 100. Results go back to each waiting promise by key, so ordering bugs can't happen, and a missing key just resolves to null. The cache lives only for that request, which means there's no invalidation to manage and no way for one user's data to reach another. That takes the screen from 101 calls to 3. The things I'd watch are the batch timeout, since one slow call now affects every field, and nested depth, because each level is still one sequential round trip. For hot keys across requests, I'd put Redis inside the batch function rather than widening the loader's cache.

Likely follow-ups

How does the loader know when to dispatch?

It doesn't know the query plan. It relies on the event loop. The first load() in a tick schedules a dispatch after pending work drains: setImmediate in Node, call_soon in asyncio. Sibling resolvers all run within that tick, so their keys are queued by then. In synchronous PHP, the first time a value is read acts as the flush point instead.

What if the downstream service has no bulk endpoint?

You still get deduplication, so 50 references to 7 teachers become 7 calls instead of 50, and you can run those 7 in parallel under a concurrency cap. The real fix is to add a bulk read, which is usually a small change since the database already supports IN or ANY.

Why not cache across requests in the loader to get even more hits?

Because the loader has no invalidation and stores results already filtered for the caller's permissions. A shared cache belongs one layer down: Redis MGET inside the batch function with a TTL such as 60 s and explicit invalidation on teacher profile updates. That keeps both the security boundary and the staleness policy explicit.

How would you detect a regression back to N+1?

Count downstream calls per request in the HTTP client, tag the count with the operation name, and alert when calls per request correlate with page size, or when any loader dispatches more than 2 batches per level. A test that runs the 50-item query and checks for exactly 3 outbound calls catches it in CI.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Is DataLoader only for GraphQL?

No. It fits any code that resolves a list and then looks up related records one item at a time: REST aggregators, report generators, template rendering, queue consumers that enrich messages. GraphQL just makes the problem show up more often, because resolvers are isolated from each other by design.

Why not just write one big SQL join in the list resolver?

That works when the list resolver knows which fields the client asked for and all the data sits in one database. In Cadenza, teachers and students live in separate services, and the client chooses which fields to request. A join would fetch teacher data even for queries that never ask for it. Loaders fetch only what was actually requested, from wherever it lives.

Should the cache be shared across requests to save more calls?

Not the loader's cache. It holds results filtered for one caller's permissions and is never invalidated, so sharing it leaks data and serves stale rows. If you want cross-request caching, put a TTL cache with explicit invalidation inside the batch function and keep the loader itself per request.

What does the batch function have to guarantee?

It returns one value or an explicit miss for every key it was given, and the loader matches results by key, not by position. The reference JavaScript DataLoader instead expects an array the same length and order as the keys. Either contract works as long as the batch function honours it. A batch function that drops keys or reorders rows is the most common source of wrong-teacher bugs.

How many round trips does a nested query make?

One per data source per nesting level that needs it. For lessons, then teacher, then teacher.reviews, then review.author, that is four sequential batches. Batching removes the width of the N+1 but not the depth, so you still keep deep queries in check with query depth limits or a dedicated bulk endpoint.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.