Thuta Learning
GraphQL
ExercisesWeb Developmentbeginner

Exercise — Debug an N+1 Query

What you'll walk away with

  • Explain the core ideas behind Exercise — Debug an N+1 Query
  • Run the sample GraphQL query or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

Lesson 14 covered the root cause of the N+1 problem — a list field whose per-item resolver fires a separate database query for each item. This exercise asks you to spot that pattern in a real code snippet, diagnose it, fix it with DataLoader, and verify the fix — in production, you can also notice N+1 from database query logs, where query count scales with list size.

Connect it to a real scenario

The Tutorial Platform's database query log shows `SELECT * FROM authors WHERE id = ?` repeating once per tutorial whenever the tutorials list resolves through `Tutorial.author` — identify this bug and convert it into one batched query using `authorLoader`.

Try the working example

javascript
// Buggy: fires one query per tutorial
const resolvers = {
  Tutorial: {
    author: async (tutorial) => {
      return db.author.findUnique({ where: { id: tutorial.authorId } });
    },
  },
};

// Your task: rewrite this resolver to use a DataLoader
// so N tutorials cause exactly one authors query.
You should see
You can spot an N+1 bug in resolver code and write a DataLoader-based fix yourself.

5-minute try-it

Rewrite the buggy resolver above using an `authorLoader` (following lesson 14's example). After the fix, state how many author queries would run for 10 tutorials.

One important caution

Fixing it with a simple in-memory object cache that has no request boundary can keep serving stale data across new requests — keep the DataLoader instance request-scoped inside context.

Apollo Server — Batching with DataLoaderGraphQL

Easy traps

  • Fixing it with a simple in-memory object cache that has no request boundary can keep serving stale data across new requests — keep the DataLoader instance request-scoped inside context.
  • Validate sample queries and mutations on a local or test server with recoverable data before applying them to production.

Exercise

Rewrite the buggy resolver above using an `authorLoader` (following lesson 14's example). After the fix, state how many author queries would run for 10 tutorials.

You'll know it worked when: You can spot an N+1 bug in resolver code and write a DataLoader-based fix yourself.

Exercise — Debug an N+1 Query | Thuta Learning