88 points · by tepidandroid · 7y ago · 79 comments
A few years back I designed a REST API and made the mistake of allowing too many query parameters, which made it really hard to optimize the database as there were hundreds of possible filter combinations (some requiring joins) that a client could ask for and that needed to be covered with indexes, so while most of the common queries worked well some of the "long tail" queries would always run into timeouts.
When using GraphQL with a backend like Hasura that generates SQL queries I would think that you have the same problem for complex data models, as there will be countless combinations of filters and joins that your database would need to efficiently cover. From what I understand most organizations solve this by either restricting the types of queries you can make through GraphQL or by just defining timeouts and dropping queries that take too long (which does not offer a great user experience).
To all of you who use GraphQL in practice, how do you solve this issue?
It just converts a custom syntax represented in GraphQL into arbitrary SQL queries, which is absolutely absurd. They have mechanisms to restrict access, but the fundamental foundation of the idea is flawed.
GraphQL is great in that you define the exact queries that you know to be performant. Once you resolve your top-level payload, most of the nested fields will be non-parameterized relations. These are usually just tons of multi-gets.
So in practice, you have top-level queries that you know to be performant, followed by multi-gets that you know to be performant. If you do have a parameterized field, make sure it's fast.
How is this meaningfully different from having an SQL query fronted by a REST API?
If your data models are pretty well structured, then basically every graphql object is a single table that you get by an indexed field, and traversing relationships can each do a where in query on the indexed id field. The parameters you expose on queries should be for indexed fields. So in practice, you’re not really autogenerating any particularly expensive queries, and if you assume the client isn’t asking for tons of data they don’t need, it’s not much different in query patterns than rest. Except that in some cases, the client can omit fields or related objects instead of re-using the rest route that’s a superset of what they need, so you can save resources sometimes too.
Then on top of all that, you have the option to not auto-map certain queries to the orm in special cases that are more complex, so you always can still write the code yourself to be more strict about what you allow. For writes, you typically would always do this to control exactly which fields you write.
GraphQL scares people because it seems to to allow arbitrary complex queries from applications. But that complexity was always there. REST just hides it in an unbounded number of predictable HTTP requests.
The same computatational challenges we've always had with mapping relational models to REST didn't go away, mainly: N+1 queries, recursive types and query parameters adding complexity.
With exceptions:
Preventing endless recursion: Or else it'd be possible for a client to timeout with queries [1]. In graphene recursion can be checked via `info.path`.
Calculated / slow fields: Makes more sense to have dedicated objects if calculations are involved, so if they're lists/connections, there can be limits imposed for how many can be grabbed at a time.
Sometimes the only way to be sure is to only allow access to these objects if they're a direct ID lookup at the root, e.g:
repos(id: <ID>) -> stats -> TotalLikesForAllIssues.
Assume that if cold and uncached, it could take <1s to calculate that. Imagine if we were to have that ran multiple times:
User -> repos(first: 20) -> stats -> TotalLikesForAllIssues.
So in my case I want to make the data available, but it's not always a direct mapping to SQL. And I'm also making rules inside where the client is limited in how, and how much they can query.
[1] Further reading: http://facebook.github.io/graphql/#sec-Fragment-spreads-must..., https://github.com/graphql/graphql-spec/issues/91
I like the arguments in favour of GraphQL. I think that what's missing is the ability to set resource limits on queries or users. That's relatively common in relational databases. I saw it used by Oracle DBAs on a regular basis, I've seen it done in Greenplum.
Makes me wonder if Hasura would run on Greenplum, actually. Then you would essentially put backpressure on the client to send less intensive queries.
Disclosure: I work for Pivotal, which sponsors and sells Greenplum.
Similarly, Postgraphile (which I'm more familiar with than Hasura) allows setting either a max query cost or a max query depth [2]. I haven't had to use either, as I don't provide a public GraphQL API (and can just whitelist the queries I intend my clients to run), but there are ways to limit query complexity.
1 - https://developer.github.com/v4/guides/resource-limitations/
2 - https://www.graphile.org/postgraphile/production/#limiting-g...
I mean, what's interesting isn't what is possible, but what people actually do.
Normally, you have an API and 2-3 different clients. While the front-end devs define the queries while they are creating these clienst, once done, they will use these exact queries for most of the time, so you can optimize for them.
IMO, REST APIs are a better fit if you open APIs to the whole world. Then, at least, you have a limited set of queries that you can optimise and plan for.
Think of an "advanced search" feature on the client that allows for creating queries of arbitrary complexity (basically, a client-side query builder). The user could certainly go overboard I'd imagine.
GraphQL may one day have the tooling and ecosystem to reduce the net complexity of the entire system, but that day wasn't a year ago, its definitely not today, and judging by how long the community has had to mature and still hasn't... probably won't be for a very long time, if ever. Probably because, again, its pushed by frontend developers primarily, so the pace of innovation on the backend side of it is dramatically slower. Apollo Client is an amazing piece of software that does some insanely smart things; Apollo Server is a thin wrapper around Express which does nearly nothing of value beside "make a GraphQL server possible."
Given how slowly things are progressing in GraphQL-land, I'd estimate that it has another two years before the zeitgeist moves against it. Though I hope I'm wrong, because its got some pretty cool ideas and is dramatically better for frontend development than anything else out there.
[1] https://twitter.com/ryanflorence/status/1060557386421723136
/graphql/{queryname}/{hash}?{params}
Multiple advantages:
1) client doesn't need to send the whole query unless it doesn't exist. All of this is handled automatically.
2) http caching of queries are now possible since it's a get instead of post
3) we can check slow queries using similar tools as rest. When we see a query being slow, we check each resolvers. We usually keep the queries simple
I mean, not any more difficult than any other internal component of an application.
Yes, you can't just aggregate by URL endpoint, but add opentracing and start at the top level resolver, and then start a new segment at each nested resolver.
Poof - you have an extremely nuanced view of your application performance.
Add in aggregate time metrics for each unique query/mutation and you'll have an even better view of what going on - far better than if you were simply looking at API endpoint timings in the first place.
Yes, this does make instrumentation and rate limiting harder, but not impossible. It’s akin to using SQL... sometimes the query optimizer does weird things, but declaratively asking for your data is much better than imperatively pulling and joining it yourself.
Why? This is always my chief complaint about GraphQL: there is no reason it should take fewer trips than directly hitting an endpoint unless you're structuring everything very rest-y in which case you're doing it wrong and GraphQL is a bandaid (and you'd still probably make the same amount of trips unless you're heavily caching things). IMO.
> 2. Clients only download the data they need.
Most third party APIs let you specify what fields you want via a query string or post variable which amounts to the same thing.
Honestly I think if people stopped trying to force REST into everything and just made RPC like calls to HTTP we'd have far less of a need for GraphQL.
Don't get me wrong, I still think GraphQL is pretty cool for third party access in some respects but I don't think it's as useful as a lot of people make it out to be.
The great thing here is that you don't have to anymore - you automatically support them all (or close to). And if it saves you from writing and documenting each of those new endpoints, that's a win at least in development time for me.
In most cases a thoughtfully designed REST API built according to HATEOAS shouldn't exhibit these problems. I've seen too many teams with a flawed understanding of both viewing GraphQL as some kind of silver bullet. Instead of stopping to consider their architecture they just rush out and implement GraphQL only to find themselves having significantly worse performance issues than they were having before.
user {
groups(first: 10) {
posts(first 1) {
content
author {
name
address {
state
}
}
}
}
}
and have all the round-trips take place within a datacentre, instead of needing to query /user
/user/12/groups?limit=10
/groups/34/posts?limit=1
/posts/56
/users/78
/users/78/address
and without having to write a separate /top_posts_view
endpoint.I don't understand from the description "a thoughtfully designed REST API built according to HATEOAS" what your proposal to solve this problem is.
For example, let's say you have have two endpoints /albums/1/ and /users/2/ and want to query them both at the same time.
They're unrelated data, so following REST best practices would make them separate endpoints.
With GraphQL, they're seperate resolvers but you can write
{
albums { get(id: 1) { .... } }
users { get(id: 2) { .... } }
}
And combine them those two calls into a single query. Maybe this is also possible via REST, but I haven't seen it.Unless you’re building one giant graphql enpoint exposing your whole database ?
It's the disadvantages, particularly the 'unknown unknowns' that I wonder about, and that's what's kept me from using it. GraphQL so far seems like the archetypal counter example for the 'use boring stuff' philosophy of software engineering. I kind of hope I'm wrong here, because the advantages are big and pretty cool.
It can get "exciting" on the client, particularly with libraries like Apollo. See for example the bug https://github.com/apollographql/apollo-client/issues/1186, which took two years to fix. The tooling for persisted queries can also be hard to set up, and they're close to required if you want to expose GraphQL to your client.
I'm usually surprised with all the comparisons to REST. It's far more practical and way less dogmatic.
I'd say that's because you should mentally substitute RPC whenever you see REST. Basically everyone talking about REST APIs mean RPC over HTTP with nouns in the endpoints.
Some trade-offs are things like more backend complexity, querying complex data (like deeply nested or recursive data structures) becomes harder, limiting exponential query complexity as the data branches out, etc. It also becomes more difficult to predict resource usage and to monitor performance, as the article mentions.