StackPractices
intermediate By Mathias Paulenko

GraphQL Batched Resolver Pattern

Resolve nested GraphQL fields in a single batched request to eliminate N+1 queries and reduce database load.

Overview

Ask GraphQL for nested fields on a list and every item fires its own database call. Querying 50 posts and their authors produces 50 extra SELECT statements, the classic N+1 problem. Batched resolvers collect all keys from the list, make one batched request, and distribute results back to each item.

Batching is a strategy rather than a library. DataLoader is the implementation you’ll see in most JavaScript codebases, but the same idea works with custom batch functions, Redis pipelines, or a gateway that coalesces sub-requests. If you already know DataLoader and want to detect where N+1 is actually hurting, pair this with N+1 query detection.

When to Use

  • Resolvers that fetch related data per parent item (posts → author, orders → product)
  • Lists of items where each item has a nested relationship
  • Any GraphQL field that triggers a database query or API call per parent
  • Gateway or stitching layers that delegate to backend services

When Not to Use

  • Single-item queries where N=1 (no batching benefit)
  • Fields resolved from already-loaded data on the parent object (use direct property access)
  • Real-time subscriptions where batching windows add unacceptable latency

Solution

1. The N+1 Problem

Without batching, each post triggers a separate author lookup:

const resolvers = {
  Post: {
    author: (post, _args, { db }) => {
      // Called once per post: 50 posts = 50 queries
      return db.user.findById(post.authorId);
    },
  },
};

Querying 50 posts generates 50 SQL queries:

SELECT * FROM users WHERE id = 1;
SELECT * FROM users WHERE id = 2;
SELECT * FROM users WHERE id = 1;  -- duplicate
SELECT * FROM users WHERE id = 3;
-- ... 46 more

2. DataLoader: Batch and Cache

DataLoader collects all authorId values within a single tick of the event loop, deduplicates them, and sends one batch request.

import DataLoader from 'dataloader';

async function batchLoadUsers(userIds: readonly string[], { db }) {
  // One query: SELECT * FROM users WHERE id IN (1, 2, 3, ...)
  const users = await db.user.findMany({ where: { id: { in: [...userIds] } } });

  // DataLoader expects results in the same order as the input keys
  const userMap = new Map(users.map((u) => [u.id, u]));
  return userIds.map((id) => userMap.get(id) ?? new Error(`User ${id} not found`));
}

// Create a new DataLoader per request to avoid cross-request caching
function createLoaders(context) {
  return {
    userLoader: new DataLoader(
      (ids) => batchLoadUsers(ids, context),
      { cacheKeyFn: (key) => key.toString() }
    ),
  };
}

3. Use the Loader in Resolvers

const resolvers = {
  Post: {
    author: (post, _args, { loaders }) => {
      // DataLoader batches all calls within the same tick
      return loaders.userLoader.load(post.authorId);
    },
  },
  Query: {
    posts: async (_parent, _args, { db }) => {
      return db.post.findMany({ take: 50 });
    },
  },
};

Now 50 posts produce one SQL query:

SELECT * FROM users WHERE id IN (1, 2, 3, 4, 5, ...);

4. Per-Request Loader Initialization

Create fresh loaders for each request to prevent leaking cached data between users:

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

const { url } = await startStandaloneServer(server, {
  context: async ({ req }) => {
    const db = getDatabase();
    const loaders = createLoaders({ db });
    return { db, loaders, user: req.headers.authorization };
  },
  listen: { port: 4000 },
});

5. Batching Across Multiple Fields

DataLoader batches across different resolver fields too. If a query asks for both post.author and comment.author, both resolve through the same userLoader:

const resolvers = {
  Post: {
    author: (post, _args, { loaders }) => loaders.userLoader.load(post.authorId),
  },
  Comment: {
    author: (comment, _args, { loaders }) => loaders.userLoader.load(comment.authorId),
  },
};

A query like { posts { author { name } } comments { author { name } } } still produces one batched call for all author IDs.

Explanation

Mermaid graph LR diagram

The batching window

GraphQL executes sibling field resolvers roughly in parallel. Every .load(key) call returns a pending promise and queues the key. When the current tick of the event loop ends, the batch function fires once with all collected keys, and each pending promise resolves with the item at its position. That is why batching “just works” without you scheduling anything.

Why per-request

The loader caches every key it resolves. If that cache outlives a single GraphQL operation, one user’s data can leak into another user’s response, and mutations leave stale entries behind. Creating loaders inside the context factory gives each request a clean cache that is discarded when the response is sent.

Order and errors

DataLoader matches results to callers by position, not by key. If your batch function returns rows in database order instead of key order, every resolver silently gets the wrong item. The same positional contract applies to errors: return new Error() as the value for a failed key so one missing row does not reject the whole batch.

