Skip to content

    System Design

    GraphQL on the Server and the N+1 Problem

    Learn why GraphQL resolvers cause N+1 downstream calls, then fix them with Spring for GraphQL batch mapping or a DataLoader and count the calls in a lab.

    By Published 12 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: REST, gRPC, GraphQL and WebSockets: Choosing an API Style

    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 @BatchMapping or 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.

    A client sends one GraphQL query; resolvers inside the server call three downstream servicesApp to GraphQL server (POST /graphql); GraphQL server to Orders (1 call); GraphQL server to Shoppers (N calls?); GraphQL server to Order lines (N calls?)App: one queryAppone queryGraphQL server: resolversGraphQL serverresolversOrdersOrdersShoppersShoppersOrder linesOrder linesPOST /graphql1 callN calls?N calls?

    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).

    sequenceDiagram accTitle: Naive resolution of orders and their shoppers accDescr: The server calls the order service once and gets twelve orders. It then runs the shopper resolver for each order, and each run calls the shopper service separately, so twelve more calls follow. participant G as GraphQL server participant O as Order service participant S as Shopper service G->>O: findAll (1 call) O-->>G: 12 orders loop for each of the 12 orders G->>S: findById(shopperId) S-->>G: one shopper end

    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.

    sequenceDiagram accTitle: Batched resolution with a DataLoader accDescr: The server calls the order service once. The shopper resolver runs for each order but only asks the loader for a key, which returns a future. When all keys of this level are queued the loader is dispatched, and the batch function calls the shopper service once with the distinct ids. participant G as GraphQL server participant L as DataLoader participant O as Order service participant S as Shopper service G->>O: findAll (1 call) O-->>G: 12 orders G->>L: load(s1) ... load(s4), 12 loads in total Note over L: keys queued, nothing called yet G->>L: dispatch L->>S: findByIds(s1, s2, s3, s4) (1 call) S-->>L: 4 shoppers L-->>G: each future completes

    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.

    flowchart TD accTitle: Choosing how to load a nested GraphQL field accDescr: If the field is computed from the parent alone, no loading is needed. If it needs a remote lookup per parent, use a batch mapping when the key is the parent, or a DataLoader when several parents share a key or the lookup is by another key. If the downstream has no batch endpoint, add one or move the join to a different layer. S["A field needs data from another service"] --> A{"Computed from the parent alone?"} A -->|"yes"| P["Plain resolver, no loading"] A -->|"no"| B{"Does the downstream offer a lookup by many keys?"} B -->|"no"| C["Add one, or join in the owning service"] B -->|"yes"| D{"Is the key the parent object itself?"} D -->|"yes"| BM["@BatchMapping"] D -->|"no, shared or other key"| DL["DataLoader keyed by that id"]

    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.

    ShopStream order history: a GraphQL query fans out to three servicesWeb and mobile to GraphQL server (1 query); GraphQL server to Orders (1 call); GraphQL server to Shoppers (20 calls); GraphQL server to Order lines (20 calls)Web and mobileWeb and mobileGraphQL server: order historyGraphQL serverorder historyOrdersOrdersShoppersShoppersOrder linesOrder lines1 query1 call20 calls20 calls

    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 @BatchMapping key 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; @BatchMapping is the Spring shortcut and a DataLoader argument 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.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments