Graphql and round trips. Is this just an ios app i

2019-07-23 02:58发布

问题:

I'm taking another look at graphql, and I'm trying to understand why saving round trips is a benefit to developers. Is the cost of making a request so expensive? I'm coming from a web development background.

Lets compare a standard rest api with a graphql api.

I need to retrieve a users personal info, and a list of their friends. Traditional rest api might require 2 calls, one to get the personal info, and one to get the friends.

With graphql, I get the same results with one request.

But as a frontend developer, I want my page to have the shortest possible stagnant period. I would like to render only a portion of the page as fast as possible, rather than wait for all the information I need in one go to then render the page.

Now from my understanding, graphql was partly created to solve mobile application api issues. Is there something about ios apps that makes it more beneficial to load all the data at once, as opposed to parallel requests? Or is there something else that I'm missing?

回答1:

So generally speaking, network traffic inside the system you control (i.e. your backend) is fast. A request that make take 205ms (200ms network, 5ms data) to the outside world, might take just 6ms (1ms network, 5ms data) internally.

If you want to build a screen of your app, and that requires making two REST requests because the 2nd depends on the result of the first, you're looking at (given these crude numbers) 410ms to get the data you need to render your screen.

With GraphQL (or any other gateway layer that consolidates the data), you'd get everything in slightly over 212ms (200ms latency to GraphQL server + 6ms for each internal call).

In scenarios where you could make all your requests in parallel (i.e. they don't depend on the data from other requests), the performance benefits aren't quite as apparent, but you'll find that these situations are actually pretty rare as the complexity of your app grows.

The general rule of thumb with GraphQL is that your initial query fetches enough data for the page to be functional, if there's less important content you can always fetch that with another query.

Alongside the performance benefits, letting mobile devices make fewer network requests is a big win when it comes to battery life. Network usage is expensive, and should be avoided as much as possible.



回答2:

Before using GraphQL instead of REST API one needs to understand the benefits of GraphQL over REST

GraphQL is a query language and it uses the type system you define GraphQLInt, GraphQLString, customType...

REST

  • multiple round trips - slow
  • overloaded data
  • Many EndPoint

GraphQL

  • 1 Endpoint
  • declaratives: types, queries, mutations
  • exact shape of the data you want in one call
  • no underfetching, no overfetching of data
  • query == result, better performance