One form, one box
Mia wants lunch: some rice, a piece of fish and one sweet. At the old food hall she queues at the rice counter, then the fish counter, then the sweets counter. Each counter only sells its own fixed tray, so she also gets soup, pickles and a salad she never wanted. Three queues, and half the food goes to waste.
The bento shop works differently. There is one window and one order form. Mia ticks exactly the three things she wants, hands in the form once, and gets back one box with three compartments, filled with exactly what she ticked. Behind the window, helpers fetch each item from the right counter. Nothing missing, nothing extra.
That's GraphQL: the shopper says exactly what goes in the box, instead of taking whatever each counter's tray holds.
Ask for exactly the fields you need
GraphQL is a query language for APIs plus a runtime that executes it. Instead of many endpoints that each return a fixed shape, a GraphQL server exposes one endpoint and the client describes the shape of the response it wants:
1query {2user(id: "7") {3name4orders(last: 3) { dish }5reviews { stars }6}7}
The response is JSON with the same shape as the query, under a data key. That fixes two common problems of
resource-based HTTP APIs (REST):
- Over-fetching:
GET /users/7returns the whole user, twenty fields, when the screen needs one. - Under-fetching: the screen also needs orders and reviews, so the client makes more round trips
(
/users/7/orders,/users/7/reviews), often one after another.
The trade-off is that the server now runs whatever combination of fields clients ask for, which moves work (and risk) from the client to the server. REST is still simpler for plain resources, file downloads and anything that benefits from HTTP caching; GraphQL shines when many different screens need different slices of connected data.
The printed menu
Next to the window hangs a printed menu, called the schema. It lists every box you can order and every item that can go in each compartment, and what kind of thing each item is: a number of pieces, a word, a yes or no. If it isn't on the menu, you can't order it.
So when Mia ticks "dragon roll", which the shop has never made, the window hands the form straight back before anyone starts cooking. And anyone can ask the window for a copy of the menu, so new customers can see what exists.
The menu has three sections. The first is for getting food. The second is for changes, such as "save this box as my favourite". The third is for "tell me whenever there's a new special", and the shop keeps shouting to Mia each time one comes out.
The schema, mutations and subscriptions
Every GraphQL API is described by a schema, usually written in the Schema Definition Language (SDL):
1type Query {2user(id: ID!): User3}45type Mutation {6saveFavourite(dishId: ID!): User!7}89type Subscription {10newSpecial: Dish!11}1213type User {14id: ID!15name: String!16orders(last: Int): [Order!]!17}
Object types have fields, and every field has a type: scalars (Int, Float, String, Boolean, ID),
other object types, lists [T], and ! for non-null. Enums, interfaces, unions and input types complete the
type system.
Three root types are the entry points. Query fields read. Mutation fields change data; top-level mutation fields in one request run one after another, in order. Subscription fields deliver a stream of results over a long-lived connection, typically a WebSocket or server-sent events.
Every request is validated against the schema before anything runs: an unknown field or a wrong argument type
is rejected with an error and no data. The schema is also queryable through introspection (__schema,
__type), which is what powers autocompletion in tools like GraphiQL and code generators.
Kitchen stations
Behind the window, the box isn't filled by one cook. Each compartment has its own station, called a resolver: the fish station fills the fish, the sweets station fills the sweet.
The head cook reads the form from the top. First the account desk finds Mia's account, then each station gets told "this is for Mia" and fills its compartment. Simple things, like writing Mia's name on the lid, need no station at all: it's already on her account card. When every compartment is full, the box goes out.
Resolvers, field by field
The server executes a query by calling a resolver (in graphql-java, a DataFetcher) for each field. Execution
starts at the root: Query.user runs first and returns a user object. Then each selected child field is resolved
with that object as its parent (source): User.orders and User.reviews each receive the user and fetch
their own data, possibly from different databases or services.
Fields without a custom resolver use a default resolver, which reads a property of the same name from the
parent object, so name simply becomes user.getName(). The engine assembles the results into a response that
mirrors the query.
Because each field resolves independently, a GraphQL server is a natural place to stitch together several backends. It also means one innocent-looking query can trigger a lot of calls, which is the next topic.
One trip to the storeroom
Ten customers each order a box with fish. The fish station gets ten tickets. A careless cook walks to the storeroom for the first piece of fish, comes back, walks again for the second, and so on: ten trips, plus the one to find the orders in the first place.
A smart shop has a runner, called a DataLoader. Each ticket tells the runner "I need fish number 3". The runner waits a moment, collects all ten requests, makes one trip with one list, and hands each station its piece. Two trips instead of eleven.
The N+1 problem and DataLoader
Field-by-field resolution has a classic trap. A query for the last 10 orders and the dish of each runs one query
for the orders, then Order.dish once per order: 1 + N database calls. Nested lists multiply it further.
The fix is batching. A DataLoader collects the keys requested by every Order.dish resolver during one
level of execution, then calls a batch function once with all of them (WHERE id IN (...)) and hands each
resolver its own result. It also caches per request, so the same key is loaded only once. The batch function must
return results in the same order as the keys, or as a map keyed by them.
DataLoaders should be created per request, so their cache never leaks one user's data to another. The same problem exists with ORMs and REST; see JPA's N+1 for the database side.
One window, sealed forms
Every order goes through the same window, on a folded form. That makes life hard for the shop's ready-made shelf, a cache where popular boxes wait already packed: the shelf can't see inside a folded form, so it can't tell that two forms ask for the same box. The fix is a numbered set order: "the usual, number 12". A number on the outside is easy for the shelf to recognise.
If one compartment can't be filled, the shop doesn't send the whole box back. You get the box with that compartment empty and a note tucked inside: "sorry, no fish today". So always read the note, even when the box arrives.
And the window refuses silly forms, like a box inside a box inside a box, a hundred times over, which would keep every station busy all day.
GraphQL over HTTP: caching, errors and limits
Most GraphQL APIs use a single endpoint such as /graphql, with the query sent as JSON in a POST body:
query, operationName and variables. Because the URL never changes and POST responses aren't cached by
default, browser and CDN caching (Cache-Control, ETag) doesn't work out of the box. Clients make up for it with
normalized caches keyed by type and id (Apollo Client, Relay).
Persisted queries restore HTTP caching: the client sends a hash or id of a query the server already knows,
often as a GET with the id and variables in the URL, so CDNs can cache it when the response carries
Cache-Control (Spring for GraphQL accepts GET only once you enable it). They also shrink requests, and an
allow-list of persisted queries can block every query you didn't ship.
Errors don't map to status codes the way REST does. Once the operation executes, the reply is a success
status (in practice 200 OK, which is what Spring for GraphQL sends) even if some fields failed. Each failed field
is null in data (or, if the field is non-null, its nearest nullable parent is), and an errors array explains
each one with a message, a path and often extensions.code. Clients must check errors, not just the status.
A body that isn't valid JSON gets a 400. A query that fails to parse or validate gets a 4xx when the client
accepts the newer application/graphql-response+json media type, but still a 200 with plain application/json.
Safety limits matter because clients write the queries: cap query depth and query complexity (a cost per field, multiplied by list sizes), set timeouts and pagination limits, and consider disabling introspection on public production APIs.
A bento shop in Java
In a Java shop, the manager doesn't wire up every station by hand. They pin the printed menu on the wall and stick a label, called an annotation, on each cook: "you make the boxes". The fish cook's label says "fill all the fish compartments in one go", so that cook gets every waiting box at once, just like the runner.
Spring for GraphQL
Spring for GraphQL builds on graphql-java. Spring Boot loads schema files (.graphqls or .gqls) from
src/main/resources/graphql/ and exposes the API at POST /graphql by default. Resolvers are methods on a
@Controller:
1// interface AuthorRepository extends ListCrudRepository<Author, String> {}23@Controller4class BookController {56private final BookRepository books;7private final AuthorRepository authors;89BookController(BookRepository books, AuthorRepository authors) {10this.books = books;11this.authors = authors;12}1314@QueryMapping // Query.books15List<Book> books() {16return books.findAll();17}1819@QueryMapping // Query.bookById(id: ID!)20Optional<Book> bookById(@Argument String id) {21return books.findById(id);22}2324@MutationMapping // Mutation.addBook25Book addBook(@Argument String title, @Argument String authorId) {26return books.save(new Book(null, title, authorId));27}2829@BatchMapping // Book.author, once for all books30Map<Book, Author> author(List<Book> bookList) {31var ids = bookList.stream().map(Book::authorId).toList();32var byId = authors.findAllById(ids).stream()33.collect(Collectors.toMap(Author::id, a -> a));34return bookList.stream()35.filter(b -> byId.containsKey(b.authorId()))36.collect(Collectors.toMap(b -> b, b -> byId.get(b.authorId())));37}38}
@QueryMapping and @MutationMapping bind a method to a field of Query or Mutation, named after the method
unless you say otherwise. @SchemaMapping binds any field of any type: @SchemaMapping(typeName = "Book", field = "author") on Author author(Book book) would be called once per book, the N+1 pattern.
@BatchMapping registers a DataLoader for you and is called once per batch with all the parent objects; it
returns a Map from parent to value, or a List in the same order.
Introspection in production: Spring Boot has introspection on by default (tools need it). Set
spring.graphql.schema.introspection.enabled=false to hide the schema on a public API. Disabling it isn't
security on its own: your shipped client code still reveals the queries it sends, so every field still needs its own
authorization check.
Depth and complexity: graphql-java ships MaxQueryDepthInstrumentation and
MaxQueryComplexityInstrumentation. Expose one as a bean and Spring Boot adds it to the engine, so a query
nested deeper than the limit is rejected before any resolver runs.
Errors: an exception thrown in a controller becomes an entry in errors. If nothing resolves it, Spring reports
a generic INTERNAL_ERROR with only an execution id, on purpose, so internal details don't leak. To turn your own
exceptions into clear messages and classifications such as NOT_FOUND, implement a DataFetcherExceptionResolver,
or (since Spring for GraphQL 1.2) write a @GraphQlExceptionHandler method in a controller or @ControllerAdvice.