Automatic Persisted Query in GraphQL: What It Is and How It Works
Automatic Persisted Query (APQ) in GraphQL is a technique where queries are saved on the server with a unique hash, allowing clients to send only the hash instead of the full query text. This reduces bandwidth and speeds up repeated requests by avoiding sending large query strings multiple times.How It Works
Imagine you have a favorite recipe that you share with friends. Instead of writing the whole recipe every time, you give them a short code that refers to it. Similarly, with Automatic Persisted Queries, the client sends a small hash code representing the full GraphQL query to the server.
The server keeps a list of these queries linked to their hashes. When it receives a hash, it looks up the full query and runs it. If the server doesn’t recognize the hash, the client sends the full query once, and the server saves it for future use.
This process saves time and data because after the first request, only the small hash needs to be sent, not the entire query text.
Example
const { ApolloClient, InMemoryCache, createHttpLink } = require('@apollo/client'); const { createPersistedQueryLink } = require('@apollo/client/link/persisted-queries'); const fetch = require('cross-fetch'); const httpLink = createHttpLink({ uri: 'https://example.com/graphql', fetch }); const persistedQueriesLink = createPersistedQueryLink(); const client = new ApolloClient({ cache: new InMemoryCache(), link: persistedQueriesLink.concat(httpLink), }); const QUERY = ` query GetUserName($id: ID!) { user(id: $id) { name } } `; client.query({ query: QUERY, variables: { id: '123' } }) .then(response => console.log(response.data)) .catch(error => console.error(error));
When to Use
Use Automatic Persisted Queries when you want to reduce the amount of data sent over the network, especially for mobile or slow connections. It is helpful when clients repeatedly send the same queries, as it saves bandwidth and speeds up response times.
Real-world use cases include mobile apps with limited data plans, web apps with complex queries, and any situation where performance and efficiency are important.
Key Points
- APQ saves queries on the server with a hash to avoid sending full queries repeatedly.
- Clients send a small hash first; if unknown, they send the full query once.
- Reduces bandwidth and improves performance, especially on slow networks.
- Works well for apps with repeated queries and limited data usage.