GraphQL
Data loaders
Stop the N+1 problem: one batch call instead of fifty.
The N+1 problem
Ask for 50 books and their authors:
{ books { title author { name } } }The books resolver makes 1 database call. Then GraphQL calls the author resolver once per book: 50 more calls. That is "N+1", and it makes GraphQL APIs slow and databases busy.
The fix: a batch loader
A batch loader collects the keys asked for during one request, then answers them all at once:
@Resolver
class BookResolvers(private val repo: AuthorRepository) {
// 1. The loader: receives ALL the ids at once, returns one value per id, IN THE SAME ORDER
@BatchLoader("authors")
fun authors(ids: List<String>): List<Author?> {
val found = repo.findByIdIn(ids) // one query for every author
return ids.map { id -> found.firstOrNull { it.id == id } }
}
// 2. The resolver asks for it with a parameter NAMED after the loader
@ResolveField("Book")
fun author(book: Book, authors: DataLoader<String, Author?>) = authors.load(book.authorId)
}authors.load(key) does not call the database: it records the key and returns a promise. When the resolvers for all 50 books have asked, the loader runs once with the 50 keys (duplicates folded, so 3 distinct authors means 3 keys), and each promise is completed.
Rules:
- The loader must return one value per key, in the same order (use
nullfor a missing one), or aMap<key, value>. - Each request has its own loaders, so values are never cached across users. (This is also why a loader is safe for data that depends on who is asking.)
- A loader runs on a virtual thread, so it can do blocking work.
- Use a loader whenever a field resolver does a lookup by an id that varies per parent. A field that is the same for everyone (a constant) does not need one.
Tested
Six posts with three distinct authors made one call to the loader with three keys, and a second request batched again independently.