Why is GraphQL useful

GraphQL is a data query language initially used in 2012 internally by Facebook teams. In 2015, a first open-source prototype was opened to the public through Facebook Open Source, the branch of Facebook dedicated to free and open source software.

Most of the time it is used to serve as an API to query data on the web through HTTP or Websocket although it is not constrained to these uses and protocols.

GraphQL allows you to ask for all you need in a single query, reducing unseful requests and saving bandwidth. Clients may also order their own custom data requirements.

GraphQL acts as a middleware between the clients requesting the data (mobile terminals, web browsers, etc.) and the owners of this data (third-party services, databases, etc.). It enables the aggregation of these various data and provides an abstraction allowing to query them unitarily, very simply and in a secure way.

The diagram illustrates where the middleware layer is positioned on a client/server architecture.

REST vs GraphQL

GraphQL defines a contract between actors, a declarative interface describing what is possible to request and to what extent, where REST is more abstract although some standards such as JSON API have tried to standardize the concept a little.

The Advantages of GraphQL

An acceleration of frontend development by using a declarative paradigm. Developers focus more on the what rather than the how.

Reduction of over and under fetching. The network is lightened because only the data needed for the request is passed through. There is no need for multiple round trips to get the data needed for display.

More predictability. We know in advance thanks to the interface contract what is possible to query and what kind of data will be returned.

More eco-design. There is no excess of data and several requests can be grouped in a single HTTP call for example, which allows a reduction of network loads.

A query language that is: protocol, programming language, client agnostic. GraphQL runs on all configurations and for all use cases.

Consequences

Like everything else in this world, the use of a tool leads to new issues, here too: I’ll just go over a few principles that will be discussed later.

The number of server-side requests induced by GraphQL’s lazy-loading can explode. This can impact performance and require some optimizations.

A change of mindset is needed in the way services are architected. We need to think in terms of Graph design.

Difficulties to use HTTP caching with Varnish, NginX, HAProxy for example because there is only one endpoint that receives requests.

To conclude

GraphQL is a very useful tool that could well take your application to the next level, making it more robust and predictable.

Although at first glance it seems wordy and quite complex, in reality, it is quite easy to learn, especially with tools like Apollo or Prisma.

Open chat
Powered by