Thuta Learning
GraphQL
AdvancedWeb Developmentbeginner

Subscriptions — Real-Time Updates

What you'll walk away with

  • Explain the core ideas behind Subscriptions — Real-Time Updates
  • Run the sample GraphQL query or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

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

typescript
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 should see
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 — SubscriptionsGraphQL

Easy traps

  • 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.
  • Validate sample queries and mutations on a local or test server with recoverable data before applying them to production.

Exercise

Design a `commentAdded(tutorialId: ID!): Comment!` subscription and describe how `addComment` would publish to it.

You'll know it worked when: You can write a subscription field and explain a mutation-to-event-publish flow.

Subscriptions — Real-Time Updates | Thuta Learning