--- title: Complexity plugin description: Complexity plugin docs for Pothos --- This plugin allows you to define complexity of fields and limit the maximum complexity, depth, and breadth of queries. ## Usage ### Install ```package-install npm install --save @pothos/plugin-complexity ``` ### Setup ```typescript import SchemaBuilder from '@pothos/core'; import ComplexityPlugin from '@pothos/plugin-complexity'; const builder = new SchemaBuilder({ plugins: [ComplexityPlugin], }); ``` ### Configure defaults and limits To limit query complexity you can specify a maximum complexity either in the builder setup, or when building the schema: ```typescript const builder = new SchemaBuilder({ plugins: [ComplexityPlugin], complexity: { defaultComplexity: 1, defaultListMultiplier: 10, limit: { complexity: 500, depth: 10, breadth: 50, }, }, }); // or const schema = builder.toSchema({ complexity: { limit: { complexity: 500, depth: 10, breadth: 50, }, }, }); ``` #### Options - fieldComplexity: (optional, `(args, ctx, field) => { field: number, multiplier: number } | number`): default complexity calculation for fields. `defaultComplexity` and `defaultListMultiplier` will not be used if this is set. - defaultComplexity: (optional `number`) defines the default complexity for every field in the schema - defaultListMultiplier: (optional `number`) defines a default complexity multiplier for a list fields sub selections - limit: Defines limits for queries. For request-specific limits, pass a function such as `limit: (ctx) => ({ complexity: 500, depth: 10, breadth: 50 })`. - complexity: defines the maximum complexity allowed for queries - depth: defines the maximum depth of selections in a query - breadth: defines the maximum total selections in a query - complexityError: (optional `function`) defines the error to throw when the query complexity exceeds the limit. The function is passed the errorKind (depth, breadth, or complexity), the result (with the depth, breadth, complexity, and max values), and a GraphQL `info` object. It should return (or throw) an error, or an error message as a string ### How complexity is calculated Complexity is calculated before resolving any root level fields (query, mutation, subscription), and is based purely on the shape of the query before execution begins. The complexity of a query is the sum of the complexity of each selected field. If a field has sub-selections, the complexity of its sub-selections are multiplied by a fields multiplier, and then added to the fields own complexity. The default multiplier for fields is 1, and 10 for list fields. This multiplier is meant to represent the n+1 complexity of list fields. #### Example The following query has a complexity of `131` (assuming we are using the default options), a depth of `3`, and a breadth of `5`: ```gql query { posts { # complexity = 131 (posts + 10 * (2 + 11)) author { # complexity = 2 (author + 1 * name) name # complexity = 1, depth: 3 } comments { # complexity = 11 (comments + 10 * comment) comment # complexity = 1, depth: 3 } } } ``` ### Defining complexity of a field The following alternatives assume a `Post` object ref and a `loadPosts(limit)` function returning that model's records. Set a fixed cost with a number: ```typescript builder.queryFields((t) => ({ posts: t.field({ type: [Post], complexity: 20, resolve: () => loadPosts(20), }), })); ``` The complexity option can also set the multiplier for a field: ```typescript builder.queryFields((t) => ({ posts: t.field({ type: [Post], complexity: { field: 5, multiplier: 20 }, resolve: () => loadPosts(20), }), })); ``` A fields complexity can also be based on the fields arguments, or the context value: ```typescript builder.queryFields((t) => ({ posts: t.field({ type: [Post], args: { limit: t.arg.int(), }, // base multiplier on how many posts are being requested complexity: (args, ctx) => ({ field: 5, multiplier: Math.max(0, args.limit ?? 5) }), resolve: (parent, args) => { const limit = Math.max(0, args.limit ?? 5); return loadPosts(limit); }, }), })); ``` ### Example: a bounded list This configuration caps query cost at `20`, depth at `3`, and breadth at `5`: playground-examples/plugin-complexity/schema.ts#limits For a `Post` object with a `title` field, the list's base cost is `5` and its `limit` argument sets the multiplier. Here, `posts` is an array of records and `resolverCalls` is a counter used to observe whether the resolver is invoked: playground-examples/plugin-complexity/schema.ts#field-cost The selection `{ posts(limit: 2) { title } }` costs `5 + 2 × 1 = 7`. A limit of `16` costs `21`, so the budget rejects that query before invoking the resolver. A limit of `15` costs exactly `20` and is accepted. The multiplier follows the requested limit even when fewer records exist; query cost estimates the operation rather than measuring the records actually returned. ## Utilities ### `complexityFromQuery(query, options)` Returns the query complexity for a given GraphQL query. ```typescript import { complexityFromQuery } from '@pothos/plugin-complexity'; const complexity = complexityFromQuery(query, { schema: schema, // Complexity can be calculated based on the context and arguments, // so you may need to provide valid values for the context and arguments. // Both are optional, and will default to empty objects. ctx: {}, variables: {}, }); ``` ### `createComplexityRule(options)` Use this validation rule with GraphQL's `specifiedRules` to enforce `maxComplexity`, `maxDepth`, or `maxBreadth` during validation. Supply the request's `context` and raw `variableValues`; operation variable defaults and input defaults are applied before complexity callbacks run. Pass `operationName` when the request selects a named operation. Only that operation is measured, and an unknown name or invalid variables for it produce validation errors. Without `operationName`, all operations whose variables can be coerced are measured independently. In a multi-operation document, variable errors for other possible operations are left to GraphQL execution to report for the selected operation. A single operation's variable errors are reported during validation. ```typescript import { type GraphQLSchema, parse, specifiedRules, validate } from 'graphql'; import { createComplexityRule } from '@pothos/plugin-complexity'; function validateRequest( schema: GraphQLSchema, query: string, context: object, variableValues: Record, operationName?: string, ) { return validate(schema, parse(query), [ ...specifiedRules, createComplexityRule({ context, variableValues, operationName, maxComplexity: 500 }), ]); } ``` These validation results depend on the request's variables, context, and operation name. Do not reuse them across requests based only on the query text. `complexityFromQuery` also applies variable defaults and throws for invalid variables; it measures the first operation in the document.