Subscriptions & Real-Time Data

◕ GraphQLLesson 5Intermediate

GraphQL subscriptions enable real-time functionality. Instead of polling an endpoint repeatedly, clients subscribe to events and the server pushes updates as they happen — powered by WebSockets under the hood.

1 Writing Subscriptions
GraphQL — Subscription Syntax
# Subscribe to new comments on a specific post
subscription WatchComments {
  commentAdded(postId: "42") {
    id
    text
    createdAt
    author {
      id
      name
      avatar
    }
  }
}

# Subscribe to live messages in a chat room
subscription ChatRoom {
  messageSent(roomId: "room-1") {
    id
    content
    sender { name }
    timestamp
  }
}

# Subscribe to order status changes
subscription TrackOrder {
  orderStatusChanged(orderId: "ord-99") {
    id
    status      # PENDING, PROCESSING, SHIPPED, DELIVERED
    updatedAt
  }
}
2 Implementing Subscriptions (Apollo Server)
JavaScript — Apollo Server Subscription Setup
const { ApolloServer } = require("@apollo/server");
const { expressMiddleware } = require("@apollo/server/express4");
const { makeExecutableSchema } = require("@graphql-tools/schema");
const { WebSocketServer } = require("ws");
const { useServer } = require("graphql-ws/lib/use/ws");
const { PubSub } = require("graphql-subscriptions");

const pubsub = new PubSub();

const resolvers = {
  Mutation: {
    addComment: async (_, { postId, text }, { currentUser }) => {
      const comment = await Comment.create({ postId, text, authorId: currentUser.id });

      // Publish event to all subscribers
      pubsub.publish("COMMENT_ADDED", {
        commentAdded: comment,
        postId
      });

      return comment;
    }
  },

  Subscription: {
    commentAdded: {
      subscribe: (_, { postId }) =>
        // Filter events — only send if postId matches
        pubsub.asyncIterableIterator("COMMENT_ADDED"),
      resolve: (payload) => payload.commentAdded
    }
  }
};

// WebSocket server for subscriptions
const wsServer = new WebSocketServer({ server: httpServer, path: "/graphql" });
useServer({ schema }, wsServer);
3 Code Challenge
Challenge: Build a live notification system using GraphQL subscriptions. Create a notificationReceived(userId: ID!) subscription that fires whenever a new notification is created for that user via a sendNotification mutation.