Apollo Server and TypeORM: N+1 User Queries Even Though a DataLoader Is in the Context

TechLab Editorial TeamPublished 74 views1 answer
0

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

The problem

A product catalog API built with Apollo Server 4, TypeGraphQL and TypeORM returns products, their reviews, and each review's author. A DataLoader for users is created once per request and placed in the context to batch author lookups, but the database still receives one user query per review.

Stack:

  • Node.js: 22
  • Apollo Server: v4.x
  • TypeORM: v0.3.x (with PostgreSQL v14 as the database)
  • dataloader library: v2.x
  • type-graphql: v2.x (for schema and resolver generation)

What happens: fetching 10 products with 5 reviews each produces 50 separate SELECT ... FROM users WHERE id = $1 queries, instead of one batched query for the distinct author IDs.

The relevant code, simplified:

src/index.ts (Apollo Server Setup & Context):

TypeScript
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSchema } from 'type-graphql';
import { AppDataSource } from './data-source'; // TypeORM data source
import { ProductResolver } from './resolvers/ProductResolver';
import { ReviewResolver } from './resolvers/ReviewResolver';
import { UserDataLoader } from './dataLoaders'; // DataLoader factory
import { User } from './entities/User';
import { Repository } from 'typeorm';

export interface MyContext {
  dataSources: {
    userRepository: Repository<User>;
  };
  dataLoaders: {
    userLoader: UserDataLoader;
  };
}

async function main() {
  await AppDataSource.initialize();

  const schema = await buildSchema({
    resolvers: [ProductResolver, ReviewResolver],
  });

  const server = new ApolloServer<MyContext>({ schema });

  const { url } = await startStandaloneServer(server, {
    context: async ({ req, res }) => { // DataLoader instance created once per request
      const userRepository = AppDataSource.getRepository(User);
      const userLoader = new UserDataLoader(userRepository);
      return {
        dataSources: {
          userRepository,
        },
        dataLoaders: {
          userLoader,
        },
      };
    },
  });

  console.log(`🚀 Server ready at ${url}`);
}

main().catch(console.error);

src/dataLoaders.ts (User DataLoader Definition):

TypeScript
import DataLoader from 'dataloader';
import { In, Repository } from 'typeorm';
import { User } from './entities/User';

export class UserDataLoader extends DataLoader<string, User | null> {
  constructor(userRepository: Repository<User>) {
    super(async (userIds: readonly string[]) => {
      // This batch function should ideally be called once per request for all unique user IDs.
      console.log(`[DataLoader] Fetching users for IDs: ${userIds.join(', ')}`);
      const users = await userRepository.findBy({ id: In(userIds as string[]) });
      const userMap = new Map(users.map(user => [user.id, user]));
      return userIds.map(id => userMap.get(id) || null);
    });
  }
}

src/entities/User.ts, Product.ts, Review.ts (Simplified for brevity):

TypeScript
// Example User entity
import { BaseEntity, Column, Entity, PrimaryColumn } from 'typeorm';
@Entity()
export class User extends BaseEntity {
  @PrimaryColumn() id: string;
  @Column() name: string;
}

// Example Product entity (similar structure for Review)
import { BaseEntity, Column, Entity, OneToMany, PrimaryColumn } from 'typeorm';
import { Review } from './Review';
@Entity()
export class Product extends BaseEntity {
  @PrimaryColumn() id: string;
  @Column() name: string;
  @OneToMany(() => Review, review => review.product)
  reviews: Review[];
}

// Example Review entity
import { BaseEntity, Column, Entity, ManyToOne, PrimaryColumn } from 'typeorm';
import { Product } from './Product';
import { User } from './User';
@Entity()
export class Review extends BaseEntity {
  @PrimaryColumn() id: string;
  @Column() rating: number;
  @Column() comment: string;
  @Column() authorId: string; // Foreign key
  @ManyToOne(() => User) author: User;
  @ManyToOne(() => Product, product => product.reviews) product: Product;
}

src/resolvers/ProductResolver.ts (Querying Products and Reviews):

TypeScript
import { Resolver, Query, FieldResolver, Root } from 'type-graphql';
import { Product } from '../entities/Product';
import { Review } from '../entities/Review';
import { AppDataSource } from '../data-source';

@Resolver(Product)
export class ProductResolver {
  @Query(() => [Product])
  async products(): Promise<Product[]> {
    // Eagerly load reviews here to avoid N+1 for reviews themselves.
    return AppDataSource.getRepository(Product).find({ relations: ['reviews'] });
  }

  @FieldResolver(() => [Review])
  reviews(@Root() product: Product): Review[] {
    return product.reviews; // Reviews are already loaded by `products` query
  }
}

src/resolvers/ReviewResolver.ts (Field Resolver for Author):

TypeScript
import { Resolver, FieldResolver, Root, Ctx } from 'type-graphql';
import { Review } from '../entities/Review';
import { User } from '../entities/User';
import { MyContext } from '../index';

