Build the mental model
`subscription` is GraphQL's third operation type: where query and mutation use one HTTP request-response cycle, a subscription keeps a WebSocket connection open and pushes data from server to client whenever an event occurs. On the server, the `subscribe` function must return an `AsyncIterator` — a PubSub library (in-memory or Redis-backed) commonly serves as the event channel. When a mutation triggers the event, it calls `pubsub.publish(...)` to notify subscribers.
Connect it to a real scenario
Build the Tutorial Platform's live-notification feature with a `tutorialPublished` subscription — every successful `publishTutorial` mutation calls `pubsub.publish('TUTORIAL_PUBLISHED', ...)`, updating every subscriber with the browse page open. In a multi-server deployment, an in-memory PubSub is not enough and a Redis-backed PubSub is required.
Try the working example
const typeDefs = `#graphql
type Subscription {
tutorialPublished: Tutorial!
}
`;
const resolvers = {
Subscription: {
tutorialPublished: {
subscribe: () => pubsub.asyncIterator(['TUTORIAL_PUBLISHED']),
},
},
Mutation: {
publishTutorial: async (_parent: unknown, args: { id: string }) => {
const tutorial = await tutorialRepository.publish(args.id);
pubsub.publish('TUTORIAL_PUBLISHED', { tutorialPublished: tutorial });
return tutorial;
},
},
};You can write a subscription field and explain a mutation-to-event-publish flow.5-minute try-it
Design a `commentAdded(tutorialId: ID!): Comment!` subscription and describe how `addComment` would publish to it.
One important caution
Leaving subscription connections unauthorized or unfiltered can let a user subscribe to data outside their scope, such as a private tutorial's events — put auth checks inside the subscribe function too.
Apollo Server — Subscriptions — GraphQL