Skip to the page

GraphQL in production · mid

The N+1 problem and DataLoader

GraphQL runs a resolver once for every object in a list, so a naive server sends one SQL query per object. A DataLoader created for each request collects the keys asked in one tick of the event loop and sends one batched query.

The notes

What you must know

  • A resolver runs once per object. 500 restaurants with 50 menu items each means tens of thousands of resolver calls. If each one runs a SQL query, that is the N+1 problem.
  • DataLoader collects every load(key) call made in the same tick of the event loop and calls your batch function once with all the keys. Fifty resolver calls become one query like WHERE id = ANY($1).
  • The batch function must return an array with the same length and the same order as the keys. SQL IN returns rows in any order and skips missing ids, so build a Map by id and return map.get(id) ?? null for each key.
  • Create the loaders when the request context is built, one set per request. DataLoader also caches by key, and a cache shared between requests would show one user's data to another and go stale.
  • load() returns a promise for one key. loadMany() is the same for several keys. A batch function that throws fails every key in the batch, so return an Error object for one bad key.
  • Prove the fix with a test that counts SQL queries for one operation. The count must stay flat when the list grows.
  • In other stacks use the framework batch loader, for example Java DataLoader or Python aiodataloader.

The red pen

Common traps: mistake → fix

  • Mistake: Resolvers run in parallel, so GraphQL already batches database calls

    Fix: Nothing batches by itself. Parallel resolvers still each send their own query until you add a loader.

  • Mistake: One global DataLoader is faster because the cache lives longer

    Fix: A global loader leaks data between users and serves stale rows. Create it per request.

  • Mistake: The batch function may return rows in any order

    Fix: It must return results in the same order and length as the keys, with null for a missing key.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the N+1 problem in GraphQL? Give an example.
  2. How does DataLoader know which calls to put in one batch?
  3. What must a DataLoader batch function guarantee about its return value?
  4. Why do you create loaders per request and not once at startup?
  5. A page of 50 orders runs 51 queries. How do you find the cause and prove the fix?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview