Medición del Costo de una Consulta GraphQL con mercurius-explain

Rate this content
Bookmark

La experiencia de desarrollo con GraphQL ofrece una forma simple e inmediata de acceder a los datos. Trabajar en el backend implica enfocarse en cómo y dónde se obtienen los datos, mientras que el frontend se enfoca en recuperar los datos necesarios para el cálculo y la visualización. Sin embargo, esta libertad de acción oculta algunos posibles problemas de rendimiento. Los fragmentos te permiten construir conjuntos de campos y luego incluirlos en las consultas donde se necesiten. A menudo, un cliente solicita datos innecesarios en una llamada de API con la suposición de que los campos adicionales son gratuitos. En cambio, son la causa de consultas adicionales, a veces incluso costosas. No conocer el costo de una consulta hace imposible realizar la optimización correctamente.

7 min
17 Apr, 2023

Video Summary and Transcription

Hoy vamos a hablar sobre la medición del costo de una consulta GraphQL con Mercury's Explain. GraphQL nos permite crear una lista de elementos que queremos sin necesidad de conocer sus ubicaciones. NearForm creó Mercurius Explain, un complemento que agrega un Perfilador a tu instancia de GraphQL. Este complemento proporciona información detallada sobre el tiempo de resolución y el número de llamadas al resolutor para cada campo, lo que facilita la optimización y depuración de consultas. Mercurius Explain es una herramienta valiosa para comprender el costo de tus consultas GraphQL.

Available in English

1. Medición del Costo de una Consulta GraphQL

Short description:

Hoy vamos a hablar sobre la medición del costo de una consulta GraphQL con Mercury's Explain. GraphQL nos permite crear una lista de elementos que queremos sin necesidad de conocer su ubicación. Sin embargo, esto puede generar problemas a la hora de entender el costo de una consulta. Para solucionar esto, NearForm creó Mercurius Explain, un complemento que agrega un Perfilador a tu instancia de GraphQL. Este complemento proporciona información detallada sobre el tiempo de resolución y el número de llamadas al resolver para cada campo, lo que facilita la optimización y depuración de consultas. Ya sea en producción o desarrollo, Mercurius Explain es una herramienta valiosa para entender el costo de tus consultas GraphQL.

Hoy vamos a hablar sobre la medición del costo de una consulta GraphQL con Mercury's Explain. Primero, permíteme presentarme. Mi nombre es Marco Ippolito, soy un desarrollador de software en NearForm y colaborador de Node.js. Soy de Spoltore, que es una pequeña ciudad en Abruzzo, Italia, pero actualmente vivo en Milán.

Así que empecemos. Me gusta comparar GraphQL con nuestro comprador personal. Simplemente creamos una lista de elementos que queremos. No necesitamos saber dónde se encuentran los elementos. No necesitamos saber en qué supermercado, en qué pasillo. Simplemente tenemos una consulta, que es básicamente una lista, y él los va a buscar por nosotros. A diferencia de REST, hay algunas diferencias. Por ejemplo, con REST tienes que conocer la ruta donde se encuentra el elemento, mientras que con GraphQL simplemente no te importa. Si cambias la disposición de la tienda, no te importa, pero esto oculta algunos problemas.

¿Y qué hay del costo? Bueno, hay algunas implicaciones. Por ejemplo, cuando tenemos una consulta GraphQL, solo podemos ver el costo total. Por ejemplo, cuántos milisegundos tardó en resolverse la consulta, lo cual no es ideal porque si obtenemos docenas de campos, no sabemos qué campo es más costoso que el otro. Esto significa que es muy difícil depurar y optimizar una consulta lenta, especialmente si usas fragmentos. En aplicaciones de producción grandes, tendemos a usar fragmentos con campos centralizados que queremos solicitar, pero esto dificulta detectar campos adicionales que no necesitamos en una consulta específica. Podemos decir que en GraphQL es muy importante conocer el costo de cada campo de una consulta. De lo contrario, tendrás grandes problemas de rendimiento.

