Skip to the page

GraphQL in production · senior

Limits, query cost and trusted documents

One GraphQL request can ask for a huge amount of work, so a request-count rate limit is not enough. Limit depth, aliases and list sizes, add a cost limit per client, and let first-party apps send only known operations.

The notes

What you must know

  • Why one request is expensive: nested lists multiply. Without batching every level also multiplies SQL queries. Normal traffic and a normal request-count rate limit can both look fine while the database is at 100 percent CPU.
  • A depth limit alone is not enough. Aliases (a1: restaurants(first: 500) ... a200: ...) repeat a field many times at shallow depth. Also limit aliases and top-level fields.
  • Cap list sizes: make first or limit required, with a maximum such as 100. Without a cap, first: 100000 is a valid query.
  • Cost limit: give each field a weight, multiply by the list sizes, and reject the request before it runs if the total is above the limit. Tools: GraphQL Armor, graphql-query-complexity, Apollo Router demand control.
  • Rate limit by cost per client per minute, not by request count, because one request may be cheap or huge.
  • Trusted documents (persisted queries registered at build time): the server runs only operations it knows by id. Unknown operations are refused, or allowed for partners inside a cost budget. This is the strongest control for first-party apps.
  • Put a timeout on every operation on the server so stuck queries end. Turn introspection off in production for first-party-only APIs, but know that this alone is not security.
  • Detect early: metrics per operation name (count, latency, cost, SQL queries per request), an alert on unknown operations, and the client name in logs.

The red pen

Common traps: mistake → fix

  • Mistake: A query depth limit stops abusive queries

    Fix: A wide query or one with many aliases is shallow but very costly. Add alias, field and cost limits.

  • Mistake: Rate limiting to 60 requests a minute protects a GraphQL API

    Fix: One request can do the work of thousands. Limit by cost.

  • Mistake: Turning off introspection makes the API safe

    Fix: Attackers can guess fields, and error messages can leak the schema. It is only one small step.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why is a request-count rate limit weak for GraphQL?
  2. A query is only four levels deep but the database is at 100 percent. How is that possible?
  3. How does a cost limit work? What do you multiply?
  4. What are trusted (persisted) documents and when would you not use them?
  5. The database is falling over right now because of GraphQL queries. What do you do in the first five minutes, and what do you fix afterwards?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview