What you'll learn: By the end of this lesson you will be able to explain why a GraphQL server calls a child resolver once per parent object, count the downstream calls a query really causes, fix the N+1 pattern with a Spring for GraphQL
@BatchMappingor a hand-registered DataLoader, say what a batch function must return and what happens when it fails or misses a key, and decide when batching is the right fix and when a different one is.
A concierge is asked to bring each of twelve guests their newspaper. Walking to the newsagent twelve times is slow, and most of the walking repeats. A better concierge collects the twelve names first and goes once with a list. A GraphQL server has the same trap built in: the query says "for each order, its shopper", and the engine asks for the shopper twelve separate times unless something collects the requests.
The API styles lesson covers what GraphQL promises and how its responses and errors look on the wire, and the front-end lesson covers the client's view. The ORM-level version of this problem, one SQL query per row, is in JPA and Hibernate: N+1, Lazy Loading and Batching. This lesson is about the layer above the database: the resolvers of a GraphQL server and the downstream calls they make.
Verified with Spring Boot 4.1.2, Spring for GraphQL 2.0.6 and GraphQL Java 25.1 (the versions Boot manages), compiled with --release 25 and run on a JDK 27, against the Spring for GraphQL (current documentation, 2.1.0), GraphQL Java and GraphQL specification pages, on 2026-12-01.
The core idea
GraphQL resolves each field of each object on its own. A field that needs a remote lookup, selected inside a list of N objects, runs N lookups. The fix is to collect those N requests during one query and answer them with one call; the tool that does it is a batch loader (a DataLoader).
Three illustrations run through the lesson: a minimal example (twelve orders and their shoppers, counted), a realistic example (ShopStream's order history screen, in "In practice") and a failure example (a failing or incomplete batch).
Resolvers: one function per field
The GraphQL execution guide says "each field on each type is backed by a resolver function", and that when a field returns an object, execution continues into that object's selected fields; for a list, it loads each item's fields concurrently. The specification says the executor may run a selection set's entries "in whatever order it chooses (normally in parallel)", and that for a list type each item is completed separately. Nothing in either document batches the lookups: a resolver sees one parent.
In Spring for GraphQL a resolver is a controller method. The Spring Boot reference says schema files (.graphqls or .gqls) under src/main/resources/graphql/ are picked up automatically and the HTTP endpoint is POST /graphql by default. The lab's schema is:
type Query {
orders: [Order!]!
}
type Order {
id: ID!
status: String!
shopper: Shopper
lines: [OrderLine!]!
}
The controllers page says @QueryMapping binds a method to a field under Query, and @SchemaMapping "maps a handler method to a field in the GraphQL schema and declares it to be the DataFetcher for that field"; the field name defaults to the method name and the type name to the simple class name of the parent object the method takes. That gives the naive version of the shopper field:
@SchemaMapping
Shopper shopper(Order order) {
return downstream.findShopper(order.shopperId());
}
Figure 1. The layers a query passes through. How to read this: the GraphQL layer is one endpoint. Behind it, each resolver may call a different downstream service, so the number of calls depends on the query, not on the endpoint.
Where the N+1 comes from
For { orders { id status shopper { name } } } the orders resolver runs once and returns 12 orders (the "1"). Then the shopper resolver runs once per order, each time calling the shopper service (the "N"). The query never said "twelve calls"; the shape of the data did. A query that does not select shopper runs no shopper resolver at all (row 1 of the lab), and each further nested field adds its own N (row 5).
Figure 2. The naive shape: 1 + N. How to read this: the loop is the cost. Each pass is a network round trip in a real system, and several orders share the same shopper, so many of the passes ask the same question.
The fix: collect, then call once
The idea is the DataLoader. A resolver does not call the downstream service; it asks a loader for one key and gets a future. The loader queues the keys, and when the engine has asked for all the keys at this level it calls a batch function once with the whole list. The GraphQL Java batching page says that at each level of a query dataloader.dispatch() is called to fire the batch requests for that part of the query. The java-dataloader README says loads are queued, that a load "delay[s]" execution, and that without a dispatch the futures "will never be batched". Its contract is that a batch loader must provide a value for each requested key.
Figure 3. Batching: 1 + 1. How to read this: the resolvers still run twelve times, but they only queue keys. The remote call happens once per level, when the loader is dispatched.
Spring for GraphQL offers two ways to use it.
@BatchMapping is the shortcut. The controllers page says it addresses the N+1 problem "through the use of an org.dataloader.DataLoader", and the method receives a List of parent objects and returns a Map from each parent to its value (or a Flux in the same order as the parents):
@BatchMapping
Map<Order, Shopper> shopper(List<Order> orders) {
Set<String> ids = orders.stream().map(Order::shopperId).collect(Collectors.toSet());
Map<String, Shopper> byId = downstream.findShoppers(ids);
Map<Order, Shopper> result = new HashMap<>();
for (Order order : orders) {
Shopper shopper = byId.get(order.shopperId());
if (shopper != null) result.put(order, shopper);
}
return result;
}
The page adds a caveat that matters: to be used as a unique key, the parent type "must implement hashcode and equals", which is why the lab's Order is a record.
A hand-registered DataLoader gives control of the key. The request execution page says Spring Boot declares a BatchLoaderRegistry bean, and the registry ensures DataLoader registration per request. A @SchemaMapping method can then take a DataLoader argument; by default the loader is found by the full class name of the value type:
registry.forTypePair(String.class, Shopper.class)
.registerMappedBatchLoader((ids, env) -> Mono.just(downstream.findShoppers(ids)));
@SchemaMapping
CompletableFuture<Shopper> shopper(Order order, DataLoader<String, Shopper> loader) {
return loader.load(order.shopperId());
}
Here the key is the shopper id, not the order, so the twelve loads name only four distinct keys. The GraphQL Java page says DataLoaders cache by default and should be created per web request so data is cached only within that request.
Build it: the same queries, three strategies, counted by call
This is the minimal example you can run. Everything is in memory: the downstream services are plain Java classes that write each call to a log, and no web server or network is involved. One Spring application context is started per strategy and queries go straight to Spring's ExecutionGraphQlService.
Setup. From the repository's examples/spring-labs folder:
./gradlew :labs:graphql-n-plus-1:test
It runs 11 tests, including a golden-file comparison and one MockMvc request. The data (illustrative): 12 orders, 4 shoppers with 3 orders each, 3 lines per order.
Expected output, captured from a real run (Spring Boot 4.1.2, Spring for GraphQL 2.0.6, 2026-12-01):
Spring for GraphQL on Spring Boot, in memory, no web server. 12 orders, 4 shoppers (3 orders each), 3 lines per order.
'calls' counts what the resolvers asked the downstream services for.
1 naive, no nested fields calls=1 orders=12 withShopper=0 errors=0
query: { orders { id status } }
1 x orders.findAll
2 naive, shopper calls=13 orders=12 withShopper=12 errors=0
query: { orders { id status shopper { name } } }
1 x orders.findAll
12 x shoppers.findById
3 @BatchMapping, shopper calls=2 orders=12 withShopper=12 errors=0
query: { orders { id status shopper { name } } }
1 x orders.findAll
1 x shoppers.findByIds (4 ids: [s1, s2, s3, s4])
4 DataLoader by hand, shopper calls=2 orders=12 withShopper=12 errors=0
query: { orders { id status shopper { name } } }
1 x orders.findAll
1 x shoppers.findByIds (4 ids: [s1, s2, s3, s4])
5 naive, shopper and lines calls=25 orders=12 withShopper=12 errors=0
query: { orders { id shopper { name } lines { sku quantity } } }
1 x orders.findAll
12 x shoppers.findById
12 x lines.findByOrderId
6 @BatchMapping, shopper and lines calls=3 orders=12 withShopper=12 errors=0
query: { orders { id shopper { name } lines { sku quantity } } }
1 x orders.findAll
1 x shoppers.findByIds (4 ids: [s1, s2, s3, s4])
1 x lines.findByOrderIds (12 ids)
When the downstream is not perfect (query 2 shape, shopper s3 owns orders o03, o07 and o11)
7 @BatchMapping, s3 unknown calls=2 orders=12 withShopper=9 errors=0
query: { orders { id status shopper { name } } }
1 x orders.findAll
1 x shoppers.findByIds (4 ids: [s1, s2, s3, s4])
8 naive, s3 lookup throws calls=13 orders=12 withShopper=9 errors=3
query: { orders { id status shopper { name } } }
1 x orders.findAll
12 x shoppers.findById
first error: path=orders[2].shopper type=INTERNAL_ERROR
9 @BatchMapping, s3 lookup throws calls=2 orders=12 withShopper=0 errors=12
query: { orders { id status shopper { name } } }
1 x orders.findAll
1 x shoppers.findByIds (4 ids: [s1, s2, s3, s4])
first error: path=orders[0].shopper type=INTERNAL_ERROR
| Row | What it shows |
|---|---|
| 1 | A query that selects no nested field runs no nested resolver: 1 call. |
| 2 | Naive: 13 calls, twelve of them findById. |
| 3 | @BatchMapping: 2 calls, with the four distinct shopper ids in one. |
| 4 | A hand-registered loader keyed by shopper id: the same 2 calls; its cache, not code in the method, keeps the ids distinct. |
| 5, 6 | Two nested fields: 25 naive calls, 3 batched. Each nested field adds its own N or its own single call. |
| 7 | A shopper missing from the batch's map: the field is null for those three orders, and there is no error (the schema allows a null shopper). |
| 8 | A lookup that throws, per order: only the three orders of that shopper fail. |
| 9 | A batch that throws: the field fails for all 12 orders, because they shared one call. |
What the lab leaves out. It never measures time, and an in-memory call costs nothing, so it shows counts, not speed. It does not show real downstream failures, timeouts, concurrency or pagination, and @BatchMapping with Flux or Callable returns is not exercised. The MockMvc test shows only that a failed field reaches an HTTP client as a body with data and errors and HTTP status 200.
Break it. In BatchMappingController.shopper, replace Collectors.toSet() with Collectors.toList(). The call count stays 2, but batchMappingMakesOneCallForAllOrdersWithTheDistinctShopperIds fails because the batch now carries 12 ids instead of 4; row 4's loader gets the distinct ids from its cache without that code. Restore it and re-run.
Stretch. Add a product field to OrderLine and watch N compound; page the orders field; add a cost limit.
When the batch is the problem
Batching trades N small calls for one big one, and the failure rows show the price. A missing key must be handled in the batch function, because the contract is one value per key; for the map-returning style, the java-dataloader README says keys absent from the map become null. A failing batch fails every field that waited on it (row 9), so the blast radius of one bad downstream grows from "some orders" to "all orders on the page". And one batch call grows with the parent list: the java-dataloader README mentions a maximum batch size, so check how to bound it for your version, and cap page sizes at the orders field.
Figure 4. Choosing a loading style per field. How to read this: the first question avoids loading at all, and the second checks that batching is possible. A batch only helps if the downstream can answer many keys in one call.
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
| Naive resolvers | Least code | 1 + N calls per nested field | A list can be more than a handful of rows |
@BatchMapping |
One call per field per query | Parent must have equals and hashCode; a batch failure hits every parent | The key is not the parent object |
| DataLoader by key | Distinct keys, control of the key | More wiring | @BatchMapping already fits |
| A purpose-built endpoint | One predictable query | Gives up GraphQL's flexibility | Many clients need different shapes |
The other side of this topic
The consumer of this schema sees the same problem as latency and partial results: a nested field that fails shows up as an entry in errors next to the data it could return, which the front-end lesson shows how to handle. The choice of a purpose-built screen endpoint, shown in the last table row, is the Backend for Frontend pattern.
In practice: ShopStream's order history on GraphQL
This is the realistic example, an educational scenario on the course's running project ShopStream. The page of 20 orders and the 3 lines per order are illustrative.
This is a realistic scenario, not a case history.
The situation
The web and mobile teams share one GraphQL schema for the order history screen: each of 20 orders with its shopper and its lines. Orders, shoppers and lines live in three services. The schema works, and the team has been told to keep downstream load flat as screens add fields.
Starting architecture
Figure 5. One query, three services. How to read this: the arrows show calls per page of 20 orders, scaled from the lab's counts. The two N arrows are what batching removes.
Options considered
| Option | Calls per page of 20 orders | Risk |
|---|---|---|
| A. Naive resolvers | 1 + 20 + 20 = 41 | Grows with every field and page size |
B. @BatchMapping for shopper and lines |
1 + 1 + 1 = 3 | Batch failure hits the whole page |
| C. A single order-history endpoint behind a BFF | 1 to 3, by design | Less flexible for other screens |
The decision
Option B, because the downstream services can answer many keys in one call and several screens use the schema. The orders field gets a maximum page size, and a test asserts the call count for the screen's query using a call log like the lab's.
Rollout and verification
Port the lab's call log into the service's tests: seed 20 orders, run the screen's query, assert 3 calls, then run each new field's query and assert its count. In production, record downstream calls per GraphQL request and alert on the ratio. The count carries over to real services; the time does not, so measure latency on the real downstream too.
The 2 a.m. failure
The page reads: "catalogue service latency up, order history slow after the mobile release". The release added lines { product { name } }. The product resolver was written naive, and it runs once per line: 20 orders times 3 lines is 60 catalogue calls per page, and N compounds at every level. Checks: the slow requests' query text or operation name, downstream calls per request, and which field has no batch mapping. Mitigation: a @BatchMapping for product (or a lower page size until it ships). Lasting fix: the per-field call-count test and a review rule that every field returning another service's entity has a batch mapping.
Architect's notes
- Count calls per query, not per endpoint, and put the count in a test.
- Batch every field that fetches another service's entity, at the time it is added.
- Make the key explicit: parent object for
@BatchMapping, an id for a DataLoader. - Cap list sizes at the field that returns the list.
- Plan for a failing batch: it fails every parent in it.
Common mistakes
- Treating one endpoint as one call. The query decides the number of downstream calls.
- A
@BatchMappingkey without equals and hashCode. - A batch function that skips missing keys silently when the schema field is non-null.
- Judging by an in-memory test that shows counts but not time.
- Sharing a DataLoader across requests, which caches one user's data for another.
Key takeaways
- A GraphQL resolver sees one parent, so a remote lookup inside a list runs N times.
- Only selected fields run their resolvers, and each nested field adds its own N.
- A batch loader queues keys and calls once per level;
@BatchMappingis the Spring shortcut and aDataLoaderargument gives control of the key. - A batch needs a value for every key and fails as a whole.
- Loaders are per request, so their cache never crosses users.
- Count downstream calls in tests; counts transfer to production, timings do not.
Practice exercises
Exercise 1 (20 min). Predict the call count of { orders { id shopper { name } lines { sku } } } under the naive strategy for 20 orders, then run the lab's query with 12 and compare with your formula.
Exercise 2 (45 min). Add product: Product to OrderLine with a naive resolver, predict the count for the full query, then fix it with a @BatchMapping and compare.
Exercise 3 (1 hour). Make the batch function throw only for shopper s3 and change the schema field to shopper: Shopper!. Predict what the response looks like, then check it.
Exercise 4 (2 hours). Write a test helper that fails when a query makes more than a given number of downstream calls, and use it for the order history query.
Related reading
- REST, gRPC, GraphQL and WebSockets: Choosing an API Style: responses, errors and when to choose GraphQL.
- Consuming REST, GraphQL and tRPC from a Client: the client's side of the same schema.
- JPA and Hibernate: N+1, Lazy Loading and Batching: the same pattern one layer down.
- Backend for Frontend: a purpose-built endpoint per screen.
Official documentation
- Spring for GraphQL, Annotated controllers and Request execution.
- Spring Boot, Spring for GraphQL.
- GraphQL, Execution and the specification, October 2021.
- GraphQL Java, Batching, and the java-dataloader README.