Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A public GraphQL endpoint built with Spring for GraphQL is being hit with deeply nested queries that take down the database. What protections do you add?

We limit what any single query may do: maximum depth and complexity through graphql-java instrumentation registered as Spring beans, timeouts and maximum result sizes, and for known clients persisted or allow-listed queries so arbitrary documents are rejected. Batch loaders remove N+1 multiplication and per-field authorisation keeps expensive or private fields closed, and rate limiting is based on each query's computed cost, not only on the number of requests.

Why this question is asked

A REST endpoint does a fixed amount of work per request; a GraphQL endpoint does whatever the query asks. On a public endpoint, that means anyone can write a query that nests friends of friends of friends ten levels deep, each level multiplying the work, and a single request can generate millions of database rows. Interviewers ask this scenario because the protections are specific to GraphQL and easy to forget until the database falls over. In this answer, we will see why nested queries are so expensive, then add depth and complexity limits, timeouts and result limits, persisted queries, batch loading and field authorisation, and cost-based rate limiting.

1Why a Nested Query Takes Down the Database

In GraphQL, every field in a list is resolved for every element of that list. If a schema lets Author have books and Book have an author, a client can alternate them as deep as it likes. Let us estimate a query that goes authors, books, author, books, four levels, asking for 100 authors with about 20 books each. Level one is 100 authors, level two 2,000 books, level three 2,000 authors, level four 40,000 books. Add one more pair of levels and it is 800,000 books. Without batch loading, each element is a separate database query, so a request of a few hundred bytes can produce hundreds of thousands of queries.

Aliases make it worse. A client can ask for the same expensive field 500 times in one query under different alias names, which does not increase depth at all. So depth limits alone are not enough; we need to measure total cost too.

Java
query { # about 300 bytes of text
authors(first: 100) { # 100
books { # x20 = 2,000
author { # 2,000
books { # x20 = 40,000
author { books { title } } # x20 = 800,000
}
}
}
}
}

No single field here is wrong, which is why the code review never caught it. The danger is in the combination, so the protections must look at the whole query.

2Limiting Depth and Complexity With Instrumentation

graphql-java analyses each query before executing it and lets instrumentations reject it. Two built-in ones fit our problem: MaxQueryDepthInstrumentation rejects queries nested deeper than a limit, and MaxQueryComplexityInstrumentation assigns each field a cost and rejects queries whose total is too high. In Spring for GraphQL, any Instrumentation bean is picked up by the Spring Boot auto-configuration and added to the engine.

Java
@Configuration
class GraphQlLimits {
@Bean
Instrumentation maxDepth() {
return new MaxQueryDepthInstrumentation(8); // deeper queries are rejected before running
}
@Bean
Instrumentation maxComplexity() {
return new MaxQueryComplexityInstrumentation(500, (env, childComplexity) -> {
int first = env.getArguments().get("first") instanceof Integer n ? n : 10;
return 1 + childComplexity * first; // a list field multiplies its children
});
}
}
// the nested query above: depth 7 passes, complexity in the hundreds of thousands -> rejected

The complexity calculator is where we encode knowledge of our schema: list fields multiply the cost of their children by the page size, expensive fields can cost more, and simple scalar fields cost 1. The thresholds come from real traffic: we log the depth and complexity of legitimate queries for a week, then set limits comfortably above the largest ones. We should also keep the parser's own limits on document size and token counts, which graphql-java applies by default (check your version for the exact values), so a giant document is rejected before analysis.

3Timeouts and Maximum Result Sizes

Analysis catches most abuse, but some queries are expensive for reasons the calculator cannot see, such as a slow filter. So we bound time and size as well. Each request has an overall timeout, set at the HTTP layer or in Spring for GraphQL's request handling, so a slow query is abandoned instead of holding threads and connections. The database gets its own statement timeout, for example 2 seconds for this endpoint's queries, so even an abandoned request stops costing the database quickly.

Result size is bounded through pagination: every list field takes a first argument with a maximum, say 100, and lists without arguments are not exposed on the public schema. A query that asks for first: 100000 is rejected with a validation error rather than silently trimmed, so clients learn the rule.

4Persisted and Allow-Listed Queries

If the endpoint serves our own web and mobile apps, they do not need arbitrary queries at all; they send the same few hundred documents every time. Persisted queries take advantage of this. At build time, each client's queries are registered on the server, keyed by a hash. At runtime, the client sends only the hash and the variables, and the server runs the stored document. With an allow list, the server rejects any document that is not registered.

