Fauna logo
FeaturesPricing
Learn
Customers
Company
Support
Log InSign Up
Fauna logo
FeaturesPricing
Customers
Sign Up
© 2021 Fauna, Inc. All Rights Reserved.
<- Back

What is GraphQL? Use Cases, Applications and Databases

Jul 16th, 2020
More than ever, applications and data are the foundational elements for running a successful business. Right from the start, technology was built to be interconnected to exchange data — evolving from monolithic business applications running on a mainframe to complex internet-scale digital applications composed of several different microservices. Even today, there is one overarching goal for connecting disparate applications — to improve the way that information is encapsulated, shared, and processed between different elements of the core architecture stack.
Application Programming Interface or API is the glue that allows disparate applications to communicate and transfer data to one another. It is the digital connective tissue that bridges systems together to be reused, shared, and monetized effectively.
apps
Today, there are over 24,000 active web-based APIs on ProgrammableWeb, a global catalog of public APIs. While it is true that the internet era fueled the explosion of APIs, earlier forms of system integration existed much before APIs dominated the web. The 1970's IBM mainframe era had monolithic business applications that mainly used a request-response protocol called Remote Procedure Call ( or RPC ). Applications would execute an RPC call, which goes over the network, hits a mainframe server running a specific subroutine, and responds to the application. While RPCs successfully hid the underlying network complexities from the application, they had their own share of design issues, including lack of a standard to build on, huge performance overhead, vulnerability to failures, and no flexibility to run them across different hardware architectures.
Between 1980 and 1990, a surge in the number of advanced enterprise and internal apps, coupled with the mainstream launch of the personal computer, needed a rethinking of how systems would interact with each other. During the early part of this decade, object-oriented programming helped facilitate integration between various systems through Common Object Request Broker Architecture (or CORBA). With CORBA, different systems written in different languages across different machines could interact with each other. CORBA made use of an Interface Definition Language ( or IDL ), allowing language mappings and bindings to specific programming languages like C and C++.
As the internet began to flourish, more open standards emerged, such as TCP/IP, HTTP, and REST (Representational State Transfer) to serve as a guideline for creating Web 2.0 SaaS applications. Using a REST-based design, developers could build apps that interact with other apps based on the data and perform simple CRUD (Create, Read, Update and Delete) operations on data over HTTP using verbs such as POST, GET, PUT and DELETE. For example, if you were implementing an image service application, a HTTP GET '/images' request could be used to display a list of all images, and a HTTP POST '/image' request could be used to upload a new image. REST soon became widely popular, and even today, it is still used by many internet services. But what if your application needs to be able to do things that fall outside of the simple CRUD pattern that REST offers?
Fast forward today, mobile apps and cloud computing are quickly transforming our daily lives, adding more pressure for developers to deploy new app features which require efficient ways to transfer data. With REST, new client-side changes require corresponding changes to be done on the server-side — reducing developer agility. With the emergence of serverless and microservice-based architectures, something different was the need of the hour— something that is scalable and aligns with how data is created and consumed today on the internet. Acknowledging some of these critical requirements, Facebook developed the Graph Query Language ( or GraphQL) in 2012 to address some of the gaps in REST. In the remainder of this article, we will talk about GraphQL, its advantages and disadvantages, and how it compares to the currently widely used REST software architecture, how it can be integrated with your database and when it stands out as a helpful tool.

What is GraphQL?

In a nutshell, GraphQL is a query language (denoted by “QL'' in its name) for APIs and a server-side runtime for executing those queries. It allows you to fetch only the data that your app is requesting from the server and nothing more. This means that your app can send a GraphQL query to your server API endpoint, and it is always guaranteed to get a predictable data response — GraphQL provides control over the data and not the server.
In today's world, developers are craving more agility. With the strong type system in GraphQL, developers can closely follow the data model of their app by specifying the exact data fields needed from the server. GraphQL will do all the hard work in the background on the server, including traversing multiple server resources if required, to fetch the data that is needed and return it to the app in the form it was requested. This also improves application performance because only the required data is fetched from the server and transmitted over the network, nothing more.
For example, let's imagine you need to do your weekly grocery shopping within a limited time and on a tight budget. Getting precisely the amount of groceries you need to get for the rest of the week will allow you to save money and time spent shopping. If you have to make multiple stops at different shops, it would be beneficial to have a nicely labeled way to navigate your trip. This is similar to how GraphQL uses a type convention for labeling data to hide away all the complexities and get the data you need in a single round-trip without over-fetching.
graphql
GraphQL Query
query
{
  person(id: "1000") {
    name
    location
  }
}
GraphQL Query Response
{
  "data": {
    "person": {
      "name": "Mary",
      "location": "Chicago"
    }
  }
}
Due to its growing popularity with accessing data, GraphQL is often confused with being a database technology, but it is NOT one. In fact, it is a query language for APIs that isn't tied to a specific database or storage engine, and it doesn't require you to even run a Graph database. This makes it database agnostic and effectively usable in any broader context wherever an API gets used, for example, a proxy service that isn't tied to a specific database. Using GraphQL allows the developer to mask all the complexities behind the scene.
GraphQL can be used with various programming languages, including Javascript, Python, Ruby, PHP, Scala, and C#. Several companies have adopted it for their production apps, including Facebook, GitHub, Shopify, New York Times, and PayPal.
trends
Google Trends - GraphQL popularity in the last few years

