0Pricing
Spring Boot 4 Complete Guide · Lesson

Solving N+1 with Batch Loaders

Eliminate the N+1 problem using @BatchMapping and DataLoader-style batched resolution.

What the N+1 Problem Looks Like

In GraphQL, fields are resolved lazily. When a query asks for a list of objects and then a nested field on each one, Spring for GraphQL calls the nested resolver once per parent.

  • 1 query to fetch N authors
  • N extra queries to fetch each author's books

That is N+1 database round-trips. With 100 authors you fire 101 queries. This is the single biggest performance killer in naive GraphQL APIs, and batching is the cure.

The Naive @SchemaMapping Resolver

Here is the per-parent resolver that causes N+1. For every Author in the result set, Spring invokes books separately, each issuing its own SQL query.

It is correct, but it does not scale. Notice there is no batching at all: one author in, one DB call out.

@Controller
public class AuthorController {

    private final BookRepository books;

    public AuthorController(BookRepository books) {
        this.books = books;
    }

    // Called once PER author -> N+1
    @SchemaMapping(typeName = "Author")
    public List<Book> books(Author author) {
        return books.findByAuthorId(author.id());
    }
}

All lessons in this course

  1. Schema-First Design and Type Mapping
  2. Data Fetchers and Argument Binding
  3. Solving N+1 with Batch Loaders
  4. Subscriptions, Errors, and Schema Security
← Back to Spring Boot 4 Complete Guide