This removes the attack almost entirely for first-party clients, because an attacker cannot run a query we have not reviewed. graphql-java has persisted query support, and in Spring for GraphQL a WebGraphQlInterceptor can check the document or hash against the list before execution. Public partner APIs that must accept arbitrary queries keep the depth, complexity and rate limits, and we usually disable introspection there (spring.graphql.schema.introspection.enabled=false) so the schema is not handed out to anyone who asks.

Step throughWhat happens to a public request
  1. Known persisted query hash?first-party clients
    YesRun stored documentNoArbitrary document
  2. Parse within size and token limitsgiant documents rejected
  3. Depth <= 8 and complexity <= 500?instrumentation
    YesContinueNoReject with error
  4. Enough cost budget left for this client?cost-based rate limit
    YesExecute with timeoutsNo429 Too Many Requests
  5. Batch loaders, field authorisationduring execution

5 steps in order. Play them, or step through them one at a time.

5Batch Loading and Per-Field Authorisation

The limits decide which queries run; batch loading decides how much an allowed query costs. With @BatchMapping (backed by a DataLoader), the author field of 2,000 books becomes one database query with 2,000 ids instead of 2,000 queries, so each level of nesting costs one query, not one per element. That turns the cost of a legal query from multiplicative into roughly linear in depth.

Authorisation must also be per field, because a GraphQL query can reach any field from many paths. A field such as Author.email or a costly analytics field gets its own check, for example @PreAuthorize on its @SchemaMapping method or a check in the batch method, so a client cannot reach it through a nested path the REST API would never have exposed. Unauthorised fields return an error for that field only, and the rest of the response is still returned.

6Rate Limiting by Cost

A classic limit of 100 requests per minute treats a 1-point query and a 500-point query the same, so an attacker simply sends 100 of the expensive ones. Instead, each client gets a budget in cost points, say 5,000 per minute, and each request spends its computed complexity from the analysis step. A typical app screen costing 30 points can be loaded 160 times a minute, while the expensive nested query exhausts the budget in ten requests. We return the remaining budget in response headers or extensions so well-behaved clients can adapt, and 429 when it runs out.

7Follow-up questions

Is a depth limit enough if we choose it well?

No. Aliases and wide queries can make a shallow query huge, for example the same list field requested 500 times at depth 2. Depth limits stop the simplest attacks; complexity analysis is what actually measures the work, so we use both.

Do persisted queries break GraphQL's flexibility?

Only for clients that do not need it. Our own apps change their queries when they ship new versions, and the registration step becomes part of their build. Third-party clients that need flexibility use the arbitrary-query path with stricter limits and cost budgets.

Where do you enforce the statement timeout?

In the database connection used by the GraphQL service, for example a PostgreSQL statement_timeout set for that role or per transaction, or a JDBC query timeout. It must be in the database, because an HTTP timeout alone stops waiting but does not stop the query that is still running.

8Conclusion

In this answer, we saw why nested and aliased GraphQL queries multiply work until the database falls over, and added layered protections: depth and complexity limits through graphql-java instrumentation beans, request and statement timeouts, maximum page sizes, persisted or allow-listed queries for known clients, batch loaders that make each level one query, per-field authorisation for sensitive or expensive fields, and rate limits that spend each query's computed cost rather than counting requests.

What to say in the interviewAbout 90 seconds aloud

Open with

The core problem is that GraphQL work is multiplicative: every list field is resolved for every parent, so a nested authors, books, author, books query of a few hundred bytes can mean hundreds of thousands of database queries.

Then, if they want more

I would add protections in layers. First, analysis before execution: graphql-java's MaxQueryDepthInstrumentation and MaxQueryComplexityInstrumentation, which I register as beans so Spring for GraphQL picks them up. The complexity function multiplies child cost by the page size, because depth alone misses wide or aliased queries, and I set thresholds from a week of real traffic.

Second, bounds: request timeouts, a database statement timeout so abandoned queries really stop, and a maximum first argument on every list. Third, for our own clients, persisted or allow-listed queries, so only registered documents can run at all, and I would disable introspection on the public endpoint.

Fourth, inside execution, @BatchMapping with DataLoaders so each level is one query rather than one per element, and per-field authorisation so sensitive or expensive fields cannot be reached through nested paths.

Finally, rate limiting by computed cost: each client has a budget of points per minute and each query spends its complexity, so a cheap screen can be loaded often while the abusive query runs out of budget after a few requests and gets 429.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A public GraphQL endpoint built with Spring for GraphQL is being hit with deeply nested...": https://scrivio-interview-library.netlify.app/spring-boot/web-other/3223dc49bc/