0
0
GraphQLquery~15 mins

Persisted queries in GraphQL - Deep Dive

Choose your learning style9 modes available
Overview - Persisted queries
What is it?
Persisted queries are a way to save GraphQL queries on the server so clients can send a short identifier instead of the full query text. This reduces the amount of data sent over the network and improves performance. Instead of sending the entire query every time, the client sends a key that the server uses to look up the saved query and execute it.
Why it matters
Without persisted queries, clients must send the full GraphQL query text with every request, which can be large and slow down communication. Persisted queries reduce bandwidth, speed up requests, and improve security by limiting which queries can be run. This makes apps faster and more reliable, especially on slow or limited networks.
Where it fits
Before learning persisted queries, you should understand basic GraphQL queries and how clients communicate with servers. After this, you can explore advanced GraphQL optimizations like query batching, caching, and security practices.
Mental Model
Core Idea
Persisted queries let clients send a small key instead of a full query by storing queries on the server ahead of time.
Think of it like...
It's like ordering food at a restaurant by just giving the waiter a menu item number instead of describing the whole dish every time.
Client                Server
  │                      │
  │--- Send query key --->│
  │                      │
  │<-- Execute saved query│
  │                      │
  │<--- Return results ---│
Build-Up - 7 Steps
1
FoundationWhat is a GraphQL query
🤔
Concept: Understanding the basic structure and purpose of a GraphQL query.
A GraphQL query is a request sent by a client to ask for specific data from a server. It looks like a structured text describing exactly what fields and objects the client wants. For example, a query might ask for a user's name and email.
Result
The server receives the query and returns only the requested data in a structured format.
Knowing what a GraphQL query is helps you see why sending the full query every time can be inefficient.
2
FoundationHow clients send queries to servers
🤔
Concept: Learning the communication process between client and server in GraphQL.
Clients usually send the full GraphQL query text in each request, often over HTTP. The server parses and executes the query to return data. This means every request carries the entire query text, which can be large.
Result
Each request includes the full query, which can slow down communication and increase data usage.
Understanding this communication shows why reducing query size can improve performance.
3
IntermediateIntroducing persisted queries concept
🤔Before reading on: do you think sending a query key instead of full text can improve speed or security? Commit to your answer.
Concept: Persisted queries store queries on the server and let clients send only a key to identify them.
Instead of sending the full query text, the client sends a unique key (like a hash). The server looks up the saved query by this key and runs it. This reduces the data sent and can prevent unauthorized queries.
Result
Requests become smaller and faster, and the server controls which queries can run.
Knowing that queries can be stored and referenced by keys reveals a powerful way to optimize network use and security.
4
IntermediateHow persisted queries improve performance
🤔Before reading on: do you think persisted queries only reduce data size or also affect caching and latency? Commit to your answer.
Concept: Persisted queries reduce bandwidth and can improve caching and latency by avoiding repeated parsing of query text.
Because the server already knows the query, it can skip parsing the full text each time. Also, smaller requests mean less network delay. This is especially helpful on slow or mobile networks.
Result
Faster responses and less data usage, improving user experience.
Understanding these performance benefits explains why persisted queries are popular in real-world apps.
5
IntermediateSecurity benefits of persisted queries
🤔
Concept: Persisted queries limit which queries clients can run, reducing risks.
Since only pre-approved queries are stored on the server, clients cannot send arbitrary or malicious queries. This reduces risks like denial-of-service attacks or data leaks.
Result
Improved security by controlling query execution.
Knowing this helps you appreciate persisted queries beyond speed—they also protect your system.
6
AdvancedImplementing persisted queries in GraphQL
🤔Before reading on: do you think clients send the key first or the full query when using persisted queries? Commit to your answer.
Concept: Clients can send the query key first; if the server doesn't recognize it, clients send the full query as fallback.
A common pattern is sending the key in a request. If the server has the query, it runs it. If not, the client sends the full query to register it. This two-step approach ensures smooth operation.
Result
Efficient query execution with fallback for new queries.
Understanding this fallback mechanism prevents confusion and errors in real implementations.
7
ExpertAdvanced caching and CDN integration
🤔Before reading on: do you think persisted queries can help CDNs cache responses effectively? Commit to your answer.
Concept: Persisted queries enable better caching at CDNs because requests are uniform and predictable.
Since clients send only keys, requests look the same for the same query, allowing CDNs to cache responses easily. This reduces load on origin servers and speeds up delivery globally.
Result
Improved scalability and faster global response times.
Knowing this advanced use shows how persisted queries fit into large-scale production systems.
Under the Hood
When a persisted query request arrives, the server uses the key to look up the stored query in a fast-access storage like memory or a database. If found, it parses and executes the query directly without needing the full text. If not found, the server can request the full query from the client to store it for future use. This reduces repeated parsing and network transfer of query text.
Why designed this way?
Persisted queries were designed to solve performance and security problems in GraphQL APIs. Sending full queries every time wastes bandwidth and exposes the server to arbitrary queries. Storing queries server-side and referencing them by keys reduces data transfer and limits execution to known queries. Alternatives like sending full queries or using query whitelisting were less efficient or flexible.
Client Request Flow
┌───────────────┐       ┌───────────────┐
│ Client sends  │       │ Server checks │
│ query key     │──────▶│ if key exists │
└───────────────┘       └───────────────┘
         │                      │
         │                      │
         │                      │
         │              ┌───────────────┐
         │              │ Key found?    │
         │              ├───────────────┤
         │              │ Yes           │
         │              │ Execute query │
         │              └───────────────┘
         │                      │
         │                      │
         │              ┌───────────────┐
         │              │ No            │
         │              │ Request full  │
         │              │ query from    │
         │              │ client        │
         │              └───────────────┘
         │                      │
         │                      │
         │◀─────────────────────┤
         │                      │
         │ Client sends full query
         │                      │
         │ Server stores query
         │                      │
         │ Executes query
         │                      │
         │◀─────────────────────┤
         │                      │
         │ Returns results
