GraphQL for Java backends
Schema-first with Spring for GraphQL, resolvers, DataLoader against N+1, and depth and complexity limits.
REST gives every client the same response and lets the server decide its shape. GraphQL turns that round: the server publishes a schema of types and fields, and each client asks for exactly the fields it wants, across relationships, in one request. It solves the mobile team's "three round trips and 80% of the payload unused" problem precisely, and it creates a set of server-side problems — the N+1 in every resolver, a query that can ask for the whole graph, errors that arrive as 200 — that a Java backend has to solve before the first client ships.
The schema, and schema-first
type Query {
order(id: ID!): Order
orders(customerId: ID!, first: Int = 20, after: String): OrderConnection!
}
type Order {
id: ID!
status: OrderStatus!
total: Money!
lines: [Line!]!
customer: Customer!
}
type Customer { id: ID! name: String! orders(first: Int = 10): [Order!]! }
type Line { sku: String! qty: Int! product: Product! }
enum OrderStatus { PAID SHIPPED DELIVERED CANCELLED }
scalar Money
type Mutation { cancelOrder(id: ID!, reason: String!): CancelOrderPayload! }The .graphqls file is the contract, reviewed before the code exists — the design-first argument from the OpenAPI lesson, with the difference that here it is the only way: Spring for GraphQL loads the schema and maps fields to methods, so the schema cannot drift from the implementation. ! is non-null, and it is a promise the server keeps or the whole parent field becomes null; make a field nullable when its resolver can fail independently of its parent. Custom scalars (Money, DateTime) need a coercing implementation registered with the runtime wiring; the graphql-java-extended-scalars library has most. Mutations return a payload type rather than the bare object, so a business failure (CancelOrderPayload { order, error }) has somewhere to go that is not the errors array.
Resolvers: a method per field, and where the data comes from
@Controller
class OrderGraph {
@QueryMapping
Order order(@Argument String id) { return orders.findById(id).orElse(null); }
@SchemaMapping(typeName = "Order", field = "customer")
Customer customer(Order order) { return customers.findById(order.customerId()); } // called ONCE PER ORDER
}@QueryMapping binds a root field; @SchemaMapping binds a field of a type, and its first parameter is the parent object. Anything not mapped is resolved by the default property fetcher — a getter or a record component of the same name — which is why a DTO shaped like the type needs no resolvers at all. A @MutationMapping is the same for Mutation, and @Argument binds inputs, with Bean Validation on an @Valid input type as in the REST course.
That comment on customer is the whole difficulty of GraphQL on a backend. The client asks for twenty orders and each one's customer; the runtime resolves the orders field once, gets twenty orders, then calls the customer resolver twenty times, one query each. It is the JPA course's N+1 problem, produced by the engine on purpose, for every relationship in every query, and no amount of JOIN FETCH in the first resolver helps, because the engine does not know what the client will ask for next.
DataLoader: batch the second level
The fix is to make the per-parent resolver collect keys instead of loading, and load them all at once when the engine has finished the level:
@Controller
class OrderGraph {
@BatchMapping(typeName = "Order", field = "customer")
Map<Order, Customer> customers(List<Order> orders) { // called ONCE for all twenty
Set<String> ids = orders.stream().map(Order::customerId).collect(toSet());
Map<String, Customer> byId = customers.findAllById(ids).stream().collect(toMap(Customer::id, c -> c));
return orders.stream().collect(toMap(o -> o, o -> byId.get(o.customerId())));
}
}@BatchMapping is Spring's front for DataLoader: the engine defers every customer fetch on a level, hands the batch to this method, and one WHERE id IN (...) replaces twenty queries. The rules that make it correct: return a Map (or a List in the same order as the input — the DataLoader contract), return an entry for every key even when it is null, and register a loader per request, never as a singleton, because it also caches by key for the request's lifetime and a shared cache would leak one user's customer into another's query. For loaders with more logic, BatchLoaderRegistry and DataLoader<K, V> as a method parameter are the explicit form.
Do the same for lines → product and customer → orders, and the graph resolves in one query per level rather than one per node. Which is still one query per level per relationship, and a client that asks for orders { lines { product { supplier { ... } } } } is four levels deep; the JPA course's projections apply — a resolver that loads a Product for a sku and name should select those two columns.
Errors: the 200 that is not OK
A GraphQL response is { "data": ..., "errors": [...] }, and the HTTP status is 200 whenever the query was parseable — a resolver that threw puts its field to null and an entry in errors with a path and extensions. Three consequences for a Java backend. Classify exceptions with a DataFetcherExceptionResolver: a NotFoundException becomes extensions.classification: NOT_FOUND with a clean message, and everything else becomes INTERNAL_ERROR with the message replaced, because the default is to leak the exception's message and the REST course's "what never leaves the server" applies here with more force (the error path names your schema). Business outcomes are not errors: "cannot cancel a shipped order" is a field on the mutation's payload type, so the client handles it as data, not as an exception it has to parse out of a list. And monitor the errors array, because an HTTP dashboard sees 200s while half the queries are failing; the observability course's error metric here counts responses with a non-empty errors.
Limits: a query is a program the client wrote
The client chooses the shape, so the client can choose a shape that reads the whole database: orders { customer { orders { customer { orders ... } } } }, or a list field with first: 1000000. Every public GraphQL API needs the same four guards, and Spring for GraphQL exposes the graphql-java instrumentation for them:
- Depth limit (
MaxQueryDepthInstrumentation): reject a query nested past, say, ten levels, before it runs. - Complexity limit (
MaxQueryComplexityInstrumentation): each field costs one, a list field costs itsfirstargument times the child cost; reject past a budget. This is the one that stopsfirst: 1000000. - Pagination on every list, with a maximum page size enforced in the resolver — the REST course's "bound everything" — and the Relay connection shape (
edges,pageInfo, cursors) when clients page. - Persisted queries for a first-party client: the client sends a hash of a query the server already knows, so an attacker with the endpoint cannot run arbitrary shapes at all, and the queries can be reviewed like an API.
Plus the ones REST already has: authentication before the schema (the security course's filter chain sits in front of /graphql like any endpoint), authorisation per field where the schema exposes something not everyone may read (@PreAuthorize on the resolver method works), introspection disabled in production so the schema is not a free map for an attacker, and a request timeout, because a slow resolver holds a thread exactly as a slow endpoint does. Test the whole thing with @GraphQlTest and GraphQlTester, the slice from the testing course for this layer.
Under the hood: how the engine actually collapses a level into one call, and what a complexity limit really bounds
"N+1" understates what a naive resolver does: it is not N+1 calls total, it is one call per object the parent field returned, at every level, for every field that has its own resolver. Twenty orders means twenty customer calls; if each of those customers also resolves a tier field with its own lookup, that is twenty more. The mechanism is a tree walk — the engine resolves the orders field, gets a list back, and then, for every field selected under Order in the query, calls that field's resolver once per item in the list, because the engine has no way to know in advance that twenty of those calls will ask for the same shape of data.
@BatchMapping does not make the engine call the resolver less often in the naive sense — it changes what "the resolver" is. Instead of registering a per-object customer(Order) method, you register a per-level customers(List<Order>) method, and the engine's execution changes shape to match: as it walks the Order list resolving the customer field for each one, it does not invoke your batch method immediately. It records that this order's customer is pending and moves on to the next order in the same list, and only once every order at that level has either resolved or registered a pending key does it dispatch — call your batch method exactly once with the full set of keys collected during that pass, then resolve every pending customer field from the single Map (or List) that comes back. That deferred-then-dispatched shape is what graphql-java's DataLoader is: a level of the query tree turns from N sequential calls into one collection pass plus one batch call. The per-request cache half of a DataLoader is a separate thing layered on top: if two different orders in the same query happen to share a customer id, the second ask is served from that request-scoped cache instead of appending a duplicate key to the batch — which is why a loader is created fresh per request rather than shared as a singleton; a cache that outlived the request would start returning one user's data to a resolver running inside another user's query.
Depth limiting and complexity limiting police two different shapes of abuse, and only one of them catches the other. MaxQueryDepthInstrumentation walks the parsed query's selection set — before any resolver runs — and counts nesting; it rejects orders { customer { orders { customer { ... } } } } past a fixed number of levels. But depth says nothing about a query that is shallow and wide: orders(first: 1000000) { id } is one level deep and would sail past a depth limit while asking the database for a million rows. MaxQueryComplexityInstrumentation catches that instead, by walking the same selection-set tree and multiplying a per-field cost (default 1) down through every list argument it passes under — a first: 50 list field under another first: 20 list field costs roughly 20 × 50 × (fields selected inside), so the number the client controls (first) is exactly the number the cost formula multiplies by. That is the structural reason GraphQL needs a cost budget where a REST endpoint does not: a REST route's cost is fixed by the code behind it, but a GraphQL query's cost is a number the client writes into the request, and only a walk of that request — before touching a resolver — can bound it.
Try it yourself
Trace the resolver call count, naive versus batched
A query asks for five orders and each order's customer. Work out, before running it: how many times does a naive per-order resolver run, and how many times does a batched one run for the same five orders?
List<String> orderIds = List.of("A1", "A2", "A3", "A4", "A5");
int naiveResolverCalls = 0;
for (String id : orderIds) {
naiveResolverCalls++; // one call per order, because the engine
} // does not know they share a shape
System.out.println("naive: " + naiveResolverCalls + " customer resolver calls for " + orderIds.size() + " orders");
int batchedResolverCalls = 1; // one @BatchMapping call for the whole level,
System.out.println("batched: " + batchedResolverCalls + " customer resolver call for " + orderIds.size() + " orders");The batched count does not depend on how many orders there are — that is the entire point of moving the key collection ahead of the dispatch, and it is why the fix does not get worse as a client's query gets wider.
Misconceptions
- "A DataLoader's cache is what fixes the N+1 problem." The cache only dedupes a key that two different resolvers in the same request both ask for; it does nothing to combine separate keys into one call. Batching — the deferred collection of keys across a level, dispatched once — is the part that turns N calls into one; a resolver that still calls a repository once per key, one at a time, does not become batched just because a DataLoader cache sits in front of it.
- "Depth limiting stops an expensive query." It stops a deep one. A query can be one level deep and still ask for a million rows through a list argument with no bound, which depth limiting never sees because it only counts nesting. Complexity limiting, which multiplies cost through list arguments, is the guard that actually bounds a wide query.
Sources
- GraphQL Specification (GraphQL Foundation) — execution and selection-set semantics.
- The
graphql/dataloaderproject's own documentation — batching and per-request caching contract. graphql-javaproject documentation —Instrumentation,MaxQueryDepthInstrumentation,MaxQueryComplexityInstrumentation.- Spring for GraphQL reference documentation —
@BatchMappingandDataLoaderRegistry.