0
0
GraphQLquery~5 mins

Query complexity analysis in GraphQL

Choose your learning style9 modes available
Introduction

Query complexity analysis helps us understand how much work a GraphQL query will do before running it. This keeps the system fast and safe.

When you want to stop very big queries that slow down your app.
When you want to protect your server from too many requests at once.
When you want to give users limits on how detailed their queries can be.
When you want to plan how much resources your server needs for queries.
When you want to avoid accidental heavy queries that crash your system.
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
This example shows how to set a maximum complexity of 100 for queries using a complexity rule in a JavaScript GraphQL server.
GraphQL
# Example of assigning complexity in JavaScript GraphQL server
const complexityRule = queryComplexity({
  maximumComplexity: 100,
  estimators: [fieldConfigEstimator(), simpleEstimator({ defaultComplexity: 1 })],
});
This query asks for a user's name, their posts' titles, and comments' text. Complexity analysis will count how many fields are requested.
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
//     }
//   }
// }
OutputSuccess
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.