GraphQL N+1 problem and DataLoader batching

Difficulty: Advanced

Question

What is the N+1 problem in GraphQL and how does DataLoader solve it?

Answer

Here's the intuition. Imagine you are a waiter with a list of 50 tables, and each table needs a jug of water. The N+1 way is to walk to the tap 50 separate times. The batched way is to fill 50 glasses in one trip. GraphQL resolvers, by default, behave like the first waiter.

Why it happens: in GraphQL each field has its own resolver function, and resolvers run independently per parent object. Take the query orders(first: 50) { id customer { name } }. One query fetches 50 orders (that's the 1). Then the customer resolver runs once for each order, issuing SELECT * FROM users WHERE id = ? fifty times (that's the N). With nested fields the numbers multiply, and a page that should take three queries takes hundreds, wrecking latency and database load. Note the same issue exists in ORMs with lazy loading; GraphQL simply makes it easy to trigger accidentally, because resolvers are written in isolation and do not see each other.

DataLoader, created at Facebook, solves this with two ideas: batching and per-request caching. You create a loader with a batch function that takes an array of keys and returns a promise of an array of results in the same order and length. When a resolver calls loader.load(userId), the loader does not fetch immediately. It collects all keys requested during the current tick of the event loop (using process.nextTick or promise microtask scheduling), then invokes the batch function once with all of them: SELECT * FROM users WHERE id IN (...). Each caller's promise resolves with its own value. So 50 loads collapse into one query. The caching part memoises by key within the loader instance, so if the same user appears in ten orders, they are fetched once.

Critical implementation details. First, the batch function must return results ordered exactly as the keys, with an entry (or an Error, or null) for each missing key; a common bug is returning DB rows in arbitrary order. Second, create new loader instances per request, typically in the GraphQL context, never globally: otherwise the cache leaks data between users and becomes stale, a security and correctness issue. Third, loaders batch only within a tick, so resolvers should call load() promptly and not after awaiting unrelated work. Fourth, for one-to-many relations, key by parent id and group results: a loader from orderId to items[].

Alternatives and complements: join monster or query planners that translate GraphQL selections into joins; looking ahead at the selection set (info argument) to eagerly load relations at the parent resolver; and in Prisma, its own built-in batching of findUnique calls. For federation, entity resolvers use the _entities batch by design. Also protect the server: enforce query depth limits, complexity/cost analysis, persisted queries, and pagination arguments on list fields, since DataLoader fixes N+1 but not unbounded fan-out.

How to prove it in an interview: mention logging query counts per request; before, 51 queries; after, 2. Also mention the REST analogue: over-eager lazy loading in ORMs, solved by eager joins or IN queries.

So the summary is that N+1 arises from per-field resolvers, and DataLoader turns many single lookups into one batched lookup with per-request caching.

Code examples

DataLoader for users

import DataLoader from 'dataloader';

const makeLoaders = () => ({
  userById: new DataLoader(async (ids) => {
    const rows = await db.user.findMany({ where: { id: { in: [...ids] } } });
    const byId = new Map(rows.map((u) => [u.id, u]));
    return ids.map((id) => byId.get(id) ?? new Error('User ' + id + ' not found'));
  })
});

// per request, not global
const server = new ApolloServer({ typeDefs, resolvers });
startStandaloneServer(server, { context: async () => ({ loaders: makeLoaders() }) });

const resolvers = {
  Order: {
    customer: (order, _args, { loaders }) => loaders.userById.load(order.customerId)
  }
};

Fifty customer resolver calls become one IN query; results are re-ordered to match the keys.

Key points

Common follow-up questions

Interview tips

Concepts covered

GraphQL, N+1, DataLoader, batching

More API Design questions