Suscripciones de GraphQL para datos en tiempo real
Añada capacidades en tiempo real a su API de GraphQL mediante suscripciones, para que los clientes reciban actualizaciones en directo por WebSockets en cuanto cambien los datos.
Suscripciones de GraphQL para datos en tiempo real es una lección gratuita de Node.js Backend Development Bootcamp en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Node.js Backend Development Bootcamp, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Node.js Backend Development Bootcamp incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Three GraphQL Operations
GraphQL defines three root operation types:
- Query: read data
- Mutation: change data
- Subscription: receive a stream of live updates
Queries and mutations are request/response; subscriptions keep a connection open for ongoing events.
When to Use Subscriptions
Subscriptions shine when clients need real-time data:
- Chat messages
- Live notifications
- Collaborative editing
- Live dashboards and scores
For data that rarely changes, polling a query is simpler.
WebSockets Under the Hood
Queries and mutations travel over HTTP, but subscriptions need a persistent two-way channel — a WebSocket. The server pushes events to subscribed clients without them asking again.
Defining a Subscription in the Schema
Add a Subscription type to your schema with fields clients can subscribe to. Each field is an event stream returning some type.
type Subscription {
messageAdded(channelId: ID!): Message!
}The PubSub Engine
Subscriptions rely on a publish/subscribe system. A PubSub instance lets your resolvers publish events and your subscriptions listen for them.
const { PubSub } = require('graphql-subscriptions');
const pubsub = new PubSub();Publishing an Event
Inside a mutation, after saving data, publish an event on a named topic. Anyone subscribed to that topic receives the payload.
const message = await Message.create(input);
pubsub.publish('MESSAGE_ADDED', { messageAdded: message });
return message;The Subscription Resolver
A subscription resolver returns an async iterator via asyncIterator, telling the server which topic to forward to the client.
const resolvers = {
Subscription: {
messageAdded: {
subscribe: () => pubsub.asyncIterator('MESSAGE_ADDED')
}
}
};Filtering Events
Often a client only cares about events for one channel. withFilter wraps the iterator and forwards only events that match the subscription's arguments.
const { withFilter } = require('graphql-subscriptions');
subscribe: withFilter(
() => pubsub.asyncIterator('MESSAGE_ADDED'),
(payload, vars) => payload.messageAdded.channelId === vars.channelId
)Client Subscription Query
The client writes a subscription operation just like a query, but with the subscription keyword. The server streams results as they happen.
subscription OnMessage($id: ID!) {
messageAdded(channelId: $id) {
id
text
}
}Scaling Across Servers
The in-memory PubSub only works on a single instance. To broadcast across many servers, swap in a backend like graphql-redis-subscriptions so events reach all connected clients.
const { RedisPubSub } = require('graphql-redis-subscriptions');
const pubsub = new RedisPubSub();Cleaning Up Connections
Open WebSockets consume resources. The server should detect disconnects and stop streaming. Apollo Server handles much of this, but watch for orphaned subscriptions and authenticate the connection on setup.
Quick Check
Test your GraphQL subscription knowledge.
Recap
You added real-time data with GraphQL subscriptions:
- Subscriptions stream live events over WebSockets
- Declare a
Subscriptiontype and resolve it withasyncIterator - Mutations
publishevents;withFiltertargets the right clients - Scale across servers with a Redis-backed PubSub and clean up connections
Now your API can power chat, notifications, and live dashboards.
Preguntas frecuentes
¿La lección «Suscripciones de GraphQL para datos en tiempo real» es gratis?
Sí — el texto completo de «Suscripciones de GraphQL para datos en tiempo real» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Node.js Backend Development Bootcamp, actualiza a CoddyKit PRO. El curso de Node.js Backend Development Bootcamp incluye 4 lecciones en total.
¿Qué aprenderé en «Suscripciones de GraphQL para datos en tiempo real»?
Añada capacidades en tiempo real a su API de GraphQL mediante suscripciones, para que los clientes reciban actualizaciones en directo por WebSockets en cuanto cambien los datos. Practicas Node.js Backend Development Bootcamp con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Node.js Backend Development Bootcamp?
No se requiere experiencia previa. Node.js Backend Development Bootcamp en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Suscripciones de GraphQL para datos en tiempo real»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Node.js Backend Development Bootcamp?
Sí. Cada lección de Node.js Backend Development Bootcamp incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción al serverless con Node.js
- Principios de diseño de API GraphQL
- Creación de un servidor GraphQL con Apollo
- Suscripciones de GraphQL para datos en tiempo real