Query limits
Depth and complexity ceilings that catch the recursive bomb, the wide sweep, fanout and fragment repeats before a resolver runs.
A GraphQL endpoint accepts whatever the client asks for. Without a ceiling, five shapes of query can take a production app down, the first four before a resolver even runs:
- Recursive —
{ a { a { a { … 50 levels … } } } }. Tiny payload, massive resolve work. - Wide / flat — a single selection with hundreds of fields.
- Volumetric fanout —
{ users { posts { comments { … } } } }where every step ishas_many. Three levels of page-sized fanout multiply out per parent. - Fragment repeats —
fragment A on Query { ...B ...B }at each of a few dozen levels. Under a kilobyte of text, billions of selections to read before any ceiling answers. - Rows’ copies —
query($v: String) { rows { f(x: $v) } }. Each row reads its arguments again, so 1,000 rows of a 1 MiB variable held a gigabyte at once, scoring 2.
nestrs wraps async-graphql’s two validation visitors that cover the
first three, and counts the other two before anything runs.
All of it is on by default; tune the ceilings to your
traffic. A subscription socket has bounds of its own — its message size,
its wait for connection_init and the operations it runs at once — on
Subscriptions.
The two ceilings
Section titled “The two ceilings”| Limit | Catches | Config field | Env var |
|---|---|---|---|
| Depth | Recursive | max_depth | <PREFIX>_GRAPHQL__MAX_DEPTH |
| Complexity | Wide + fanout (with per-field annotations) | max_complexity | <PREFIX>_GRAPHQL__MAX_COMPLEXITY |
Both are on by default (max_depth = 15, max_complexity = 2000). Each holds
to a range, refused at boot outside it: max_depth from 1 to 33, past which
async-graphql’s own recursion bound refuses a document whatever the limit says,
and max_complexity from 1 to ten million.
Keep both — depth alone misses wide queries, complexity alone misses
queries that depth-bomb the parser before the visitor even runs.
use nest_rs::core::module;use nest_rs::graphql::{GraphqlConfig, GraphqlModule};
#[module(imports = [ GraphqlModule::for_root(GraphqlConfig { max_depth: Some(15), max_complexity: Some(1000), ..Default::default() }),])]pub struct ApiModule;NESTRS_GRAPHQL__MAX_DEPTH=15NESTRS_GRAPHQL__MAX_COMPLEXITY=1000The validation runs before any resolver, so a query that exceeds
either limit costs the parse pass plus one visit — no DB round-trip,
no dataloader batch, no Repo call.
What each ceiling does
Section titled “What each ceiling does”The visitor walks the AST and tracks the deepest selection chain.
A query nesting deeper than max_depth returns a validation error.
Typical production value: 10 to 20. Real queries rarely go past 6 even with multi-level relation traversal; 15 leaves headroom for admin tooling.
Complexity
Section titled “Complexity”The visitor sums a score across every selected field. The default
scoring is async-graphql’s: each field contributes 1 + child_complexity (one for the field itself, plus the sum of its
selected sub-fields). A flat wide query of 500 fields scores 500;
a 4-level relation chain scores roughly 4. The score reads the document that
runs: copies of one field GraphQL merges into one, a mutation’s root field or a
list of lists selected twice, count once, as they run once
(where a failed field’s null lands).
The per-field override is where complexity becomes a real
anti-DoS mechanism. The #[expose] macro applies one
automatically — see field complexity.
Typical production value: 1000 to 5000, tuned from observed
legitimate queries. The check is strict > — max_complexity = 1000 admits a query scoring exactly 1000; pin 999 to reject it.
Pinning max_depth = Some(0) or max_complexity = Some(0) fails at
boot with a config error: 0 would block every query, so None is
the way to disable a check in code, and 0 its spelling from the
environment (<PREFIX>_GRAPHQL__MAX_DEPTH=0).
What fragments and variables multiply
Section titled “What fragments and variables multiply”A visitor scores a document by walking it, and a fragment is walked again at each of its spreads, so a walk can cost far more than the document weighs: 1,068 bytes held a release build for ten seconds, on a worker no request timeout can interrupt. nestrs counts what a document adds to its own text first, once per fragment and once per variable, in time linear in the document:
- A fragment spread again adds what it expands to. Those additions are held
to
max_complexity, whatever the visitor would score them: a__typenameor an unknown fragment counts one here, and nothing there. - A reference to a variable copies its value and scans the operation’s
definitions for its own, so
[$v, $v, …]costs the references times the value, and no score reads a list. What the operation a request runs copies and scans, as its fragments expand it, is held to twice what the request may carry:max_body_byteson aPOST,max_message_byteson a graphql-ws socket. A value counts what its text weighs and a step of a scan a byte, so every variable may be referred to twice. There is no key of its own to tune. - A field below a list reads its arguments again at each row, every row’s copy
held at once while the rows resolve together, so
query($v: String) { rows { f(x: $v) } }over 1,000 rows and a 1 MiB$vpeaked past a gigabyte, scoring 2. What the fields a list stands above read, their own arguments, their fragments’ and each reference’s value, is held tomax_list_argument_bytes(<PREFIX>_GRAPHQL__MAX_LIST_ARGUMENT_BYTES), 4 KiB by default, from1to a gibibyte,Noneor0off: a cursor, a page size and a filter at each of several connections stay far below it. A root field, or a field only objects stand above, reads its arguments once, so a mutation’s large input is never counted. The schema’s types are read only for a document whose fields below another field read past the bound. - A response key repeated looks each of its arguments up in the other’s, so two selections holding thousands cost their square. Each field’s arguments, squared, are held to that same limit, which the few a schema declares never come near.
- A fragment no operation spreads is refused unread, in validation’s words: async-graphql’s rules would otherwise recurse through it, and a long enough chain of them overflows the stack.
- A document rewritten as GraphQL collects it
(where a failed field’s
nulllands) copies a condition on a union once per member, or copies merged into a field per type, each copy around the next: 434 bytes nesting ten such conditions would add millions of fields. What the rewrite copies, past what it takes out, is held to the same limits as it writes it: its fields tomax_complexity, their arguments’ text to twice what the request may carry.
A document past a limit answers as one past max_complexity does:
{ "errors": [{ "message": "Query is too complex." }], "data": null }A document spreading each fragment once adds nothing, so what it scores stays the
visitor’s to say. One fragment under several parents, or the full
IntrospectionQuery, sits far below the default: a three-field document pays 30 ns
for the check, one with a variable 75 ns and one with three fragments 233 ns.
Field complexity
Section titled “Field complexity”A HasMany relation #[expose] writes scores its page — first times what each
row costs — and any exposed field or #[field_resolver] may name its own score.
Field complexity is the formula and the override.
On the wire
Section titled “On the wire”Validation failures come back as a regular errors[] array with a
200 OK:
{ "errors": [{ "message": "Query is nested too deep." }], "data": null}The message comes straight from async-graphql. Inspect it as you would any other validation error.
Calibration walkthrough
Section titled “Calibration walkthrough”- Set
max_depth = 15from day one. Cheap, almost never a false positive, catches the recursive bomb. - Set
max_complexity = 5000(generous) and log every denial atwarnfor a few weeks. Watch what hits the ceiling. - Once denials cluster around abusive queries (deep relation chains on public endpoints, scrapers requesting hundreds of fields), tighten to the lowest value that doesn’t trip legitimate traffic.
- Override on individual fields only when a relation’s realistic cost differs from its page size — a known-bounded set can use a smaller literal, and an expensive computed scalar a larger one.
Limits
Section titled “Limits”- A count is no score. A document repeating its fragments, whose fields the
schema scores under one each —
#[expose(complexity = 0)], a literal pinning a parent over its children, afirst: 1relation — can be refused for its repeats where its score alone would pass. Raisemax_complexity, which holds both. - A rewrite counts its copies, though one runs. Copies merged into a field per type, or a union’s condition copied per member, each count, where a value runs its own type’s alone; and the rewrite is counted at its largest, before a merge inside a copy per type folds a repeat away. Such a document can be refused below what runs: select the field once per type yourself.
- One unused fragment at a time. A document holding several, or another validation error beside one, reads the first in its text alone, where validation would have listed them all.
- A list’s rows are bounded by what one row copies, not by how many there are.
How many rows a list answers is known only once it ran, so a page of 100,000 rows
each reading 4 KiB still holds 400 MB of copies at once. Score the list by its rows
with a
complexity, which#[expose]writes for a relation, and page what a field answers. - A value is counted as text, and held in memory as values. A list of a million
small numbers fills a 2 MB body, and may be referred to twice as any variable may:
that request peaks at 233 MiB, 160 MiB of it before any copy, where a count of what
values take in memory would refuse a body the transport admits. Lower
max_body_bytesto lower both.
Underlying library
Section titled “Underlying library”The depth and complexity visitors live in
async-graphql. The framework
just exposes them through GraphqlConfig and threads the
#[graphql(complexity = "…")] attribute through #[expose]. The
expression grammar — child_complexity plus field arguments —
is async-graphql’s; see its
query complexity docs
for the full reference.
Reference
Section titled “Reference”crates/nest-rs-graphql/src/config.rs— theOption<usize>limitsmax_depth,max_complexityandmax_list_argument_bytes, and their env parsing.crates/nest-rs-graphql/src/resolver.rs—build_schemaapplies the limits to theSchemaBuilderbefore.finish().crates/nest-rs-graphql/src/document_cost.rs— what a document’s fragments and variables add, and what a list’s rows copy, counted before anything walks them.crates/nest-rs-seaorm-macros/src/relations.rs— theDEFAULT_HAS_MANY_COMPLEXITYconstant;attr.rsbeside it — the#[expose(complexity = …)]parsing.
Going further
Section titled “Going further”- Configuration — where
max_depth,max_complexityandmax_list_argument_bytesare set. - Relations — the auto-emitted
HasManyconnection and its complexity formula.