What batching costs you

The pattern adds one tick of latency to every batched field and keeps keys in memory until the batch fires. For lists of thousands of parents, cap maxBatchSize so IN clauses stay within database limits, and monitor batch sizes in production. If your backend cannot accept multi-key requests (some REST endpoints), batching buys nothing there.

Variants

Custom Batch Functions for REST APIs

Batch against a REST endpoint that accepts multiple IDs:

const productLoader = new DataLoader(async (productIds: readonly string[]) => {
  const response = await fetch(
    `https://api.example.com/products?ids=${productIds.join(',')}`
  );
  const products = await response.json();
  const productMap = new Map(products.map((p) => [p.id, p]));
  return productIds.map((id) => productMap.get(id));
});

Batch with Max Batch Size

Limit batch size to avoid oversized SQL IN clauses:

const userLoader = new DataLoader(batchLoadUsers, {
  maxBatchSize: 100,
  cache: true,
});

Batch with Priming

Pre-populate the cache when you already have data:

Query: {
  user: async (_parent, { id }, { db, loaders }) => {
    const user = await db.user.findById(id);
    // Prime the cache so nested resolvers don't re-fetch
    loaders.userLoader.prime(id, user);
    return user;
  },
},

Batch with Custom Cache Key

For composite keys (e.g., tenant + user ID):

const loader = new DataLoader(batchLoad, {
  cacheKeyFn: (key) => `${key.tenantId}:${key.userId}`,
});

Best Practices

  • Create one DataLoader instance per request, never shared across requests
  • Always return results in the same order as the input keys in batch functions
  • Use prime() when you already have data to avoid redundant fetches
  • Set maxBatchSize to keep SQL IN clauses within database limits
  • Handle errors per-key: return an Error object for failed items, not a thrown exception
  • Monitor batch sizes in production to catch unexpected query patterns

Common Mistakes

  • Sharing DataLoader across requests: Causes data leaks between users and stale cache hits
  • Returning results out of order: DataLoader matches by position, so misaligned results silently return wrong data
  • Throwing in batch function: One failed key rejects the entire batch. Return new Error() per item instead
  • Not using cacheKeyFn for non-string keys: Objects as keys cause cache misses because {} !== {} by reference
  • Forgetting to clear cache on mutations: After updating a user, call loader.clear(id) to prevent stale reads

Detailed Scenario: Users and Orders

A one-to-many field is the most common N+1 source. Here each user loads its orders through a loader that groups rows back per key:

import DataLoader from "dataloader";

const orderLoader = new DataLoader<string, Order[]>(async (userIds) => {
  // One query for every user in the batch
  const res = await db.query(
    "SELECT * FROM orders WHERE user_id = ANY($1)",
    [userIds]
  );

  // Group rows by user_id so each key gets its own list
  const ordersByUser = new Map<string, Order[]>();
  for (const order of res.rows) {
    const list = ordersByUser.get(order.user_id) || [];
    list.push(order);
    ordersByUser.set(order.user_id, list);
  }
  // Return one entry per key, in key order
  return userIds.map((id) => ordersByUser.get(id) || []);
});

const resolvers = {
  User: {
    orders: (parent: User) => orderLoader.load(parent.id),
  },
};

{ users { orders { id } } } over 100 users goes from 101 queries to 2. The same grouping pattern works for any 1:N or N:1 relationship; for many-to-many, join through the link table and group by the parent’s key.

See Also

Frequently Asked Questions

Does DataLoader work with subscriptions?

It does, though events arrive over time rather than in one execution pass, so the batching window behaves differently. For subscriptions, consider a shorter batch interval or disabling batching for latency-sensitive fields.

How is this different from the DataLoader pattern?

The batched resolver pattern is the broader concept: any strategy that coalesces per-item fetches into one call. DataLoader is the standard JavaScript implementation, and the one you'll meet in the wild. You can also batch with custom logic, Redis pipelines, or GraphQL.js's info field collection.

Can I batch mutations?

Not directly; mutations execute sequentially by design. If clients need to write several records, give them one mutation that takes a list (say createPosts(input: [PostInput!]!)) instead of fanning out separate mutation calls.

What about batching in a federated graph?

Apollo Federation's query planner already coalesces entity resolution across subgraphs via _entities. You still need batching inside each subgraph for its own database calls, but not usually for cross-service fields.

How do I configure DataLoader in Apollo Server?

Create the loaders inside the context factory so they live for exactly one request: context: async () => ({ loaders: createLoaders(db) }). Sharing a loader across requests is the dangerous version: its cache can leak one user's rows into another user's response. When you want caching that outlives one request, reach for Redis or another shared store rather than the DataLoader cache.