StackPractices
intermediate By Mathias Paulenko

Detect and Fix N+1 Queries in GraphQL Resolvers

Identify N+1 query problems in GraphQL resolvers using logging, DataLoader, and query analysis tools before they hit production

Overview

N+1 queries are the most common performance problem in GraphQL APIs. Ask for 20 posts and their authors, and a naive resolver issues one query for the list plus one per post — 21 round trips where 2 would do. This recipe shows how to catch that pattern during development by counting queries per request, and how to fix it with DataLoader batching.

When to Use This

  • GraphQL queries are slow under load but fast for single items
  • Database connection counts spike during list queries
  • You want to catch N+1 issues in development or CI before they reach production
  • Skip this if your resolvers only fetch flat resources with no nested relations — there’s nothing to batch

Prerequisites

  • A GraphQL server with resolvers that fetch related data (the examples use Apollo Server 4 and TypeScript)
  • A database client you can wrap or extend (Prisma, an ORM, or a thin data-access layer)

Solution

1. Instrument the Database Client

Wrap your database client in a proxy that records every call into a per-request QueryLog:

// db/instrumented.ts
export interface QueryLog {
  count: number;
  queries: string[];
}

export function instrumentDbClient(db: any, queryLog: QueryLog) {
  const handler: ProxyHandler<any> = {
    get(target, prop) {
      const original = target[prop];
      if (typeof original === 'function') {
        return (...args: any[]) => {
          queryLog.count++;
          queryLog.queries.push(`${String(prop)}(${JSON.stringify(args[0] ?? {})})`);
          return original.apply(target, args);
        };
      }
      if (original && typeof original === 'object') {
        return new Proxy(original, handler);
      }
      return original;
    },
  };

  return new Proxy(db, handler);
}

2. Create the Query Log in the Context Function

The wiring lives in Apollo’s context function: every request gets a fresh QueryLog and its own instrumented client, so counters never leak between requests:

// server.ts
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { instrumentDbClient, type QueryLog } from './db/instrumented';
import { queryLoggerPlugin } from './middleware/queryLogger';

interface Context {
  db: ReturnType<typeof instrumentDbClient>;
  queryLog: QueryLog;
  loaders: { user: ReturnType<typeof createUserLoader> };
}

const server = new ApolloServer<Context>({
  typeDefs,
  resolvers,
  plugins: [queryLoggerPlugin],
});

const { url } = await startStandaloneServer(server, {
  context: async () => {
    const queryLog: QueryLog = { count: 0, queries: [] };
    return {
      queryLog,
      db: instrumentDbClient(db, queryLog),
      loaders: { user: createUserLoader(db) },
    };
  },
});

3. Read the Count in willSendResponse

The plugin reads the request’s QueryLog from contextValue just before the response is sent. Declaring the plugin as ApolloServerPlugin<Context> is what makes contextValue typed and accessible:

// middleware/queryLogger.ts
import type { ApolloServerPlugin } from '@apollo/server';

interface QueryLogContext {
  queryLog: { count: number; queries: string[] };
}

export const queryLoggerPlugin: ApolloServerPlugin<QueryLogContext> = {
  async requestDidStart() {
    return {
      async willSendResponse({ contextValue, operationName }) {
        const { count, queries } = contextValue.queryLog;
        if (count > 5) {
          console.warn(
            `[N+1 SUSPECT] ${count} queries for operation: ` +
            `${operationName ?? 'anonymous'}\n` +
            queries.slice(0, 10).map((q, i) => `  ${i + 1}. ${q}`).join('\n')
          );
        }
      },
    };
  },
};

4. The N+1 Problem — Before

// BEFORE — N+1 problem
const resolvers = {
  Query: {
    posts: () => db.posts.findMany({ take: 20 }),
  },

  Post: {
    // This runs once per post — 20 posts = 20 queries
    author: (post: { authorId: string }) =>
      db.users.findById(post.authorId),
  },
};

A query for 20 posts with their authors produces 21 queries: 1 for posts + 20 for authors.

5. The Fix — After with DataLoader

// AFTER — batched with DataLoader
import DataLoader from 'dataloader';

function createUserLoader(db: any) {
  return new DataLoader<string, any>(async (userIds: readonly string[]) => {
    const users = await db.users.findMany({
      where: { id: { in: [...userIds] } },
    });
    const userMap = new Map(users.map((u) => [u.id, u]));
    return userIds.map((id) => userMap.get(id));
  });
}

const resolvers = {
  Query: {
    posts: (_: unknown, __: unknown, ctx: Context) =>
      ctx.db.posts.findMany({ take: 20 }),
  },

  Post: {
    // DataLoader batches all authorIds into one query
    author: (post: { authorId: string }, _: unknown, ctx: Context) =>
      ctx.loaders.user.load(post.authorId),
  },
};

The same query now produces 2 queries: 1 for posts + 1 batched query for all authors. The DataLoader batching recipe covers caching and cache invalidation within a request in more depth.

Flowchart comparing the N+1 pattern (21 queries) with DataLoader batching (2 queries)

6. Limit Query Complexity

Batching fixes queries that run; complexity limits stop expensive queries from running at all. In Apollo Server 4, compute the cost inside didResolveOperation and reject queries above a threshold:

npm install graphql-query-complexity
import { getComplexity, simpleEstimator } from 'graphql-query-complexity';
import { GraphQLError } from 'graphql';

