Video in progress

You want to build a GraphQL API on top of JPA entities. What problems come up with N+1 and control over loading, and how do you structure the architecture?

In GraphQL the client chooses the query shape, so each field resolver calls lazy loading and multiplies the N+1. I don't rely on the entity graph in resolvers: associations are batched by IDs through a DataLoader, and depth and complexity are limited.

📖 Answer

In REST we know which data the endpoint returns, and we write the fetch join or EntityGraph ahead of time. In GraphQL, a query can arrive like this:

{ orders(first: 50) { number customer { name } lines { product { title } } } }

If the resolvers call order.getCustomer().getName() and line.getProduct(), that is 1 + 50 + 50 + (the number of lines) queries. Every new client query produces a new loading shape.

My approach:

Batch loading. In Spring for GraphQL, @BatchMapping is a convenient form of DataLoader:

@BatchMapping
Map<Order, Customer> customer(List<Order> orders) {
    Set<Long> ids = orders.stream().map(Order::customerId).collect(toSet());
    Map<Long, Customer> byId = customers.findAllById(ids).stream()
        .collect(toMap(Customer::getId, c -> c));
    return orders.stream().collect(toMap(o -> o, o -> byId.get(o.customerId())));
}

Now it is one query per level: 3-4 depending on depth, independent of the number of orders.

Don't make the entity the API model. The GraphQL types are separate, and linking by ID is enough for them. This keeps OSIV and lazy proxies away from the serialization layer.

Protection. A query depth and complexity limit (MaxQueryDepthInstrumentation, MaxQueryComplexityInstrumentation), and mandatory pagination. Otherwise a single client writes a query that takes the database down.

Observability. A SQL count metric per GraphQL operation shows which query shapes are expensive.

Some teams build a dynamic EntityGraph by looking at DataFetchingFieldSelectionSet. It works, but it is complex and clashes with pagination; I find batch loading simpler and more predictable.