Esta es una de las principales razones por las que en NearForm creamos Mercurius Explain. Mercurius es el adaptador GraphQL para Fastify, y Mercurius Explain es un complemento que puede agregarse fácilmente a tu instancia de Mercurius. Las principales características de este complemento son el Perfilador, que básicamente registra el tiempo de resolución de cada resolutor GraphQL en el atributo Explain de tu respuesta GraphQL. Esto es muy útil porque puedes ver el tiempo de resolución en milisegundos. Como puedes ver en este JSON, está el inicio, el fin y el tiempo total que un resolutor específico tardó para un campo específico de tu consulta. También cuenta con las llamadas al resolutor, que es básicamente un contador de cuántas veces se invoca un resolutor. Funciona perfectamente en una puerta de enlace en una Federación, que es básicamente lo que usamos para aplicaciones de producción grandes. Está asegurado por la firma, por lo que puedes usar tus propias políticas de autorización, por ejemplo, verificar si en la solicitud hay un encabezado específico, y también es muy rápido. Creamos este complemento que está destinado a ser utilizado específicamente en producción, pero también durante el desarrollo. Por eso este complemento también cuenta con un complemento GraphQL. Como puedes ver en esta imagen, en el lado izquierdo está el tiempo de resolución de cada campo de nuestra consulta. Mientras estás en la fase de desarrollo, puedes detectar fácilmente un campo lento o si hay algún problema de rendimiento con este complemento, puedes detectarlo de inmediato. También tenemos el diagrama de barras para cada resolutor. Como puedes ver a la izquierda, está en milisegundos. Para cada resolución puedes ver cuándo comenzó, cuándo terminó, es muy específico. Así que te recomiendo que uses este complemento en prácticamente todas las circunstancias, producción, desarrollo, pequeño, grande, porque es muy útil y es muy importante en GraphQL conocer el costo de una consulta. Así que gracias por escuchar, aquí dejo mis cuentas en redes sociales, y también quiero agradecer a Davide Fiorello, quien es el cerebro detrás de este complemento. Y eso es todo, muchas gracias.

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

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
React Summit 2023React Summit 2023
32 min
Speeding Up Your React App With Less JavaScript
Top Content
Too much JavaScript is getting you down? New frameworks promising no JavaScript look interesting, but you have an existing React application to maintain. What if Qwik React is your answer for faster applications startup and better user experience? Qwik React allows you to easily turn your React application into a collection of islands, which can be SSRed and delayed hydrated, and in some instances, hydration skipped altogether. And all of this in an incremental way without a rewrite.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
JSNation 2022JSNation 2022
21 min
The Future of Performance Tooling
Top Content
Our understanding of performance & user-experience has heavily evolved over the years. Web Developer Tooling needs to similarly evolve to make sure it is user-centric, actionable and contextual where modern experiences are concerned. In this talk, Addy will walk you through Chrome and others have been thinking about this problem and what updates they've been making to performance tools to lower the friction for building great experiences on the web.
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
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
JSNation 2023JSNation 2023
170 min
Building WebApps That Light Up the Internet with QwikCity
Featured WorkshopFree
Building instant-on web applications at scale have been elusive. Real-world sites need tracking, analytics, and complex user interfaces and interactions. We always start with the best intentions but end up with a less-than-ideal site.
QwikCity is a new meta-framework that allows you to build large-scale applications with constant startup-up performance. We will look at how to build a QwikCity application and what makes it unique. The workshop will show you how to set up a QwikCitp project. How routing works with layout. The demo application will fetch data and present it to the user in an editable form. And finally, how one can use authentication. All of the basic parts for any large-scale applications.
Along the way, we will also look at what makes Qwik unique, and how resumability enables constant startup performance no matter the application complexity.
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
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 Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
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.
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
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.