How it works
The explanation, with examples you can run.
Estimating cost before execution
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
Real cost analysers work on the parsed document, use the schema to know which fields are lists, read page sizes from arguments or variables, and let you weight expensive fields (a search, a call to a slow service) more than cheap ones. The same number can drive rate limiting: give each client a cost budget per minute instead of a request count, and report the cost in extensions so client developers can see it.
The other limits
- Paginate every list and enforce a maximum page size. Without that, cost analysis has nothing to multiply.
- Depth: cap nesting, with a smaller cap for nested lists. Schemas with cycles (
user.friends.friends...) need it most. - Breadth and batching: cap fields and aliases per request, and the number of operations if your server accepts batched requests. Aliases can multiply a login mutation into hundreds of password guesses in one request.
- Timeouts and cancellation at the HTTP and resolver levels, so a query that slips through doesn't run forever.
Trusted documents
For APIs used only by your own apps, the strongest control is an allowlist. At build time, the client's operations are extracted, hashed and registered with the server; at runtime the client sends the hash and the server runs only documents it knows. Arbitrary queries become impossible, and requests get smaller and cacheable as a bonus. Public APIs can't do this, because they can't know their clients' queries in advance, so they rely on cost limits.
Introspection and error detail
Introspection lets anyone download the full schema. For private APIs it is common to disable it in production and keep it in development and for tooling. Similarly, mask internal error messages and stack traces, and disable "did you mean…" field suggestions, which can reveal the schema piece by piece. None of these replace authorisation and limits: a determined client can recover most of a schema from your app's network traffic.
Check yourself
3 questions. Get them all right to finish this topic.
0 of 3 right so far. Get all three to finish this topic.