Myth Busters - 4 Common Misconceptions
Quick: Do persisted queries mean clients never send full queries? Commit yes or no.
Common Belief:Persisted queries mean clients only ever send the query key, never the full query.
Tap to reveal reality
Reality:Clients send the full query at least once to register it on the server, then use the key for future requests.
Why it matters:Thinking clients never send full queries can cause confusion during initial setup and debugging.
Quick: Do persisted queries automatically make queries faster? Commit yes or no.
Common Belief:Persisted queries always make query execution faster on the server.
Tap to reveal reality
Reality:Persisted queries reduce network size and parsing time but do not speed up the actual data fetching or resolver execution.
Why it matters:Expecting faster data fetching can lead to wrong performance assumptions and misdiagnosis.
Quick: Can persisted queries prevent all security risks? Commit yes or no.
Common Belief:Persisted queries completely eliminate security risks in GraphQL APIs.
Tap to reveal reality
Reality:They reduce risks by limiting queries but do not replace other security measures like authentication and authorization.
Why it matters:Overreliance on persisted queries can leave systems vulnerable to other attacks.
Quick: Are persisted queries only useful for large queries? Commit yes or no.
Common Belief:Persisted queries are only beneficial when queries are very large.
Tap to reveal reality
Reality:Even small queries benefit from persisted queries by reducing repeated parsing and improving caching.
Why it matters:Ignoring persisted queries for small queries misses opportunities for optimization.
Expert Zone
1
Persisted queries require careful versioning and invalidation strategies to handle schema changes without breaking clients.
2
The choice of storage for persisted queries (in-memory, database, or CDN) affects latency and scalability significantly.
3
Combining persisted queries with automatic persisted queries (APQ) protocols can optimize network usage further by sending hashes first.
When NOT to use
Persisted queries are less suitable for highly dynamic or user-generated queries that change frequently. In such cases, traditional full query sending or query batching might be better. Also, for very small or simple APIs, the added complexity may not justify the benefits.
Production Patterns
In production, teams often use persisted queries with a build step that pre-registers queries. They combine this with CDN caching and APQ protocols. Monitoring tools track cache hit rates and fallback occurrences to optimize performance and reliability.
Connections
Content Delivery Networks (CDNs)
Persisted queries enable better CDN caching by making requests uniform and predictable.
Understanding how persisted queries create consistent request patterns helps grasp CDN caching strategies for APIs.
Hash Functions
Persisted queries use hash functions to create unique keys representing queries.
Knowing how hash functions work clarifies why keys uniquely identify queries and how collisions are avoided.
Database Indexing
Persisted queries rely on fast lookup of stored queries, similar to how database indexes speed up data retrieval.
Seeing persisted query storage like indexing helps understand performance tradeoffs in query retrieval.
Common Pitfalls
#1Client sends only query key without registering the query first.
Wrong approach:{ "extensions": { "persistedQuery": { "sha256Hash": "abc123" } } }
Correct approach:First send full query with key, then subsequent requests send only the key.
Root cause:Misunderstanding that the server must know the query before accepting key-only requests.
#2Assuming persisted queries speed up data fetching on the server.
Wrong approach:Expecting resolver functions to run faster just because queries are persisted.
Correct approach:Recognize persisted queries reduce network and parsing overhead but resolvers run at normal speed.
Root cause:Confusing query parsing optimization with data fetching performance.
#3Not handling schema changes causing persisted queries to become invalid.
Wrong approach:Continuing to use old persisted queries after schema updates without invalidation.
Correct approach:Implement versioning and invalidate or update persisted queries when schema changes.
Root cause:Ignoring the need to sync persisted queries with schema evolution.
Key Takeaways
Persisted queries let clients send a small key instead of full GraphQL queries, saving bandwidth and improving speed.
They improve security by limiting execution to known queries and reduce server parsing overhead.
Clients must send the full query at least once to register it before using the key alone.
Persisted queries enable better caching and scalability, especially when combined with CDNs and hashing protocols.
They are not a silver bullet and require careful management of query storage and schema changes.