0
0
GraphQLquery~5 mins

Query depth and complexity in GraphQL

Choose your learning style9 modes available
Introduction

Query depth and complexity help keep GraphQL queries simple and fast. They stop queries from asking for too much data at once.

When you want to protect your server from very large or slow queries.
When you want to make sure users only ask for data you can handle quickly.
When you want to avoid crashes caused by too many nested fields in a query.
When you want to limit how much data a client can request at one time.
When you want to keep your API fast and responsive for everyone.
Syntax
GraphQL
No direct GraphQL syntax for depth and complexity.
These are rules set on the server side using tools or middleware.
Example: Using a library to set maxDepth or maxComplexity limits.
Depth means how many levels deep a query goes into nested fields.
Complexity counts how much work a query asks the server to do.
Examples
This example limits queries to 5 levels deep to keep them simple.
GraphQL
# Example of setting max depth in a Node.js GraphQL server
const depthLimit = require('graphql-depth-limit');

const server = new ApolloServer({
  schema,
  validationRules: [depthLimit(5)]
});
This example limits queries to a complexity score of 100 to avoid heavy queries.
GraphQL
# Example of setting max complexity
const queryComplexity = require('graphql-query-complexity').queryComplexity;

const server = new ApolloServer({
  schema,
  validationRules: [
    queryComplexity({
      maximumComplexity: 100,
      onComplete: (complexity) => {
        console.log('Query complexity:', complexity);
      }
    })
  ]
});
Sample Program

This query asks for a user's name, their posts' titles, and comments' text on those posts. The depth here is 3 levels: user -> posts -> comments.

GraphQL
# Sample GraphQL query with nested fields
query {
  user(id: "1") {
    name
    posts {
      title
      comments {
        text
      }
    }
  }
}
OutputSuccess
Important Notes

Setting query depth and complexity limits helps keep your API safe and fast.

These limits are usually set on the server, not in the GraphQL query itself.

Too strict limits might block useful queries, so choose limits carefully.

Summary

Query depth limits how many nested levels a query can have.

Query complexity measures how much work a query asks the server to do.

Both help protect your server and keep responses fast.