Kest

Search

Search the documentation

GraphQL

Complexity

Refuse queries designed to exhaust your server.

GraphQL lets the client choose the query, which is powerful and dangerous. On a public API, someone can send a query that is very deep or very wide and costs your server dearly:

{ author(id: 1) { books { author { books { author { books { author { name } } } } } } } }     # loops back on itself

Kest stops such queries before they run:

useGraphQL {
    schema = SCHEMA
    maxDepth = 12            // the longest chain of nested fields (the default)
    maxComplexity = 1000     // the total number of fields selected, each counts 1 (the default)
}                            // 0 switches a limit off

A query over either limit is answered with a GraphQL error naming the limit and does not execute:

{ "errors": [{ "message": "maximum query depth exceeded 15 > 12" }] }
SettingProtects againstTypical value
maxDepthcircular and deeply nested queries8 to 12
maxComplexitywide queries that select thousands of fields500 to 2000

Defence in depth

Limits are one layer. A public GraphQL API should also have:

  • Authentication on resolvers (@Authenticated), see Resolvers;
  • Rate limiting per client (Rate limiting), because a cheap query repeated 10,000 times is also an attack;
  • Pagination on every list field, with a maximum size (Pagination): never books: [Book!]! that returns a whole table;
  • Data loaders so a legitimate query does not turn into hundreds of database calls (Data loaders);
  • No explorer in production (explorer = false) if the API is private.

Set the limits from what your real clients need: look at your biggest legitimate query and add some room.

Read more