Bird
Raised Fist0
GraphQLquery~10 mins

Depth limiting in GraphQL - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Depth limiting
Client sends GraphQL query
Parse query into AST
Calculate depth of query
Depth <= limit
Execute query
Return data
The server checks the query depth before running it. If the depth is too big, it rejects the query to keep the server safe.
Execution Sample
GraphQL
query {
  user {
    posts {
      comments {
        text
      }
    }
  }
}
This query asks for user posts and their comments text, which has a depth of 4.
Execution Table
StepActionCurrent DepthMax Depth FoundDecision
1Start parsing root field 'user'11Continue
2Parse 'posts' inside 'user'22Continue
3Parse 'comments' inside 'posts'33Continue
4Parse 'text' inside 'comments'44Continue
5End of query fields44Check depth limit
6Compare max depth 4 with limit 344Reject query - depth too high
💡 Query rejected because max depth 4 exceeds limit 3
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
Current Depth012344
Max Depth Found012344
DecisionNoneContinueContinueContinueContinueReject
Key Moments - 3 Insights
Why does the depth count increase when we go inside nested fields?
Each nested field adds one level to the depth. For example, 'user' is depth 1, 'posts' inside 'user' is depth 2, and so on, as shown in execution_table rows 1 to 4.
What happens if the query depth equals the limit?
If the depth is equal to or less than the limit, the query is allowed. In this example, the query depth 4 is greater than limit 3, so it is rejected (see execution_table row 6).
Why reject queries with too much depth?
Deep queries can overload the server and slow down responses. Depth limiting protects the server by rejecting queries that are too complex, as shown in the final decision in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the max depth found after parsing 'comments'?
A2
B4
C3
D1
💡 Hint
Check the 'Max Depth Found' column at Step 3 in the execution_table.
At which step does the server decide to reject the query?
AStep 4
BStep 6
CStep 5
DStep 3
💡 Hint
Look at the 'Decision' column in the execution_table where it says 'Reject query - depth too high'.
If the depth limit was increased to 5, what would be the final decision?
AExecute query
BReject query
CError in parsing
DPartial execution
💡 Hint
Compare the max depth 4 with the new limit 5 in the execution_table logic.
Concept Snapshot
Depth limiting in GraphQL:
- Measures how deep a query's nested fields go
- Server calculates max depth before execution
- If depth > limit, query is rejected
- Protects server from expensive queries
- Example: depth 4 query rejected if limit is 3
Full Transcript
Depth limiting in GraphQL means checking how many nested levels a query has before running it. The server parses the query and counts the depth step by step. If the depth is more than the allowed limit, the server rejects the query to keep the system safe and fast. For example, a query with user, posts, comments, and text fields has depth 4. If the limit is 3, the server will reject it. This prevents very complex queries from slowing down or crashing the server.

Practice

(1/5)
1.

What is the main purpose of depth limiting in GraphQL?

easy
A. To speed up the client-side rendering
B. To increase the depth of queries for more data
C. To limit the number of users accessing the server
D. To stop queries from going too deep and protect the server

Solution

  1. Step 1: Understand what depth limiting controls

    Depth limiting restricts how deep a GraphQL query can go into nested fields.
  2. Step 2: Identify the purpose of this restriction

    This prevents overly complex queries that can slow down or crash the server.
  3. Final Answer:

    To stop queries from going too deep and protect the server -> Option D
  4. Quick Check:

    Depth limiting = Protect server from deep queries [OK]
Hint: Depth limiting stops deep queries to keep server safe [OK]
Common Mistakes:
  • Thinking depth limiting speeds up client rendering
  • Confusing depth limiting with user access control
  • Believing depth limiting increases query depth
2.

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: [ /* ??? */ ]
});
easy
A. validationRules: [depthLimit(5)]
B. validationRules: [depthLimit.max(5)]
C. validationRules: [depthLimit.setMaxDepth(5)]
D. validationRules: [depthLimit.limit(5)]

Solution

  1. Step 1: Recall the usage of graphql-depth-limit

    The package exports a function called depthLimit that takes the max depth as an argument.
  2. Step 2: Match the correct syntax

    The correct way is to pass depthLimit(5) inside validationRules array.
  3. Final Answer:

    validationRules: [depthLimit(5)] -> Option A
  4. Quick Check:

    depthLimit(5) sets max depth 5 [OK]
Hint: Use depthLimit(number) inside validationRules [OK]
Common Mistakes:
  • Using non-existent methods like max or setMaxDepth
  • Passing depthLimit without parentheses
  • Placing depthLimit outside validationRules array
3.

Given this GraphQL query and a server with depth limit set to 3, what will happen?

{
  user {
    posts {
      comments {
        text
      }
    }
  }
}
medium
A. The query will succeed and return all comments' text
B. The query will return only user and posts without comments
C. The query will fail due to exceeding the depth limit
D. The query will return an empty response

Solution

  1. Step 1: Calculate the query depth

    The query goes user (level 1) -> posts (level 2) -> comments (level 3) -> text (level 4). Depth is 4.
  2. Step 2: Compare with the depth limit

    The server limits depth to 3, but query depth is 4, so it exceeds the limit.
  3. Final Answer:

    The query will fail due to exceeding the depth limit -> Option C
  4. Quick Check:

    Query depth 4 > limit 3 = fail [OK]
Hint: Count nested fields; if deeper than limit, query fails [OK]
Common Mistakes:
  • Counting leaf fields as separate depth
  • Assuming depth limit applies per field, not whole query
  • Thinking partial data returns on depth limit exceed
4.

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)
});
medium
A. validationRules should be an array, not a single function
B. depthLimit should be called without arguments
C. schema must be inside validationRules
D. ApolloServer does not support validationRules

Solution

  1. Step 1: Check the expected type of validationRules

    validationRules expects an array of functions, not a single function.
  2. Step 2: Identify the mistake in the code

    The code passes depthLimit(4) directly, missing the array brackets.
  3. Final Answer:

    validationRules should be an array, not a single function -> Option A
  4. Quick Check:

    validationRules = [depthLimit(4)] [OK]
Hint: Wrap depthLimit call inside array for validationRules [OK]
Common Mistakes:
  • Passing function directly instead of array
  • Calling depthLimit without max depth argument
  • Misplacing schema inside validationRules
5.

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)]
});
hard
A. depthLimit cannot be wrapped; this will cause runtime errors
B. This code correctly wraps depthLimit to log warnings on depth exceed
C. validationRules must be a single function, not an array
D. Logging should be done outside validationRules, this is incorrect

Solution

  1. Step 1: Understand wrapping validation rules

    Validation rules are functions that can be wrapped to add behavior like logging.
  2. Step 2: Analyze the custom logging wrapper

    The code creates a function that calls depthLimit and logs warnings if errors occur.
  3. Step 3: Confirm usage in ApolloServer

    Passing the wrapped function inside an array to validationRules is correct.
  4. Final Answer:

    This code correctly wraps depthLimit to log warnings on depth exceed -> Option B
  5. Quick Check:

    Wrap validationRules to add logging = correct [OK]
Hint: Wrap depthLimit in function to add logging, pass in array [OK]
Common Mistakes:
  • Assuming validationRules can't be wrapped
  • Passing validationRules as single function instead of array
  • Trying to log outside validationRules without access to errors