GraphQL Persisted Queries: Smaller Payloads, Smaller Attack Surface
How persisted queries shrink GraphQL payloads, unlock CDN caching, and close off arbitrary-query abuse.

Every GraphQL request ships the full query document over the wire, on every call, forever. A dashboard that fires the same 40-line query a hundred times a session sends that same 40 lines a hundred times. Worse: because the client can send any valid query, your GraphQL endpoint is effectively an open SQL console with extra steps — unless you do something about it.
Persisted queries fix both problems at once. The client sends a short hash instead of the query text, the server resolves the hash to a known operation, and anything not on the allowlist gets rejected before it touches a resolver. It's one of those changes that reads like a performance optimization but is really a security boundary wearing a performance optimization's clothes.
What a Persisted Query Actually Is
A persisted query is a GraphQL operation that's been registered ahead of time and identified by a hash (typically SHA-256 of the query text) instead of the raw document. The client sends the hash; the server looks up the corresponding query from a store it controls.
# ❌ What goes over the wire today, every single request
query GetDashboard($userId: ID!) {
user(id: $userId) {
id
name
recentOrders(limit: 10) {
id
total
status
items {
sku
quantity
}
}
}
}// ✅ What goes over the wire with persisted queries
{
"id": "a13f9e2c8b7d4f0e1a9c8b7d4f0e1a9c",
"variables": { "userId": "usr_8821" }
}The hash is deterministic and derived from the query text, so two clients registering the identical operation produce the identical identifier. Apollo's Automatic Persisted Queries (APQ) formalized this handshake, and Relay ships the same idea as a first-class compiler feature rather than a runtime fallback.
Automatic vs. Fully Persisted
There are two flavors, and they solve different problems.
| Approach | Registration | Security guarantee |
|---|---|---|
| Automatic (APQ) | Lazy, on first request | None — any query can still register |
| Fully persisted | Build-time, allowlist-only | Strong — unknown hashes are rejected |
APQ is purely a bandwidth optimization: the client sends a hash first, and if the server hasn't seen it, the client falls back to sending the full query once so the server can cache it. After that, every subsequent call is hash-only. It's a great first step and requires almost no server changes, but it does nothing to stop an attacker from registering an arbitrary query of their own — the server will happily cache whatever it's given.
Fully persisted queries close that gap. The allowlist is built at compile time from your actual client codebase, shipped to the server as a fixed manifest, and the server refuses anything not in it. This is the version worth reaching for if introspection abuse or query-complexity attacks are on your threat model, alongside things like query cost analysis for depth and complexity limiting.
Building the Allowlist at Build Time
Most GraphQL build tooling (Relay compiler, graphql-codegen, Apollo's persisted-query-lists package) can extract every operation from your client source and emit a manifest keyed by hash.
// scripts/build-persisted-queries.ts
import { createHash } from "node:crypto";
import { glob } from "glob";
import { readFile, writeFile } from "node:fs/promises";
import { parse, print } from "graphql";
interface PersistedQueryEntry {
hash: string;
query: string;
operationName: string;
}
async function buildManifest(): Promise<void> {
const files = await glob("src/**/*.graphql");
const entries: PersistedQueryEntry[] = [];
for (const file of files) {
const raw = await readFile(file, "utf8");
// Normalize whitespace so semantically identical
// queries always hash to the same value.
const normalized = print(parse(raw));
const hash = createHash("sha256")
.update(normalized)
.digest("hex");
const operationName =
parse(raw).definitions[0]?.kind === "OperationDefinition"
? (parse(raw).definitions[0] as any).name?.value ?? "anonymous"
: "anonymous";
entries.push({ hash, query: normalized, operationName });
}
await writeFile(
"dist/persisted-queries.json",
JSON.stringify(entries, null, 2),
);
}
buildManifest().catch((err) => {
console.error("Failed to build persisted query manifest:", err);
process.exit(1);
});That manifest ships to the server as part of deployment — not as a database row an attacker could poison, but as a build artifact tied to a specific client release.
Enforcing the Allowlist on the Server
The server-side check is deliberately boring: look up the hash, reject if it's missing, run the stored query with the client-supplied variables.
import type { Request, Response, NextFunction } from "express";
import manifest from "./dist/persisted-queries.json";
const allowlist = new Map(
manifest.map((entry) => [entry.hash, entry.query]),
);
export function persistedQueryGuard(
req: Request,
res: Response,
next: NextFunction,
): void {
const { id, query, variables } = req.body;
// ❌ Never fall back to executing an inline query
// in production once the allowlist is enforced.
if (!id) {
res.status(400).json({ errors: [{ message: "Missing query id" }] });
return;
}
const resolvedQuery = allowlist.get(id);
if (!resolvedQuery) {
res.status(400).json({
errors: [{ message: "Unknown persisted query", code: "PERSISTED_QUERY_NOT_FOUND" }],
});
return;
}
req.body = { query: resolvedQuery, variables };
next();
}The PERSISTED_QUERY_NOT_FOUND error code mirrors the convention Apollo clients already know how to handle, so existing client libraries degrade gracefully instead of throwing on an unfamiliar shape.
Enforcing the allowlist only pays off if introspection is also disabled in production. A fully locked-down operation list next to an open __schema query still leaks your entire API surface to anyone who asks.
Turning Mutations into Cacheable GET Requests
Because a persisted query identifier plus its variables fully determines the response for a given query, you can send read operations as GET requests with the hash and variables in the query string instead of a POST body. That single change makes GraphQL responses cacheable by any standard HTTP cache — a CDN, a reverse proxy, even the browser — using the same Cache-Control semantics defined in RFC 9111.
# ✅ Cacheable: deterministic URL, standard HTTP caching applies
curl "https://api.example.com/graphql?\
id=a13f9e2c8b7d4f0e1a9c8b7d4f0e1a9c&\
variables=%7B%22userId%22%3A%22usr_8821%22%7D"# ❌ Not cacheable by anything downstream of your app server
curl -X POST https://api.example.com/graphql \
-d '{"query": "query GetDashboard($userId: ID!) { ... }"}'A CDN can now cache that GET response keyed on the full URL, give you edge-level hit rates for your hottest read queries, and shave real latency off anything that doesn't need to be per-request fresh.
Rolling It Out Without Breaking Existing Clients
Flipping allowlist enforcement on for every client at once is how you take down production. Roll it out in three stages:
- Deploy APQ first. No allowlist enforcement, just hash-based caching. This validates the hashing and fallback logic with zero risk.
- Log unknown hashes instead of rejecting them. Run the allowlist check in shadow mode for a release cycle to catch clients you forgot to rebuild — old mobile app versions in particular.
- Enforce, with a documented minimum client version. Once logs show the unknown-hash rate at zero for the versions you intend to support, flip the guard to reject.
Key Takeaways
- Persisted queries replace full query documents with short hashes, cutting payload size on every request after the first.
- Automatic Persisted Queries are a bandwidth win; a build-time allowlist is the version that actually improves security.
- Normalize query text (via
print(parse(query))) before hashing so semantically identical queries always collapse to one entry. - Disable introspection alongside allowlist enforcement — one without the other leaves your schema discoverable anyway.
- Converting persisted reads to
GETrequests unlocks standard HTTP and CDN caching thatPOST-only GraphQL never gets. - Roll out enforcement in shadow mode first; a hard cutover on an unlogged allowlist will silently break whatever client you forgot about.


