Сохранённые запросы и автоматические сохранённые запросы
Сократите размеры запросов и повысьте производительность, регистрируя запросы заранее. Узнайте, как работают Automatic Persisted Queries (APQ) и как включить их в Spring Boot GraphQL.
«Сохранённые запросы и автоматические сохранённые запросы» — бесплатный урок GraphQL APIs with Spring Boot на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения GraphQL APIs with Spring Boot, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
The Cost of Sending Full Queries
Every GraphQL request normally carries the entire query string. Large queries mean larger payloads, more bandwidth, and repeated parsing and validation on the server.
Persisted queries reduce this overhead by sending a short hash instead.
What Is a Persisted Query?
A persisted query is a query string the server already knows, stored under a unique ID (usually a SHA-256 hash). Clients send the ID, and the server looks up the full query.
Automatic Persisted Queries (APQ)
APQ automates registration. The client first sends only the hash. If the server does not recognize it, the client resends with the full query, which the server then caches under that hash.
The APQ Handshake
The flow has two possible steps:
- Client sends hash only -> if known, server responds
- If unknown, server returns
PersistedQueryNotFound - Client resends hash + full query -> server caches and responds
The Request Extension
APQ travels in the request's extensions field, carrying the hash and protocol version.
{
"extensions": {
"persistedQuery": { "version": 1, "sha256Hash": "abc123..." }
}
}Performance Benefits
Once a query is persisted, the server can skip parsing and validating its document, and the network carries only a small hash. This lowers latency and CPU for hot queries.
GET Requests and CDN Caching
Because a persisted query is just a hash, it fits in a URL. Sending it as a GET request lets a CDN cache the response, offloading the server entirely for repeated reads.
GET /graphql?extensions={"persistedQuery":{"sha256Hash":"abc123"}}Enabling APQ in Spring
Add an AutomaticPersistedQueriesProvider backed by a cache (such as Caffeine) when building the GraphQL source.
PreparsedDocumentProvider provider =
new ApolloPersistedQuerySupport(cacheStore);
GraphQL.newGraphQL(schema)
.preparsedDocumentProvider(provider)
.build();Security as a Bonus
You can run APQ in safelist mode: only pre-approved queries are allowed, and unknown hashes are rejected outright. This blocks arbitrary client queries, shrinking your attack surface.
When Not to Use APQ
APQ shines for stable, repeated queries from your own apps. For ad-hoc tooling, exploratory queries, or constantly changing documents, the handshake overhead may outweigh the savings.
Best Practices
Get the most from persisted queries:
- Size the cache to hold your hot queries
- Use GET + CDN for cacheable reads
- Consider safelist mode for production security
- Monitor cache hit rates to tune
Quick Check
Test your persisted query knowledge.
Recap
You optimized with persisted queries:
- Send a hash instead of the full query string
- APQ registers queries automatically via a handshake
- Skips re-parsing and enables GET + CDN caching
- Safelist mode adds security; enable via a document provider
Persisted queries cut payload, latency, and attack surface for hot queries.
Часто задаваемые вопросы
Урок «Сохранённые запросы и автоматические сохранённые запросы» бесплатный?
Да — полный текст урока «Сохранённые запросы и автоматические сохранённые запросы» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс GraphQL APIs with Spring Boot, подпишись на CoddyKit PRO. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.
Чему я научусь в уроке «Сохранённые запросы и автоматические сохранённые запросы»?
Сократите размеры запросов и повысьте производительность, регистрируя запросы заранее. Узнайте, как работают Automatic Persisted Queries (APQ) и как включить их в Spring Boot GraphQL. Ты практикуешь GraphQL APIs with Spring Boot с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать GraphQL APIs with Spring Boot?
Предыдущий опыт не требуется. GraphQL APIs with Spring Boot на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Сохранённые запросы и автоматические сохранённые запросы»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке GraphQL APIs with Spring Boot?
Да. Каждый урок GraphQL APIs with Spring Boot включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Анализ сложности запросов
- Стратегии кэширования GraphQL
- Мониторинг и трассировка GraphQL
- Сохранённые запросы и автоматические сохранённые запросы