The N+1 problem

Intermediate · 16 min

Per-field resolvers turn one list query into 1 + N database calls. Count the queries, see why GraphQL invites it, and what a fix must do.

Before thisConnecting a databaseResolvers

Ben Awad · 16 min

The N+1 problem

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ben AwadReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • N+1 means one query fetches a list of N items, then a per-item resolver fires one more query for each, so N items cost N + 1 database calls.
  • GraphQL makes it easy to hit because each field resolves on its own, with no view of its siblings, and the client decides how deep to nest.
  • Measured on a SQLite-backed server, 3 posts cost 4 queries, 10 cost 11 and 100 cost 101; the same list without the author field cost 1.
  • Nesting multiplies it: `posts { author { posts } }` over 10 posts cost 21 queries.
  • Count queries per request in a test or a debug log; a fix must collect the keys wanted in one tick and fetch them together.

The problem: correct code that is slow

Here is a schema and resolvers that look reasonable:

type Author { id: ID! name: String! }
type Post { id: ID! title: String! author: Author! }
type Query { posts(limit: Int = 10): [Post!]! }
const resolvers = {
  Query: {
    posts: (_, { limit }) => q('SELECT * FROM posts LIMIT ?', limit),
  },
  Post: {
    author: (post) => q('SELECT * FROM authors WHERE id = ?', post.author_id)[0],
  },
};

q is a small wrapper around the SQLite driver that increments a counter, so I can see what happens. Each resolver does one obvious thing. Run { posts { title author { name } } } and the answer is right. It is also slow, and gets slower as the list grows.

Counting the queries

The logged SQL for one request starts like this:

SELECT * FROM posts LIMIT ?
SELECT * FROM authors WHERE id = ?
SELECT * FROM authors WHERE id = ?
... (10 times)

I ran the same operation over different list sizes, using Yoga 6.1.0 and better-sqlite3:

{ posts { title } }                               1 query    (10 posts)
{ posts(limit: 3) { title author { name } } }     4 queries
{ posts { title author { name } } }               11 queries (10 posts)
{ posts(limit: 100) { title author { name } } }   101 queries

One query for the list, plus one per item: N + 1. The first row shows that the list alone is cheap. All the extra cost comes from selecting author.

Now notice something worse. The ten posts belong to five authors, and the server still ran ten author lookups, loading each author twice. Each Post.author call has no idea what the others fetched.

Why GraphQL makes this easy

In a REST handler you write the query for the whole page, so you write the join once. In GraphQL, resolvers are small and local, and the client picks the shape at runtime. Post.author cannot see the other ten posts being resolved at the same moment. It sees only its own post, so it does the only thing it can: fetch one author.

Think of a waiter who walks to the kitchen separately for every dish on the table, when one trip with all the orders would do. The kitchen is not slow, the walking is.

Nesting multiplies the effect. Add an author’s posts:

{ posts { author { name posts { title } } } }     21 queries (10 posts)

That is 1 + 10 authors + 10 posts-by-author queries. Another level of nesting would multiply again.

The database latency changes the stakes

My queries run in-process against SQLite, where a lookup costs microseconds, so even 101 queries finish quickly. Against Postgres on another machine, each call is a network round trip, maybe a millisecond or more. A hundred of them in a row, repeated for every user who opens the page, is the difference between a snappy page and a slow one. Do not judge N+1 by how fast your local test feels. Judge it by the count.

What a fix has to do

Two simple fixes both fail:

  • Join in the parent resolver. Query.posts could JOIN authors and attach each author to the row. It works for that one shape, but then every query that returns posts must remember to join, including the ones that do not select author, and nested shapes multiply the join cases.
  • Cache by id. A per-request cache would stop the duplicate loads of the same author. It would still do one query per distinct author, and it does not help when ids come in a sequence of calls rather than all at once.

What the problem needs is a way to say “I want author 2” from each resolver without running a query yet, and then let one piece of code collect all the requested ids in the same moment and run WHERE id IN (...) once. That is batching, and the usual implementation is a DataLoader. The next lesson builds one and runs the same count again.

Meanwhile, make N+1 visible. Count database calls per request in your tests and assert a bound that does not grow with the data. In development, log each query with the operation name. A request whose count rises with the length of a list is the signal.

What the video covers

Ben Awad’s “GraphQL N+1 Problem” is sixteen minutes from 2019 with over 118,000 views. I could not read its description or a transcript, so this lesson rests on the title: it explains the N+1 problem in GraphQL. Because it is from 2019 and likely uses a different server stack, treat the code in this lesson as the reference. Warren Day’s shorter explainer, “The GraphQL performance killer (N+1 Problem),” is listed below as a second view.

Where this fits

You can find N+1 and measure it. The fix is a small, specific library with one idea behind it. Next: DataLoader and batching.

Check yourself

  1. 01Why does `{ posts { title author { name } } }` over 10 posts run 11 queries?

    `Query.posts` runs once and returns 10 rows. Then `Post.author` runs once for every row, each doing its own `SELECT` for one author. That is 1 + 10.

  2. 02The 10 posts belong to only 5 distinct authors. Why does the naive server still run 10 author queries?

    Each `Post.author` call is independent and does not know what its siblings fetched, so the same author is loaded again for each of their posts.

  3. 03Why is N+1 especially likely in GraphQL compared with a REST endpoint?

    A REST handler can write one join for the page it returns. In GraphQL the shape is chosen by the client at query time, and each field resolves separately, so no single piece of code sees the whole picture.

  4. 04How would you detect N+1 before it reaches production?

    Count database calls per operation in tests or logs, and assert a bound. A request whose count grows with the size of a list is the warning sign.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark