¡Utiliza tu esquema para el almacenamiento en caché!

Rate this content
Bookmark

Basado en nuestra experiencia ejecutando GraphCDN, hemos visto esquemas que facilitan el almacenamiento en caché y otros que pueden presentar dificultades. Permíteme compartir cómo evitar problemas comunes y mantenerse alejado de los obstáculos, y cómo tu esquema puede ayudarte con el almacenamiento en caché de las respuestas de GraphQL.

6 min
09 Dec, 2021

Video Summary and Transcription

En esta charla relámpago, el orador discute las mejores prácticas para el almacenamiento en caché de las APIs de GraphQL. Enfatizan la importancia de nombres y configuraciones consistentes para los campos de almacenamiento en caché. Mantener los tipos consistentes y hacer que la caché sea consciente del esquema puede mejorar la eficiencia. El orador también sugiere dividir las consultas para optimizar el almacenamiento en caché y reducir las solicitudes al servidor.

Available in English

1. Caching Best Practices

Short description:

En esta charla relámpago, me gustaría darte algunos consejos sobre cómo tu esquema puede ayudar al almacenamiento en caché de las API de GraphQL, tanto a través de cachés de documentos como GraphCDN, como a través de cachés normalizados implementados en clientes como Apollo Client o Urql. El primer punto del que me gustaría hablar es tener un nombre consistente para los campos que deseas almacenar en caché. Es importante configurar tus clientes de manera precisa para utilizar los campos apropiados. Mantener tus tipos consistentes también es crucial para evitar duplicaciones y hacer que tu caché sea más eficiente. Además, hacer que tu caché sea consciente de tu esquema desbloquea funcionalidades adicionales y permite tomar decisiones más inteligentes basadas en los tipos devueltos por tus consultas. Por último, considera dividir las consultas en algunos casos para optimizar el almacenamiento en caché y reducir las idas y vueltas al servidor.

Hola a todos. Mi nombre es Marco Locher y soy parte del equipo de GraphCDN. Si estás interesado en GraphCDN o en el almacenamiento en caché de GraphQL en general, espero que no te hayas perdido la charla de Max sobre cómo almacenar en caché las API de GraphQL más temprano hoy. En esta charla relámpago, me gustaría darte algunos consejos sobre cómo tu esquema puede ayudar al almacenamiento en caché de las API de GraphQL, tanto a través de cachés de documentos como GraphCDN, como a través de cachés normalizados implementados en clientes como Apollo Client o Urql. El primer punto del que me gustaría hablar puede parecer muy obvio, pero tener ideas sobre los tipos que deseas almacenar en caché y tener un nombre consistente para esos campos es bastante importante. Hemos visto algunos proyectos de nuestros propios usuarios donde cambiar eso tuvo un gran impacto. Si puedes usar ID o underscore ID, la mayoría de los clientes y herramientas relacionadas de GraphQL utilizarán esos campos de forma predeterminada. Sin embargo, si no puedes hacerlo porque ya estás usando otros nombres para esos campos en tus API heredadas o no es fácil, puedes configurar tus clientes para usar los campos apropiados. Es muy importante asegurarse de que esa configuración sea precisa. En GraphCDN, por ejemplo, configurarías esos campos como campos clave, y estos definen cómo puedes encontrar esos objetos en la caché nuevamente, y lo que es más importante, cómo puedes purgarlos si realizas modificaciones en tu backend. De manera similar, recomendamos que te adhieras a IDs globalmente únicos en tu aplicación, por ejemplo, utilizando UUID o algo similar, pero si eso no es algo que puedas acomodar, también hay soluciones alternativas que la mayoría de los clientes implementan.

El segundo punto es mantener tus tipos consistentes. Al trabajar con nuestros usuarios, hemos visto esquemas donde los tipos se duplican para agregar un solo campo. Sin embargo, eran idénticos en todos los demás aspectos y representaban los mismos datos. Esto hará que tu caché sea menos eficiente, ya que ahora necesitará almacenar los datos dos veces, dependiendo de si ese campo adicional está presente o no. De manera similar, si deseas enriquecer los datos con metadatos que solo pueden ser requeridos en un contexto muy específico, como los resultados de búsqueda, por ejemplo, donde deseas mostrar la cadena de búsqueda de manera destacada, recomendamos implementar un concepto como la especificación de conexión de cursor para esos metadatos, en lugar de extender tu tipo con campos que solo se requieren en un contexto muy específico. Aunque la especificación de conexión de cursor está principalmente destinada a manejar la paginación, también se presta muy bien para ser extendida a otros casos de uso similares, como el que acabo de mencionar.

Muy importante también es asegurarse de que tu caché sea consciente de tu esquema. Cada caché ofrecerá alguna funcionalidad, ya sea consciente del esquema o no. Sin embargo, si haces que tu caché sea consciente del esquema de tus datos, desbloqueará funcionalidades adicionales que de otra manera no serían posibles. Puede tomar decisiones más inteligentes basadas en los tipos devueltos por tus consultas, algo que es especialmente importante en el contexto de los fragmentos o cuando se utilizan interfaces. Hacer que tu caché sea consciente de tu esquema también le permitirá devolver resultados parciales basados en los datos ya almacenados en caché si los campos faltantes se designan como opcionales. Y mientras tu aplicación ya está mostrando cierta información al usuario, la caché recupera los campos faltantes en segundo plano. Sin ese conocimiento, esa habría sido una consulta que habría sido devuelta directamente por tu API y la caché no habría estado involucrada en absoluto.

Y por último, si estás utilizando una caché de documentos como RefCDN, en algunos casos, es posible que sea mejor dividir tus consultas en lugar de enviar solo una. Sé que GraphQL es conocido por su flexibilidad y por el hecho de que puedes personalizar cada consulta para obtener exactamente los datos que necesitas. Pero en algunos casos, dividir las consultas y tener más de una puede ser beneficioso. Por ejemplo, echemos un vistazo a una consulta que obtiene una lista de los artículos más recientes de un blog, así como una lista de recomendaciones basadas en el usuario que ha iniciado sesión actualmente. Una caché basada en documentos como RefCDN, por ejemplo, analiza toda la respuesta que obtienes. Y si está vinculada a un usuario específico, solo podrá utilizar esos datos en caché para ese usuario específico en el futuro. Sin embargo, si divides esa consulta en una parte pública y una parte más privada, la parte pública se puede reutilizar para cada usuario, sin importar si han iniciado sesión o no, sin importar dónde se encuentren. Y especialmente cuando trabajas tanto con una caché basada en documentos como con una caché normalizada como parte de tu cliente de GraphQL, el cliente no se verá afectado por eso, ya que ya tendrá la mayoría o incluso todos los datos requeridos en su caché local y no requerirá ninguna ida y vuelta al servidor en absoluto.

Muchas gracias por escuchar. Espero que hayan sido algunos puntos valiosos para todos ustedes. Si tienen alguna pregunta, estaré encantado de responder durante la sesión de preguntas y respuestas o también pueden contactarme en Twitter. 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

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!
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.
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
Though GraphQL is declarative, resolvers operate field-by-field, layer-by-layer, often resulting in unnecessary work for your business logic even when using techniques such as DataLoader. In this talk, Benjie will introduce his vision for a new general-purpose GraphQL execution strategy whose holistic approach could lead to significant efficiency and scalability gains for all GraphQL APIs.

Workshops on related topic

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
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.
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
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
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.