Batching for N+1 problem
GraphQL Mesh v0 documentation (superseded by v1): Learn how GraphQL Mesh can solve the N+1 Query problem by batching requests with specific parameters. Check out the multiple-sources example.
A Mesh Gateway that is not properly configured will face the same famous issue as any other GraphQL servers: the N+1 Query problem.
Fortunately, GraphQL Mesh provides a way to batch requests with specific parameters.
Enable requests batching
Our
multiple-sources
example Gateway:
Will emit multiple requests to the “Authors” API when resolving the nested Book.author field:
Fortunately, Mesh allows an extra directive-based configuration to provide a “batching” query that will help resolve many record of the same type.
Our current resolver configuration for Book.author is the following:
Assuming that the “Authors” is exposing a
authors_v1_AuthorsService_GetAuthors(input: authors_v1_GetAuthorsRequest_Input) with
authors_v1_GetAuthorsRequest_Input being:
We could update our .meshrc.yaml configuration as follows:
requiredSelectionSet and sourceArgs got replaced by keyField and keysArg:
keysArgprovides the name of the batching primary key argument (input.idsfromauthors_v1_GetAuthorsRequest_Input)keyFieldindicates whichBookselection-set field should be used to provide theidsvalue
By default, batched results are mapped back to keys by array position: the upstream must return
one result per key in key order. Collection-style sources that return rows in their own order (or
with gaps / multiples) should also set valueKeyField to the field on each result used for
correlation — see
Schema Extensions → valueKeyField.
Now, our Mesh Gateway will try to batch calls to the “Authors” API when resolving Book.author:
Request Batching on the gateway level
Mesh also provides a way to batch requests on the gateway level. This is useful when you want to send multiple requests to the gateway in a single HTTP request. This follows Batching RFC