I am using GraphQL java implementation.
Although one of GraphQL's strengths is fetching different fields in parallel, I found that only one thread is in use if I do not use multi-threading methods like CompletableFuture
in DataFetchers.
So my question is, should I always use multi-threading in DataFetcher as shown below in the official doc, even if it is just fetching from one source (a database for example) instead of multiple sources?
It seems that this is the recommended approach and will do no harm at least.
But I would like to hear from more experienced devs.
Thanks in advance!
In graphql-java implementation by default, all the resolver is called sequentially.
Consider below schema
type Query {
allPost: [Post!]
}
type Post {
id: ID!
tittle: String!
postDetail: PostDetail!
comments: [Comments!]
}
type PostDetail {
id: ID!
# This can be converted into enum
postMediaType: String!
postUrl: String!
}
type Comment{
id:ID!
name: String!
description: String!
}
And this is the query over the schema given above
{
allPost{
id
tittle
postDetail {
id
postMediaType
postUrl
}
comments{
id
name
description
}
}
}
When the server will execute this query first Post resolver will be called and if Post resolver does not returns comments or postDetail data then graphQL will try to search for there respective resolvers if it does not find it the server will fail during boot up.
Now graphQL server will first call the PostDetail resolver and it will wait for its completion and then it will call Comments Resolver to get the list of all the comments for that post.
As we can see resolvers are called sequentially even though PostDetail resolver and Comments resolver does not depend on each other. This is where we can use CompletableFuture to make the PostDetail resolver and Comments resolver asynchronous.
In this case first Post resolver will be called after that graphql will call PostDetail resolver which will return CompletableFuture and then it will call Comments resolver which will also return CompletableFuture and later when both of these future will complete it will send a response back to the client.
So it does not depend upon the number of Datasource you have GraphQL does not care about different types of data sources it just cares about the wiring of Datafecters for the type/field.
You can run your resolvers in parallel if there is no dependency between them.