Graphql N+1 problem
- The N+1 problem in GraphQL work
- since GraphQL has a separate resolver function for each field, as each field is resolved GraphQL will end up potentially making one or more database requests per field
- if a GraphQL request asks for nested data, the N+1 problem is a threat due to potential redundant database requests
- these extra/redundant roundtrips can slow GraphQL requests down considerably
Example:
query {
authors { # fetches authors (1 query)
name
address { # fetches address for each author (N queries for N authors)
country
}
}
}
-
in this example:
- GraphQL makes 1 query to fetch all the
authors
- for each author, GraphQL then makes an additional request to fetch the address of that author (
n
requests) - if there are 50 authors, then GraphQL makes 51 requests (
authors
+address foreach author
)
- GraphQL makes 1 query to fetch all the
-
This problem can be solved