Breaking REST Chains: A Fastify & Mercurius Pathway to GraphQL Glory

Rate this content
Bookmark
The talk discusses building a GraphQL server using Fastify and Mercurius, emphasizing the benefits of GraphQL over REST API for serving different devices with a single endpoint. It explains how GraphQL schemas define queries, mutations, and subscriptions, enabling efficient data retrieval and updates. Mercurius, a high-performance GraphQL adapter for Fastify, supports features like caching, subscriptions, and Apollo Federation. The speaker demonstrates setting up a GraphQL server with Fastify, registering Mercurius, and defining schemas and resolvers. Topics like the N+1 problem and its resolution with loaders, pagination, and TypeScript integration are covered. The video also highlights the importance of monitoring and carefully exposing data to frontend developers.

From Author:

Are you tired of wrestling with the limitations of REST APIs? ""Breaking REST Chains: A Fastify & Mercurius Pathway to GraphQL Glory"" is your roadmap to a better way.

Discover how GraphQL solves REST's shortcomings and how to implement it using Fastify and Mercurius. We'll cover:


1. REST limitations that hold back modern apps.

2. GraphQL's game-changing features.

3. Steps to transition using Fastify and Mercurius.


Unlock the full potential of your APIs and break free from REST's constraints. Join us to learn, adapt, and elevate your API game.

This talk has been presented at Node Congress 2024, check out the latest edition of this JavaScript Conference.

FAQ

Luca Del Pupo is a science software developer at Neo4m and a JavaScript and Typescript enthusiast. He runs a YouTube channel and writes technical posts for tech people.

GraphQL is preferred over REST API in scenarios where different devices need different subsets of data. It allows for a single endpoint to serve various devices like desktops, mobiles, and smartwatches efficiently.

Mercurius is a high-performance GraphQL adapter built on top of Fastify. It supports features like caching, subscriptions, and Apollo Federation, and is open source under the MIT license.

Mercurius supports query parsing and validation caching, N+1 problem resolution using loaders, just-in-time compilation, subscriptions, federation, gateway aggregation, batch queries, and persistent queries.

To set up a GraphQL server using Fastify and Mercurius, you need to create a Fastify application, register the Mercurius plugin, define your schema and resolvers, and start your server. Optionally, you can configure GraphiQL for testing.

The N+1 problem occurs when a server makes multiple database calls for related data, which can be inefficient. Mercurius solves this by using loaders that batch and cache these calls, reducing the number of queries made to the database.

GraphiQL is a graphical user interface for testing and querying GraphQL servers. It allows developers to interact with the API and see real-time results.

When building a GraphQL server, consider the layout of your application, what data to expose to frontend developers, and add a layer of monitoring to track application performance.

GraphQL can aggregate different microservices into a single endpoint, simplifying the client-server interaction. It allows for merging various services and exposing them through one GraphQL server.

Recommended resources include the official documentation of Fastify and Mercurius, NearForm blog, backend cafe blog, NearForm YouTube channel, Adventure in Nordland YouTube channel, and the book 'Fastify' which has a chapter on Mercurius.

Luca Del Puppo
Luca Del Puppo
23 min
04 Apr, 2024

Comments

Sign in or register to post your comment.

Video Transcription

1. Introduction to GraphQL and its Advantages

Short description:

Hello, and welcome to this talk about how to build a GraphQL server using Fastify and Mercurius. GraphQL is a query language that permits you to create a sort of server that serves different kinds of devices. It allows you to use only one server and create only one API to serve different types of devices like desktop, mobile, smartwatch, etc. GraphQL contains a schema where you can define queries, mutations, and subscriptions. Queries retrieve data, mutations update data, and subscriptions allow you to subscribe to events.

Hello, and welcome to this talk about how to build a GraphQL server using Fastify and Mercurius.

So, first of all, let me introduce myself. I'm Luca Del Pupo, a science software developer at Neo4m and a JavaScript and Typescript enthusiast. My free time, I try to run my YouTube channel and also write technical posts for tech people. I also love running, hiking, and pets, but now it's time to jump in the topic of today.

Why GraphQL? So, basically, when we start to work with API, we start with SOA and then move to REST API, but we serve only desktop application or desktop browser application. But nowadays, we have to serve different kinds of devices, like mobile, or smartwatch, and TV. And in some cases, the REST API is a limitation. For instance, every device has its specific user interface and different needs, because the desktop has a big screen, the mobile has a small one, and the smartwatch has a pretty, pretty small one. So, the info that you can show in this kind of device are different. And basically, what happens is that the mobile needs a subset of the data that is needed in the desktop application, and the same is for the smartwatch. And what happens is that basically, the people start to create specific endpoint just to remove the not needed fields, to improve also the performance of the mobile application and the time that the server had to spend to serialize and deserialize the data.

Another problem is that if you are in the browser, your browser has a limitation in time of request in the same moment in parallel, and the number is 10. So, in some scenario, this also is another limitation that you cannot avoid if you are using a REST API. And this is Bill. Bill is a junior backend developer that every day fight with the frontend and the mobile to build a specific endpoint for a single view that they need. Joking apart, REST API is not a mess, but in some scenario, they are not the best solution for your application. And this is why Facebook, now Meta, has created GraphQL.

GraphQL is a query language that permits you to create a sort of server that serves different kind of service device. And if you are a good developer and you build it in the right way, you can use only one server and create only one API and serve different kind of server of device like desktop, mobile, smartwatch, and so on and so on. GraphQL is pretty simple. So basically, it contains a schema. A schema is like your open API, okay? And inside, you can define the queries that is the way to retrieve data from the server. You can define mutation that is the way to update data, delete data, or add data in your server. And there is also subscription. There are also subscriptions that permit you to subscribe to an event. And when something happens in the server, the server will emit this event, and the client maybe can react in some way. I don't know. You can use a mutation to add an item in the car. And when this happens, you can modify the client that is a subscribe to this event.

