Query depth and complexity limits
One small query can demand millions of nodes in a cyclic schema. Cap depth and estimated cost in GraphQL Yoga with GraphQL Armor, and learn what limits miss.
Query depth and complexity limits
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- The client chooses the shape of a GraphQL query, so a schema with cycles lets a tiny query demand an enormous response.
- A depth limit rejects queries nested deeper than N levels before any resolver runs.
- A cost limit adds up weights for each field and object and rejects queries over a budget, which also catches wide queries that depth misses.
- Both checks run at validation time, so a rejected query costs almost nothing to refuse.
- Limits are a ceiling, not a defence on their own. Pair them with pagination caps, timeouts and rate limiting.
The client writes the query
In a REST API the server decides what each endpoint returns. In GraphQL the client decides, and the schema is a graph. This is the useful part of the design and it is also the risk.
Take the schema from the earlier server lessons: Book has an author, and Author has books. That is a cycle, and a cycle means a query can walk it forever:
{ books { author { books { author { books { author { id } } } } } } }
Each hop multiplies the rows. If every author has twenty books and every book has an author, depth n costs on the order of 20^n objects. The query text is under a hundred bytes. This is a cheap denial-of-service attack, and it can also happen by accident from a client developer who nests one level too many. The N+1 problem you met in the n+1 lesson is how each level turns into a database round trip.
A depth limit
The simplest ceiling counts how deeply the selection nests and refuses anything past a threshold. I ran this with GraphQL Yoga 6.1.0 and @escape.tech/graphql-armor-max-depth 2.4.2:
import { createYoga } from "graphql-yoga";
import { maxDepthPlugin } from "@escape.tech/graphql-armor-max-depth";
const yoga = createYoga({ schema, plugins: [maxDepthPlugin({ n: 4 })] });
A normal query, { books { title } }, ran. The six-level query above returned:
{"errors":[{"message":"Syntax Error: Query depth limit of 4 exceeded, found 6."}]}
The “Syntax Error” prefix is how that plugin reports a rejection in validation; it is not a parse failure. The important fact is that the request was refused before any resolver was called, which is what makes the limit cheap.
Pick n from your real clients. Look at the deepest query your frontend legitimately sends, add a margin, and set the limit there. A limit somewhere around seven to ten is a typical starting point, not a rule. Too low breaks real screens; too high stops nothing.
A cost limit
Depth is a blunt tool. This query is shallow, yet expensive:
{ a: books { id } b: books { id } c: books { id } d: books { id } e: books { id } }
Five aliases of the same list, depth two. A cost limit assigns a weight to each field and sums over the query. I used @escape.tech/graphql-armor-cost-limit 2.4.3:
import { costLimitPlugin } from "@escape.tech/graphql-armor-cost-limit";
plugins: [costLimitPlugin({ maxCost: 10, objectCost: 2, scalarCost: 1 })]
With a deliberately low budget, { books { id title author { name } } } was refused with Query Cost limit of 10 exceeded, found 10.25. The plugin charges for objects and scalars and applies a factor for depth, so even that small query used more than my toy budget. In a real service you would set maxCost against the heaviest legitimate query, and use the plugin’s options for per-type or per-field weights.
Static cost has an honest limit: it estimates from the query alone. It does not know how many rows exist. A list field is the usual place to correct for that. Require a first or limit argument, cap it on the server, and have your cost function multiply by it. Pagination is partly a safety feature for this reason. I only ran the default weights; list-size multipliers are described in the library’s docs and in rate limiting and cost analysis.
What limits do not do
- They do not authenticate. Everyone pays the same budget unless you vary it by user.
- They do not bound time. A cheap-looking query can hit a slow resolver. Add a request timeout and database statement timeouts.
- They do not stop volume. A thousand legal queries a second is still a flood. That is rate limiting.
- They do not replace batching limits. Servers that accept arrays of operations, or many aliased mutations in one request, need a cap on operations per request too.
Together these form the usual posture: validate cheaply first, then bound the rest. The general API view is in the OWASP API Security Top 10, which lists unrestricted resource consumption as its own risk.
Where to put them
In Yoga, validation plugins like these run in the Envelop pipeline before execution, so they cost almost nothing when they refuse. With a gateway in front, such as the router, you can enforce limits there so every subgraph benefits.
What the video covers
StackHawk’s “GraphQL Security Best Practices” is a five-minute overview from October 2025. Its chapters are: an introduction, implement query depth and complexity limits, control batching and operation limits, manage introspection in production, and a fourth item that its chapter list cuts off. The first two numbered items are this lesson; the introspection item belongs to disabling introspection and hardening. It is a vendor overview rather than a code walkthrough, so the Yoga setup above is from my own run. Jamie Barton’s older Express video, linked under “go deeper”, shows a depth limit with the older query-depth-limit package, so treat it as a concept demo. I did not have a transcript for either.
Where this fits
You can now refuse a query that is too deep or too costly. Next, rate limiting and cost analysis bounds how often a client can spend that budget.
Check yourself
Why does a schema where Author has books and Book has author invite abuse?
The two types form a cycle, so a client can nest author { books { author { books ... } } } to any depth and multiply the work at each level.
What does a cost limit catch that a depth limit does not?
A shallow but wide query, such as many aliases of an expensive field, or a list with a huge first argument.
Why do these limits run before execution?
They inspect the parsed document against the schema, so the server can refuse a bad query without resolving any field.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.