720 points · by randytandy · 4y ago · 433 comments
but beginner to mid level developers are lead down the path of USE GRAPHQL especially on youtube... and this is just unfair and wrong.
The good:
- It makes working with describing the data you want easy
- It can save you bandwidth. Get what you ask for and no more
- It makes documentation for data consumers easy
- It can make subscription easier for you to use
- Can let you federate API calls
The bad
- It is actually a pain to use, depending on the backend you are using you'll have to manage
two or more type systems if there are no code first generates in your language
- It doesn't support map/tables/dictionaries. This is actually huge. I get that there might be
some pattern where you don't want to allow this but for the majority of situations working with json api's you'll end up with a {[key: string] : T} somewhere
- No clear path for Api versioning you'll end up with MyQueryV1.01 MyQueryV1.02 MyQueryV1.03
Don't use Graphql unless you're managing a solution/problem set that facebook intended graphql for
Invest your time in a simpler solution then running to GraphQL first
thanks for reading my ted talk
please any senior dev's drop your wise words so that any new dev's can avoid tarpits
The more fine-grained nature of boring REST calls makes it more easy to control client impact on the system.
If you want to see the kind of work you actually need to put in to make a graphql API, look at Shopify. They have rate limits based on quantity of data returned. Cursors and pagination. The schema is a huge ugly mess with extra layers that never show up in the pretty examples of GraphQL on the internet.
Note that even if you use graphql for a private api to your web client, folks will reverse engineer it and use it for their own purposes. There are no private apis on the web.
I'm not a fan of graphql for anything that the public could see. It's somewhat akin to exposing a SQL interface; it opens up too many avenues of trouble. Keep public communication channels as dumb as possible.
We also have user roles, which, if you’re an admin, you can run raw queries of whatever you want, but basic users are locked to the persisted query options.
It’s pretty cool, definitely adds complexity to our builds/permissions, but it works. We rolled our own, but I think Apollo GraphQL supports this out of the box now.
Not saying people should use GraphQL for everything though. It’s kind of overkill for a lot of apps.
I worked with a team that was going down a similar path. At some point it felt like they were reinventing REST on top of GraphQL with a strict set of predefined queries and result shapes.
They hadn't gone too deep into GraphQL tooling so we just switched to REST and implemented those predefined queries. Had a separate, developer-only GraphQL endpoint for prototyping things for a while, but the production stuff was easier to just build out as plain old REST.
I’m not going to argue whether one is better than the other implementation wise. That’s purely personal preference.
GraphQL has one super power though. I have access to an API directly and can save bandwidth by only querying and returning what I explicitly want in the data. That plus the allowed query rules stuff comes free in Apollo GraphQL now. At scale, this is huge for our bandwidth cost savings.
A second big win is federation of many GraphQL schemas under one giant god schema. This is useful when you are a big company, merging two architectures with different API’s together under one umbrella. You can define the mappings from the child schemas to the god schema in another spec that has no code, just a federation schema. Again, you can do this in REST too with layered API’s, but GraphQL arguably makes it somewhat easier to do this with just config files.
I also find that out of the box, the type safety guarantees of GraphQL are a lot cleaner/batteries include than the REST work I did the many years prior.
It’s all do-able with either tech and you are correct in feeling like it’s re-inventing the wheel. It is, and that’s purely a business decision to make money pivoting devs to a new library/environment.
I won’t judge you for wanting to stick with REST. It’s tried and true methods that will work for many many use cases. To each their own!
I was later involved in productising said research into an API gateway (called DataPower) offered by IBM. We implemented our GraphQL static analysis in a quite flexible and performant way (all of GraphQL's query validation and the static analysis are implemented in C++). The required configuration for the static analysis can be provided using GraphQL schema directives (cf. https://ibm.github.io/graphql-specs/cost-spec.html). Unfortunately, DataPower is quite inaccessible to the common developer.
I find that persisted queries are a very interesting approach to also solve this issue. They still grant developers the full flexibility to define queries during development, but then require providers to validate and vet queries only once before persisting them (instead of validating and vetting queries on every request). This has huge benefits for runtime performance, of course.
[0]
A very simple convention for including nested resources in a JSON API: https://www.jsonapi.net/usage/reading/including-relationship...
A totally cool but kinda over the top library that exposes a REST API over your database with a very GraphQLesque query string syntax that supports recursively nested resource inclusion, filtering, etc.: https://postgrest.org/en/stable/api.html#nested-embedding
GraphQL falls into the same trap that a lot of things do IMO - it assumes that because 5% of things are complex, that you need a solution that can deal with that complexity for 100% of your API, which needlessly complicates everything else.
Or you could just make an endpoint that gives you the data you want.
It’s pretty neat but nice graphql standardized it so things like consoles and other tools can be written against it.
It gives you all the benefits of GraphQL during development while in production you’re only dealing with JSON-RPC
How is this a GraphQL specific problem?
Can you give an example?
query dos { allDogs(onlyFree: false, limit: 1000000) { id veterinary { id dogs { id veterinary { id dogs { id veterinary { id dogs { .....
SELECT * FROM master_table LEFT JOIN sub_table LEFT JOIN sub_sub_table LEFT_JOIN sub_sub_sub_table...
...which is effectively "dump everything". In a REST environment you'll at least need a lot more individual requests - that's both the blessing and curse.
It's that the team maintaining the API is different from the team that needs changes to the API. Due to the scale of the organization the latter doesn't have the access or know-how to easily add fields to that API themselves, so they have to wait for the maintainers to add the work to their roadmap and get back to it in a few quarters. Relevant Krazam: https://www.youtube.com/watch?v=y8OnoxKotPQ
At a small start-up, if the GET /foo/:fooId/bar/ endpoint is missing a field baz you need, you can usually just add it yourself and move on.
Some reasons:
- Front end devs save time by.... sharing queries. So component B ends up fetching records it has no use for because its sharing GQL with component A.
- Backenders never optimise column selection. You may think you are really optimising by sending a GQL query for one column, but the backend will go ahead and collect ALL the columns and then "filter" down the data that was asked for.
- Backenders can also forget to handle denormalisation. If you query related many to many records but the GQL only asks for related ids of implementations will go ahead and do a full join instead of just returning results from the bridge table.
- Frontenders aren't even aware you can send multiple graphql GraphL requests simultaneously.
GraphQL is great, but any technology is limited by how well people can extract its value. I personally feel sometime we'd be better off with REST, or at least make sure people receive the training to use GraphQL effectively.
An unfortunate problem that really only exists with Apollo. Facebook’s graphql client, relay, does not have this issue as it requires each component to explicitly declare its data dependencies.
Citation needed. If two components call into the same data fetching utility for expediency's sake, and that utility queries data that one or both components do not need, you have this problem. What makes that uniquely likely with Apollo?
In the scenario described, wouldn't this lead to the same problem because someone copied the code or reused a utility from another project and so they have at least the superset of those dependencies plus whatever new ones they added?
Making scalable, well performing queries work is nontrivial, particularly with the current ecosystem of GraphQL libraries. The main workaround for this provided appears to be directly mapping GraphQL to an ORM.
But more and more, I think Backend For Frontends solve this issue in a much better way. And of course that idea isn’t new and Yahoo for instance had that kind of architecture.
Frontend teams get to adjust by themselves a simple interface to their needs, and backend teams can provide more info through internal APIs with less restrictions than if it was directly exposed to the outside.
Going with basic REST gives you simpler caching/optimisation paths, more straightforward mapping between the front request and the backend calls, and it makes it easier for other teams to look at what you’re doing and comment on/fix stuff as needed. GraphQL would be pure syntax sugar, and I’m not sure it would be worth the trade-off.
With that structure you can have any number of layers with your front call and the different business abstractions all representated by an API (let’s say you want a user’s average engagement with a service, you’d hit the high level API, which will fetch access stats from another API, which rely on a lower level API which goes through another separate layer managing DB cache etc.
Most of these call are of course internal to a data center.
So what you can do is some sort of generative graphql thingie when doing your initial iteration, with the client hitting whatever is convenient (in that situation you'd just expose the entire backend unprotected).
Once the needs have gelled out you strip it out and replace the graphql queries by bespoke API endpoints.
The other part about team dependence is very true but it also shows a lack of knowledge/thinking/care by whoever formed the teams. It seemed for a while Amazon had things right both in terms of boundaries of teams and in terms of forcing people to use APIs- not sure what they do these days.
Also tends to use a lot less bandwidth.
Compare it to a database, what if you couldn't use random queries with SQL, but only had the option to call stored procedures?
Of course there are ways to prevent data from being returned but that’s fragile.
For some reason I don’t think graphql actually works this way. Can’t quite put my finger on why allowing access to any column on a table might be a really bad idea.
Backend developers describe the data model, expose it via graphql. Front end developers, often ones who never met those backend developers, can see the data model and just use it. They can change what they're querying on the fly, get more or less as they see fit.
It lets everyone move faster.
But as a backend developer, I actually fucking hate it, myself.
You should probably be comfortable enough to work with both ends of the spectrum, but specialization allows you to do a much deeper dive into complex subjects.
A backend engineer probably has a much deeper understanding of every little nuance of their prefered database. A great backend engineer can make sure that you're getting near-optimal performance from every important query.
A frontend engineer probably knows about various UX techniques along with how to avoid unecessary reflows and repaints. A great frontend engineer can implement a UI toolkit as well as advanced techniques such as windowing.
The separation of front/backend has always been mildly entertaining to me and I’ve worked on both teams. Btw, if you ever want to cause a political mess, just submit a PR to add a new API endpoint to the backend team that “doesn’t have the time” to work on it. Woah boy, they will get mighty pissed. As a backend engineer these days, it would be a blessing to get free work from another team… I don’t know why they were so pissed that one time.
The main idea is that writing some code to achieve any particular effect in the system is typically easy. But writing code, that is efficient and maintainable isn't easy. So, there's a team X, which has people working on some specific system. They own the code. To them, their work isn't quite about "implementing requested features". It is about inventing proper abstractions that both reflect the logic of the requested feature and reasonably anticipate the logic of any future feature requests. They want to avoid having 2 implementations of the same thing, they want every piece of code to be idiomatic to their system, etc. And they are right thinking like that, BTW. Every new developer they get is treated with some suspicion at first, and when he learns the idioms of the system he becomes a honored member of the team X. If he fails to learn them, he gets fired or passed to another team, where he may turn out a better fit.
So, for the members of team X, they are professionals, who know how to work on the product and on the system X. Members of other back-end teams are probably not, even if they are good devs otherwise. Some frontend dev — doubly so. Some junior frontend dev coming from military or helpdesk or whatever — triply so.
So, you may think that you are a great and charitable developer, who just implemented a Feature. But to them, you are a lowly ape who made a wobbly hut out of some sticks and leaves that is going to fall down now any moment, and it's going to fall down on THEIR heads (and you will be long gone).
Worse than that, they understand, that other non-engineers (like their manager) also are prone to mistaking a wobbly hut for a Feature. And you basically humiliated them in front of these people by "solving" their problems (while in fact you created more problems). So it gets political here. In fact, because of that, even if the above is not a fair description of your work, they kind want it to be fair, they want you to fuck up, because it at least makes it easier to explain why your help wasn't a real help.
And, in all fairness, it is kinda unlikely that a guy who is new to a codebase didn't fuck up in any way, even ever so slightly. Especially if that's a kind of guy who doesn't understand why dedicated back-end and front-end teams exist.
It's an easy conclusion to get to, whether justified or not.
No one likes being made to look incompetent, regardless of whether they actually are.
I have the impression you didn't ask for permission before you did it - the dynamic is wildly different if you start things off by asking if they'd be okay with you taking some time to build it, then involve them in your process as much or as little as they want.
If that's what you actually did, then my analysis is way off.
It is strange to see developers preferring to stay in their isolated environments and not wanting to touch the entire stack.
What a weird thing to say. That was the original state. At some point people started splitting things up because they felt that would be better (or they just weren’t capable of grasping more than one thing?), but I’m extremely sceptical of all this specialization.
If your API looks like this...
/ios-app/v1/landing-page
/android-app/v1/landing-page
/android-app/v2/landing-page
/windows-mobile/v1/landing-page (legacy)
/web/v5/...
where each platform has its own subtly different UI structure, the ability for frontend teams to get basically an arbitrary JSON structure of their choosing starts looking worth the extra work on the backend.You might not encounter this problem at any point that's fine - there are other ways to avoid it, like having a cross-platform codebase. I have "hand-rolled" similar solutions to the GraphQL field selection before, and I would use the GraphQL protocol if I were to do it again today.
People specialize in different things. A great React developer may not be a great Java developer, and vice-versa
You may need one or two really great React and/or Java developers.
Nowadays a full stack dev is an intermediate Fe dev, with junior backend skills. He will make your backend un-maintainable. Get a proper master on a proper contract rate to design your architecture.
FFBs and GraphQL is a way to tightly couple to a backend system and then have that backend system loosely coupled.
I guess its all 6 of one, half-dozen of the other, but I usually prefer to just handle things client side. You can maybe get less data transfer optimization but that's down the road from the fast development stage, anyway.
Has this been addressed? I don't see how you can decouple the back-end data from front-end queries without that.
``` const SAMPLE_JOIN_QUERY = gql` query ($main_data_id: String!) { mainData( main_data_id: $main_data_id) { id main_data_field_1 main_data_field_2 main_data_field_3 related_data{ related_data_field_1 related_data_field_2 related_data_field_3 } } } `; ```
const SAMPLE_JOIN_QUERY = gql`
query ($main_data_id: String!) {
mainData( main_data_id: $main_data_id) {
id main_data_field_1 main_data_field_2 main_data_field_3
related_data {
related_data_field_1 related_data_field_2 related_data_field_3
}
}
}`;On the frontend, you have a choice to use some of the heavier libraries that support all of the features (like subscriptions) - but otherwise, you can just POST a gql query to the server and it will return a blob of json, which really isn't so much more than REST.
My concern is not specialization which I think is necessary for a larger company. It is more the technical solution of "here is GraphQL now your teams don't need to talk and you don't need anyone thinking end to end". I can't believe that is helpful.
I may have created a strawman though?
Segmentation makes some sense but the industry is lacking end to end thinking as you point out.
Until I understood the point, the organizational decoupling. Then it clicked why it's great.
GraphQL is a way to describe not only your API but also the entities and relationships in it. This enables certain useful things for client heavy applications, like cache normalization. If you look at clients like URQL they enable high quality features in your app that are otherwise extremely difficult.
You can also do this with JSONAPI but the GraphQL ecosystem is more developed.
Setting up GraphQL to minimize its rough edges is incredibly difficult. I've currently landed on a combination of Pothos + Genql + URQL to enable me to do everything in typescript instead of untyped strings.
It takes very high skill to use GraphQL well. Few teams get there because they don't have the upfront time to do all the research.
But if you pull it off it can be an incredibly productive system that is friendly to iteration and refactoring. I can send you some content we've produced on this if you're interested.
That said, if I'm not working on a client heavy app, I'd just use a less featureful RPC framework.
This isn’t that though; the first sentence starts “GraphQL is great, but” and then the post lists first “the good” and then “the bad.” Even the provocative headline hedges with “kinda.”
I wish there was more of this sort of balanced discussion on HN. There is a tendency among devs at least in public toward trying to get others to use the tech they use and are excited about, which is understandable, but everything involves trade offs and it would be nice to hear more of those up front (as opposed to one day “mongo is the bomb” and the next “actually mongo is terrible to back to postgres for everything).
while the discussion can be balanced the real world outcome is normally binary: use it or drop it.
i will not start investing huge amounts of time to learn graphql if it has very specific use cases for specific environments. so i naturally look for red flags and objectively negative experiences to see if those might be the roadblocks i would run into 2 months down the line.
imagine a PM coming in all happy "i know nothing about graphql besides the hype but i think it's a great fit for our next project". where will balanced discussion take you there?
It is perfectly fine to start with an early implementation that treats GraphQL as mostly an RPC, with only resolvers for Query & Mutation types. You still benefit from GraphQL's type-safety, batching and code-generation.
Once you have more familiarity with dataloaders, query complexity etc. update your output objects to have links to other output objects building the graph model.
The issue is that too many people get fascinated with GraphQL early, then build deep & complex topologies and expose it in inefficient and potentially insecure way.
On the flip side, you should also be careful of anyone who says some technology is 100% good always. It's far more common to see people talking up the advantages of some trendy new technology without ever mentioning the downsides. All technologies have tradeoffs.
THIS 100%.
> It takes very high skill to use GraphQL well. But if you pull it off it can be an incredibly productive system that is friendly to integration and refactoring.
I could not agree more. It's like any other piece of tech: once you internalize the mental model and are able to translate those abstractions in your language of choice everything clicks. And then it's hard to imagine going back to something more "primitive" (i.e. what's conventionally called "REST").
After building "RESTful" APIs for years I can confidently say GraphQL (with a decent implementation) is a step up across almost every possible dimension (performance aside because of the additional parsing).
While this is true, I think the ultimate assesment of a technology is how easy is it for someone skilled at doing similar work to internalize the model and abstractions.
A tech stack can become really successful only if this is easy and relatively quick, otherwise, it will meet a lot of resistance. Partly because it's hard to master, but partly because so many people will be misusing it (which makes an even bigger annoyance for someone who's trying to get to a proper mental model).
As such, I've come to appreciate only models that majority of developers can easily get right on the first go: or rather, models which are hard to get wrong.
Completely agreed. Without knowing the team experience, greenfield project or not or in general more information about the task at hand, how can anyone say GraphQL is good or not?
One thing I've noticed among some people who've failed to move up in their career is that they carry these extreme opinions due to a proper understanding or a bad experience. Right tool for the job and all that.
Have you never used MongoDB?
A crashing MongoDB instance in default configuration was more likely to lose data irrevocably than a MySQL 3.23 MyISAM setup.
(note that while I still don't particularly enjoy using it, post-WiredTiger MongoDB is a different story so take this as a criticism of the people making choices in the early days, not at all of the current state of affairs)
So what does this mean?
You're saying that in the universe we live in there is absolutely nothing that is 100% bad always. Everything is good for something? There is no concept of bad or obsolete things because it's all good for something?
Let's restrict this to programming languages and frameworks and apis.
Are you saying that in the universe of ALL programming languages, ALL frameworks and all APIs, None of them are at all bad and they are all good for something?
I don't agree with this sentiment at all. In fact I think it's a sign of two possibilities:
1. that the person saying it is highly biased and unable to detect things that are genuinely bad.
2. The person saying it is just being temporarily illogical, there are clearly things in the programming world that are bad. He knows this but is so biased that he's incapable of processing this concept while promoting his favorite language/api/framework.
Scenario 2 is the most likely scenario here. Not saying graphQL is bad. But to love graphQL so much as to say Nothing in the universe is actually bad?
Let's be real, I am not against graphQL. However you cannot actually say that people against graphQL have invalid opinions because there is nothing in the programming universe that is definitively bad. This argument does not make any sense at all.
For example:
1) “Haskell is bad because it’s too theoretical” 2) “Haskell is bad in corporate environments, as its roots in mathematical and academia make it harder for people to get productive with it compared to something like Java or C#”
The difference is clear. In my opinion it’s best if people who care about what they’re saying avoids #1, and instead frames their criticism like in #2.
Note: those examples don’t reflect my actual opinion on Haskell, it’s just something I came up with while writing this.
>The point is that “bad” isn’t a useful descriptor of anything regarding their real-life applications, because it simply doesn’t mean anything.
This is just a complicated way of saying "Bad things have no meaning and don't exist in the universe."
Without getting too pedantic, in general, nobody agrees with this concept. Sure if you get pedantic you may find a couple people in this world who enjoy punching themselves in the face, but in general the overwhelming majority agree that punching yourself in the face is a pretty bad thing.
Note: Punching yourself in the face is just an example of a universally "bad" thing. I'm not personally against punching yourself in the face, it's just something I came up with while writing this.
Default hostility to new concepts and frameworks can save a lot of time, energy and mistakes in software but sometimes for some use cases the new (variation of an old) solution can be superior.
We use it as the API we expose for our React and mobile clients and it's just, so good. I'd never want to consume it for a non-FE client but it's night and day versus stitching the results of multiple API calls together using some godawful chunk of mess like Redux.
We have a C# backend and Typescript frontend. We write our backend resolvers of the form `public async Task<SomeResultType> GetSomeNamedField(TypedParams pq)` and it just works, Apollo generates type safe client code and we define the schema in a single place. We still write backend code to implement each resolver method, exactly how we did in a normal API but... that's just the same.
I wonder how bad other backend devx must be for all these people to hate it, it seems more like a language specific implementation flaw than a genuine problem.
What I've noticed is people get their first taste of a type safe api and automatic client creation via GraphQL and don't understand that exists without it.
I mean, yes, you can technically write any project in C if you're smart and dedicated enough, but data scientists still use Python because it's easier to work with for the things they need to do. The fact that GraphQL is inherently safe, while REST is inherently not, is why people like GraphQL. OpenAPI is hardly the standard in Rest APIs.
Perhaps we are talking about different kinds of "safety" or "aspects of safety"?
- Makes caching more challenging since there are now more possible permutations of the data depending on what query the client uses. A hacker could just spam your server's memory with cache entries by crafting many variations of queries.
- Makes access control a lot more complicated, slower and error-prone since the query needs to be analyzed in order to determine which resources are involved in any specific query in order for the server to decide whether to allow or block access to a resource. It's not like in REST where the request tells you exactly and precisely what resource the client wants to access.
- Adds overhead on the server side. It requires additional resources to process a query rather than just fetching resources by ID or fetching simple lists of resources. A lot of work may need to happen behind the scenes to fulfill a query and GraphQL hides this from the developer; this can lead to inefficient queries being used. I have a similar complaint about database ORMs which generate complex queries behind the scenes; this makes it difficult to identify performance issues in the underlying queries (since these are often completely hidden from the developer). Hiding necessary complexity is not a good idea... Maybe worse than adding unnecessary complexity.
You could use something like https://stellate.co/.
> - Makes access control a lot more complicated, slower and error-prone since the query needs to be analyzed in order to determine which resources are involved in any specific query in order for the server to decide whether to allow or block access to a resource.
Hasura and Postgraphile can do this - in the case of Postgraphile it obviously requires Postgres.
> It's not like in REST where the request tells you exactly and precisely what resource the client wants to access.
It can be. You can have a query that does `getObject(id: $id): Object`.
> Adds overhead on the server side.
Yep it pulls a heap of complexity around data fetching, synchronisation, and data modelling from the client to the server.
As it requires both the client and server to come to some agreement about a shared data model, it can appear as more work up front. But it enables a decoupling of the client and server such that the client can make requests for new use cases with the existing shared data model.
> No clear path for Api versioning
GraphQL came about as a way for mobile clients to call backend services. At Facebook, once a version (of th emobile app) was released, it was essentially out there forever. Some people would simply never upgrade until they absolutely had to.
So the point of GraphQL is that you want to get away from thinking about versioning your API and cleanly upgrading because you probably can't. You can do versions but you don't have clean divisions. You'll mark a given field as "since v2.1". And fields that you ahve added can basically never be removed. The best you can do is make them return null or an error.
So if you want to do versions it probably means you have control over the server and the client such that you can deploy them almost simultaneously. If so, GraphQL isn't really designed for your use case. If not, get out of the mindset that client and server versions can move in lockstep.
I will say I think GraphQL made one mistake and that's baking in string values into the API. You can't change a field name without breaking your API. Same with enum values.
Protocol buffers (including gRPC) instead went for numbering. The name is just a convenience for reading the IDL and data definitions and for code generation but it doesn't translate to the wire format at all.
This can have downsides too but they're fairly minimal. For example, if you accidentally renumber your enums by inserting a new value in the middle, the whole thing can break (side note: always explicitly number your enum values in protobuf! That should've been the only way to do it).
Another issue is that fragments seem like a good idea for code reuse but they can get really out of hand. It's so much easier just to add a field to an existing fragment. If that fragment is used in a bunch of places you may find yourself regenerating a ton of code. You will never be able to remove that field from the fragment once added.
Disclaimer: Ex-Facebooker.
This nails it. For distributed apps where a client might never be updated, you can't really change your schema if you want to guarantee that your app works for everyone. You can build in a mechanism to prompt users to update to a later version, though, and that can be very effective.
1. Remove all uses from the frontend. 2. Deploy. 3. A day later, delete it from the schema.
If deleting it causes relay compiler errors, go back to step 1.
(The less lazy way to do it would be to actually pull some stats about how long-lived frontend bundles are)
Not being able to delete fields only really applies if you have a huge number of clients that you can’t easily force to update on a whim. Plenty of folks just have web clients.
My company doesn’t have this, but I’d love to get per-field usage stats about our schema.
* Autogenerated documentation
* Autogenerated wrappers for scripting languages
* Autogenerated validator for requests and responses
For a REST API, you can get most of these things with swagger or stuff like that, but clearly it's an afterthought. If you have a schema, it's all much more natural and elegant.
But the most important thing you get with GraphQL is batching. For our use case (a decompilation pipeline) if you make 10 requests one after the other or 10 requests altogether it makes a huge difference in terms of performance.
If you need batching and design a REST API, for every nice endpoint you have you need to make a bulk version of the API. You're likely going to do that POST'ing a JSON. Now, once you're at that point, you're reinventing the wheel with six sides.
If your backend is in C/C++ and I suggest to make a C API for Python and use ariadne:
https://ariadnegraphql.org/
Don't do GraphQL in C/C++.Doesn't HTTP/2 make this mostly obsolete? One of its big features is request multiplexing.
Regarding the auto-generated code bit, are auto-generated GraphQL clients a thing? It seems like it would be doable, but I haven't found any (at least for the languages I'm using).
HTTP/2 helps with the network layer, but your backend will still handle requests one-by-one. Depending on what you need to do, this might make a hell of a difference.
> Regarding the auto-generated code bit, are auto-generated GraphQL clients a thing? It seems like it would be doable, but I haven't found any (at least for the languages I'm using).
There's this:
https://www.graphql-code-generator.com/
But yeah, on a second look I expected to find more.
Anyway, having a standard way to do things instead of relying on one specific piece coupled to some language (swagger), it's certainly better.
On the other hand REST APIs have a much longer history, so I guess it's normal for them to have more tools.When I built Joystick [1], this is why I implemented the API system [2] as a JSON-RPC model, but stole the idea of validating inputs (optionally) and then on the client, optionally specifying tailored output (also optional—like how you can request specific fields back in GraphQL but instead of a custom query language, just pass an array of paths like ['customers.creditCard.expirationMonth', 'customers.creditCard.expirationYear'] for the specific data you want returned).
What I learned implementing that is that the typing/querying for specific fields ideas is brilliant, but much better when it's flexible (i.e., I want it sometimes but not all the time).
I feel like this a false truth.
Most people are building a web app, or a mobile app and consuming an api and displaying all the data they retrieve.
If you have an rest api which returns an object with 6 properties. And a graphQl scheme which returns those same 6 properties. You’re not saving anything.
Now if you have a website and a mobile app, where the mobile app needs 3 fields and the website needs 6 fields. You will obviously save on bandwidth with the mobile app.
The problem here is most of us are not building Facebook. The data saved is peanuts and the bandwidth cost is probably going to be far less than the total cost of doing the work to support graphql.
For a company like Facebook which has many different integrations as well as 3rd parties integrating, graphql is obviously a godsend as integrators and integrations can consume only what they require and save Facebook millions of dollars in bandwidth.
In a REST paradigm you over fetch because not all of these variations need the same data, or you send less but then the clients thicker because they merge API calls and have divergent presentation logic, or you have a bajillion API versions.
There's often a lot of back and forth between the various teams for each rev of the API.
GraphQL lets the clients drive the definition of the data fetching. That's it.
95% of the criticism of GraphQL is people complaining that GraphQL doesn't solve the problem of preparing the API response for these different requests. While that's true, that's not what it's supposed to provide. Whether you have a REST API with 26 versions or a GraphQL API with 26 variations of query you're going to have to write a backend-for-frontend style service that resolves the results.
GraphQL just standardizes this process.
This problem is solved by quite a few GraphQL providers nowadays. Hasura, DGraph (not true graphql but close enough), Prisma. I like Hasura quite a lot for many projects. Just define your database and you instantly have a full GQL API for the clients to use however they please, no backend required really. Doesn’t work for everything, but it’s pretty great for a wide swath of projects.
You aren't thinking big enough. We have a graphql API where we have a bunch of enterprise users all wanting to pull out different types of data. They can decide what they want to get, and pull exactly that data. They want access to different tables, fields, and for different purposes and with different filters. We don't have to be involved, we just give them the schema.
But there's also the issue that some presentation and business logic is also provided by the graphql schema. Graphql knows which nodes connect, the db itself doesn't. And special cases like overrides, formatting, etc can be handled by the graphql server.
That’s a great use for graphql. My issue is toooo many people are building web apps with graphql where they are the only consumer. They are not getting any of the benefits of graphql, especially bandwidth savings.
If you have many people integrating and you in vision the types of integrations needing very different queries for data then graphql is great.
But most companies are a website, maybe some mobile stuff, and not enough traffic to warrant the complexity or benefits of graphql.
Not entirely true, as it allows you schemas to scale, but your requests to remain small.
For example a "User" record might have 30 fields, and it might have more as the system evolves. But your requests that only specify "User First name" will remain the same size.
What I like doing is to create a REST layer that sits just on top of the database, and a GraphQL layer on top of it that allows all kind of fancy queries. Yes, HTTP is slow and multiple calls for a single request should be avoided if possible. But it's much easier to run server-to-server HTTP calls (especially if the servers live in the same DC or physical machine) than running client-to-server requests.
> It doesn't support map/tables/dictionaries. This is actually huge. I get that there might be
It does. You can define, say, an "any" or "json" type in your schema and emit anything you want at a field with such a type. For example https://stackoverflow.com/a/63588485
> No clear path for Api versioning
Some options include:
- Prefixes (`/v1/graphql`, `/v2/graphql`)
- Backward compatibility: only adding and not subtracting things you want to support.
Lots of fair criticisms though. My two cents:
There are very few cases for starting a GraphQL based project by writing a GraphQL server (resolvers, queries, etc). This is where devs waste time instead of exploring their concepts. Instead, use GraphQL with something like Hasura that generates the GraphQL service for you based on database schema.
I generally disagree. While Hasura and the like can get you moving quickly, they let you cheat on designing your data model.
Ideally it’s a collaboration between all involved to develop a shared understanding of the domain, and the queries and mutations (how to read and write).
Where possible avoiding implementation details leaking into the schema will let you change those implementation details when needed.
If you auto-generate from a database, your database itself becomes your schema. This is rarely the best way to represent your data model in an API.
I've completely avoided it for years. If a potential new job contacts me and they use graphql, it's an immediate no from me. It's an immediate red flag that the engineering culture at the company is poorly run and would be a nightmare to work in.
Run away, as fast as possible.
Well, at least I'm glad I know I'll never be working with you!
I'm not giving you shit because you don't like GraphQL, I'm giving you shit because of your asinine "if you use GraphQL your company is poorly run and a nightmare" comment.
Whenever I see a comment from any developer that says "If you use technology X then you are an idiot", then I know that developer is either incredibly junior and doesn't understand the tradeoffs in choosing any technology, or they're showing typical "if you don't like what I like than you don't know what you're doing" arrogance that inevitably always makes it a pain in the ass to work with that person.
Needless to say, the VB app worked fine and became the product.
The primary, inviolable value I have, and look for, in dev teams is "strong opinions, loosely held". Meaning I want to work with engineers that have the experience, motivation and intelligence to have strong opinions about how things should be done, but it's also critically important that developers are humble enough to know other developers may have other experiences that can inform why a different decision can be better.
If you've worked in a dev team that embodies this attitude, you know how great it can be and how dev team members will naturally work to strongly defend the group dynamic that it fosters. Meaning if a developer with a bit too much arrogance joins the team, they can often be trained into not having to be so judgemental, or making disagreements about real issues and not emotional arguments ("GraphQL sucks and you're stupid if you use it") If not, the existing team will quickly reject that arrogant developer because they know how dangerous they can be to a healthy group dynamic.
Too many tech shops sabotage their culture and dozens of potentially great contributors in order to keep a few (or one) toxic contributors that the powers that be erroneously believe are irreplaceable.
Anyone can be a 10x developer when you sabotage the well-being and productivity of those around you.
Most software engineers I’ve worked with have been incredibly humble and dedicated. The mythical bearded guy that showers three times a day, comes to the office with shorts and flip flops, and refuses to install Windows on the accountant person’s machine because it’s objectively bad is something I’ve only seen in memes and stories from older people I’ve worked with.
I personally think dissolving this myth, along with the one that programming is easy and / or none of us know what we’re doing, should be a shared goal between people who care about what they do and how others perceive it. Otherwise we’re unknowingly cultivating it into existence, and I definitely don’t want to work with arrogant, dogmatic developers.
When it's a junior, I remember myself and think they still need to learn.
When it's a senior, I know it's not a senior.
Says who, exactly? What data are you basing this on? Or is it a completely subjective opinion dictated by frustration likely caused by the lack of understanding of it?
> Or is it a completely subjective opinion dictated by frustration likely caused by the lack of understanding of it?
You can ask this this very same question when people say graphql is an amazing piece of software/paradigm, except s/frustration/hype/
And, in general, there's no such thing as a "good" or a "bad" technology, there are dimensions and each dimension is a spectrum: utility, adoption, availability, cost, complexity (although hard to determine), etc. to compress all that down to "hype" or "it sucks" just show how little time has been spent on understanding the nuances I mentioned above.
I don't claim GraphQL is amazing or even good, it just proved to be a great way to build APIs for the projects I worked on. I'm sure someone who builds firmwares for embedded automated plumbing systems would disagree (within that context). If you decide not to adopt it I just hope you do it after a rational, unbiased review of what the tech is capable of and what the shortcomings are, rather than "oh it's over hyped".
> Did you try reading the thread? What do you mean by data?
Please don't question whether someone read the thread or not (which is irrelevant within the scope of this discussion anyway) just because they disagree with you.
Great. What is your take on the postal service structure of Turkmenistan btw?
If many manage to use GraphQL and be content with it, that should be an indicator to you. But, you chose it isn't and that you'll merely display how politely negative you can be.
Thank you.
> pure, unfiltered truth
noone is forcing anyone to believe in anything, it's just some guy expressing his strong opinions about a subject, but no, you act like someone uttered a blasphemy against the lord's name
...I get it, the gql request did succeed, I've previously described it as like a 'layer 8' on top of HTTP: the problem being that all the tooling is for HTTP.
I wish 'REST' was one thing - with generated OpenAPI servers/clients & 'links' for example we could achieve what gql sets out to, if only there was a single way to do it.
Building on this are result types, where you can return a union with the intended type and something like AccessDenied for specific fields a user does have access to, but some other user might. Here you start to model the happy and unhappy paths of the data model.
GraphQL itself doesn’t really say anything about the network layer, it sits above that, in the application layer. You can run your queries and mutations over a websocket connection, at which point 200/4xx/5xx don’t make sense.
I'm not sure how that's a problem? The client knows where to look for errors: not in the http response code but in the JSON payload. Why is that an issue?
Backend to backend communication is almost never graphql (is that changing in a big way?) which would indicate the main reason for graphql in a client-server situation is data saving but at the cost of complexity and other downsides. Almost certainly the data savings in many cases is not worth it.
Oh and then you have things like Apollo having cache bugs that result in incident level problems.
Granted, it’s a problem to have to do that. But such is life with entity-level caching.
On the other hand, you tend to do "select * from FOO" and get more data from the db, because you don't know what the caller will ask for.
I don't think I've even seen a codebase filter the SQL based on the caller. I think I tried doing it once and it was a pita. (Please correct me if it's easy).
I still don't think I would personally recommend GraphQL to most companies.
I was honestly surprised by this: when I first heard about the idea behind GraphQL, I was certain that I'd pass in nested data structures.
I use it because I have to (external services jumped on the hype bandwagon), but I don't consider it significant progress. And this "save bandwidth" advantage is totally oversold, I really can't see how the savings can be significant in a practical way.
That's like saying SQL is crap because you need to build queries by hand. Conflating a protocol/spec with its implementation and/or the way it's used is not something a "very senior dev" should do (not questioning you personally, just the validity of what you wrote in this specific comment).
There are plenty of good GraphQL libraries that make writing queries/mutations and the whole schema a breeze. I've been using graphene for Python for a couple of years and, although it has some rough edges, it's actually pretty decent. And GraphQL is quite a good mental model to work with that both backend and frontend can share.
<rant>Honestly I'm getting tired of seeing these comments on HN, it's the same for Kubernetes or other technologies. Often written by someone who didn't take the time to actually study and understand the tech and use it for actual projects. Often with no data to back it up whatsoever. The quality of posts and comments here used to be a lot higher but it's slowly turning into a plaintext version of dev.to </rant>
And yes, SQL is "bad" because you write query strings. The funny bit is that GraphQL may be just as hard to model in a type-safe way as SQL is, if not a little harder. At least with SQL we have a reasonably good way to model it with methods (see LINQ). LINQ was built 15 years ago, so this problem was well understood back then.
Says who?
> [...] its actually surprisingly difficult to build a type-safe API around it.
Again, says who? The consumers of the APIs I work on are mostly written in Typescript and constructing types based on the GraphQL schema is a completely automated process. Are you telling me that it's easier to build type safe APIs based on examples of what JSON each endpoint might output?
> And yes, SQL is "bad" because you write query strings
Ok then every single language is bad because every language's syntax is based on (conceptually) constructing strings. I don't get your point.
If we want to use these terms, then SQL is indeed crap, because you need put query parameters in-band instead of out-of-band. This led to numerous exploits over the years, as it's difficult to ensure the data is correctly escaped. GraphQL just repeated the same mistakes.
Would be nice if we all stopped with these blanket statements and just focused on evaluating individual pros/cons of things.
EDIT: formatting of pointer
You can go on with your GraphQL, Kubernetes, gigantic frameworks, and pages with 3MB of JS if you want.
And let's see what stands the test of time.
https://github.com/typed-graphql-builder/typed-graphql-build...
No docs yet, that's WIP
If you work with a bunch of Micro services, and you’re only a backend developer, you likely don’t understand the problem graphql is solving. The alternatives are almost always way worse.
> No clear path for Api versioning you'll end up with MyQueryV1.01 MyQueryV1.02 MyQueryV1.03
You’re not supposed to version it. That’s what the @deprecation is for.
> It is actually a pain to use, depending on the backend you are using you'll have to manage
Do some front end work, or use your companies API as a client. Something where you have to talk to several services and try to stitch together some sort of combined data with all the latency and unreliability of http over a cell phone network. Then pontificate about how the boundaries between the services are wrong, but never change anything - or better yet change a bunch of boundaries then change the UI to cross different boundaries - then complain about how the UI should always have to exactly match your services because the world should revolve around how you’ve decided to see the problem.
Yikes, where did that come from. That wasn’t directed at you.
Don’t use graphql. When you figure out what it’s for, it’ll be easier to learn.
That said, if I'm not mistaken GraphQL is almost explicitly designed with a versionless paradigm in mind. Whether or not that's a good decision is up for debate, but it's less "no clear path" and more like it's the responsibility of the backend to add support for new access patterns without causing old patterns to fail.
Like you said it makes sense in larger companies. As a consumer of a well documented API it’s great, as someone who had to stitch together 2 microservices to provide the required data it sucks.
Turns out, if you have lots of objects from disparate sources, graphql don’t like that. Now you must stitch these schemas together into an über schema roll query and use with graphql. Maybe we missed a step. Maybe we misunderstood. Maybe it was a bad decision.
Worth watching some youtube tutorial videos. Here's one I watched recently (~26mins): https://www.youtube.com/watch?v=v_1bn2sHdk4
We also had micro services. It was the most unstable backend I've ever worked with.
Yet the architects who picked all these techs were mostly lauded and didn't stick around to deal with the mess.
What I don't understand about GraphQL, is that the majority of data people deal with is simple and relational. It's rare enough to have a deep (more than 4 layers) relational data structure that needs to be queried at once. And usually those data structures are relational to ever smaller relations; think user->company->address->country->county. Solving this with GraphQL just seems a bit bizarre when you can write a view of this data.
Maybe though, it owes its popularity in bootcamps because it allows unqualified developer to forget about writing the query layer.
In my experience the most pain around GraphQL was due to a lack of care/time. Too often schemas are not strictly defined, are too generic (type: any) and fields are not documented. Errors are poorly defined etc. Combine that with untyped code, it's almost the same as sending blobs of arbitrary JSON around. In the short term it works, the feature is live, business is happy. But takes double the effort to untangle the code when you need to change something....
GraphQL also requires effort to make tooling and monitoring work well with it as it deviates from a traditional REST like model.
Unless there are multiple in production, i.e /v1/api, /v2/api, etc
Setting aside security and scalabilty for a second: Ifeel like GQL is at its best a complicated database driver, with the data types being defined and implemented twice: once in the DB layes, once in the backed.
The thing is that GraphQL is an RPC mechanism, contrary to REST that is a protocol to do CRUD operations on resources, and that has all the complexity associated with an RPC itself.
At the same time, with most backend GraphQL frameworks the decoupling will be very illusory, as in practice you'll have to tune the backend to the frontend use cases or you'll just end up with a ton of N+1 queries and terrible performance.
In other words, application-specific http endpoints have their advantages and let you have fine tuned queries for each use case, which makes sense for app-style frontends.
[1]: https://sixfold.medium.com/reducing-database-queries-to-a-mi...
I'm fine with request batching/complexity overloads/all that craziness. Most GraphQL libraries have some kind of protection mechanism in there, or allow you to artificially split up the request and forward it to your application load balancer.
I'm also fine with a lack of API versioning, especially for internal services.
Hell, I'll even tolerate the lack of dictionaries/maps because you can replicate the same data interchange by putting the key in the object you're requesting most of the time.
What I really want is to do not have to write a custom pagination wrapper type every time I write an API. Let me write a Paginated<T> that contains a list of T and some metadata, dammit! I don't want to dump BookPaginated/PagePaginated/AuthorPaginated into different schemas!
Another thing that bothers me is how types extending an interface need to have each and every field repeated. If I declare interface Car with wheels: Int! then I don't want to have to specify wheels: Int! again inside SportsCar. Any kind of inheritance creates giant schemas and adding new types to the super type means you have to re-insert the same parameter a million times.
Combined with a well-integrated ORM, GraphQL can have serious performance improvements over REST and similar so I definitely prefer it for big applications, but there are so many things that annoy me to no end.
I don't understand this point. Is this talking about implementing GraphQL on the backend? Because consuming GraphQL you get a map, you get JSON! Do you mean a more specific data structures like a Set or Stack?
Random-access structures like dictionaries, hashmaps make no sense in this context: It would be stupid if you had to do extra work to tell graphql what your preferred key parameter(s) are so that it can create a dictionary, and then you get list-like performance anyway.
Second, there's a reason DBA (Database Administrator, something like that) is a formal, separate role.
If you don't have a DBA it's not because that's a good idea, it's because you (or your bosses) are too cheap to do things well. That's okay, a lot of times cheap is more important than correct.
You're still going to need schema.
Both NoSQL and GraphQL seem to throw the baby out with the bath water. It was all done before, and Relational Model won. Gotta know your history kids: https://en.wikipedia.org/wiki/Database#History
- - - -
Tidbit of lore: SQL is not the original language for relational model databases, Codd had a language he called Alpha: https://en.wikipedia.org/wiki/Alpha_(programming_language)
SQL is the JS of DBs!
hasn't been a problem for years in the ts, python, and .net communities
> It doesn't support map/tables/dictionaries. This is actually huge. I get that there might be some pattern where you don't want to allow this but for the majority of situations working with json api's you'll end up with a {[key: string] : T} somewhere
unions, embedded types, and custom resolvers, OR better api design
> No clear path for Api versioning you'll end up with MyQueryV1.01 MyQueryV1.02 MyQueryV1.03
this one is actually insane. /api/v1/graphql. sounds like you are new to apis
---
all of the complaints i hear about graphql have come from people who are early in the process of learning it and/or have built up faulty assumptions through malpractice
Graphql itself has no concept of versioning so I need to go out of my way to host a different schema at a different endpoint. And god help any client that's not consistently up to date with the latest schema in all places. You want to query for new feature X only available in api v2, but your client is on api v1? Better go back and upgrade all your existing api v1 schema queries first. Or have a separate gql client for each api version, and remember to use the correct one in the correct place.
Saying "just use better api design" isn't an answer to missing maps. Maybe I am dealing with third party data where I don't have control over the schema?
> unions
Then you need to know the keys in advance
> embedded types, and custom resolvers
That is "kind of" cheating. I think OP meant a builtin type.
> OR better api design
Sometimes possible but not always.
It's a valid criticism. Emulating another http endpoint in graphql should be super simpel in the best case, but sometimes it is not.
Another example where that is true is union inputs - you can define and return a union of types, but you cannot accept the exact same union in a mutation. Very very unfortunate.
However, I think GraphQL vs REST is a false dichotomy. One could probably maintain a GraphQL endpoint as well as a REST API, and use whatever is most appropriate for the use case of the client. People really should stop treating GraphQL as some kind of complete replacement for a REST API or "the new way of doing things" or acting like "the days of REST APIs are counted".
One more very annoying shortcoming is that you can define a union of types and return them when queried, but you cannot write a mutation and ask the client to send the exact same union. You'll have to create different standalone mutations.
In general the typesystem is quite lacking. But then again, it's better than pretty much everything else language-agnostic out there.
1) That it doesn't deal in graphs, but trees, and 2) It's not a query language, but an RPC language with result subsetting
I would love to see something similar to GraphQL that could return actual graphs. Like in the canonical Books/Authors example, a query over books that included the authors would return Books with _references_ into an Authors collection so that authors were not duplicated as children of the books.
I would also love to see real and standard query operations like where, limit, groupby, and ideally some sort of cursor. All that has to be added bespoke on top of GraphQL severely limiting the ability to write generic frontends and interfaces against GraphQL APIs.
Then there's the type-system problems like lack of Maps, the overly strict input/output separation, paltry scalar types with no standard for dates and times, etc...
I'll resist pedantry on point one but I totally agree on point 2. Plus its syntax poorly reflects the data 'schema' it's defining.
The "cool" features of graphql (treating your data like a graph, so you that n+1 queries are not the consumer's issue to deal with) are not at all available, I sti have to manually do joins.
I am terrified that since graphql is all "you don't have to version your shit" there will be a breaking API change in the future that I (or worse, someone not me) will have to watch out for, so on that day our supply chain database will be horribly broken.
What the hell happened that we got APIs like this?
That said, versioning of a graphql api has been done at scale before. Shopify has done it, using versioning in the URL, specifically their admin data api, using month-year release dates as the versions [2]
In reality, of course API versioning is needed.
The "prevailing wisdom" is people who like the tool, don't like its limitations, and want to pretend it isn't a problem.
.
> That said, versioning of a graphql api has been done at scale before. Shopify has done it
Perl people will happily point out that object systems exist for Perl.
Having it not be a standard, uniform part of the core tool is a severe limitation. Shopify needed this rudimentary feature, and tried to give it away because others need it to, and the tool vendors aren't willing (or able) to deliver.
I’d recommend not picking a technology that is versionless by design if you think you’re going to need it. Also I’d dispute that versioning is needed as a rule.
I mean, I don't pick GraphQL, and this is just one small part of why.
Every place that I've ever worked that's attempted to adopt GraphQL has rapidly given it up.
.
> Also I’d dispute that versioning is needed as a rule.
The IEEE once measured peoples' expectations regarding how necessary versioning was, and got a response of something on the order of 40%. There was an uproar, and a whole bunch of people on both sides of the topic tried to call bullshit.
Some middle manager somewhere sent in a letter that said approximately "how about you write a follow-up article where you bin the responses by years of experience?"
The rest of the story writes itself.
This is a shortcoming of the language, not of GraphQL.
> It doesn't support map/tables/dictionaries. This is actually huge. I get that there might be
If you ever tried to cram a JSON like payload in a GraphQL field you'll know why this limitation is in place. It quickly starts getting abused by clients and you end up adding validation, which you might as well have codified in a properly structured type. For blobs you can just send encoded strings (JSON, base64, binary, you choose).
> No clear path for Api versioning you'll end up with MyQueryV1.01 MyQueryV1.02 MyQueryV1.03
The whole point of using something like GraphQL is that you don't need or even want versioning. You can still deprecate fields (and remove them according to your deprecation policy) but in general you can just keep adding fields/types without removing the old ones until you are sure consumers don't need them any more. So there's no breaking change and consumers can transition to the new fields whenever they want. Something else you start appreciating when you have multiple, heterogeneous consumers of your API.
Or you can just add the version to your schema URL, e.g. `/graphql/v1/` and then route your queries based on that, which kind of defeats the purpose.
> Invest your time in a simpler solution then running to GraphQL first
GraphQL is as simple to set up as anything else, assuming the language has good support for it. If it doesn't that's, again, a limitation of the language, not of GraphQL.
GraphQL solves a ton of problems related to typical JSON APIs' conventions, since JSON isn't inherently "schemable" unless you generate something like an OpenAPI spec which is, arguably, more complicated. There might be superior alternatives (I've never tried JSON schema) but I think all the pain points you described can be easily solved one way or another.
I've worked at a few companies that used GraphQL poorly. I've yet to see it done in a way that makes me think it's the right tool for the job. And I understand the benefit of allowing the client to choose what they want to get back.
GraphQL queries select specific fields for “performance reasons” so each request is custom and you can't cache at the edge. This is ridiculous because SQL joins are costly but fetching a few extra textual fields is basically never a bottleneck.
So in order to save a few bytes or KBs (which nobody care about anyway), you ruin your caching abilities...
...Well unless you manually cache your GraphQL queries with more fields than needed but then what's the point of using GraphQL at all?
That's very often a terrible compromise.
And I doubt there will ever be any PWA POSSIBLE with graphql, so no offline usage, no local storage , nothing cool toward the web6 decentralised stack.
I feel like there’s two approaches that one could take to approach queries: a series of programming commands (the way most ORMs work), or an attempt at “plain language” (SQL and GraphQL).
Both approaches are fine, but if one wanted to take the latter approach… why not just use the syntax of SQL? It’s better in every conceivable way that GraphQL, equally legible but much more powerful.
GraphQL is idiot baby talk, I’m baffled by why we have to waste time dumbing down expressions for no clear payoff.
SQL also sucks, since you have to SELECT before defining FROM. Which means, code completion isn't there for SELECT. At least with graphql you get full code completion all the time. I agree though that it lacks in other areas. Choice between pest and colera.
If you are using Typescript on backend and frontend (react/reactnative ok, native ios/android app no) then checkout tRPC. https://trpc.io/ tRPC is basically: you just call your backend functions on your frontend, and TRPC handles the API that makes it work. It shares types and when you define a type for your backend, and call that function, you get the type on your frontend.
Incredible for small apps/teams, but has it's limitations (especially before the most recent version) and probably not the solution for a big honkin app.
I've been playing with create-t3-app and it's pretty nice, great way to launch a basic typescript/trpc/nextjs/prisma app. https://github.com/t3-oss/create-t3-app
I use GraphQL at work and it's fine, it's just a lot of code and codegen and work for a small team, we'd be faster on tRPC but tRPC didn't even exist when this codebase chose graphQL lol
Perhaps it would have been the case if they just cleaned up and released a new Rest endpoint, but I'm not so sure.
As far as I can tell, one of the best ways to use GraphQL is as a sort of RPC framework. At which point, my question becomes why not just use an actual RPC framework? Personally I find the field filtering and reduced network I/O to be overblown. Anecdotally, most of the GQL queries I've seen request HUGE amounts of data up front to reduce the number of overall requests that need to be made. Obviously not saying that's everyone's usage, but in my experience GQL has never really been much of a value add.
I've often thought that this would be a great use case for GQL. Seems like a good choice if your front end wants to specify exactly what data to get.
In an ideal world, we can grow into the tech pulling in features as needed, but REST (in its modern form) is all about day 1 productivity, not day 100.
Unless you don't need those features to begin with? I also think with this mentality you'd end up with a lot of teams saying "lets do GQL in case we need it later" and it ends up being a ton of work for no benefit later.
I saw it coming for miles and evaded it.
Your complexity is my competitive advantage. Please continue to be followers of any new shit.
It's actually easy to implement. Just define custom scalar type: scalar JSON type MyObject { myField: JSON }
https://www.apollographql.com/docs/apollo-server/schema/cust...
I have used this before this works to get past the errors but doesn't actually solve the issue GraphQL tries to solve. This just hides it so you have to deal with it months later.
- The consumers don't know what the JSON looks like unless they test the query or get told what the query is explicitly. This means that the schema definitions don't capture the problem that the graphql try's to solve "describe your data that you want"
- also some of the other languages that aren't Javascript don't have GraphqlJsonScalar
I think that supporting dictionaries/maps/tables as apart of the Graphql language spec could of been possible as the key and value types are static. They are also iterable so it should be fairly straight forward for a consumer to deal with the data returned.
If it's a pain to use, perhaps you're using the wrong language or framework.
You're right that many APIs have maps, those are bad APIs. The map should be happening in your API. The alternative was a poor workaround to stop latency in a REST api.
My previous project involved complex data in a graph DB, and twice we considered if maybe we should use GraphQL. After looking into it, we decided to stick with REST, because it's easier, we're the only ones using our backend, and all our responses are highly customised for what we're going to use it for. GraphQL would be a lot of extra work for no real gain; maybe we would end up with somewhat less highly customised hard-coded Cypher queries, but then we'd have to figure out how to represent them in GraphQL and translate that to the queries we'd need, and that was not going to be trivial.
In my current project, other people made the opposite decision: they do use GraphQL for a fairly similar use case, and they regret it. It works, but it complicates things for fairly little gain. REST would have worked just as well.
The vast majority of people who've used GraphQL haven't used it with something like Relay; and in my mind that means they haven't used GraphQL in a way that really shows off its strengths. This isn't to say that GraphQL doesn't have any benefits without Relay, but rather that the cost/benefit scale only really tip heavily towards benefits if you're using it to solve the problems it was intended to solve -- that of reliably getting a component's data dependencies into the component.
Every time I use GraphQL without Relay I find myself questioning whether it's adding anything except complexity, every time I use Relay (other than the initial architecture build, on-ramp is steep) it feels great. Relay's learning curve and poor documentation is really unfortunate, because the difference is quite pronounced.
It quite literally solves many easy issues and pretends solve the hard ones, but does nothing to actually do this and just says that you "can".
I designed a typical JSON api that had customizable fields and filters and joins and authorization on orm level on classes(could easily be extended to do authorization on fields of the orm classes.) This was years before Graphql came along and pretends to solve these issues, while actually just leaving them up to the implementor of the resolvers. As if the idea itself of resolving per fields in so special.
And then you have people that think graphql = the semantic web(web3 before crypto shit stole the term). Inventing the same cyberpunk dreams from 40 years ago...
Nobody is even actually doing REST, just Rpcs over http with json. If they read the REST paper they'd know this is what they actually want but I fear it's a pipedream.
But people who hype graphql seems to imagine graphql solves such things. Which it doesn't do at all.
I feel most people's negative opinions on GraphQL are mainly due to their own lack of familiarity and expertise on the subject. They simply don't want to RTFM.
When used properly and competently, the DX buffs far outweigh a traditional REST API.
I'm curious what people think about this use case of the Query language.
No, no, no! I love GraphQL, and have been using it on projects for many years now, but the thing that is difficult for me to forgive the original designers of the spec that they put "QL" in the name, confusing so many developers into thinking it is a generic query language.
GraphQL is simply a spec and contract for exposing an API. Its "competing technologies" are things like RESTful APIs and gRPC. It really has nothing to do with a generic "query language" like SQL.
The field selection is certainly possible in REST via something like /foo?include=a,b,c but starts to get just downright silly with /foo?include=a,b.c[1].d,e[*].f which has now become its own DSL
Option 1: return a property list. In other words, a list of objects that have a key and a value. It’s easy write a getter function to search by key, or convert it to a map outright.
Option 2: make a Json custom “scalar”, send back whatever dynamic structure you want.
I hated the namespaces on the code-generated classes and ended up manually wrapping them, obviating the benefit.
It was also super brittle, when the back end would change something it would break the clients.
- There's really no need for API versioning in GraphQL. Just keep iterating on the fields.
Pros:
- front-end implementation is near-trivial. I re-wrote half of my framework because I wasn't happy with it in a few days.
- can use some cookbooks for some good front-end patterns
- overall very easy to use, and very easy to extend front-end stuff
Cons:
- Poor back-end implementations. JSONApi Resources kinda sucks. Graphiti might be significantly better.
- No clear pattern for submission of data. You don't want your front-end to contain operational logic, dumb front-ends are the way to go (front-ends do what they are told, they don't make decisions).
- Not the "IT" thing, so not too much big corporate money backing it. :( This is actually kind of a big deal.
It seems like a lot of overhead to me since the backend has to perform some redundant queries (i.e. fetch and authorize the user, etc.) in order to serve each of those requests. I had thought one of the main selling points of GraphQL was that the frontend could make a single API request and have everything it needs to render the entire page. Any thoughts?
I appreciate everyones passion and level of thought going into the replies. I will try read most of them.
Please note that if you reading this.
My intention of this post was to get a little rant off my chest and find out about potential solutions and gotchas about using GraphQl. It's unproductive attacking me or anyone else for character like "clearly not a senior developer" or "clearly never used API's before" because if anything this is about trying to find a solution and to save each other time.
For all the security layers there are usually great frameworks doing the job.
Its guide "RPC vs GraphQL/REST"[2] explains you when to use GraphQL and when not.
[1]: https://telefunc.com/ [2]: https://telefunc.com/RPC-vs-GraphQL-REST
What do you think if I just use graphql for the typed schema, flex return objects without the “graph” part? Or at least I would have a very shallow graph without nested data structure. Do you think it would help in this case?
At work we have a use case like: well we create the data layer that you can query the way you want and the field you want with many clients involved. So like an API where you can make composable queries.
To me that sounds like an API with query parameters, do we really need to use GraphQL?
Let's see!
It has some benefits when you have multiple different products that need different "pieces" of the data, rather than 2 different clients for the same product.
I never quite understood how much hype it got, but it provides some nice benefits in an internal corporate environment, especially when data within said environment has an "owner" and accessing it from a new place requires an entire process.
So I’m curious to see how this will we actually implemented.
(We also have Kafka topics where you can consume all the sources in your storage but that gives other problems so I’m not completely negative on giving a single point where you can aggregate data)
Do you care about the API being discoverable and the schema being well described? Being able to see the relationships between the data? The type-safety that comes from the tooling? The ability to expose the field once on an entity that allows consumers to use it in any variety of queries?
> some pattern where you don't want to allow this but for the majority of situations working with json api's you'll end up with a {[key: string] : T} somewhere
Please don’t use maps in API responses. Rarely do they map well and in all cases you can instead use a list of objects which is substantially easier to parse.
I’m not always RESTful, but in GraphQL the state transfer part is left as an exercise for the reader.
I love natural data models. I also think RPC makes sense when there are clear verbs in a system.
Poor GraphQL. It’s like a Greatish novel where the first half is compelling and intricate, and the last half was rushed by the publisher.
Everyone's experience differs quite a bit depending on the used client library (plain, apollo or relay) or the server library specific for your server languages.
This is true of any technology, so if you think the tech you are using doesn’t require a trade-off of some sort, you are likely missing something.
I’ve yet to select GraphQL over straight RESTful APIs, but I also don’t work in an ecosystem where disparate client needs are important.
That said, graphs are dangerous because they are so flexible; you can draw a tree or a table in one and it all seems fine but you're paying all the time in conceptual load and friction.
Microcosm: graph vs table db. In the middle: social pressure dominating data model choices. Macrocosm (relatively speaking): The swing of the pendulum between bodgy vernacular attempts to describe the world (dev don't need some control freak's schema) and esoteric priesthood attempts to describe the world (all knowledge graph structural changes must be initiated by our ontologist...).
Back in the good old days, you could open up the network tab, see the request made by the client and copy as curl to debug it.
Now with SSR and graphql, such a workflow is out the window.
Between that and the (at the time, anyways) abysmal serialization performance of Juniper we ended up abandoning GraphQL.
Even on a REST API, you can achieve the same pros
> - It makes working with describing the data you want easy > - It can save you bandwidth. Get what you ask for and no more
You can describe the fields you need (and I assume that is what reduces the bandwidth)
GET /users?fields=name,addresses.street,addresses.zip
> - It makes documentation for data consumers easy
I don't think so in practice. You can see Shopify's GraphQL documentation [1]. If anything it is more complex than their REST API docs
> - It can make subscription easier for you to use
Not too different from using something like SSE or even websockets and every decent web framework seems to have a decent implementation
> - Can let you federate API calls
So many ways to achieve this at the application layer (which is what GraphQL federation does with a Router). In the python world this could be separate WSGI apps or racks in ruby? And makes no difference if done at the load balancer level.
[1] https://shopify.dev/api/admin-graphql/2022-07/enums/localiza...
Okay, so don't make a poorly implemented one?
Also, no, it kind of won't. Let's look at what they are again
.
"It is actually a pain to use"
Not an API characteristic
.
"you'll have to manage two or more type systems if there are no code first generates in your language"
Not an API characteristic
.
"It doesn't support map/tables/dictionaries."
Not an API characteristic
.
"No clear path for Api versioning"
Not an API characteristic
.
Looks like it's actually zero for four
I think we can do better than GraphQL but until that solution arrives and achieves wide adoption I will keep using it
I don't, and never have believed this argument. I would bet that JSON with Gzip or Zstd is just as small, or close enough that it doesn't matter.
It all depends on what the end goal is.
Think very hard about your API. And absolutely do not ever introduce any query called V1 or V2.
You "join" by using the parent ID (e.g. employerID of parent container to get employees). This can (and often) introduces an n+1 problem unless you watch for it and use dataloaders.
Not saying this is great or anything. :)
I just made that up as something that would likely require a join without really thinking it through too much...
I want all of my code to be readable by non-programmers.
It also doesn’t speak normal REST dialect so you are missing out on basic things like status 200.
It is cheaper for me to put my react app in front of a cdn, split out my app into an api and front end than for me to have my site be entirely uncacheable.
I can also cache certain endpoints behind the cdn that are mostly invariant for users. And, the network egress of json is much lesser than the egress of markup.
In the boring old days we just did it all on the server and used the semantics of HTTP to handle caching ... it worked great.
If the main issue is you have to learn something complex, sure that’s probably a little fair, but it’s really easy to get GraphQL to do what you want once you’ve gotten over that initial learning curve.
Specifically, queries and mutations can literally do whatever you want them to.
Your company is not Facebook, you don't have an impossibly large graph dataset that needs querying
I've used it 3 times, each time it was a nightmare. REST with some additional params to query extra data is so much easier and safer ... that's just not very cool I guess.