What are GraphQL persisted queries and how do they work?
A persisted query replaces the operation text in a request with an identifier. The client sends a key, usually a SHA-256 hash of the operation document, and the server uses it to look up the full document in a store. Parsing, validation and execution then proceed as if the client had sent the text. Requests get smaller, and because the key is fixed, GET requests become cacheable by CDNs.
The two variants covered in this guide use this same lookup but differ in what happens when the key is unknown.
- Automatic persisted queries (APQ), popularized by Apollo, register documents at runtime. If the server misses, the client retries with the full text and the server stores it. Any client can register any operation.
- Build-time operation allowlists register documents ahead of time from a manifest your build produces. If the server misses, it rejects the request. Only operations you shipped can run.
The main claim of this guide is that the two share a mechanism but solve different problems. APQ is a bandwidth and caching optimization. An allowlist is a security control.
Request path
| Step | APQ: hit | APQ: miss and retry | Allowlist |
|---|---|---|---|
| 1 | Client sends the hash only | Client sends the hash only | Client sends the hash or ID only |
| 2 | Server finds the document in its cache | Server misses and returns a PersistedQueryNotFound error |
Server looks up the document in the deployed manifest |
| 3 | Server parses, validates and executes it | Client resends the hash plus the full query text | On a hit, the server parses, validates and executes it |
| 4 | — | Server checks that the hash matches the text, stores it, then executes | On a miss, the server rejects the request, with no fallback and no registration |
APQ: registration at runtime, on a cache miss
Client Server APQ cache
| | |
| 1. hash only | |
|-------------------------->|-- lookup hash ------------>|
| |<-- HIT: document ---------|
|<-- 200 data --------------| parse, validate, execute |
| | |
| 1. hash only | |
|-------------------------->|-- lookup hash ------------>|
| |<-- MISS ------------------|
|<-- PersistedQueryNotFound | |
| 2. hash + full query text | |
|-------------------------->| check hash matches text |
| |-- store document -------->|
|<-- 200 data --------------| parse, validate, execute |
Allowlist: registration at build time, before deploy
Build Client Server Manifest
| | | |
|-- deploy operation manifest ------------------------------>|
| | hash or ID only | |
| |------------------>|-- lookup -------->|
| | |<-- HIT: document -|
| |<-- 200 data ------| parse, validate, |
| | | execute |
| | |<-- MISS ----------|
| |<-- reject --------| no fallback, |
| | | no registration |
Both variants resolve a hash to a stored document before parsing, validation and execution: on a miss, APQ lets the client register the operation by retrying with the full text, and an allowlist rejects the request.
Why are automatic persisted queries not an operation allowlist?
Automatic persisted queries (APQ) are a bandwidth optimization, not a security control. The client first sends only a hash, for example {"extensions": {"persistedQuery": {"version": 1, "sha256Hash": "abc123…"}}}. On a cache miss, the server replies with an error such as {"errors": [{"message": "PersistedQueryNotFound"}]}. The client then retries with the full query text and the same hash. The server stores the pair and executes the query. Every later request can send only the hash.
The registry is filled at runtime by whoever calls the API. An attacker who wants to run a deeply nested or costly query sends it once with its hash, and the server registers it. APQ therefore blocks nothing. It only changes how often the query text crosses the network. Because anyone can write to the store, it is also an unbounded write target: a script can generate millions of unique queries and fill memory or the cache.
| Property | APQ | Build-time allowlist |
|---|---|---|
| Who populates the registry | Any caller, at runtime | Your build pipeline |
| Unknown operations | Registered and executed | Rejected |
| Primary goal | Smaller requests, CDN-friendly GET | Restrict executable operations |
| Write exposure | Public | None at runtime |
If you run APQ, you need these safeguards:
- Size limits: cap the query length and the total store size.
- Eviction: use LRU or TTL so that junk entries expire.
- Hash verification: recompute the SHA-256 on registration and reject mismatches. Without this check, a caller can map a legitimate hash to different query text.
- Shared store: put the store in a shared cache such as Redis. With per-instance memory, a load balancer sends requests to instances that have never seen the hash, which causes repeated misses and doubles round trips.
# 1) First attempt: the client sends only the hash, no query text
POST /graphql
{"variables": {"id": "42"},
"extensions": {"persistedQuery": {"version": 1,
"sha256Hash": "<64-hex SHA-256 of the exact query text>"}}}
# Response: the shared store has no entry for this hash
{"errors": [{"message": "PersistedQueryNotFound",
"extensions": {"code": "PERSISTED_QUERY_NOT_FOUND"}}]}
# 2) Retry: full query text plus the same hash
POST /graphql
{"query": "query GetUser($id: ID!) { user(id: $id) { id name } }",
"variables": {"id": "42"},
"extensions": {"persistedQuery": {"version": 1,
"sha256Hash": "<64-hex SHA-256 of the exact query text>"}}}
# Server, before storing:
# - reject if the query length exceeds the configured cap
# - recompute SHA-256 over "query" and compare it to sha256Hash
# - write to the shared cache with a TTL so that every instance can see it
# - then execute (APQ does not decide whether the query is allowed)
{"data": {"user": {"id": "42", "name": "Ada"}}}
# 3) Registration with a hash that does not match the text: reject, store nothing
POST /graphql
{"query": "query { __schema { types { name } } }",
"extensions": {"persistedQuery": {"version": 1,
"sha256Hash": "<hash of GetUser, reused>"}}}
{"errors": [{"message": "Persisted query hash does not match query text"}]}
This APQ exchange shows a hash-only miss, a retry that registers the query after length and hash checks, and a rejected registration whose hash does not match its query text.
How do you implement a build-time operation allowlist?
An allowlist differs from APQ in one respect: the set of operations is fixed at build time, not learned at runtime. The pipeline has four steps.
- Extract. A build step parses every GraphQL document in the client source and collects each named operation together with the fragments it references.
- Write a manifest. Emit a JSON file that maps each ID to its full document text, for example
{"a1f3…": "query GetUser($id: ID!) { user(id: $id) { ...UserFields } } fragment UserFields on User { id name }"}. - Publish. Push the manifest to the server or a shared store as part of the client release, before any client that depends on it ships.
- Enforce. The server looks up each incoming ID. If the ID is missing, it rejects the request without parsing or executing anything. In strict mode, the server also rejects any request that carries raw query text. Without that check, an attacker can bypass the allowlist by sending a query instead of an ID.
Client and server must agree on normalization: whitespace collapsing, whether referenced fragments are inlined or appended, and their order. If the client hashes one form and the server rehashes a different one, valid operations fail. You can avoid this by never rehashing on the server and treating the manifest as the source of truth.
For IDs, you can use opaque identifiers or content hashes such as SHA-256 of the normalized document. Content hashes are deterministic and deduplicate identical operations across builds. Collisions are not a practical concern with a cryptographic hash. The real failure mode is a mismatch between build and deploy: a client ships with IDs from a manifest that was never published, or was overwritten by a later release.
// Manifest published with the client release: ID -> full document text.
// The server treats this as the source of truth and never rehashes documents.
type Manifest = Record<string, string>;
interface IncomingRequest {
id?: string; // operation ID from the client build
query?: string; // raw query text (rejected in strict mode)
variables?: Record<string, unknown>;
}
type Resolved =
| { ok: true; document: string }
| { ok: false; status: number; error: string };
export function resolveOperation(
req: IncomingRequest,
manifest: Manifest,
strict: boolean
): Resolved {
// Strict mode: raw text is never accepted, so an attacker cannot
// bypass the allowlist by sending a query instead of an ID.
if (strict && req.query !== undefined) {
return { ok: false, status: 400, error: "Raw queries are not allowed" };
}
if (!req.id) {
return { ok: false, status: 400, error: "Missing operation ID" };
}
// Plain lookup. Use hasOwn so IDs like "__proto__" cannot match.
if (!Object.hasOwn(manifest, req.id)) {
// Reject before parsing or executing. Log the ID: an unknown ID usually
// means a build/deploy mismatch (manifest never published or overwritten).
console.warn(`unknown operation id: ${req.id}`);
return { ok: false, status: 400, error: "Unknown operation" };
}
// Only the stored document is parsed and executed, never client-supplied text.
return { ok: true, document: manifest[req.id] };
}
This server-side lookup takes the operation ID, finds its document in the published manifest, and rejects the request before parsing if the ID is unknown or, in strict mode, if the request carries raw query text.
How should you deploy and version persisted query manifests?
The fix is to treat the manifest as a deployment artifact with its own release order: the server must know an operation ID before any client that sends it reaches users. Before persisted queries, a client release could not break the API by itself. With an enforced allowlist, a late or skipped upload means every request from the new build is rejected the moment it ships.
A CI pipeline for the client should enforce that order:
- Extract operations from the client source and generate the manifest.
- Publish the manifest to the operation registry or server store, tagged with the client name and build version.
- Verify that the server can resolve every ID in the manifest, and fail the pipeline if it cannot.
- Only then build and release the client binary or web bundle.
Publishing should be additive. Do not replace the previous manifest, because the operations it contains are still live. A web client mostly updates on its next page load. A mobile build can stay installed for months or years, and you cannot force every user to update. Each operation an old build can send must stay registered for as long as that build has meaningful traffic.
This slows down schema evolution. A deprecated field cannot be removed while any registered operation still selects it, so field removal is limited by your oldest supported client.
Retire operations on purpose. Log request counts per operation ID and per client version. Set a traffic threshold, and remove an operation only after its usage stays below that threshold for an agreed window. Do not expire entries automatically on a timer. A timer will eventually delete an operation that a long-lived install still depends on.
#!/usr/bin/env bash
# Client release pipeline: publish the manifest, verify it, then ship the client.
# Any failing command stops the script, so the release step is never reached.
set -euo pipefail
CLIENT_NAME="ios-app"
CLIENT_VERSION="${BUILD_VERSION:?BUILD_VERSION must be set}"
REGISTRY_URL="${OPERATION_REGISTRY_URL:?OPERATION_REGISTRY_URL must be set}"
MANIFEST="build/persisted-operations.json" # format: { "<sha256 id>": "<query text>" }
# 1. Extract operations from client source and write the manifest.
npm run generate:manifest -- --out "$MANIFEST"
# 2. Publish additively, tagged with client name and build version.
# The registry stores this as a new manifest and keeps earlier versions,
# because older installed builds still send those operation IDs.
curl --fail -sS -X POST \
-H "Authorization: Bearer ${REGISTRY_TOKEN:?REGISTRY_TOKEN must be set}" \
-H "Content-Type: application/json" \
--data-binary @"$MANIFEST" \
"$REGISTRY_URL/manifests/$CLIENT_NAME/$CLIENT_VERSION"
# 3. Confirm the server can resolve every ID before any user gets this build.
missing=0
for id in $(jq -r 'keys[]' "$MANIFEST"); do
if ! curl --fail -sS -o /dev/null \
-H "Authorization: Bearer $REGISTRY_TOKEN" \
"$REGISTRY_URL/operations/$id"; then
echo "Unresolved operation ID: $id" >&2
missing=$((missing + 1))
fi
done
[ "$missing" -eq 0 ] || { echo "$missing operations not registered; aborting release" >&2; exit 1; }
# 4. Only now build and release the client.
npm run build
npm run release -- --version "$CLIENT_VERSION"
An outline of a client CI script that publishes the persisted query manifest additively and checks that the server can resolve every operation ID before building and releasing the client. The registry endpoints and npm script names are placeholders for your own setup.
How do you roll out an allowlist on an existing open GraphQL API?
Turning an open API into an allowlisted one is a migration, not a switch. Run it in stages so you learn what traffic exists before you start rejecting any of it.
- Log, don't block. Accept every request, but tag operations that are not in the manifest and record their hash, client name and client version.
- Measure by client. Break unknown-operation traffic down by client and version. Stale mobile builds and forgotten scripts show up here. An attacker probing the API does not.
- Enforce for first-party clients. Once their unknown rate is effectively zero, reject unregistered operations from clients you build and ship.
- Decide on the exceptions. Third parties, partners, GraphiQL-style exploration and internal scripts still need a way in.
| Access path | Who it serves | Cost to the guarantee |
|---|---|---|
| Separate endpoint | Partners, public API users | That endpoint is open again and needs its own limits |
| Authenticated bypass | Internal scripts, staff exploration | A leaked credential reopens arbitrary queries |
| Separate public schema | Third-party developers | Smaller exposed surface, but more to maintain |
Every exception weakens the guarantee, so keep each one narrow and audited.
Operation IDs also improve observability. They give stable names for metrics, tracing and error tracking, so dashboards no longer depend on parsing query text. Alert on rejected unknown operations. A spike usually means a deploy-ordering mistake, such as a client shipping before its manifest, rather than an attack. Log both the received ID and the loaded manifest version. A not-found error is hard to debug unless you can tell whether the hash was wrong or the server had an old manifest.
When should you use persisted queries, and when should you avoid them?
Use an operation allowlist when you own every client: your web app, mobile apps and internal tools. The server then runs only operations you shipped. Unbounded nesting and probing queries are rejected before resolvers execute. Use automatic persisted queries when queries are large and request volume is high. Each request then sends a short hash instead of kilobytes of query text.
Hash-based GET requests let CDNs and proxies cache responses, but only for cacheable operations: queries with public or correctly keyed responses. Mutations never qualify. For authenticated or personalized data, either vary the cache key on the auth context or send Cache-Control: private. Otherwise a shared cache can serve one user's data to another. GET also puts variables in the URL, where proxies and access logs may record them, so keep tokens and personal data out. URL length limits still constrain large variable payloads.
| Situation | Fit |
|---|---|
| First-party clients, production API | Allowlist |
| Large queries, high request volume | APQ |
| Public or partner API needing ad hoc queries | Avoid allowlist |
| Small queries or low traffic | Avoid. Overhead exceeds bandwidth savings |
| No reliable CI for publishing manifests | Avoid until the pipeline exists |
The costs are coupling client releases to manifest publishing and debugging normalization mismatches between client and server hashes. What you get back is stable operation names in logs, a security review that covers known operations instead of the whole schema, and less query-cost tuning for first-party traffic. Illustrative estimate: assume a one-time setup of three engineer-days. Assume an ongoing cost of an hour a month, and that each security review drops from two days to half a day. With quarterly reviews, the setup pays for itself within the first year.
What are the alternatives and complementary controls to an operation allowlist?
An allowlist constrains which operation documents the server will execute. It says nothing about the variables passed to those operations or about who is calling them. If an approved query accepts first: Int, a client can still send first: 100000 and force a large database read. If a resolver forgets to check that the caller owns the requested order, the approved GetOrder operation will return someone else's data. The allowlist shrinks the attack surface to code you wrote, but the bugs in that code remain reachable.
Treat it as one layer alongside these controls:
| Control | Threat it addresses | What it does not address |
|---|---|---|
| Operation allowlist | Arbitrary, attacker-crafted queries | Abusive variables, broken authorization |
| Authorization in resolvers | Reading or mutating data the caller should not access | Expensive but legitimate requests |
| Rate limiting (per client or user) | Request floods, scraping, credential stuffing | A single very expensive request |
| Depth and complexity limits | Deeply nested or high-fan-out ad hoc queries | Authorization flaws |
| Argument bounds (e.g., max page size) | Oversized pagination in approved operations | Request volume |
| Disabling or restricting introspection | Casual schema discovery | Determined attackers, who can infer the schema from client bundles or error messages |
Authorization belongs in resolvers or the data layer because it has to hold regardless of which operation reached it. Depth and complexity limits still matter for any path that accepts arbitrary queries, such as internal tooling, partner endpoints, or the migration period before enforcement is switched on. Restricting introspection is obscurity, not access control. It makes reconnaissance slower, but it should never be the reason a field is considered safe.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to graphql persisted queries, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.