Real-time subscriptions in GraphQL

From the GraphQL cheat sheet · Subscriptions · verified Jul 2026

Real-time subscriptions

javascript
// Server-side subscription setup
const { PubSub } = require('graphql-subscriptions');
const pubsub = new PubSub();

// Type definitions
const typeDefs = gql`
  type Subscription {
    postAdded: Post!
    commentAdded(postId: ID!): Comment!
    userTyping(chatId: ID!): TypingEvent!
  }
  
  type TypingEvent {
    userId: ID!
    userName: String!
    isTyping: Boolean!
  }
`;

// Resolvers
const resolvers = {
  Mutation: {
    createPost: async (parent, args, context) => {
      const post = await db.post.create({ data: args });
      
      // Publish event
      pubsub.publish('POST_ADDED', { postAdded: post });
      
      return post;
    },
    
    addComment: async (parent, { postId, content }, context) => {
      const comment = await db.comment.create({
        data: { postId, content, userId: context.user.id }
      });
      
      // Publish to specific channel
      pubsub.publish(`COMMENT_ADDED_${postId}`, { 
        commentAdded: comment 
      });
      
      return comment;
    }
  },
  
  Subscription: {
    postAdded: {
      subscribe: () => pubsub.asyncIterator(['POST_ADDED'])
    },
    
    commentAdded: {
      subscribe: (parent, { postId }) => {
        return pubsub.asyncIterator([`COMMENT_ADDED_${postId}`]);
      }
    },
    
    userTyping: {
      subscribe: withFilter(
        () => pubsub.asyncIterator(['USER_TYPING']),
        (payload, variables) => {
          // Only send to users in the same chat
          return payload.chatId === variables.chatId;
        }
      )
    }
  }
};
💡 Real-time updates via WebSocket
⚡ Server pushes updates to clients
📌 Use for live features like chat
🔥 Efficient for selective updates
Back to the full GraphQL cheat sheet