So, How Does GraphQL Work?

Now, let’s talk about how GraphQL actually works and discuss what sets it apart from the rest of the other API query languages.
GraphQL allows you to define your own strongly typed schema using a GraphQL Schema Definition Language (SDL). You can think of this as a contract between the server and client — the server-side exposes only what you define through your schema, and the client gets only what is offered by the schema. Having a schema also allows early detection and correction of issues during the development stages. With the schemas in place, you can streamline the communication between the server and client, eliminating potential miscommunication issues and delays. Going back to the earlier grocery shopping example, if we could accurately know the inventory items at each store, we could use that information to optimize and make our whole trip more efficient.
The most essential component of a GraphQL schema is the Object type. It represents the kind of object you can fetch from your service and what fields it has. In the GraphQL schema language, a GraphQL object type might look like the following -
type Comment { 
   id: String 
   content: String 
}
Clients fetch data using GraphQL queries, equivalent to the 'read' operation in the CRUD pattern. With queries, clients can only bring data but not modify it. To modify data (i.e., perform create, update, and delete operations), mutation types need to be used. In addition to queries and mutations, GraphQL also supports subscriptions,** which can help you to build real-time functionality into your applications by accessing notifications and data changes typically over a web socket. Query, mutation, and subscription commands are dealt with by a resolver**, a collection of functions that generates responses for a graphQL query. You can think of a resolver like a GraphQL query handler.
type Subscription { 
    commentAdded(repoFullName: String!): Comment 
} 

schema { 
   query: Query 
   mutation: Mutation 
   subscription: Subscription 
}

GraphQL compared to REST

If you're a developer looking for ways to implement or consume APIs, GraphQL and REST are two possible options in your toolbox. While it might appear like there are no big differences on the surface, there are some critical things in GraphQL that make it a big deal for developers. Using the table below, let's explore what sets these two options apart -
GraphQL vs REST
REST GraphQL
Data Fetching With REST you have to access multiple server resource endpoints, requiring multiple round trips between the client and the server. With GraphQL, data access is handled through a single endpoint that defines all the data requirements for the API call. This single-shot design is quite beneficial in mobile apps, where multiple round trips are frowned upon in low bandwidth scenarios.
Web Caching Caching is part of the HTTP specification which REST APIs can benefit from. GraphQL does not follow the HTTP specification for caching. Instead, it uses a single endpoint, so it is up to the developer to ensure that caching is appropriately implemented for non-mutable queries.

Several third-party GraphQL libraries such as FlacheQL, and Relay exist to solve this problem.

File Uploading REST supports file uploading to different computers over the internet Does not support file uploading
Technology Ramp up If you’re familiar with the HTTP and client-server architecture, you can easily understand the REST API and start using it in your projects. The GraphQL SDL has a bit of a learning curve. If your engineering team hasn't worked with GraphQL before, they should plan to spend time and resources learning it and ramping up.

When should you use GraphQL?

Even though REST is quite a popular web API technology, there are several scenarios where GraphQL is heavily used and worth considering -

Reducing app bandwidth usage

Mobile applications deal with slow networks and reduced bandwidth limitations all the time. If you’re a mobile developer and need to optimize your app for bandwidth and speed, give GraphQL a look. With GraphQL, multiple network requests can be bunched up in a single query, reducing the total number of mobile app requests. Additionally, you only need to send the data fields that your mobile app is using, which reduces the payload of the response sent back from the server over the constrained network.

Complex and Composite systems

