Overview
We've seen how the router's cache helps with performance by storing query plans and introspection responses. It can also store a particular operation's identifier, allowing client queries to take up fewer network resources.
In this lesson, we will:
- Explore automatic persisted queries (APQ)
- Discuss the router's role in both receiving and sending APQ
- Explore router output when using APQ and build requests that utilize them
What are automatic persisted queries (APQ)?
APQ optimize the operations clients send to a GraphQL server. Instead of sending the full operation string, the client sends an operation identifier: the unique SHA-256 hash of the operation string.
Let's take a look at how this works!
First, a client sends a request to the GraphQL server, containing both the operation string and its unique identifier.
The server validates that the provided identifier matches the operation it receives. It calculates the SHA-256 hash of the operation string, then compares it with the provided identifier. If all goes well, it stores the identifier as an automatic persisted query.
The next time the client wants to send the same operation, it no longer needs to send the full-length operation string, just the identifier.
The server checks its cached list of APQ for the identifier and retrieves the full operation it corresponds to. It resolves the operation as usual and sends the data back to the client.
APQ and the router
In our federated architecture, the router is uniquely positioned to be the go-between for both client and server. It receives GraphQL queries from the client, then breaks them up and forwards them to each responsible subgraph server.
As the first point of contact for clients, the router acts as a GraphQL server that can receive automatic persisted queries.
Then, it breaks up the request into smaller operations that are then sent to the responsible subgraph. In this way, the router acts as a client sending APQ.
Whether the router is receiving the query or sending queries on to subgraphs, we can configure exactly how it handles automatic persisted queries.
Practice
Key takeaways
- Automatic persisted queries (APQ) are operation strings that have been converted into SHA-256 hashes for faster querying between client and server.
- To use APQ, clients first send the router an operation string along with its SHA-256 hash, for validation. When the router confirms its hash of the string matches the hash provided, it stores it for future use.
- Subsequent queries for the same data can provide the hash instead of the entire operation string.
Up next
Up next, let's see exactly how the router receives APQ from a client.
Share your questions and comments about this lesson
This course is currently in
You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.