0

I have a very simple setup. Express-GraphQL API with MongoDB database. MongoDB responses are in general quite fast but when I would like to return from GrapQL API, TTFB is taking too long especially for multi-user queries.

For example, when I request a user, TTFB is 25.65 ms and content download is around 0.6 ms. But when I request all users with same fields TTFB is 4.32s and content download is around 1.28s.

Content download is no problem but I feel like TTFB is longer than it should be. You can check part of my Schema with RootQuery below.

 const RootQuery = new GraphQLObjectType({
     name: 'RootQueryType',
     fields: {
         user: {
             type: UserType,
             args: {mail: {type: GraphQLString}},
             resolve(parent, args){
                 return User.findOne({mail: args.mail});
             }
         },
         users: {
             type: new GraphQLList(UserType),
             resolve(parent,args){
                 return User.find({}).collation({ locale: "en" }).sort({name: 1, surname: 1});
             }
         }
     }
 });

What would be the best way to decrease TTFB?

btutal
  • 115
  • 2
  • 7

1 Answers1

0

From your code snippet I can't see how the UserType is defined and I don't know also how the graphql query you are performing is exactly. Having said that, high TTFB numbers usually indicate that the server is performing heavy tasks, so, is very likely you are requesting a field from UserType in the query that has an expensive resolver associated (performing another MongoDB query maybe) which will be executed as many times as users exist. This is known as the N+1 problem and you could get rid of it using a dataloder, which will allow you to batch those expensive MongoDB queries in one query.

If you could give more information about the UserType and the query you are performing it would help a lot.

References: - https://itnext.io/what-is-the-n-1-problem-in-graphql-dd4921cb3c1a - https://github.com/graphql/dataloader

simonpedro
  • 46
  • 1
  • 3
  • You can find my UserType and query below. All the fields except it has a type GraphQLString ``` const UserType = new GraphQLObjectType({ name: 'User', fields: () => ({ id:, username:, name:, surname:, displayName:, department:, mobilenumber:, mail: jobTitle:, division: , company: }) }); ``` Query ``` query { users { name surname department mobilenumber mail } } ``` – btutal Jul 23 '19 at 17:05