What are GraphQL persisted queries and how do they work?
A GraphQL request normally carries the full operation document: every field, fragment, and variable definition, sent as text on every call. Persisted queries replace that document with an identifier. Typically this is a SHA-256 hash of the query text. The server looks the identifier up in an operation store and recovers the document before parsing, validating, and executing it.
The request flow
- Client computes or embeds the operation's hash. It sends the hash plus variables and operation name, without the query string.
- Server receives the request and queries the operation store (an in-memory map, a key-value cache, or a database) for that hash.
- If the store returns a document, the server passes it to the executor. The executor parses, validates, and runs it as if the client had sent the text directly.
- If the store has no entry, the server's behavior depends on its policy. It either asks the client to resend the full text or rejects the request outright.
That final step is where two different uses of the same mechanism separate.
Automatic persisted queries (APQ) treat the store as a cache that clients populate at runtime. The goal is smaller request payloads and URLs short enough for GET requests, which makes CDN caching practical.
An operation allowlist treats the store as the authoritative list of operations the server will execute. That list is built and registered ahead of time, and anything not on it is refused. The goal is to restrict what clients can ask for.
This article's position is that these are separate decisions. They have different threat models, different failure modes, and different rollout paths, and adopting one does not give you the other.
+--------------------------+
| Client |
| hash = SHA-256(query) |
+--------------------------+
| 1. { hash, variables, operationName }, no query text
v
+--------------------------+ 2. lookup(hash) +---------------------+
| Server | -----------------------> | Operation store |
| (GraphQL endpoint) | <----------------------- | map / KV / database |
+--------------------------+ document or none +---------------------+
|
+----------------------------+
| 3. hit | 4. miss
v v
+--------------------------+ +-------------------------------------------+
| Executor | | On miss, policy decides: |
| parse -> validate -> run | +---------------------+---------------------+
+--------------------------+ | APQ (cache) | Allowlist (registry)|
| | ask client to | reject: operation |
v | resend full text; | not registered |
response to client | store fills at | ahead of time |
| runtime | |
+---------------------+---------------------+
The client sends a hash instead of the query text, and the server resolves it from the operation store; a hit goes to the executor, while a miss shows the split between APQ, which asks the client to resend the full text, and an allowlist, which rejects the request.
How does Apollo APQ work, and why is it not a security control?
Automatic persisted queries (APQ) is a cache negotiation protocol between client and server. The client first sends only a SHA-256 hash of the operation document in the extensions field, for example {"persistedQuery": {"version": 1, "sha256Hash": "<64 hex chars>"}}, with no query field. If the server has that hash stored, it executes the operation. If not, it returns an error with the message PersistedQueryNotFound. The client then retries with the full query plus the same extensions payload. The server checks that the hash matches the document, stores it, and executes. Later requests from any client hit the stored entry.
Why it does not restrict anything
The server registers documents at runtime, from whoever sends them. An attacker sends a hash and the full query, and the server registers it the same way it registers any other document. APQ only changes how a query reaches the server. It does not limit which queries the server will run.
Trade-offs
- Extra round trip: Every operation pays one failed request per cache state: first use, after a deploy, or after an eviction.
- Retry bursts: If the store is flushed, every client retries with full documents at the same moment.
- Store pollution: Registration is open, so the store needs size limits, eviction, and rate limiting on the registration path.
Savings depend on how large the document is compared with the response. Illustrative estimate: assume a 4 KB document and a 40 KB response. Sending a hash cuts about 4 KB from each request but leaves roughly 90% of the bytes on the wire unchanged. Measure your own request sizes before relying on APQ for bandwidth savings.
#!/usr/bin/env bash
# Walks through the APQ handshake against a GraphQL endpoint.
# Anyone who can reach the endpoint can run this, which is why APQ is not an allowlist.
set -euo pipefail
ENDPOINT="" # placeholder
QUERY='query GetUser($id: ID!) { user(id: $id) { id name } }'
# The hash covers the exact document bytes (no trailing newline).
HASH=$(printf '%s' "$QUERY" | sha256sum | cut -d' ' -f1)
EXT=$(jq -nc --arg h "$HASH" '{persistedQuery: {version: 1, sha256Hash: $h}}')
# 1) Hash-only request: no "query" field.
jq -nc --argjson ext "$EXT" '{variables: {id: "42"}, extensions: $ext}' \
| curl -s -H 'Content-Type: application/json' --data @- "$ENDPOINT"
# On a cache miss an Apollo-compatible server answers roughly:
# {"errors":[{"message":"PersistedQueryNotFound",
# "extensions":{"code":"PERSISTED_QUERY_NOT_FOUND"}}]}
# 2) Retry with the full document plus the same extensions.
# The server checks sha256(query) == sha256Hash, stores it, and executes.
# Nothing here checks who the caller is or whether the operation is expected.
jq -nc --arg q "$QUERY" --argjson ext "$EXT" \
'{query: $q, variables: {id: "42"}, extensions: $ext}' \
| curl -s -H 'Content-Type: application/json' --data @- "$ENDPOINT"
# {"data":{"user":{"id":"42","name":"Ada"}}}
# 3) Hash-only again: now a cache hit for every client, until eviction or flush.
jq -nc --argjson ext "$EXT" '{variables: {id: "42"}, extensions: $ext}' \
| curl -s -H 'Content-Type: application/json' --data @- "$ENDPOINT"
# Measure bytes yourself instead of assuming savings:
printf 'document bytes: %s\n' "$(printf '%s' "$QUERY" | wc -c)"
A curl and jq walkthrough of the APQ handshake: a hash-only request, the PersistedQueryNotFound miss, the retry that registers the full document, and a later hash-only hit. Any caller can run the same steps to register an arbitrary operation.
How do you implement a build-time operation allowlist?
The lockdown path moves the decision from runtime to build time. Instead of the server learning documents from clients, the build learns them from source code, and the server accepts nothing else.
Extract, hash, publish
During the client build, a step scans source files for GraphQL operations, normalizes each document, and computes a hash, typically SHA-256 of the exact document text. The output is a manifest: a JSON object mapping each hash to its full document, often with the operation name and client identifier attached for auditing. The build publishes this manifest to the server or a registry before the client artifact ships.
At request time, the server reads the operation ID, looks it up, and executes the stored document. If the ID is missing, it rejects the request outright and does not fall back to a document in the request body. Ignoring client-supplied text is what makes this a security control.
Storage and deploy ordering
A single instance can load the manifest into memory at startup. With multiple instances, use a shared store such as Redis so that every replica sees a newly published manifest at the same moment. Always deploy the manifest first. If a client ships before its operations are registered, its requests fail.
Never delete entries while older versions are still in use. Mobile users can run old builds for months. Remove entries only when usage metrics show that no traffic still references them.
The manifest also has value beyond security. It gives reviewers a single inventory of every operation clients can run, which simplifies schema deprecation and code review.
import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
// Manifest produced by the client build and published before the client ships:
// { "<sha256 hex of document>": { "name": "GetUser", "client": "web@4.12.0", "document": "query GetUser($id: ID!) { ... }" } }
type Entry = { name: string; client: string; document: string };
const raw: Record<string, Entry> = JSON.parse(readFileSync("persisted-operations.json", "utf8"));
// Single instance: an in-memory Map. With several replicas, replace this lookup with a shared store such as Redis.
const allowlist = new Map<string, Entry>(Object.entries(raw));
// Fail fast at startup if any key does not match its document.
for (const [id, entry] of allowlist) {
const actual = createHash("sha256").update(entry.document, "utf8").digest("hex");
if (actual !== id) throw new Error(`Manifest hash mismatch for operation ${entry.name}`);
}
type Incoming = { id?: string; query?: string; variables?: Record<string, unknown> };
type Resolved =
| { ok: true; document: string; variables?: Record<string, unknown> }
| { ok: false; status: number; error: string };
export function resolveOperation(body: Incoming): Resolved {
// Ignore client-supplied text entirely. Never fall back to body.query.
if (body.query !== undefined) {
return { ok: false, status: 400, error: "Ad hoc documents are not accepted" };
}
if (typeof body.id !== "string") {
return { ok: false, status: 400, error: "Missing operation id" };
}
const entry = allowlist.get(body.id);
if (!entry) {
// Unknown ID: either an attacker or a client deployed before its manifest. Reject in both cases.
return { ok: false, status: 403, error: "Operation not in allowlist" };
}
return { ok: true, document: entry.document, variables: body.variables };
}
A build-time manifest maps SHA-256 hashes to operation documents, and the server executes only documents found in that manifest, rejecting any request that sends its own query text or an unknown ID.
Why do persisted query hashes not match?
A hash is computed over bytes, not meaning. Two documents that GraphQL considers identical produce unrelated SHA-256 digests if a single character differs. Most "persisted query not found" errors come from this gap.
The usual causes:
- Whitespace and formatting. The extraction tool prints the document one way, and the client sends it minified or reformatted.
query GetUser { user { id } }and the same text with newlines and indentation hash differently. - Fragment ordering. Some tools append fragment definitions in dependency order, others alphabetically. The operation is the same, but the bytes are not.
- Added
__typenamefields. Normalized client caches often inject__typenameinto every selection set at request time. If extraction ran before that injection, the manifest holds the hash of a document the client never sends. - Other late transforms. Any client-side step that rewrites the document after extraction breaks the match. Examples include stripping client-only directives, inlining fragments, and removing unused variables.
The rule is to hash exactly the bytes sent on the wire, or to define one canonical printer and run it on both sides. With the first approach, extraction must run after every client transform, ideally by capturing the final document from the client's own pipeline. With the second, the server re-prints incoming documents with the same printer before hashing. That printer must be pinned so an upgrade cannot silently change its output.
Also send and log the operation name alongside the hash. When a lookup fails, GetUser with an unknown hash points straight at a drifted document. A bare digest forces a reverse lookup against every manifest version.
import { createHash } from 'node:crypto';
import { parse, print } from 'graphql';
const sha256 = (s: string) => createHash('sha256').update(s, 'utf8').digest('hex');
// Three documents GraphQL treats as the same operation (or nearly so).
const minified = 'query GetUser { user { id } }';
const formatted = `query GetUser {
user {
id
}
}`;
// What a normalized cache might send after injecting __typename at request time.
const withTypename = 'query GetUser { user { id __typename } }';
// Raw bytes: every variant gets an unrelated digest.
for (const doc of [minified, formatted, withTypename]) {
console.log('raw ', sha256(doc).slice(0, 12));
}
// One canonical printer, run on both build and server side, removes whitespace drift.
// Pin the graphql version: a printer change would change every hash.
const canonical = (doc: string) => print(parse(doc));
console.log('canonical', sha256(canonical(minified)) === sha256(canonical(formatted))); // true
// Printing does NOT undo semantic transforms: __typename is still a different document.
console.log('canonical', sha256(canonical(minified)) === sha256(canonical(withTypename))); // false
// On lookup failure, log the operation name next to the hash so the drifted
// document is identifiable without reverse-looking up the digest.
function logMiss(operationName: string | undefined, hash: string) {
console.warn(JSON.stringify({ event: 'persisted_query_not_found', operationName, hash }));
}
logMiss('GetUser', sha256(withTypename));
Whitespace, formatting, and an injected __typename each produce a different SHA-256 for the same GetUser query, a shared printer from graphql-js removes only the formatting differences, and failed lookups are logged with the operation name next to the hash.
Can you cache GraphQL responses at the CDN with persisted queries?
Yes. Once the query text is replaced by a hash, a read operation fits in a URL, and anything that caches GET requests can store the response. A public operation might be requested as GET /graphql?operationName=ProductList&variables={"category":"shoes"}&extensions={"persistedQuery":{"version":1,"sha256Hash":"…"}}, URL-encoded in practice. The CDN treats this like any other URL, with no GraphQL awareness required.
Three rules keep this safe:
- Keep mutations on POST. Reject mutations sent over GET. Otherwise a crawler or prefetcher can trigger writes, and a cache may replay a side effect it should never store.
- Build cache keys from the full request. The key needs the hash, the operation name, and the variables. It also needs any header that changes the response, such as
Authorization, locale, or tenant ID. If your CDN normalizes or drops query parameters by default, check thatvariablessurvives. - Set
Cache-Controlper operation. Do not apply one global policy.ProductListcan returnCache-Control: public, max-age=60withVary: Accept-Language.GetViewershould returnCache-Control: private, no-store, so shared caches never keep it.
The main risk is serving one user's data to another. This happens when a personalized operation is marked public, or when the cache key ignores the auth header. Default to private and opt each operation into public caching explicitly.
The second risk is URL length. Large variable payloads, such as filter objects or ID lists, can exceed URL limits in browsers, proxies, or CDNs, which are often in the low kilobytes. Those requests fail with 414 errors or get truncated. For those operations, fall back to POST and accept that they will not be cached.
How do you migrate from an open GraphQL API to a locked-down one?
Run the migration in stages so you never reject traffic you haven't seen.
- Report-only. Deploy the allowlist check but only log operations whose hash or document isn't in the manifest. Tag each log line with client name and version so you can trace it to a source.
- Compare and fix gaps. Unknown operations usually come from old app versions, scripts nobody registered, or clients that build queries at runtime. Register them, rewrite them as static documents, or schedule them for removal.
- Enforce. Turn on rejection once the unknown rate stays at zero across a full release cycle, including your slowest-updating clients.
Enforcement couples client releases to server deploys. A client that ships before its manifest reaches the server fails on its first request. CI should publish the manifest to the registry as a required step and block the client build if publishing fails. Then the server knows every operation before any user can send it.
Internal tools, GraphiQL-style exploration, and introspection still need arbitrary queries. Serve them on a separate endpoint or route that requires strong authentication, such as SSO with network restrictions. That path accepts any query against the full schema, so it is now your most valuable target. Rate-limit it, log every request, and keep it off the public edge.
The cost is ongoing. Every build pipeline needs an extraction step. The manifest grows with every release. Long-lived mobile clients mean you must keep old entries indefinitely, or until you force those versions to upgrade.
When should you use APQ, an allowlist, or alternatives?
The deciding question is who writes the queries. If every operation comes from clients you build and ship, such as your web app, your mobile apps, or internal tools, a build-time allowlist fits well. You already control the source, so extracting operations costs a pipeline step, and in return the server rejects anything it has never seen.
A public or partner API is different. Third parties write queries you cannot predict, so a strict allowlist would block legitimate use. For these APIs, rely on cost analysis, rate limiting keyed to that cost, and authorization. APQ is still worth enabling for its bandwidth savings, but it gives you no protection.
Allowlisting limits which query shapes can run. It does not decide who may read what. A listed operation that fetches order(id:) will fetch any order ID it is given, so resolver-level authorization is still required. Keep depth and complexity limits as well. They cover any path you leave open, such as an introspection endpoint, an admin route, or a fallback mode during migration.
| Goal | Protects against arbitrary queries | Payload/caching benefit | Deploy coupling | Best fit |
|---|---|---|---|---|
| APQ | No | Smaller requests; enables GET caching | None | Any API, including public |
| Build-time allowlist | Yes | Same as APQ | Manifest must ship before clients | First-party clients |
| Depth/complexity limits | Partially (bounds cost, not shape) | None | None | Public APIs; defense in depth |
| Rate limiting | No (slows abuse only) | None | None | Every API |
| Resolver authorization | No (controls data access) | None | None | Required everywhere |
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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.