⬡ GraphQL Beginner

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

Answer

DataLoader is a utility (originally from Facebook, now open-source) that batches and caches database requests within a single request/tick cycle. It works in two phases: (1) Batching: during a single event loop tick, all calls to dataloader.load(id) are collected; at the end of the tick, the batch function is called once with all collected IDs: async (ids) => db.users.findAll({ where: { id: ids } }) — one query for all. (2) Caching: within a single request, loading the same ID twice returns the cached result. Example: const userLoader = new DataLoader(ids => UserModel.findAll(ids));. In resolvers: resolve: (post) => context.loaders.user.load(post.authorId). DataLoader is per-request (not global) to ensure cache isolation between users. It is the standard solution for N+1 in GraphQL servers.