Skip to the good stuff

πŸ”¬ GraphQL - gathering query complexity information

Posted on:May 2, 2024 at 04:57 AM

The increase verbosity principle is used to collect additional information about the problem. When working with GraphQL queries and mutations, it may be helpful to understand the complexity of a query.

When understanding query complexity, be aware of the limit and the score. Any query with a complexity score higher than the limit will be rejected. This is a protection mechanism to avoid denial-of-service or resource exhaustion attacks.

You can request both the configured limit and the score of the query you are running like so:

query {
  queryComplexity{
    limit
    score
  }
  currentUser {
    id
    username
	  projectMemberships {
      nodes {
        project{
          webUrl
        }
        userPermissions {
          removeProject
        }
      }
    }
  }
}

You can run that query in GraphiQL. (That works best if you’re already authenticated to gitlab.com.)

:cool: The GraphQL server offered by Dato CMS includes query complexity information in X-Complexity and X-Max-Complexity HTTP headers. You’ll get X-Complexity from kontent.ai. Similarly, ContentStack offers HTTP headers for X-Query-Complexity (and X-Resolver-Cost and X-Reference-Depth).

❓ A Good Question

Q: Does query complexity apply to both queries and mutations?

Interesting! Yes, in some implementations (0, 1) the complexity cost/score can be returned in both a query or a mutation. That’s not possible with all implementations:

"message": "Field 'complexity' doesn't exist on type 'Mutation'",

πŸ“š READ more

Depending on the specific problem you are facing and the access you have to make changes, you may need to increase the configured limit or adjust the query in order to decrease the score. Evaluating the tradeoffs is out of scope but I would personally recommend these resources to get started with learning a bit more:

πŸ”– TL;DR

When diagnosing problems that involve GraphQL, increase verbosity by collecting the query complexity and the configured complexity limit.

🎊 Take care!