Persisted queries
Replace query text on the wire with a hash. Allowlists block arbitrary operations, automatic persisted queries save bandwidth, and both enable GET caching.
Persisted queries
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A persisted query is stored on the server under an id, usually a hash, so the client sends the id instead of the query text.
- Build-step persistence extracts every operation from your client at build time and registers them, so the server can reject any operation that is not on the list.
- Automatic persisted queries need no build step: the client sends a hash, and on a miss resends the full text once so the server can cache it.
- An allowlist is a security control. Automatic persisted queries are a bandwidth and caching optimization and do not restrict what clients can send.
- A hash request is short enough for a GET, which is what lets browsers and CDNs cache it.
Sending the whole document every time
A GraphQL client sends the query text with each request. For a real screen that text can run to several kilobytes, and the same few dozen operations repeat millions of times. That is wasteful, and it has two further costs. The server must parse and validate text it has seen before. And because the client may send any text at all, the server has to defend against every query anyone can write, which is why depth and cost limits exist.
A persisted query fixes both by storing the document on the server and giving it an id. The client then sends the id.
Two ways to get the document there
Build-step (allowlist). At build time, a tool scans your client for every operation, assigns each an id, and publishes the id-to-document map to the server. At runtime the client sends only ids. The server looks the id up and runs that document. If an id is unknown, or someone sends raw text, the server refuses.
Automatic persisted queries (APQ). Apollo’s scheme needs no build step. The client sends a SHA-256 hash of the query. If the server has it cached, it runs it. If not, it answers “not found”, the client retries once with the hash and the full text, and the server stores it. From then on the short form works. APQ is purely an optimisation. A client can still register any text it likes, so it does nothing to restrict queries. I did not run APQ in this session; that description is from Apollo’s documentation and the video.
Ben Awad’s video compares exactly these two, which is why it is the pick here.
An allowlist in Yoga
I ran the build-step style with GraphQL Yoga 6.1.0 and @graphql-yoga/plugin-persisted-operations 4.1.0, using an in-memory map in place of a build output:
import { usePersistedOperations } from "@graphql-yoga/plugin-persisted-operations";
import { createHash } from "node:crypto";
const doc = "{ books { title } }";
const hash = createHash("sha256").update(doc).digest("hex");
const store = new Map([[hash, doc]]);
const yoga = createYoga({
schema,
plugins: [
usePersistedOperations({
getPersistedOperation: (key) => store.get(key) ?? null,
allowArbitraryOperations: false,
}),
],
});
Three requests, all returned HTTP 200 as GraphQL servers usually do:
GET /graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"<hash>"}}returned the two books. The whole URL was 156 characters.- The same shape with an unknown hash returned
PersistedQueryNotFoundwith codePERSISTED_QUERY_NOT_IN_LIST. - A normal request with raw
querytext returned an error,PersistedQueryOnly.
That third result is the security point. With allowArbitraryOperations: false, the deep and wide queries from the previous lessons cannot be sent at all, because they are not on the list. The server’s attack surface shrinks from “any query” to “the queries we shipped”. The error code the plugin attached to that last rejection looked odd (CANNOT_SEND_PQ_ID_AND_BODY), so do not build client logic on it; check the plugin’s current docs.
Why GET matters
The first request is also a GET, and it is the quiet benefit. A hash is short and stable, so it fits in a URL. A browser or CDN can cache a GET response by URL, which POST bodies cannot do, so persisted queries make caching GraphQL at the edge workable. Mutations still go over POST, as shown in calling GraphQL with fetch.
Generating the list
Hand-writing hashes is not realistic. The tooling does it. GraphQL Code Generator’s client preset, from code generation, can emit a persisted-documents manifest, and Relay’s compiler produces ids natively. The deploy flow becomes: build the client, upload the manifest to the server or CDN, deploy both together. Keep old manifests live long enough for clients that have not updated, such as a mobile app that users do not upgrade quickly. An allowlist that only knows the newest release breaks everyone on the previous one.
When it is the wrong tool
An allowlist suits a first-party API with known clients: your web app, your mobile apps. It does not suit a public API where third parties write their own queries, GitHub-style. There, rely on limits, cost analysis and rate limiting instead. Many teams run both: allowlist for the first-party schema, and an open endpoint with strict limits for partners.
What the video covers
Ben Awad’s “Build Step vs Automatic Persisted Queries GraphQL” is a 9-minute video from February 2019 comparing the two approaches in the title. It is from Apollo Server 2 days, so the libraries have changed; the trade-offs have not. I could not read a transcript and I have no chapter list for it, so I am relying on the title. The two runners-up are ChilliCream’s chaptered talk, which uses Hot Chocolate on .NET, and Jamie Barton’s three-minute take on persisted queries as a security measure.
Where this fits
Persisted queries narrow what clients may send. Next, disabling introspection and hardening deals with what the server reveals about itself.
Check yourself
How is a build-step persisted query setup different from automatic persisted queries?
The build-step version registers a fixed list of operations ahead of time and can reject everything else. Automatic persisted queries learn operations at runtime from clients, so they allow anything.
Why does an allowlist help against abusive queries?
A client can only run operations you shipped and reviewed, so attackers cannot craft deep or expensive queries of their own.
Why is a public API with unknown clients a poor fit for an allowlist?
Third parties write their own queries and cannot register them in your build, so you would block legitimate use.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.