Abstraction reduces complexity. No matter how many databases, legacy systems, and third-party APIs you use, GraphQL enables you to efficiently work across these complex and composite systems. It can cleanly encapsulate how data is fetched across multiple resources without specifying where these resources exist. This pattern adds a nice layer of abstraction, hiding all the system complexity without overwhelming the developer.

Microservice based architectures

GraphQL brings several benefits, such as effective request routing, parallel request execution, and graceful failure handling when you have a growing number of microservices in your environment. For example, as a developer, your app only points to a single endpoint, and GraphQL manages to route the requests to the appropriate microservices. Your single GraphQL query can comprise many requested resources, and these requests can be handled by multiple microservices in parallel. Finally, GraphQL uses strongly typed requests that can fully succeed or partially fail, returning valuable data along with clear and helpful errors.

When you need rapid prototyping

When it comes to prototyping new apps, developers need speed. GraphQL has several features that can help accelerate development so that your front-end teams can get going without depending on your backend teams. For example, let's say you want to prototype adding authorization for your existing REST APIs. In this case, you can firewall off your REST APIs and throw in an allowlisted GraphQL server. Then, without needing any changes to the existing API by your backed teams, you can implement the logic for authorization in the GraphQL resolver.

Drawbacks of GraphQL

GraphQL may sound like a perfect solution for every problem, but in reality, it does have some drawbacks, and there may be cases where it might not meet all your requirements. Here are a few scenarios -

The “N+1” GraphQL problem

Once you get over the basics of GraphQL, you'll encounter the well-known "N+1" problem. GraphQL executes a separate resolver function for every field in the query request, whereas there is one resolver per endpoint in REST. For example, for the below query, GraphQL will fetch the authors first, and then for each author, fetch the address.
query
{
    authors {
        name
        address {
            country
        }
    }
}
This results in N+1 round trips to the database. New GraphQL libraries like Dataloader are now available, which can batch consecutive requests and make a single data request under the hood.

Your app is too simple

In cases where your app only leverages a few fields and that too in a standardized way, the added complexity of GraphQL would be overkill, and it may be more efficient to use a REST architecture.

Your use-case needs to support file uploads

Sooner or later, you will realize that uploading files with GraphQL is a significant pain point. Unlike REST, file uploads are not part of the official GraphQL spec yet. However, GraphQL enthusiasts have built several third-party libraries that are geared towards solving this problem.

vCaching issues

Caching delivers snappier app experiences for users accessing the same resources over and over again. Because GraphQL is transport agnostic— not making use of the HTTP semantics makes caching a challenge.

The learning curve is steep

GraphQL is a compelling query language for APIs with many benefits, but its higher complexity and steeper learning curve may not suit every application and team. With GraphQL, your engineering team may have to spend additional hours getting accustomed to the SDL before gaining their productive edge.

How to expose your Database via GraphQL

If you're working with a database that does not include native GraphQL, it is possible to drop in some GraphQL middleware layered on top of your database. An example of this is Apollo, which is a Javascript-based state management library that allows users to combine APIs, databases, and microservices into a single data graph that can be accessed and called by GraphQL. Based on your current architecture, the individual implementation can vary, so the best place to start is the Apollo user documentation.

Database with Native GraphQL

With GraphQL, you get a simple API query language and architecture for your server, but now you've got to engineer solutions around production issues. Instead of building your own GraphQL architecture, which can be time-consuming or introduce technical debt, serverless databases with native GraphQL can be an excellent alternative.
At Fauna, we have spent years of engineering effort building a state-of-the-art data API needed for modern applications. Fauna uses GraphQL, which means that it has solved the complex challenges such as the N+1 problem and more that keep GraphQL engineers up at night. It is provisioning-free, configuration-free, and available instantly as a serverless utility with a pay-per-use pricing model. It offers limitless capacity once it is plugged in, and this solidifies your application to make sure it does not break down under unexpected spikes in demand.

Get started on Fauna, instantly and for free

Sign-up for free
The data API for modern applications is here. Sign-up for free without a credit card and get started instantly.
Sign-up now
Quick start guide
Try our quick start guide to get up and running with your first Fauna database, in only 5 minutes!
Read more

If you enjoyed our blog, and want to work on systems and challenges related to globally distributed systems, serverless databases, GraphQL, and Jamstack, Fauna is hiring!

Share this post

TwitterLinkedIn

Subscribe to Fauna blogs & newsletter

Get latest blog posts, development tips & tricks, and latest learning material delivered right to your inbox.

<- Back