Skip to content

Securing GraphQL: Query Depth, Complexity and Rate Limiting

A single GraphQL endpoint accepts arbitrarily nested queries – convenient and at the same time a risk of abuse. I show how I build a layered defense against expensive queries with a depth limit, a complexity budget, pagination caps and rate limiting.

≈ 11 min readSoftwareGraphQLAPI

With a REST API, the cost profile of a route is usually more narrowly bounded: if you build /users/1/posts, you know the intended execution path, even if parameters and data volume still change the actual cost. GraphQL gives the caller more influence over the shape and depth of the query. For developer experience, that’s a win. For operations, it means the cost of a request can only be estimated from the incoming document and the resolver behavior.

The question on which everything hinges is: What happens when someone sends a query nested twenty levels deep with first: 1000 on every level? If you have no answer to that, you are running an API that falls over at the first unfriendly client – and you’ll notice for the first time exactly then.

This post is not about authentication or authorization – I covered that in GraphQL auth in the context. This is about something orthogonal: protection against expensive and malicious queries. A properly authenticated, authorized user can still bring the server to its knees. If all you have is auth, you are unprotected against this class of problems.

Why one endpoint becomes dangerous#

The core problem is cyclic relationships in the schema. As soon as a User has its posts and a Post has its author – who in turn has their posts – the depth is formally unbounded:

query MaliciousDepth {
  user(id: "1") {
    posts {
      author {
        posts {
          author {
            posts {
              author {
                # ... and so on, as deep as the client wants
                name
              }
            }
          }
        }
      }
    }
  }
}

Each additional level can multiply the number of resolver calls. Whether this also turns into a corresponding number of database accesses depends on batching, caching and the resolvers. Combined with unbounded lists, though, an extremely expensive query can still emerge – a denial of service with a single HTTP request. This is not a hypothetical textbook scenario. I have seen production APIs tip over exactly like this because a frontend bug accidentally generated a recursive query.

The good news: defense works well in layers here. No single measure is enough, but the combination makes the attack surface manageable. The flow I aim for looks like this:

flowchart TD
  A[Client request] --> B{Rate limit<br/>at the edge}
  B -->|budget exceeded| R1[429 Too Many Requests]
  B -->|ok| C{Depth gate<br/>graphql-depth-limit}
  C -->|too deep| R2[Validation error]
  C -->|ok| D{Complexity gate<br/>cost budget}
  D -->|over budget| R3[Validation error]
  D -->|ok| E[Resolver execution<br/>with pagination caps]
  E --> F[Response]

The crucial property: the depth and complexity checks kick in during the validation phase, i.e. before a single resolver runs. Parsing and validation also cost resources, but with size and rate limits they remain much easier to bound than the actual resolver execution.

Layer 1: Limiting query depth#

The simplest and most effective first step is a limit on nesting depth. In Apollo Server 4, you add a validation rule to the validationRules of the constructor. The widely used library for this is graphql-depth-limit:

import { ApolloServer } from "@apollo/server";
import depthLimit from "graphql-depth-limit";
import { typeDefs } from "./schema";
import { resolvers } from "./resolvers";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    // Reject any operation nested deeper than 7 levels.
    depthLimit(7),
  ],
});

depthLimit(maxDepth) returns a graphql-js validation rule that counts the deepest nesting during validation and rejects operations above the limit. Introspection fields such as __schema and __type are ignored by default so tools keep working.

A word of warning that belongs here in 2024: graphql-depth-limit (v1.1.0) hasn’t been maintained since 2018 and counts only selection depth – not the depth of lists. For many projects that is enough as a first layer, as long as you are aware of the gap. If you want to be stricter, take a look at @graphile/depth-limit, which also accounts for list depth.

The conceptual limit matters: depth limiting knows nothing about field costs. A flat query that selects a thousand expensive fields on a single level goes through without complaint. Depth is just one dimension of abuse.

Layer 2: Complexity and cost analysis#

That brings us to the second layer, which compensates for the weakness of the first. Instead of only counting depth, I assign costs per field and reject every query that exceeds an overall budget. The established tool for this is graphql-query-complexity by slicknode.

The core is createComplexityRule, which I configure with a maximumComplexity budget and a list of estimators. Estimators are the rules by which costs are calculated – they are consulted in order until one returns a value:

import { ApolloServer } from "@apollo/server";
import depthLimit from "graphql-depth-limit";
import {
  createComplexityRule,
  simpleEstimator,
  fieldExtensionsEstimator,
} from "graphql-query-complexity";

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    depthLimit(7),
    createComplexityRule({
      maximumComplexity: 1000,
      estimators: [
        // Prefer explicit costs declared on the schema fields...
        fieldExtensionsEstimator(),
        // ...and fall back to a flat cost of 1 per field.
        simpleEstimator({ defaultComplexity: 1 }),
      ],
      onComplete: (complexity) => {
        console.log(`Query complexity: ${complexity}`);
      },
    }),
  ],
});

The actual modeling happens on the fields themselves. Through fieldExtensionsEstimator, I read costs from the schema extensions – and this is exactly where I model lists realistically. A field that returns a list doesn’t have a constant cost but one proportional to the requested first value:

import { GraphQLObjectType, GraphQLList } from "graphql";
import type { ComplexityEstimatorArgs } from "graphql-query-complexity";

const UserType = new GraphQLObjectType({
  name: "User",
  fields: {
    posts: {
      type: new GraphQLList(PostType),
      args: { first: { type: GraphQLInt } },
      extensions: {
        // Cost scales with the number of requested items.
        complexity: ({ args, childComplexity }: ComplexityEstimatorArgs) => {
          const requested = args.first ?? 20;
          return childComplexity * requested;
        },
      },
    },
  },
});

This is where cost analysis plays to its strength. A deep query with small lists can be cheaper than a flat one with huge lists. The budget of 1000 is not a magic number – I derive it from real query patterns by first letting onComplete only log and observing where legitimate clients end up before I lock the gate for real.

One detail about the Apollo Server 4 integration that tends to cost time: for plain rejection, the validation rule above is enough. But if you want to process the complexity further in the request lifecycle – for example for cost accounting per API key – you use a custom plugin and compute the complexity in the didResolveOperation hook with getComplexity(). The ready-made AS3 plugin wrapper createComplexityPlugin no longer fits directly into AS4, which is why the manual plugin route is worth a brief mention:

import type { ApolloServerPlugin } from "@apollo/server";
import { getComplexity, simpleEstimator } from "graphql-query-complexity";
import { separateOperations } from "graphql";

const complexityPlugin: ApolloServerPlugin = {
  async requestDidStart() {
    return {
      async didResolveOperation({ request, document, schema }) {
        const complexity = getComplexity({
          schema,
          operationName: request.operationName,
          query: request.operationName
            ? separateOperations(document)[request.operationName]
            : document,
          variables: request.variables,
          estimators: [simpleEstimator({ defaultComplexity: 1 })],
        });

        if (complexity > 1000) {
          throw new Error(
            `Query is too expensive: ${complexity}. Maximum allowed: 1000.`,
          );
        }
      },
    };
  },
};

Layer 3: Pagination caps#

The cost rule can only evaluate lists correctly if I bound lists in the first place. A first argument without a server-side maximum is an open flank: a single call with first: 100000 triggers tens of thousands of resolvers. That’s why I clamp every pagination parameter on the server, regardless of what the client asks for:

const MAX_PAGE_SIZE = 100;
const DEFAULT_PAGE_SIZE = 20;

const resolvers = {
  User: {
    posts: (parent, args, context) => {
      // Never trust the client-supplied page size.
      const first = Math.min(args.first ?? DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE);
      return context.dataSources.posts.byAuthor(parent.id, { first });
    },
  },
};

If you build your schema cleanly following the connections pattern, you already have a natural place for this limit – I described what that looks like structurally in GraphQL pagination and connections. The cap belongs in the resolver or a shared helper function, not in the documentation as a polite request to the client.

Layer 4: Rate limiting#

