⬡ GraphQL Intermediate

What is query complexity analysis in GraphQL?

Answer

Query complexity analysis assigns a cost to each field and rejects queries whose total cost exceeds a configured threshold, preventing expensive queries from overwhelming the server. Implemented by graphql-query-complexity. Each field gets a complexity value (default: 1); list fields get a multiplier based on the requested limit. Example: complexity: (args, childComplexity) => args.limit * childComplexity — fetching 100 users each with 10 posts costs 100 * 10 = 1000. If the threshold is 500, this query is rejected. Define field-level complexity in the schema or resolver map. Integration: add as a validation rule to the GraphQL server. Pair with depth limiting, rate limiting, and timeout for comprehensive DoS protection. Apollo Studio's operation metrics can help tune complexity budgets by analyzing real query costs in production.