Full answer
Why GraphQL needs this
- One request can ask for a very large result: { users { friends { friends { friends { name } } } } } grows exponentially. Aliases let a client repeat an expensive field 100 times in one request. Rate limiting by request count does not see this.
Controls
- Depth limit: reject queries deeper than N (often 6 to 10) using a validation rule. Cheap and effective for cyclic schemas.
- Complexity or cost analysis: give each field a cost (more for lists, multiplied by first or limit arguments), reject queries above a budget, and use the cost for rate limits.
- Pagination limits: require first or limit on lists, with a maximum (for example 100). Never return unbounded lists.
- Alias and directive limits to stop batching abuse and brute force (for example 1000 login attempts in aliases of one mutation).
- Size limits: maximum body size and query length. Timeouts for resolvers and for the whole operation.
- Persisted queries: the server knows only a list of approved query ids (or hashes). It removes arbitrary queries from private clients and speeds up requests.
- Introspection off in production for private APIs, because it maps the whole schema for an attacker. It is not security by itself.
- Authorization in every resolver (and for subscriptions) and input validation for arguments.
- Do not return detailed errors or stack traces. Log with request ids.
Implementation in Node
- graphql-js: validate(schema, documentAST, [...specifiedRules, myRule]) runs rules before execute. Libraries: graphql-depth-limit, graphql-armor (a bundle of protections), graphql-query-complexity.
- NoSchemaIntrospectionCustomRule from graphql disables introspection queries.
javascript
const { buildSchema, parse, validate, specifiedRules, NoSchemaIntrospectionCustomRule, GraphQLError, Kind } = require('graphql');
const schema = buildSchema(`
type User { name: String! friends: [User!]! }
type Query { user: User }
`);
// A validation rule that measures the deepest selection path.
function maxDepth(limit) {
return (context) => ({
Document: {
enter(document) {
const depthOf = (selectionSet, depth) => Math.max(depth, ...(selectionSet?.selections ?? []).map((s) => (s.kind === Kind.FIELD ? depthOf(s.selectionSet, depth + 1) : depth)));
for (const definition of document.definitions) {
if (definition.kind === Kind.OPERATION_DEFINITION) {
const depth = depthOf(definition.selectionSet, 0);
if (depth > limit) context.reportError(new GraphQLError(`Query depth ${depth} is above the limit of ${limit}`));
}
}
},
},
});
}
// A very simple alias counter: repeating one field many times under different names.
function maxAliases(limit) {
return (context) => {
let count = 0;
return {
Field(node) { if (node.alias && ++count === limit + 1) context.reportError(new GraphQLError(`More than ${limit} aliases`)); },
};
};
}
const rules = [...specifiedRules, maxDepth(4), maxAliases(3), NoSchemaIntrospectionCustomRule];
const check = (label, source) => {
const errors = validate(schema, parse(source), rules);
console.log(label.padEnd(18), errors.length ? 'rejected: ' + errors[0].message : 'accepted');
};
check('shallow query', '{ user { name friends { name } } }');
check('deep query', '{ user { friends { friends { friends { friends { name } } } } } }');
check('alias abuse', '{ a: user { name } b: user { name } c: user { name } d: user { name } }');
check('introspection', '{ __schema { types { name } } }');Three validation rules reject a deep query, an alias flood and an introspection query before any resolver runs. A shallow query passes. Install first with npm install graphql (run here with graphql 16.15.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): shallow query accepted deep query rejected: Query depth 6 is above the limit of 4 alias abuse rejected: More than 3 aliases introspection rejected: GraphQL introspection has been disabled, but the requested query contained the field "__schema".
Key points
- Clients control query shape, so cost must be limited.
- Depth and cost limits run as validation rules before execution.
- Limit list sizes, aliases and request size.
- Disable introspection and use persisted queries for private APIs.
- Authorise in every resolver.
Common mistakes
- Rate limiting only by request count.
- Returning unbounded lists.
- Relying on hidden introspection as the only protection.
- Checking depth only for fields and forgetting fragments.
- No timeout on resolvers.
Follow-ups
- How does persisted queries support security?
- How do you estimate the cost of a list field?
- Why do aliases matter for brute-force attacks?
Tips
- Start with the exponential query example.
- List depth, cost, size, introspection.
- Say 'validation runs before execution'.