Query cost and abuse

GraphQL Course · lesson 7 of 14 · 5 min read

Letting clients shape queries means letting them shape expensive ones.

Open this lesson in the learning hub

Key points

  • A deeply nested query can explode: friends of friends of friends multiplies quickly.
  • Depth limiting rejects queries nested beyond a fixed level.
  • Cost analysis scores fields and rejects anything over a budget - fairer than raw depth.
  • Persisted queries: clients send a hash of an approved query, so arbitrary queries are impossible.
  • Disable introspection in production if you do not want your whole schema published.

Example

# a small query that is very expensive
query Bomb {
  customer(id: "1") {
    orders {                    # 50
      customer {                # 50
        orders {                # 2,500
          customer { orders { product } }   # 125,000
        }
      }
    }
  }
}

Client-shaped queries need a server-side budget - depth limiting is the minimum, persisted queries the strongest.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the GraphQL Course course, and every lesson in it is listed on the GraphQL Course contents page.