Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Security and Performance

Query Depth, Complexity and Other Attacks

Learn how abusive GraphQL queries bring servers down and how depth limits, cost analysis, timeouts, persisted queries and rate limits defend against them.

In REST, the server decides what each URL returns, so the cost of a request is fairly predictable. In GraphQL, the client writes the query. That is the whole point of the language, and it is also the main risk: a client can ask for something enormous with a few lines of text. A public GraphQL endpoint without limits is an invitation to a denial-of-service attack, even from a well-meaning developer with a typo.

This lesson covers the common abuse patterns and the defenses used in production. No GraphQL server runs on this site, so the server configuration and GraphQL documents below are read-only. The runnable examples are stand-ins: small JavaScript programs that compute depth and cost the way a validation rule in a real server library does. They are not a real GraphQL engine. Authentication and permissions are a separate topic, covered in Authentication and Authorization.

Five ways to hurt a server

Deep nesting Relationships that loop back on themselves.
Huge lists Ask for a million rows per level.
Alias floods One field repeated hundreds of times.
Batching Many operations in one HTTP request.

Each one is a valid query. Validation alone does not stop it.

1 / 2

Abusive nested queries

Imagine this schema, where a user has friends and each friend is also a user:

GRAPHQL
type User {
  id: ID!
  name: String!
  friends: [User!]!
}

Every part of the next query is valid:

GRAPHQL
query {
  user(id: "1") {
    friends { friends { friends { friends { friends { friends { name } } } } } }
  }
}

If every user has 50 friends, the server resolves 50 users, then 2,500, then 125,000, and so on. Six levels deep is already about 15 million objects. The query text is a few hundred bytes. This is why cyclic relationships need protection, and why the N+1 problem matters so much for performance.

Depth limiting

The simplest defense is to count how deeply a query nests and reject it before execution if it goes past a limit, for example 7 or 10. The rule runs during validation, after parsing and before any resolver runs, so a rejected query costs almost nothing.

Depth is a blunt tool, but it is cheap, predictable and stops the worst loops. Pick the limit by looking at your real clients: find the deepest legitimate query, and set the limit slightly higher.

The stand-in below walks a query written as a JavaScript object (a tiny stand-in for a parsed selection set) and reports its depth.

JS A stand-in depth limit

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real libraries count levels in the parsed document, follow fragments (an attacker can hide depth inside fragment spreads) and treat the introspection fields specially. Never write this yourself in production: use a maintained validation rule and add it to your server's validation step.

Cost and complexity analysis

Depth does not see width. A flat query can be just as expensive:

GRAPHQL
query {
  products(first: 100000) {
    reviews(first: 1000) {
      author { name }
    }
  }
}

That is only three levels deep, but it asks for up to 100 million reviews. Cost analysis assigns a number to each field and multiplies it by the size of any list argument. The server computes the estimate before running, and rejects the query if it passes a budget.

A common scheme:

  • a scalar field costs 0 or 1,
  • an object field costs 1 plus the cost of its children,
  • a list field multiplies its children's cost by the page size (first, limit), and
  • very expensive fields (search, reports) get a custom, higher price.

You should also cap page sizes in the schema logic itself (for example first must be 1 to 100). Without a cap, one argument defeats the whole estimate. See Pagination: Offset, Cursor and Connections.

JS A stand-in cost calculator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note how the page cap shrinks the "greedy" query from absurd to merely expensive, and the budget still rejects it. The numbers are made up: calibrate real costs by measuring your resolvers (see Caching and Performance).

Alias and batching abuse

Aliases let a client request the same field many times in one operation:

GRAPHQL
query {
  a1: login(user: "bob", password: "aaa") { token }
  a2: login(user: "bob", password: "aab") { token }
  a3: login(user: "bob", password: "aac") { token }
}

If you rate-limit per HTTP request, this sends hundreds of password guesses in one request. Many servers also accept an array of operations in one POST (batching), which multiplies the effect.

Defenses:

  • count fields and aliases, not only requests, and reject operations over a limit,
  • limit the number of operations in a batch (or turn batching off if you do not need it),
  • put expensive or sensitive fields, like login, behind their own throttle in the business layer, and
  • make cost analysis count every alias separately (the calculator above does, because each alias is its own field).
JS A stand-in alias limit and rate limiter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The point is charging by work, not by request. The limiter here charges one point per root field; real systems charge by computed cost.

Timeouts and limits on the transport

Even with analysis, some queries turn out slower than predicted. Add hard limits as a safety net:

  • an execution timeout (for example 10 seconds) after which the server stops resolving and returns an error,
  • a maximum request body size (a megabyte is plenty for almost any document),
  • a limit on variable and input sizes, such as list lengths in an input object, and
  • database-level statement timeouts so a runaway resolver cannot hold a connection forever.

Persisted queries and allow-lists

The strongest defense is to stop accepting arbitrary queries from the public. With persisted queries, the client build step extracts every query it uses, stores each one on the server under an ID (often a hash), and at runtime sends only the ID:

JSON
{ "id": "7f3a9c...", "variables": { "id": "1" } }

Two variants exist:

  • Automatic persisted queries reduce bandwidth and enable GET caching, but still accept new queries from anyone who sends the full text once.
  • A trusted-document allow-list rejects any ID the server does not know. Attackers cannot invent queries, which makes depth and cost attacks nearly impossible for first-party apps.

The trade-off is that an allow-list suits an API used only by your own apps. A public API for third-party developers usually needs open queries plus limits. The caching side of persisted queries is covered in Caching and Performance.

Introspection in production

Introspection lets anyone fetch your whole schema, which is wonderful for tools and also a free map of your API for attackers. Many teams disable it in production for apps that are not public:

JavaScript
// shape only: option names differ between server libraries
const server = new GraphQLServer({
  schema,
  introspection: process.env.NODE_ENV !== "production",
});

Hiding the schema is not access control. Field suggestions in error messages ("Did you mean ...?") can leak names too, and attackers can guess. Real protection is authorization in the business layer, plus the limits above.

Putting it together

A typical production checklist:

  1. Authenticate in HTTP middleware, authorize in the business layer.
  2. Cap request size and operation count per request.
  3. Add depth and cost validation rules, and cap every page size.
  4. Set execution and database timeouts.
  5. Rate-limit by client identity, charging by cost.
  6. Use persisted queries or an allow-list for first-party apps.
  7. Log slow and rejected operations with the operation name, so you can see abuse in the logs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a plain request-per-minute limit weak for GraphQL?

    The size of the work is decided by the query text, so you should charge by fields or computed cost, not just by HTTP requests.
  2. 2. A query is only three levels deep but asks for first: 100000 at two levels. Which defense catches it?

    Depth ignores width. Cost analysis multiplies list sizes, and a page-size cap stops one argument from defeating the estimate.
  3. 3. What does a trusted-document allow-list do?

    Only known, pre-approved operations run, so attackers cannot send a new expensive query. This suits APIs used by your own apps.
  4. 4. Is disabling introspection enough to protect private data?

    Hiding the schema only slows attackers down. Access control must be enforced where data is read or changed.

Summary

  • The client chooses the work, so a public GraphQL API needs explicit limits.
  • Depth limits stop cyclic nesting; cost analysis stops wide queries; both run during validation, before any resolver.
  • Cap page sizes, count aliases and root fields, and limit batching.
  • Add execution timeouts, request size limits and database timeouts as a safety net.
  • Persisted queries and allow-lists are the strongest defense for first-party apps.
  • Disabling introspection is optional hardening, never a substitute for authorization.
  • The depth and cost calculators here are stand-ins; use maintained validation rules in real servers.

Next: Caching and Performance.