Skip to content
API Design Learn/GraphQL Foundations
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Resolvers & the N+1 Problem

5 min read

You'll learn to

  • -Explain what a resolver is and why GraphQL runs one for every field
  • -Count the database queries a naive resolver makes and show why the count grows with the list size
  • -Use batching (the idea behind DataLoader) to turn N+1 queries into 2
  • -Know why a DataLoader must be created per request, and which caching and computed-field tools are real GraphQL features and which come from frameworks

In GraphQL, every field in the schema has a small server-side function behind it, called a resolver, whose only job is to produce that field's value. When a client asks for a user's name, one resolver returns the name. When it asks for the user's orders, another resolver goes and fetches them. This per-field design is what lets clients ask for any shape of data they like, and it is also the direct cause of GraphQL's most famous performance problem.

An Analogy: A Waiter and the Pantry

Ten tables each order soup. A naive waiter walks to the pantry for table one, returns, walks back for table two, and so on: ten trips. A smart waiter writes all ten orders on a notepad, makes one trip, and brings back ten bowls. The food is identical. Only the number of trips differs, and trips are the expensive part.

  • -A trip to the pantry is a database query.
  • -A table is one item in a list, such as one user.
  • -The naive waiter is a resolver that runs a query for every item.
  • -The notepad is the batching layer, a DataLoader, which collects requests and sends them together.

How Resolvers Execute

A query that touches three different resolvers
query {
  users(limit: 10) {
    name
    orders {
      total
    }
  }
}

The users resolver runs once and fetches 10 users. Then, if written naively, the orders resolver runs once for each user returned: 10 separate calls, each fetching one user's orders. That is the N+1 problem: 1 query for the parent list plus N queries, one per item, for the related data. A hand-written REST endpoint would usually fetch both with a single join.

Counting the Queries

Run the code below. A fake database counts every trip it is asked to make. The first half works the naive way. The second half collects the user IDs first, as a DataLoader does, and asks once.

The same ten users and their orders, fetched two ways

The naive version made 11 queries and the batched version made 2. Now scale it to the question in the signal for this chapter: 50 users and each user's recent orders. The naive way makes 51 queries, and the batched way still makes 2. The count grows with the list for the naive resolver, and stays flat for the batched one.

DataLoader: Batching Within a Single Request

A real DataLoader does what the little loader above does. Calling load() does not run anything. It records the key and returns a promise, a placeholder for a value that arrives later. After the resolvers for all the sibling fields have had a chance to ask, the loader fires one batched call with every collected key, then hands each caller its own result. GraphQL's execution engine makes this possible, because it asks for all sibling fields before waiting on any of them.

A DataLoader-style resolver (library shown schematically)
order_loader = DataLoader(batch_load_fn=lambda user_ids:
    db.query("SELECT * FROM orders WHERE user_id IN ?", user_ids)
)

def resolve_orders(user, info):
    return order_loader.load(user.id)   # queued, not executed immediately

# 10 users -> 10 load() calls queued -> exactly ONE batched query executed

Create DataLoader instances fresh for every request, never share them globally. A DataLoader also caches the results it has loaded. A long-lived, shared one would serve stale data, or worse, show one user's data to another. Think of it as a notepad you throw away at the end of every shift.

Computed Fields and Caching: What Is Standard and What Is Not

A computed field is simply a field whose resolver works out its value instead of reading a column: fullName built from firstName and lastName, or orderCount counted from a user's orders. No special syntax is needed. The resolver is the computation.

Caching is different. GraphQL itself has no @cache or @computed annotation. The only directives built into the language are @skip, @include, @deprecated and @specifiedBy. Directives such as Apollo Server's @cacheControl(maxAge: 60) are added by a framework, and you can define your own. Common caching tools are DataLoader's per-request cache, an HTTP or CDN cache in front of persisted queries, and a cache such as Redis used inside a resolver for values that change slowly, like an order count refreshed every few minutes.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

Ready to Build This?

Design The Resolver Graph in the API Design Lab's GraphQL Mastery act.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!