Depth and complexity limit the cost of a single query. They say nothing about how many queries per second someone fires. Rate limiting is not a core Apollo feature, and in my experience the most reliable place for it is the transport layer – a reverse proxy or a middleware in front of the GraphQL handler:

import express from "express";
import rateLimit from "express-rate-limit";

const app = express();

const limiter = rateLimit({
  windowMs: 60_000, // one minute
  max: 120, // limit each IP to 120 requests per window
  standardHeaders: true,
  legacyHeaders: false,
});

app.use("/graphql", limiter);

For fine-grained per-field limits, there are directive-based approaches such as graphql-rate-limit with a @rateLimit directive in the schema. That is powerful, but it also adds operational complexity. A coarse limit at the edge carries most of the load; fine-grained directives only pay off where a specific field demonstrably causes trouble.

Persisted queries and allowlisting – with caution#

At this point, the suggestion regularly comes up: “Let’s turn on Automatic Persisted Queries (APQ), then the problem is solved.” That is a widespread misunderstanding I want to clear up.

APQ is a performance feature. Instead of the full query, the client sends only a SHA-256 hash; if the server doesn’t know the hash, it responds with PERSISTED_QUERY_NOT_FOUND, the client sends the query once, and the server caches it. That saves bandwidth. It is not an allowlist – APQ automatically registers any incoming operation, including the malicious one.

const server = new ApolloServer({
  typeDefs,
  resolvers,
  // Performance optimization, NOT a security control.
  persistedQueries: { ttl: 900 },
});

Real safelisting is something else: a pre-registered list of allowed operations that the server checks against. Anything not on the list is rejected – no matter how deep or expensive. In the Apollo world, this runs through a Persisted Query List in GraphOS together with the Apollo Router, an enterprise feature where APQ is then deliberately disabled. For internal APIs with a known set of client operations, this is the strongest defense of all, because the set of possible queries is finite and checked. For a public API with arbitrary clients, however, it is not an option – there, depth and complexity carry the load.

Introspection in production#

The last building block is often overrated. Disabling introspection in production (introspection: false) prevents an attacker from conveniently querying the schema. That is a sensible default for non-public APIs – but I deliberately don’t call it security; I call it taking away an attacker’s convenience. It is security by obscurity: anyone who knows or guesses the schema gets past any disabled introspection. Disabling introspection replaces not a single one of the real limits above. It’s a nice extra, not a foundation.

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: process.env.NODE_ENV !== "production",
});

This also includes a server-side request timeout, so that a query that runs long despite all the gates doesn’t tie up resources indefinitely. That is the emergency brake behind all the other layers.

The layers at a glance#

For a production GraphQL endpoint, I add the layers from the outside in:

  • Rate limiting at the edge limits how many requests get through at all per time window.
  • Persisted queries or an allowlist only allow known operations when the circle of clients is closed.
  • A depth limit caps the nesting depth before execution even starts.
  • The complexity budget assigns costs per field and rejects queries that are too expensive.
  • Pagination caps prevent unbounded lists and make cost analysis correct in the first place.
  • A resolver timeout is the emergency brake for everything that still slips through.

None of these layers is complete on its own. Depth without complexity misses wide queries. Complexity without pagination caps calculates with the wrong multipliers. Rate limiting without cost analysis lets individual expensive queries through. Only in combination do you get an endpoint whose worst case I know and can control.

Conclusion#

GraphQL’s flexibility shifts control from the server to the client – and with it the ability to overload the server. The most common mistake in practice is assuming that authentication is enough protection. It isn’t: an attack via expensive queries is orthogonal to the question of who the user is. A legitimate, logged-in client can produce the same DoS query through a simple bug as an attacker can on purpose.

The order that has proven itself: first make the cost profile visible (log complexity), then add the gates from coarse to fine – depth limit and pagination caps as quick wins, the complexity budget as the actual backbone, rate limiting as the frame, an allowlist where the circle of clients permits it. Introspection and timeouts round things off but don’t carry the load. With these layers in place, you can bound the load per request much better and observe in operation where estimated and real resolver costs diverge.

Further reading#

Revised and translated from German with the help of AI.