Skip to content

GraphQL Subscriptions

GraphQL subscriptions enable real-time communication by allowing clients to receive updates from the server when specific events occur. Unlike queries and mutations, which are one-time operations, subscriptions keep a connection open and push data as it changes.


What Are Subscriptions?

  • They are a way to subscribe to specific events or changes.
  • Typically implemented over WebSockets.
  • Clients receive live updates without polling.

Basic Subscription Syntax

subscription OnNewMessage {
  newMessage {
    id
    content
    author {
      name
    }
  }
}

This subscription listens for new messages and returns the specified fields whenever a new message is created.


How Subscriptions Work

  1. The client initiates a subscription request.
  2. The server establishes a persistent connection (usually WebSocket).
  3. When the subscribed event occurs, the server pushes data to the client.
  4. The client updates the UI or handles the data accordingly.

Defining Subscription Types in Schema

type Subscription {
  newMessage: Message!
}

type Message {
  id: ID!
  content: String!
  author: User!
}

The Subscription type is a root type like Query and Mutation.


Example: Using Subscriptions with Apollo Server

const { PubSub } = require("graphql-subscriptions");
const pubsub = new PubSub();

const resolvers = {
  Subscription: {
    newMessage: {
      subscribe: () => pubsub.asyncIterator(["NEW_MESSAGE"]),
    },
  },
  Mutation: {
    sendMessage: (_, { content, author }) => {
      const message = { id: generateId(), content, author };
      pubsub.publish("NEW_MESSAGE", { newMessage: message });
      return message;
    },
  },
};

Client-side Usage Example (Apollo Client)

import { useSubscription, gql } from "@apollo/client";

const NEW_MESSAGE_SUBSCRIPTION = gql`
  subscription {
    newMessage {
      id
      content
      author {
        name
      }
    }
  }
`;

function Messages() {
  const { data, loading } = useSubscription(NEW_MESSAGE_SUBSCRIPTION);

  if (loading) return <p>Loading...</p>;

  return <div>{data.newMessage.content}</div>;
}

Use Cases for Subscriptions

  • Chat applications
  • Live sports scores
  • Real-time notifications
  • Collaborative document editing
  • Stock price updates

Important Considerations

  • Subscriptions require a persistent connection (WebSocket or similar).
  • More complex infrastructure than queries/mutations.
  • Consider security and authorization carefully.
  • Not all GraphQL servers support subscriptions natively.

Tools & Libraries


Summary

  • Subscriptions bring real-time capabilities to GraphQL APIs.
  • They use persistent connections to push data on events.
  • Ideal for live updates in modern applications.