const complexityPlugin: ApolloServerPlugin<Context> = {
  async requestDidStart() {
    return {
      async didResolveOperation({ schema, document, request }) {
        const complexity = getComplexity({
          schema,
          query: document,
          variables: request.variables,
          estimators: [simpleEstimator({ defaultComplexity: 1 })],
        });
        if (complexity > 1000) {
          throw new GraphQLError(`Query complexity ${complexity} exceeds limit 1000`);
        }
      },
    };
  },
};

How It Works

  1. The context function creates a fresh QueryLog and instrumented client per request, so counts never leak between operations or users.
  2. The proxy sits between resolvers and the client, so calls like db.users.findMany get logged before they run — nested objects included. Calls that go through DataLoader reach the client once per batch, so the count reflects real database traffic, not resolver calls.
  3. willSendResponse reads the final count from contextValue when execution is done; no hook is needed while resolvers run.
  4. DataLoader batching collects all .load(id) calls within a single tick and dispatches them as one WHERE id IN (...) query, reducing N+1 to 2 queries.
  5. Complexity limits assign a cost to each field and reject queries that exceed the threshold before execution, while batching makes the queries that do run cheap.

Variants

Detect N+1 with OpenTelemetry Traces

Distributed tracing reveals N+1 patterns across services — the OpenTelemetry guide covers the full setup:

import { trace } from '@opentelemetry/api';

const tracer = trace.getTracer('graphql');

const resolvers = {
  Post: {
    author: (post, _, ctx) => {
      return tracer.startActiveSpan('resolve.post.author', (span) => {
        return ctx.db.users.findById(post.authorId).finally(() => span.end());
      });
    },
  },
};

In the trace viewer, 20 sequential resolve.post.author spans under one request are a clear N+1 signal.

Assert Query Counts in Tests

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

test('posts query should not produce N+1', async () => {
  const queryLog = { count: 0, queries: [] as string[] };

  const server = new ApolloServer({ typeDefs, resolvers });
  await server.executeOperation(
    { query: 'query { posts { id title author { name } } }' },
    { contextValue: { db: instrumentDbClient(db, queryLog), loaders } }
  );

  expect(queryLog.count).toBeLessThanOrEqual(2);
});

Count Queries with a Prisma Client Extension

Prisma’s $extends API (which replaced the deprecated $use middleware) counts every operation. Create the queryLog per request and pass the extended client through context:

const countingPrisma = prisma.$extends({
  query: {
    $allModels: {
      async $allOperations({ model, operation, args, query }) {
        queryLog.count++;
        queryLog.queries.push(`${model}.${operation}`);
        return query(args);
      },
    },
  },
});

Best Practices

  • Log query counts in development — catch N+1 before it reaches staging.
  • Use DataLoader for every relation — even if you think a list will always have one item; clients can request deeper nesting than you expect.
  • Instantiate loaders inside the context function — they belong to the request lifecycle, not the module scope.
  • Assert query counts in tests — expect(queryLog.count).toBeLessThanOrEqual(2) turns a performance fix into a regression test.
  • Monitor counts in production — alert when an operation’s query count exceeds a threshold instead of waiting for the database to slow down.

Common Mistakes

  • Only fixing N+1 for list queries — a single-item query with deeply nested selections can N+1 just as hard.
  • Sharing a DataLoader across requests — its cache survives into the next request and can serve one user’s data to another. Keep it inside the context function.
  • Awaiting .load() in a loop — sequential awaits defeat batching; let field resolvers run in parallel or use Promise.all.
  • Not measuring after the fix — a passing test that still issues 50 queries is a future incident; verify the count actually dropped.

Troubleshooting

  • DataLoader returns mismatched rows: your batch function owes DataLoader one value per input key, in the same order. Map results back by key — like userMap above — rather than returning the raw findMany output.
  • Still N+1 after adding DataLoader: check for sequential await loader.load(id) in a loop — batching only collects calls within the same tick.
  • Query count grows across requests: the loader or QueryLog was created at module level. Move both inside the context function.
  • Batched query returns undefined for missing IDs: DataLoader requires one value per key. Return null explicitly for absent rows.
  • The warning fires for cheap operations: the threshold is too low, or the counter is wrapping more than the DB client. Scope instrumentation to the data layer only — DataLoader calls reach it already batched.

Further Reading

Frequently Asked Questions

How many queries is too many?

A good rule: 1 query per top-level field plus 1 batched query per relation. A list of 20 posts with authors should cost 2 queries, not 21. Treat the threshold of 5 as a starting point — set it above your worst legitimate operation.

Can I still have N+1 with DataLoader?

Yes. Awaiting .load() sequentially in a loop prevents batching, creating a loader per field access defeats it, and a batch function that falls back to individual lookups on cache misses reintroduces it.

Does N+1 only affect databases?

No. Any per-item external call can N+1: REST APIs, gRPC services, Redis, S3. DataLoader batches any function that accepts a list of keys, not just SQL.

Should I use query complexity limits instead of DataLoader?

They solve different problems. Complexity limits reject expensive queries before they run; DataLoader makes the queries that do run cheap. Use both — limits as the guardrail, batching as the fix.

How do I detect N+1 in production without logging every query?

Sample it. Keep full logging in development and staging; in production, count queries on a percentage of requests or trace them with OpenTelemetry, and alert on the distribution rather than the average — N+1 shows up as a fat tail.

What happens if the same ID is loaded twice in one request?

DataLoader dedupes keys within a request-scoped instance. posts { author } and comments { author } referencing the same user produce a single batched fetch, not two.