Depth limiting helps stop queries from asking for too much nested data. This keeps the system fast and safe.
Depth limiting in GraphQL
Start learning this pattern below
Jump into concepts and practice - no test required
const depthLimit = require('graphql-depth-limit'); const server = new ApolloServer({ typeDefs, resolvers, validationRules: [depthLimit(3)] });
This example uses the graphql-depth-limit package with Apollo Server.
The number 3 means queries can only go 3 levels deep.
validationRules: [depthLimit(2)]validationRules: [depthLimit(5)]validationRules: [depthLimit(1)]This sets up a GraphQL server that limits queries to 2 levels deep. Queries asking for more nested data will be rejected.
const { ApolloServer, gql } = require('apollo-server'); const depthLimit = require('graphql-depth-limit'); const typeDefs = gql` type Query { user: User } type User { id: ID name: String posts: [Post] } type Post { id: ID title: String comments: [Comment] } type Comment { id: ID content: String } `; const resolvers = { Query: { user: () => ({ id: '1', name: 'Alice', posts: [ { id: '101', title: 'Hello World', comments: [ { id: '1001', content: 'Nice post!' }, { id: '1002', content: 'Thanks for sharing.' } ] } ] }) } }; const server = new ApolloServer({ typeDefs, resolvers, validationRules: [depthLimit(2)] }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
Depth limiting helps protect your server from very complex queries.
Choose the depth limit based on how much nested data your app needs.
Too low a limit might block useful queries; too high might allow heavy loads.
Depth limiting stops queries from going too deep.
It keeps your server safe and fast.
Use it by adding validation rules in your GraphQL server setup.
Practice
What is the main purpose of depth limiting in GraphQL?
Solution
Step 1: Understand what depth limiting controls
Depth limiting restricts how deep a GraphQL query can go into nested fields.Step 2: Identify the purpose of this restriction
This prevents overly complex queries that can slow down or crash the server.Final Answer:
To stop queries from going too deep and protect the server -> Option DQuick Check:
Depth limiting = Protect server from deep queries [OK]
- Thinking depth limiting speeds up client rendering
- Confusing depth limiting with user access control
- Believing depth limiting increases query depth
Which of the following is the correct way to set a maximum query depth of 5 in a GraphQL server using graphql-depth-limit?
const depthLimit = require('graphql-depth-limit');
const server = new ApolloServer({
schema,
validationRules: [ /* ??? */ ]
});Solution
Step 1: Recall the usage of graphql-depth-limit
The package exports a function called depthLimit that takes the max depth as an argument.Step 2: Match the correct syntax
The correct way is to pass depthLimit(5) inside validationRules array.Final Answer:
validationRules: [depthLimit(5)] -> Option AQuick Check:
depthLimit(5) sets max depth 5 [OK]
- Using non-existent methods like max or setMaxDepth
- Passing depthLimit without parentheses
- Placing depthLimit outside validationRules array
Given this GraphQL query and a server with depth limit set to 3, what will happen?
{
user {
posts {
comments {
text
}
}
}
}Solution
Step 1: Calculate the query depth
The query goes user (level 1) -> posts (level 2) -> comments (level 3) -> text (level 4). Depth is 4.Step 2: Compare with the depth limit
The server limits depth to 3, but query depth is 4, so it exceeds the limit.Final Answer:
The query will fail due to exceeding the depth limit -> Option CQuick Check:
Query depth 4 > limit 3 = fail [OK]
- Counting leaf fields as separate depth
- Assuming depth limit applies per field, not whole query
- Thinking partial data returns on depth limit exceed
What is wrong with this GraphQL server setup code that tries to limit query depth?
const depthLimit = require('graphql-depth-limit');
const server = new ApolloServer({
schema,
validationRules: depthLimit(4)
});Solution
Step 1: Check the expected type of validationRules
validationRules expects an array of functions, not a single function.Step 2: Identify the mistake in the code
The code passes depthLimit(4) directly, missing the array brackets.Final Answer:
validationRules should be an array, not a single function -> Option AQuick Check:
validationRules = [depthLimit(4)] [OK]
- Passing function directly instead of array
- Calling depthLimit without max depth argument
- Misplacing schema inside validationRules
You want to allow queries up to depth 4 but block deeper ones. You also want to log a warning when a query exceeds the limit. Which approach correctly combines depth limiting with custom logging in a GraphQL server?
const depthLimit = require('graphql-depth-limit');
const { ApolloServer } = require('apollo-server');
const loggingDepthLimit = (maxDepth) => {
return (context) => {
const validationRule = depthLimit(maxDepth);
return (validationContext) => {
const errors = validationRule(validationContext);
if (errors && errors.length > 0) {
console.warn('Query depth exceeded:', errors);
}
return errors;
};
};
};
const server = new ApolloServer({
schema,
validationRules: [loggingDepthLimit(4)]
});Solution
Step 1: Understand wrapping validation rules
Validation rules are functions that can be wrapped to add behavior like logging.Step 2: Analyze the custom logging wrapper
The code creates a function that calls depthLimit and logs warnings if errors occur.Step 3: Confirm usage in ApolloServer
Passing the wrapped function inside an array to validationRules is correct.Final Answer:
This code correctly wraps depthLimit to log warnings on depth exceed -> Option BQuick Check:
Wrap validationRules to add logging = correct [OK]
- Assuming validationRules can't be wrapped
- Passing validationRules as single function instead of array
- Trying to log outside validationRules without access to errors
