Bird
Raised Fist0
GraphQLquery~10 mins

Query complexity analysis 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 - Query complexity analysis
Start: Receive GraphQL Query
Parse Query Structure
Traverse Query Fields
Calculate Complexity per Field
Sum Field Complexities
Compare Total Complexity to Limit
Reject Query
The system receives a GraphQL query, breaks it down, calculates complexity for each part, sums it, and decides if it is allowed based on a set limit.
Execution Sample
GraphQL
query {
  user(id: "1") {
    name
    posts {
      title
      comments {
        text
      }
    }
  }
}
This query requests a user's name, their posts' titles, and comments' text, which will be analyzed for complexity.
Execution Table
StepFieldComplexity per FieldRunning TotalAction
1user11Add complexity for user field
2name12Add complexity for name field
3posts1012Add complexity for posts field (10 posts assumed)
4title113Add complexity for title field
5comments518Add complexity for comments field (5 comments assumed)
6text119Add complexity for text field
7Total Complexity19Compare total 19 to limit 20
8DecisionAllow query execution (19 < 20)
💡 Total complexity 19 is less than limit 20, so query is allowed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6Final
total_complexity0121213181919
Key Moments - 3 Insights
Why does the 'posts' field add 10 to complexity instead of 1?
Because 'posts' is a list field assumed to return 10 items, each adding complexity 1, so total 10 is added at step 3 in the execution_table.
Why is the total complexity compared to a limit?
To prevent very expensive queries from running, the total complexity (19) is compared to a set limit (20) at step 7 to decide if the query is allowed.
Why do nested fields like 'comments' add complexity separately?
Each nested field can add its own complexity based on expected items (5 comments here), so 'comments' adds 5 at step 5, showing how nested structures increase total complexity.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the total complexity after processing the 'posts' field?
A13
B10
C12
D2
💡 Hint
Check the 'Running Total' column at step 3 in the execution_table.
At which step does the complexity for the 'comments' field get added?
AStep 4
BStep 5
CStep 6
DStep 3
💡 Hint
Look for the row with 'comments' in the 'Field' column in the execution_table.
If the limit was 15 instead of 20, what would be the decision at step 8?
AReject query
BAllow query execution
CPartial execution
DRetry query
💡 Hint
Compare the final total complexity 19 with the new limit 15 in the exit_note and step 7.
Concept Snapshot
Query complexity analysis in GraphQL:
- Parse query fields
- Calculate complexity per field (scalars = 1, lists = items * complexity)
- Sum all complexities
- Compare total to limit
- Reject if over limit, else allow execution
Full Transcript
Query complexity analysis in GraphQL involves breaking down a query into its fields, calculating how complex each field is based on expected data size, summing these complexities, and then comparing the total to a predefined limit. If the total complexity is below the limit, the query is allowed to run; otherwise, it is rejected to protect the server from expensive operations. For example, a query requesting a user, their posts, and comments will have complexity calculated step-by-step, adding complexity for each field and nested list. This process helps keep GraphQL APIs efficient and safe.

Practice

(1/5)
1. What is the main purpose of query complexity analysis in GraphQL?
easy
A. To measure how resource-heavy a query is before execution
B. To change the data returned by a query
C. To write queries faster
D. To store query results in cache

Solution

  1. Step 1: Understand query complexity analysis

    It estimates how much work a query will cause the server to do before running it.
  2. Step 2: Identify the main goal

    This helps prevent very heavy queries that slow down or crash the server.
  3. Final Answer:

    To measure how resource-heavy a query is before execution -> Option A
  4. Quick Check:

    Query complexity = resource estimation [OK]
Hint: Think: Why check query cost before running? To protect server [OK]
Common Mistakes:
  • Confusing complexity analysis with caching
  • Thinking it changes query results
  • Assuming it speeds up query writing
2. Which of the following is a correct way to define a complexity rule in a GraphQL server?
easy
A. Adding a complexity function to field definitions
B. Writing complexity inside the GraphQL query itself
C. Using @complexity directive in the query
D. Setting complexity in the client application

Solution

  1. Step 1: Recall where complexity rules are set

    Complexity rules are added in the server schema code, usually as functions on fields.
  2. Step 2: Eliminate wrong options

    Complexity is not set inside queries, directives, or client apps.
  3. Final Answer:

    Adding a complexity function to field definitions -> Option A
  4. Quick Check:

    Complexity rules = server schema code [OK]
Hint: Complexity rules live on server fields, not in queries [OK]
Common Mistakes:
  • Trying to add complexity in the query text
  • Using non-existent directives for complexity
  • Setting complexity on client side
3. Given this GraphQL query and complexity rules:
{ user { posts { comments } } }

If user has complexity 1, posts complexity 5, and comments complexity 2, what is the total complexity?
medium
A. 8
B. 15
C. 7
D. 10

Solution

  1. Step 1: Identify field complexities

    user = 1, posts = 5, comments = 2.
  2. Step 2: Calculate for nested fields

    Nested field complexities are multiplied: 1 x 5 x 2 = 10.
  3. Final Answer:

    10 -> Option D
  4. Quick Check:

    Nested fields multiply complexity = 1*5*2=10 [OK]
Hint: Multiply all nested field complexities: 1 x 5 x 2 = 10 [OK]
Common Mistakes:
  • Adding all numbers without multiplication
  • Ignoring nested field multiplication
  • Choosing sum instead of product for nested fields
4. You wrote a complexity function for a field but your server crashes on some queries. What is a likely cause?
medium
A. The query is missing required fields
B. You forgot to add the field to the schema
C. The complexity function returns a non-numeric value
D. The client sent an invalid query syntax

Solution

  1. Step 1: Understand complexity function requirements

    Complexity functions must return numbers representing cost.
  2. Step 2: Identify crash cause

    If the function returns a string or undefined, the server cannot calculate total complexity and crashes.
  3. Final Answer:

    The complexity function returns a non-numeric value -> Option C
  4. Quick Check:

    Complexity function must return number [OK]
Hint: Ensure complexity functions return numbers only [OK]
Common Mistakes:
  • Returning strings or null from complexity functions
  • Ignoring schema registration of fields
  • Blaming client query syntax for server crashes
5. You want to limit your GraphQL server to reject queries with complexity over 100. Which approach correctly implements this?
hard
A. Modify client queries to never exceed 100 complexity
B. Add a complexity rule that calculates total cost and rejects queries above 100
C. Use a directive in queries to mark complexity limits
D. Increase server timeout to handle heavy queries

Solution

  1. Step 1: Understand server-side complexity limiting

    The server must calculate query complexity and reject queries exceeding the limit.
  2. Step 2: Evaluate options

    Only adding a complexity rule on the server can enforce this limit automatically.
  3. Final Answer:

    Add a complexity rule that calculates total cost and rejects queries above 100 -> Option B
  4. Quick Check:

    Server enforces limits via complexity rules [OK]
Hint: Limit complexity on server, not client or query text [OK]
Common Mistakes:
  • Trying to limit complexity from client side
  • Using query directives which don't enforce limits
  • Increasing timeout instead of limiting complexity