2. Using Mercurius with GraphQL

Short description:

And maybe you can update the UI in your application. You can use GraphQL to merge microservices and scale your server easily. Mercurius is a high-performance GraphQL adapter built on Fastify. It has many core features and plugins and implements Apollo Federation specifications. Mercurius is open source and under the MITA license. It allows caching, avoids the N plus problem, uses just-in-time compilation, supports subscriptions and federation, and enables batch queries and query persistence.

And maybe you can, in the UI, update the badge of the basket in your application. And in this way, you can scale your server in an easy way. You can also use GraphQL to merge together different microservices. For instance, you can decide to split your server in different microservices, and they can also be used in the SAP IE GraphQL server or in basically different kinds of technology. And then you can update them inside of one GraphQL server and expose only this GraphQL server to the client. And last but not least, remember that when you create this kind of solution, you have to remember that every layer is a cost. It is a cost in terms of money, because resources and memory and resources like memory CPU are not free. But they are a cost also in terms of complexity, because maintaining a layer that has to talk with another part of the application is a cost in terms of complexity.

By the way, why do I love Mercurius? Basically, Mercurius is a high performance GraphQL adapter built on top of Fastify. Basically in 2024, I prefer to use Fastify and Auto Express, because it's a decision made in terms of security and performance. Mercurius has many core features and plugins already ready for production, and you have only to decide which one you want to use and use them in your application in the right way. Out of the box, Mercurius implemented the Apollo Federation specifications that permit you to create different microservices and aggregate them inside of a big microservice. And then Mercurius is open source and is under the MITA license. That means that you can contribute to it, you can open the issue if you want, and you can also fix the problem if you want. And there is a fantastic community that permits Mercurius to continue to release new features or fix some bug fixes if they are.

Which are the core features? So basically Mercurius permits you to cache the parsing and validation of the query, permits you to avoid the N plus problem using loader. You can use a just-in-time compiler to improve the performance of how V8 compiles your function. You can use subscription and federation, as I said before. You can also use a gateway to aggregate different federated servers, or you can also create them. You can enable the batch query and in this way you can use only one HTTP request to have different queries in the result. Or you can also persist some queries because in some cases you can assign an hash to a specific query that you already know and the client can call directly the server using this hash. Mercurius understands that the hash is related to a specific query and returns directly the result. This helps to prevent problem time in reality on parsing and validating data from the request. Because one of the problems is that using GraphQL, one of the problem is that your request can become high in terms of the size of the request.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
Tom Pressenwurter introduces Redwood.js, a full stack app framework for building GraphQL APIs easily and maintainably. He demonstrates a Redwood.js application with a React-based front end and a Node.js API. Redwood.js offers a simplified folder structure and schema for organizing the application. It provides easy data manipulation and CRUD operations through GraphQL functions. Redwood.js allows for easy implementation of new queries and directives, including authentication and limiting access to data. It is a stable and production-ready framework that integrates well with other front-end technologies.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.
Batteries Included Reimagined - The Revival of GraphQL Yoga
GraphQL Galaxy 2021GraphQL Galaxy 2021
33 min
Batteries Included Reimagined - The Revival of GraphQL Yoga
Envelope is a powerful GraphQL plugin system that simplifies server development and allows for powerful plugin integration. It provides conformity for large corporations with multiple GraphQL servers and can be used with various frameworks. Envelope acts as the Babel of GraphQL, allowing the use of non-spec features. The Guild offers GraphQL Hive, a service similar to Apollo Studio, and encourages collaboration with other frameworks and languages.
Rock Solid React and GraphQL Apps for People in a Hurry
GraphQL Galaxy 2022GraphQL Galaxy 2022
29 min
Rock Solid React and GraphQL Apps for People in a Hurry
The Talk discusses the challenges and advancements in using GraphQL and React together. It introduces RedwoodJS, a framework that simplifies frontend-backend integration and provides features like code generation, scaffolding, and authentication. The Talk demonstrates how to set up a Redwood project, generate layouts and models, and perform CRUD operations. Redwood automates many GraphQL parts and provides an easy way for developers to get started with GraphQL. It also highlights the benefits of Redwood and suggests checking out RedwoodJS.com for more information.
Adopting GraphQL in an Enterprise
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
Adopting GraphQL in an Enterprise
Today's Talk is about adopting GraphQL in an enterprise. It discusses the challenges of using REST APIs and the benefits of GraphQL. The Talk explores different approaches to adopting GraphQL, including coexistence with REST APIs. It emphasizes the power of GraphQL and provides tips for successful adoption. Overall, the Talk highlights the advantages of GraphQL in terms of efficiency, collaboration, and control over APIs.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
GraphQL has made a huge impact in the way we build client applications, websites, and mobile apps. Despite the dominance of resolvers, the GraphQL specification does not mandate their use. Introducing Graphast, a new project that compiles GraphQL operations into execution and output plans, providing advanced optimizations. In GraphFast, instead of resolvers, we have plan resolvers that deal with future data. Graphfast plan resolvers are short and efficient, supporting all features of modern GraphQL.

Workshops on related topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
Build Modern Applications Using GraphQL and Javascript
Node Congress 2024Node Congress 2024
152 min
Build Modern Applications Using GraphQL and Javascript
Featured Workshop
Emanuel Scirlet
Miguel Henriques
2 authors
Come and learn how you can supercharge your modern and secure applications using GraphQL and Javascript. In this workshop we will build a GraphQL API and we will demonstrate the benefits of the query language for APIs and what use cases that are fit for it. Basic Javascript knowledge required.
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura