Query complexity analysis helps us understand how much work a GraphQL query will do before running it. This keeps the system fast and safe.
Query complexity analysis in GraphQL
Introduction
Syntax
GraphQL
No fixed GraphQL syntax for complexity analysis; it is done by adding rules or middleware in your GraphQL server setup.
Complexity analysis is usually done in the server code, not in the GraphQL query itself.
You can assign a numeric cost to each field and sum them up to find total query cost.
Examples
GraphQL
# Example of assigning complexity in JavaScript GraphQL server const complexityRule = queryComplexity({ maximumComplexity: 100, estimators: [fieldConfigEstimator(), simpleEstimator({ defaultComplexity: 1 })], });
GraphQL
# Example query
{
user(id: "1") {
name
posts {
title
comments {
text
}
}
}
}Sample Program
This code sets up a GraphQL server that checks query complexity. It logs the complexity and blocks queries over 10 points.
GraphQL
# This is a conceptual example in JavaScript using graphql-query-complexity import { graphqlHTTP } from 'express-graphql'; import { queryComplexity, simpleEstimator, fieldConfigEstimator } from 'graphql-query-complexity'; const complexityRule = queryComplexity({ maximumComplexity: 10, estimators: [fieldConfigEstimator(), simpleEstimator({ defaultComplexity: 1 })], onComplete: (complexity) => { console.log('Query Complexity:', complexity); }, }); app.use('/graphql', graphqlHTTP({ schema: mySchema, validationRules: [complexityRule], })); // Query example: // { // user(id: "1") { // name // posts { // title // } // } // }
Important Notes
Complexity analysis helps prevent slow or harmful queries.
Assign complexity carefully to fields that return many items or do heavy work.
Use complexity analysis together with other protections like query depth limits.
Summary
Query complexity analysis measures how 'heavy' a GraphQL query is before running it.
It helps keep your server fast and safe by limiting big queries.
You add complexity rules in your server code, not in the query itself.
Practice
1. What is the main purpose of
query complexity analysis in GraphQL?easy
Solution
Step 1: Understand query complexity analysis
It estimates how much work a query will cause the server to do before running it.Step 2: Identify the main goal
This helps prevent very heavy queries that slow down or crash the server.Final Answer:
To measure how resource-heavy a query is before execution -> Option AQuick 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
Solution
Step 1: Recall where complexity rules are set
Complexity rules are added in the server schema code, usually as functions on fields.Step 2: Eliminate wrong options
Complexity is not set inside queries, directives, or client apps.Final Answer:
Adding acomplexityfunction to field definitions -> Option AQuick 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:
If
{ user { posts { comments } } }If
user has complexity 1, posts complexity 5, and comments complexity 2, what is the total complexity?medium
Solution
Step 1: Identify field complexities
user = 1, posts = 5, comments = 2.Step 2: Calculate for nested fields
Nested field complexities are multiplied: 1 x 5 x 2 = 10.Final Answer:
10 -> Option DQuick 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
Solution
Step 1: Understand complexity function requirements
Complexity functions must return numbers representing cost.Step 2: Identify crash cause
If the function returns a string or undefined, the server cannot calculate total complexity and crashes.Final Answer:
The complexity function returns a non-numeric value -> Option CQuick 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
Solution
Step 1: Understand server-side complexity limiting
The server must calculate query complexity and reject queries exceeding the limit.Step 2: Evaluate options
Only adding a complexity rule on the server can enforce this limit automatically.Final Answer:
Add a complexity rule that calculates total cost and rejects queries above 100 -> Option BQuick 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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
