Performance: N+1 and DataLoader
Batch and cache field resolution to stay fast.
The Silent Killer: N+1
GraphQL's biggest performance trap is the N+1 query problem. It is silent because each resolver looks innocent in isolation — but nest a list and a per-item field, and you fire one query for the list plus one query per item. At 100 items that is 101 round trips. This lesson shows how to collapse them into a handful of batched queries with DataLoader.
Seeing N+1 Concretely
Consider { posts { author { name } } }. The posts resolver runs one query. Then for each post, the author resolver runs its own query. The naive code below makes the cost obvious.
<?php
// 1 query for posts...
$posts = [['id'=>1,'author_id'=>7],['id'=>2,'author_id'=>7],['id'=>3,'author_id'=>9]];
$queries = 1;
foreach ($posts as $post) {
// ...then 1 query PER post to fetch its author
$queries++;
// SELECT * FROM users WHERE id = $post['author_id']
}
echo "Total DB queries: {$queries}\n"; // Total DB queries: 4
All lessons in this course
- GraphQL vs REST
- Building a Schema with graphql-php
- Resolvers, Mutations and Subscriptions
- Performance: N+1 and DataLoader