@Resolver(Review)
export class ReviewResolver {
  @FieldResolver(() => User)
  async author(@Root() review: Review, @Ctx() ctx: MyContext): Promise<User | undefined> {
    console.log(`[ReviewResolver] Attempting to fetch author ${review.authorId} directly.`);
    const user = await ctx.dataSources.userRepository.findOne({ where: { id: review.authorId } });
    return user || undefined;
  }
}

Expected behaviour: A GraphQL query for products, their reviews, and each review's author (e.g., products { id name reviews { id rating author { id name } } }) should result in:

  1. One query for all requested products (with reviews eagerly loaded).
  2. A single batch query for all unique authorIds across all fetched reviews, executed by the UserDataLoader.

Actual behaviour: Products and reviews load in one query, but the database log shows one users query per review, and the [DataLoader] Fetching users for IDs: message never appears.

The question: why isn't the DataLoader batching these lookups?

Advertisement

1 Answer

0

The DataLoader is set up correctly (one instance per request, in the context), and its batch function is fine. It's simply never called: the author resolver queries the repository directly.

Root Cause of the N+1 Problem

ctx.dataSources.userRepository.findOne(...) runs a query immediately, once per review. Batching only happens through loader.load(id): DataLoader collects every load() call made in the same tick of the event loop, then calls the batch function once with all the keys (de-duplicated, so 50 reviews by 12 distinct authors produce one query for 12 IDs).

GraphQL executes the author resolver for every review in the list before awaiting any of them, which is why all 50 load() calls land in the same tick and batch together. Leaving the repository in the context makes this mistake easy, so it's worth removing it from the context once loaders exist for each relationship.

Corrected Code Block

To fix this, you need to modify the ReviewResolver to use the userLoader instance from your context for fetching the author, rather than directly querying the userRepository.

TypeScript
// src/resolvers/ReviewResolver.ts (Corrected)
import { Resolver, FieldResolver, Root, Ctx } from 'type-graphql';
import { Review } from '../entities/Review';
import { User } from '../entities/User';
import { MyContext } from '../index';

@Resolver(Review)
export class ReviewResolver {
  @FieldResolver(() => User)
  async author(
    @Root() review: Review,
    @Ctx() ctx: MyContext
  ): Promise<User | null> { // Return type can be User | null, DataLoader returns null for unfound keys
    // CORRECTED: Use the DataLoader from context to fetch the author.
    // DataLoader will batch all calls to .load() within the same event loop tick.
    console.log(`[ReviewResolver] Using DataLoader to fetch author ${review.authorId}.`);
    const user = await ctx.dataLoaders.userLoader.load(review.authorId);
    return user; // DataLoader returns null if the user is not found, or the User object.
  }
}

Explanation of Changes:

  1. ctx.dataLoaders.userLoader.load(review.authorId): This is the key change. Instead of ctx.dataSources.userRepository.findOne(...), we now call load() on the userLoader instance. Each call to load() for a given authorId will be collected by the DataLoader.
  2. Batching in Action: When the GraphQL query resolves author for multiple reviews, all load(authorId) calls will be queued. Before the event loop continues, DataLoader will gather all unique authorIds from these calls and execute its batch function (defined in UserDataLoader's constructor) once with all the collected IDs. This results in a single database query for all users, dramatically reducing the database load and eliminating the N+1 problem.
  3. Return Type Consistency: Changed Promise<User | undefined> to Promise<User | null> for the author resolver, as DataLoader returns null for keys not found by its batch function, which is a common convention.
  1. DataLoader Scope (Instantiation): While you've correctly instantiated UserDataLoader once per request in your context function, it's a common mistake to instantiate a new DataLoader inside a resolver function. If you do this, each resolver call gets its own DataLoader instance, defeating the entire purpose of batching, as no two calls will ever hit the same DataLoader to be batched. Always ensure DataLoader instances are unique per request and passed through the context.
  2. Awaiting before load(): if a resolver awaits something else (a permission check, another query) before calling load(), its load() lands in a later tick and may not batch with the others. Call load() first, or make the earlier step use a loader too.
  3. Batch function contract: the batch function must return results in the same order as the keys, one per key. The userMap lookup in UserDataLoader does that, returning null for missing users. Returning the raw findBy result (which has no guaranteed order and skips missing rows) is a common bug that attaches users to the wrong reviews.
  4. Loading a relation directly: if a resolver usually needs the author anyway, joining it in the original query (relations: ['reviews', 'reviews.author']) avoids the second query entirely. DataLoader is most useful when the field is only sometimes requested.

💡 Bonus Tip: Monitoring and Tracing N+1 Issues

Catch N+1 problems before they reach production:

  • Log queries in development: TypeORM's logging: ['query'] option prints every SQL statement, so 50 near-identical queries for one GraphQL request are obvious.
  • Trace resolvers: Apollo Server 4 can report per-field timings to Apollo GraphOS through its usage reporting plugin, or you can instrument resolvers and database calls with OpenTelemetry. A trace that shows one database span per list item is the telltale pattern.
  • Test query counts: in integration tests, count the queries a representative GraphQL request makes (for example with a TypeORM logger or subscriber) and fail the test if the count grows with the number of items returned.
TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.