Secure GraphQL per operation, not per URL: reject documents that exceed depth, complexity, alias, batch, or page-size budgets before execution; restrict introspection but never rely on it for safety; enforce server-side persisted queries; rate-limit by operation name and cost; authorize every field; batch resolvers per request; and return stable error codes without stack traces.
- A single GraphQL endpoint hides the operation inside the request body, so path-based rate limits, WAF rules, and cache keys cannot tell a cheap query from an expensive mutation.
- Depth limits stop recursion but not breadth, aliases, or list multiplication; complexity must be scored from the validated document with variable values applied.
- Introspection lockdown and persisted queries reduce discovery and attack surface only when the server still enforces depth, cost, batching, and authorization.
- Client-side allowlists are advisory; the server must execute only trusted documents and must charge rate limits in operation cost rather than raw request count.
- Field-level authorization, per-request DataLoaders, input caps, and sanitized errors close the gaps that query-shape limits cannot cover.
GraphQL gives clients a schema and lets them choose the shape of every response. That flexibility is the feature, and it is also the attack surface: one HTTP endpoint accepts every query, mutation, and subscription the schema exposes, and the cost of a request is decided by the client's document, not by the URL. A REST API can rate-limit GET /users/:id because the route names the operation. A GraphQL server receives POST /graphql with a query in the body, so URL-based rules, WAF signatures, and cache keys see almost nothing useful. The controls that work are the ones that understand the operation: parse it, score it, authorize it, and only then execute it.
Why a single endpoint breaks rate-limiting and WAF assumptions
In REST, the path identifies the resource and roughly the cost. A WAF can block /admin/*, a CDN can cache GET /products, and a rate limiter can give each route its own budget. GraphQL collapses those distinctions. POST /graphql can carry query { viewer { id } } or a mutation that deletes an account, and both may return HTTP 200. Status-code monitoring therefore misses GraphQL failures: validation errors, authorization failures, and resolver exceptions can all arrive as a 200 with an errors array.
That has three consequences. First, rate limiting per HTTP request is the wrong unit; one request can contain thousands of field resolutions, and a client sending ten cheap queries per second may be harmless while one expensive query per minute exhausts the database. Second, WAF rules keyed on path and method cannot distinguish operations, so blocking must happen after parsing, in the GraphQL layer or in a gateway that understands GraphQL. Third, shared caches rarely help: POST bodies are not cacheable by default, so the origin absorbs the traffic unless you adopt GET plus persisted queries. Instrument operation names, normalized query hashes, and estimated cost on every request; those three fields are the minimum needed to rate-limit and investigate abuse.
Query depth and complexity limits
A depth limit rejects documents nested deeper than a fixed number of field levels. It is cheap to implement and catches recursive schemas, where comment { replies { comment { replies { ... } } } } can be expanded indefinitely. It is not sufficient. Depth ignores breadth: an operation with a thousand sibling fields at depth three is shallow and expensive. Depth also ignores list multiplication, where orders(first: 100) { items(first: 100) } returns ten thousand rows from two levels.
Complexity scoring closes both gaps. Assign each field a cost, multiply child cost by the page size of each connection, and sum the operation. The score must use variable values, because first: $pageSize hides the real page size in the request text. Fragments, inline fragments, and directives such as @include change the executed shape, so analyze the validated document after variable coercion, not the raw string. Reject anything above the per-operation budget with a stable error code such as QUERY_TOO_COMPLEX, and log the hash, the score, and the authenticated principal. Calibrate the budget against real database work, not against a round number copied from a blog post.
| Control | What it limits | Sensible starting point | Attack it stops |
|---|---|---|---|
| Depth | Field nesting | 10 to 15 levels | Recursive comment and org-chart expansion |
| Complexity | Weighted field and connection cost | Per-operation budget derived from query plans | Wide selections and nested pagination multiplication |
| Alias cap | Repeated fields in one operation | 100 to 300 aliases | Alias bombs against expensive resolvers |
| Batch cap | Operations per HTTP request | 10 or fewer | Array batching amplification |
| Page cap | Rows per connection | 100 or less per page | Unbounded first: 10000 reads |
| Body cap | Request size | A few hundred kilobytes | Oversized documents and variable payloads |
query AbuseExample {
viewer {
orders(first: 100) {
nodes {
items(first: 100) {
product {
reviews(first: 100) {
author { orders(first: 100) { totalCount } }
}
}
}
}
}
}
}
The operation above stays under ten field levels, but its connection arguments multiply into a six-figure row estimate. A depth limit of ten would pass it. A complexity score that applies page sizes would not. A GraphQL formatter makes the nesting readable, but the score must come from the validated abstract syntax tree, because formatting never changes what the server executes.
Pagination limits and unbounded list fields
Every list field needs a server-enforced maximum page size, a default, and a predictable rejection when a client asks for more. first: 10000 must not reach the database just because the schema accepts an integer. Enforce the cap in the resolver or the data-access layer, not in documentation or client code, and return a field error with a stable code instead of silently clamping: silent clamping makes client bugs invisible and complicates pagination.
Nested connections multiply. A page of 50 orders with 50 items each is 2,500 rows, and adding a third connection multiplies again. The complexity formula must reflect that, and the schema should make large collections require a connection argument rather than returning an unbounded list. Prefer cursor pagination for large tables: offset pagination makes the database scan and discard every skipped row, so a deep page is expensive even when the page size is small. Treat totalCount as a separate cost; a count over a filtered join can exceed the page query itself, so cache it or remove it from hot paths.
Batching, aliasing, and request amplification
Aliases let one operation address the same field many times with different arguments. a0: user(id: 0), a1: user(id: 1), and so on turn one HTTP request into a thousand resolver calls. The operation is syntactically valid, the depth is one, and a naive complexity score that counts fields once will miss it. Count aliases per field and per operation, set a hard cap, and reject the document before execution when the count is exceeded. Pattern matching on query text is not an enforcement mechanism: aliases, fragments, comments, and whitespace defeat it. A regex tester is useful for studying a suspected payload, but the limit belongs in the parsed document.
Array batching adds another multiplier: some servers accept a JSON array of operations in one request, and each element may itself contain aliases. Cap the batch size, ten is generous for most clients, or disable batching for untrusted clients. Set a request body size limit at the reverse proxy, a maximum number of fragments per document, and a maximum variable payload size. Parse and validate every operation in a batch, and apply the same depth, complexity, alias, and authorization checks to each one. Do not let operationName select one operation while the others bypass validation.
Introspection, schema exposure, and discovery
Introspection is a legitimate feature: clients, code generators, and IDEs use it to discover types. In production it is also reconnaissance: an attacker learns every field, argument, enum value, and deprecation note, then targets the ones with weak authorization. Disabling introspection is a sensible default for public production endpoints, but it is not a security boundary by itself. Schema details leak through error messages, "Did you mean" field suggestions, GraphiQL and Apollo Sandbox landing pages, source maps in web clients, and persisted query manifests shipped in mobile binaries.
The practical policy is layered. Disable introspection in production with a validation rule, keep it available in staging or behind admin authentication, and publish a generated schema artifact for trusted tooling. Turn off field suggestions in error formatting, remove developer landing pages, and review error text for schema hints. Then enforce depth, complexity, alias limits, and authorization regardless, because introspection-off only slows discovery; it does not stop a client from sending a valid query it learned elsewhere.
Persisted queries and trusted documents
Persisted queries replace the query text with a hash. In the automatic persisted query flow, the client sends a SHA-256 hash; the server executes a previously registered document or asks the client to resend the full text once. That saves bandwidth, but automatic persisted queries alone are a cache, not an allowlist: if the server accepts any hash-to-query registration from any client, an attacker can register an expensive query and then call it. Trusted documents are the stronger model. Extract every operation at build time, publish a manifest of hashes, and configure the server to execute only hashes present in the manifest. Unknown hashes get a stable error, never a dynamic registration path.
That model also enables safer caching and cost control. Because the server knows the exact document behind a hash, it can precompute depth and complexity, attach a fixed cost, and serve GET requests through a CDN with a cache key that includes the hash. Roll out manifest versions carefully: deploy the new manifest before the client release that uses it, keep old hashes valid during the overlap, and reject removed hashes with an error that tells the client to refresh. A JSON formatter makes the manifest diffable in review, which matters because an accidentally widened manifest is a security change.
Rate limiting per operation, not per URL
Rate limiting starts with identity. Require operation names for monitoring, hash the normalized document, and count requests per user, per IP, per operation name, and per cost unit. Login, password reset, and payment mutations deserve tighter budgets than a cached product query. A token bucket per principal plus a concurrency limit per operation prevents both sustained abuse and bursts that starve other clients. Do not rely on IP alone: mobile carriers and corporate NAT concentrate thousands of users behind one address.
Return standard signals: 429 with Retry-After when the HTTP layer rejects, or a GraphQL error with a stable code and retry hint when the operation layer rejects. Publish RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset if your stack supports the draft headers. Keep counters in a shared store such as Redis so limits hold across instances, and decide explicitly whether expensive mutations fail closed or queue when the counter store is unavailable. With trusted documents the cost is known before execution, so quotas can be charged in complexity units instead of request counts.
Field-level authorization, input validation, and schema boundaries
Authentication at the gateway proves who sent the request; it does not prove that the user may read each node the query reaches. Authorization belongs in resolvers or the service layer, close to the data. Load the record with an owner predicate such as WHERE id = ? AND tenant_id = ? instead of fetching first and comparing afterwards, and deny by default when a resolver has no explicit rule. Test every role against every field, including nested fields reached through a parent the user legitimately owns, because an authorized parent does not imply authorized children.
Input validation is part of the same boundary. Use custom scalars for email, URL, UUID, and date, cap string lengths and list sizes, validate numeric ranges, and accept only enums for closed sets. Validate variables and literals with the same rules. Schema design should expose the minimum: no generic executeSQL, no arbitrary filter strings passed into a query builder, no sequential integer IDs that invite enumeration, and no admin-only fields in the public schema. Split internal and public schemas when their audiences differ, and deprecate fields instead of leaving sensitive ones reachable.
N+1 queries, DataLoader, and safe error responses
A list resolver that loads one row per item turns a single GraphQL field into hundreds of database queries. N+1 is a performance bug that becomes a security problem: an attacker can choose a page size that multiplies the queries and exhausts the connection pool while staying inside a naive complexity budget. DataLoader batches keys within a tick and caches them for the request. Create a new DataLoader per request, never globally, and apply authorization inside the batch function per item; a request-scoped cache that ignores the user can leak another tenant's row. Monitor database query counts per GraphQL operation and set a budget that fails or alerts when a resolver pattern regresses.
Errors deserve the same discipline. A production response should carry a stable code, a safe message, and a request ID, not a stack trace, SQL fragment, internal hostname, or dependency version. Configure the server's error formatter to log the original error with the request ID and return a sanitized shape to the client. Distinguish validation errors, which are the client's responsibility, from execution errors, which are yours, and never cache error responses in a shared cache. The same rule applies to field suggestions and introspection errors: both are schema disclosure.
Verification checklist and production rules
Verify from outside, with the same requests an attacker would send. Run these checks against staging with production configuration, then repeat a subset against production after every schema or gateway change.
# 1. Deep or alias-heavy query: expect rejection before execution
curl -sS https://api.example.com/graphql \
-H 'content-type: application/json' \
--data-binary @abusive-query.json | jq '.errors[0].extensions.code'
# 2. Introspection after lockdown: expect an error, not a schema
curl -sS https://api.example.com/graphql \
-H 'content-type: application/json' \
--data-binary '{"query":"{ __schema { types { name } } }"}'
# 3. Unknown persisted-query hash: expect a stable rejection
curl -sS 'https://api.example.com/graphql?extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22deadbeef%22%7D%7D'
Then repeat the checks that matter for authorization: request another tenant's node by ID, request an admin-only field as a normal user, and confirm the response is an error or null rather than data. Treat a check as passed only when the following hold:
| Check | How to test | Pass criteria |
|---|---|---|
| Depth limit | Send a recursive query one level beyond the limit | Rejected with QUERY_TOO_DEEP, no partial data, response within the latency budget |
| Complexity limit | Send a query whose variable values push the score over budget | Rejected with QUERY_TOO_COMPLEX; variables are scored, not ignored |
| Alias amplification | Send 500 aliases of the same expensive field | Rejected before execution; the cap is enforced per field and per operation |
| Pagination cap | Request first: 10000 on every connection | Field error or capped page, never an unbounded database read |
| Batch size | Send an array of 100 operations | Rejected with a documented maximum batch size |
| Introspection | Send __schema and __type queries anonymously | Both denied; the schema stays available to authorized tooling |
| Persisted queries | Send an unknown hash, then a known hash | Unknown hash rejected; known hash executes with its precomputed cost |
| Operation rate limit | Exceed the budget with cheap and expensive operations | Expensive operations consume more budget; 429 includes Retry-After |
| Field authorization | Request another user's node and an admin field | Error or null; no data leak in the error message |
| Error hygiene | Force a resolver exception | Stable code plus request ID; no stack trace, SQL, or hostname |
The predictable mistakes look like this. Trusting a client-side query allowlist, where the mobile app or single-page app ships a list of allowed queries, fails because the server accepts whatever arrives. Disabling introspection without depth, complexity, alias, and authorization controls only hides the map. Returning stack traces and raw database errors hands the attacker the schema and the query shape. Enforcing a depth limit alone lets alias bombs and wide queries through. Rate-limiting by path or by raw request count lets one expensive request do the damage of a thousand. Computing complexity from query text without variable values undercounts first: $pageSize. These are not edge cases; they are the default behavior of an unprotected GraphQL endpoint.
The production rules are short. Parse and validate before execution, score every operation with variables, cap depth, aliases, batch size, page size, and request body, and reject with stable error codes. Put authorization in resolvers with deny-by-default ownership checks, validate every input with explicit scalars and limits, and design the schema to expose only what clients need. Use trusted documents once clients are known, rate-limit by operation and cost, batch resolvers per request, and sanitize errors. Then verify the limits from outside, keep the checks in CI as a security regression suite, and log the operation hash, cost, principal, and outcome for every request. A GraphQL endpoint is secure when the server, not the client, decides what a query is allowed to cost.
Frequently asked questions
Does disabling introspection make a GraphQL API secure?
No. It slows reconnaissance but leaves every field executable. Error messages, field suggestions, client bundles, and public schemas still reveal structure, so depth, complexity, alias, batch, and authorization controls must remain enforced.
Why is rate limiting GraphQL by URL not enough?
Every operation arrives on the same path, so a URL-based counter cannot distinguish a cheap viewer query from an expensive nested mutation. A single request can contain hundreds of aliases or a batch of operations, and each may consume a different amount of database work.
Are persisted queries the same as a client-side allowlist?
No. A client-side list only tells the client which queries it intends to send; an attacker can send anything. Persisted queries become an allowlist only when the server refuses every hash that is absent from a manifest it controls.
Is a depth limit enough to stop expensive GraphQL queries?
No. A shallow query can request thousands of aliases or multiply nested connections such as orders(first: 100) with items(first: 100). Depth must be combined with complexity scoring, alias caps, batch caps, and server-enforced page sizes.
What should a production GraphQL error expose?
A stable error code, a safe message, and a request ID. Stack traces, SQL fragments, internal hostnames, dependency versions, and field suggestions belong in server-side logs, not in a response that an attacker can read.
JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.
Primary sources are linked at the end of each guide.