This chapter follows Authentication and authorization in GraphQL.
Unbounded queries are a denial-of-service vector. Limits belong in the router (Apollo Router, Hive Gateway, Cosmo) and in standalone servers before resolvers touch databases.
Depth limits
Depth counts nested field selections. Reject documents deeper than a threshold (often 7–15 depending on schema).
Apollo Router and many frameworks expose max_depth configuration. NestJS can use validation rules from graphql-validation-complexity packages or gateway offload.
Complexity and cost analysis
Assign cost weights to fields (scalars cheap, lists expensive). Sum costs across the document including aliases:
// Conceptual: each field has a cost; lists multiply by requested count.// Reject when totalComplexity > maxComplexity (e.g. 1000).NestJS GraphQLModule supports plugins such as graphql-query-complexity wired in validationRules—assign higher cost to posts(first: n) when n is large.
Tune weights using production traces, not guesses.
Alias, root field, and page size caps
| Limit | Prevents |
|---|---|
| Max aliases | Repeating expensive fields |
| Max root fields | Wide query fan-out |
Max first / limit |
Huge list resolutions |
Encode caps in schema (first: Int = 20 with validation) and enforce maximum in resolvers.
Timeouts and rate limiting
Set resolver-level deadlines and HTTP timeouts below client timeouts. Rate limit by IP, token, or cost units at the edge.
Cost-based limits charge more for heavy operations—fairer than flat request counts.
Trusted documents and persisted queries
Automatic Persisted Queries (APQ) and persisted operation allowlists send a hash instead of full text. The gateway executes only known hashes—blocking ad-hoc attacker queries while allowing registered app operations.
Pair with codegen persisted-documents.json from the client chapter.
Production introspection and GraphiQL
Disable GraphiQL/playground in production builds. Turn off introspection for public callers. Keep staging mirrors for developers.
Next: GraphQL federation.
Check your understanding
Question 1 of 6
0 of 6 checked