Query plans and caching
Most of the time graphql.Do spends on a small request goes to parsing and
validating the document, which is the same every time a client sends the same
query. A plan is a document that is already validated and analysed for one
operation, and a plan cache keeps plans for the queries a server receives,
so repeated queries skip that work. This page shows both; the
complete program serves requests through a cache.
What each call does
| Call | Parses | Validates | Plans | Executes |
|---|---|---|---|---|
graphql.Do | every call | every call | every call | yes |
graphql.Execute | no, takes a parsed document | no | every call | yes |
PlanCache.Get + graphql.ExecutePlan | first time a query is seen; every call with Normalize | first time | first time | yes |
graphql.ExecutePlan with a plan you keep | no | no | no, except as below | yes |
A plan whose @include or @skip directives depend on variables is completed
once for each combination of those variables’ values, the first time it is
executed with it; up to 32 combinations are kept, and others are planned again
on every execution.
For a query with one variable and three fields, measured on master:
| Time | Allocations | |
|---|---|---|
graphql.Do | 80 µs | 936 |
graphql.Execute with a parsed document | 8.4 µs | 62 |
PlanCache.Get + graphql.ExecutePlan | 8.0 µs | 46 |
graphql.ExecutePlan with a kept plan | 7.4 µs | 45 |
Validation is most of the difference. Larger responses spend more time in resolvers, so the share saved is smaller, but the work saved per request stays the same.
Plan cache
graphql.NewPlanCache returns a cache that is safe for concurrent use; one per
schema, shared by all requests, is the usual setup. Get returns the plan for a
query, parsing, validating and planning it the first time:
// Execute runs req like graphql.Do, reusing the parsed, validated and
// planned document when the same query was seen before.
func (s *Server) Execute(ctx context.Context, req Request) *graphql.Result {
pr := s.cache.Get(s.schema, req.Query, req.OperationName)
if len(pr.Errors) > 0 {
return &graphql.Result{Errors: pr.Errors}
}
return graphql.ExecutePlan(pr.Plan, graphql.ExecuteParams{
Schema: *s.schema,
Args: mergeArgs(req.Variables, pr.SynthArgs),
Context: ctx,
})
}| Option | Default | Effect |
|---|---|---|
MaxEntries | 1024 | Number of queries kept; the least recently used ones are dropped. |
MaxQueryBytes | 64 KiB | Longer queries are not cached, and are parsed, validated and planned on every call. |
Normalize | off | Queries that differ only in literal arguments share a plan; see Normalization. |
Things to know:
- The schema is recognized by its address. An entry is reused only for the
same
*graphql.Schemapointer. Build the schema once and keep a pointer to it, as the program does; passing the address of a copy, such ass := schema; cache.Get(&s, ...), makes every lookup miss. After rebuilding the schema, the old entries are dropped as they are looked up, or all at once withReset. - Errors are cached too. A query that fails validation returns the same
errors from the cache the next time, without validating again. That includes
a literal a custom scalar’s
ParseLiteralrejected by returningnilor panicking, so its result should depend only on the value. - Only the specified rules are applied:
Getvalidates withgraphql.SpecifiedRules. To add rules of your own, validate and plan yourself, and keep the plans as described in Plans you keep. - Pass the schema in
ExecuteParams.ExecutePlanexecutes against the schema of the plan, but takes the extensions’ExecutionDidStartandGetResultfromExecuteParams.Schema; without it, those hooks do not run (#157). - Extensions. As with
graphql.Execute, theInit, parse and validation hooks of extensions do not run. - A nil cache works:
Geton a nil*PlanCacheparses, validates and plans every time, which turns caching off without changing the code.
HitsMisses returns the number of lookups that found a plan and that did not,
for metrics.
Normalization
With Normalize: true, the cache replaces literal field arguments with
variables before looking the query up, so { book(id: "1") { title } } and
{ book(id: "2") { title } } share one plan. The values taken out of the query
come back in PlanResult.SynthArgs, and must be added to the variables, as
mergeArgs does:
// mergeArgs adds the variables that a normalizing cache extracted from
// literals to the request's variables.
func mergeArgs(vars, synth map[string]interface{}) map[string]interface{} {
if len(synth) == 0 {
return vars
}
args := make(map[string]interface{}, len(vars)+len(synth))
for k, v := range vars {
args[k] = v
}
for k, v := range synth {
args[k] = v
}
return args
}Without them, the arguments are missing: a nullable argument reaches the
resolver as missing, without an error, and a non-null one fails the request with
Variable "$__pcv0" of required type "ID!" was not provided.
Normalizing also costs a parse on every call, hits included, since the query has to be parsed to be normalized.
Only literal arguments are shared. Queries that differ in anything else, such
as their directives (@skip(if: true) and @skip(if: false)), a variable’s
default value, or fragments and operations the executed operation does not use,
get separate plans and are validated separately (v0.14.0; before, they could
share one, and the second query ran with the first one’s plan or validation
result). Clients that send variables instead of literals, as most do, get
one plan per query without Normalize.
Plans you keep
graphql.PlanQuery builds a plan from a parsed document; it does not validate,
so validate first, as for graphql.Execute. A plan can be executed any number
of times, concurrently, with different variables, which suits operations known
in advance, such as the ones a client registers:
// prepare parses, validates and plans an operation known in advance.
func prepare(schema *graphql.Schema, query, operationName string) (*graphql.Plan, []gqlerrors.FormattedError) {
doc, err := parser.Parse(parser.ParseParams{Source: query})
if err != nil {
return nil, gqlerrors.FormatErrors(err)
}
if v := graphql.ValidateDocument(schema, doc, nil); !v.IsValid {
return nil, v.Errors
}
plan, err := graphql.PlanQuery(schema, doc, operationName)
if err != nil {
return nil, gqlerrors.FormatErrors(err)
}
return plan, nil
}result := graphql.ExecutePlan(plan, graphql.ExecuteParams{
Schema: *schema,
Args: variables,
Context: ctx,
})A plan belongs to the schema it was built with, and executes against that
schema whatever ExecuteParams.Schema holds. PlanQuery returns an error for
problems with the document as a whole, such as an unknown operation name; a
document that was not validated can still produce a plan, which then executes
what it can.
Complete program
main.go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/gql-go/graphql"
)
// Request is a GraphQL request as a client sends it.
type Request struct {
Query string
OperationName string
Variables map[string]interface{}
}
// Server executes requests through a plan cache.
type Server struct {
// schema is built once; the cache recognizes it by its address.
schema *graphql.Schema
cache *graphql.PlanCache
}
// Execute runs req like graphql.Do, reusing the parsed, validated and
// planned document when the same query was seen before.
func (s *Server) Execute(ctx context.Context, req Request) *graphql.Result {
pr := s.cache.Get(s.schema, req.Query, req.OperationName)
if len(pr.Errors) > 0 {
return &graphql.Result{Errors: pr.Errors}
}
return graphql.ExecutePlan(pr.Plan, graphql.ExecuteParams{
Schema: *s.schema,
Args: mergeArgs(req.Variables, pr.SynthArgs),
Context: ctx,
})
}
// mergeArgs adds the variables that a normalizing cache extracted from
// literals to the request's variables.
func mergeArgs(vars, synth map[string]interface{}) map[string]interface{} {
if len(synth) == 0 {
return vars
}
args := make(map[string]interface{}, len(vars)+len(synth))
for k, v := range vars {
args[k] = v
}
for k, v := range synth {
args[k] = v
}
return args
}
var titles = map[string]string{
"1": "A Wizard of Earthsea",
"2": "The Left Hand of Darkness",
}
func newSchema() (*graphql.Schema, error) {
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.ID},
"title": &graphql.Field{Type: graphql.String},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"book": &graphql.Field{
Type: bookType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.ID)},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id := p.Args["id"].(string)
if title, ok := titles[id]; ok {
return map[string]interface{}{"id": id, "title": title}, nil
}
return nil, nil
},
},
},
}),
})
return &schema, err
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
s := &Server{
schema: schema,
cache: graphql.NewPlanCache(graphql.PlanCacheOptions{MaxEntries: 512}),
}
query := `query Book($id: ID!) { book(id: $id) { id title } }`
requests := []Request{
{Query: query, Variables: map[string]interface{}{"id": "1"}},
{Query: query, Variables: map[string]interface{}{"id": "2"}},
{Query: query, Variables: map[string]interface{}{"id": "3"}},
{Query: `{ book(id: "1") { titel } }`},
{Query: `{ book(id: "1") { titel } }`},
}
for _, req := range requests {
out, _ := json.Marshal(s.Execute(context.Background(), req))
fmt.Println(string(out))
}
hits, misses := s.cache.HitsMisses()
fmt.Printf("hits: %d, misses: %d\n", hits, misses)
}The program sends the same query three times with different variables, and a query with a misspelled field twice. The first request of each is a miss, and the other three find their entry, including the cached validation error:
{"data":{"book":{"id":"1","title":"A Wizard of Earthsea"}}}
{"data":{"book":{"id":"2","title":"The Left Hand of Darkness"}}}
{"data":{"book":null}}
{"data":null,"errors":[{"message":"Cannot query field \"titel\" on type \"Book\". Did you mean \"title\"?","locations":[{"line":1,"column":19}]}]}
{"data":null,"errors":[{"message":"Cannot query field \"titel\" on type \"Book\". Did you mean \"title\"?","locations":[{"line":1,"column":19}]}]}
hits: 3, misses: 2