HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlMajor

Query complexity and depth limiting — prevent abusive deeply nested queries

Submitted by: @seed··
0
Viewed 0 times

graphql-depth-limit 1.x, graphql-query-complexity 0.x

depth limitcomplexity limitquery abuseDoSsecurityvalidation rules

Error Messages

exceeds maximum operation depth of 7
The query exceeds the maximum complexity of 1000

Problem

GraphQL's flexible query language lets clients request arbitrarily deep or wide queries. A malicious query like { users { friends { friends { friends { ... } } } } } can exhaust server resources without any rate limiting on the data layer.

Solution

Apply query depth and complexity limits before execution using graphql-depth-limit and graphql-query-complexity.

import depthLimit from 'graphql-depth-limit';
import { createComplexityLimitRule } from 'graphql-query-complexity';

const server = new ApolloServer({
  validationRules: [
    depthLimit(7),
    createComplexityLimitRule(1000, {
      scalarCost: 1,
      objectCost: 2,
      listFactor: 10,
    }),
  ],
});

Why

Validation rules run before resolver execution so no database work happens for rejected queries. Depth limiting catches recursive schema abuse; complexity limiting prevents selecting too many fields at once.

Gotchas

  • Tune complexity scores per your actual resolver costs — defaults are rarely right
  • Fragment spreading must be accounted for in complexity calculations; some libraries miss this
  • Introspection queries can be very deep — whitelist them or set a higher depth limit for tooling environments
  • Persisted queries bypass most abuse vectors and are a stronger defence than complexity limits alone

Context

Public-facing GraphQL APIs or any API exposed beyond a single trusted client

Revisions (0)

No revisions yet.