Skip to content

Subscriptions in GraphQL — Complete Guide

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Subscriptions in Graphql. We cover key concepts, practical examples, and best practices to help you master this topic.

GraphQL subscriptions provide real-time updates by maintaining a persistent connection between client and server. When events occur, the server pushes data to subscribed clients through Websocket or SSE transports.

What You'll Learn

  • Subscription schema definitions and root type
  • Pub/sub implementation patterns
  • Event-based resolver triggers
  • Client-side subscription management

Why It Matters

Subscriptions enable real-time features like live notifications, chat messages, stock tickers, and collaborative editing without polling. They reduce latency and server load compared to short-polling alternatives.

Real-World Use

GitHub uses subscriptions for real-time Pull Request reviews and status checks. GitLab uses them for CI/CD pipeline updates. Apollo's real-time features power collaborative dashboards and live data feeds.

flowchart LR
    Client[Client] -->|Subscription Request| Server[GraphQL Server]
    Server --> PubSub[Pub/Sub Engine]
    PubSub --> Event[External Event]
    Event --> PubSub
    PubSub --> Server
    Server -->|Push Data| Client

Teacher Mindset

Subscriptions follow an event-based programming model. The subscription resolver specifies which events to listen for. When an event fires, the associated payload is sent to all subscribers. The client must handle connection drops and reconnection.

Code Examples

# Example 1: Subscription definition
type Subscription {
  bookAdded: Book!
  bookRatingChanged(bookId: ID!): Book
  notificationReceived(userId: ID!): Notification!
}
// Example 2: Server-side pub/sub with EventEmitter
const { PubSub } = require('graphql-subscriptions');
const pubsub = new PubSub();

const resolvers = {
  Subscription: {
    bookAdded: {
      subscribe: () => pubsub.asyncIterator(['BOOK_ADDED'])
    }
  },
  Mutation: {
    createBook: async (_, { input }) => {
      const book = await db.insertBook(input);
      pubsub.publish('BOOK_ADDED', { bookAdded: book });
      return book;
    }
  }
};
// Example 3: Client-side subscription with Apollo Client
import { gql, useSubscription } from '@apollo/client';

const BOOK_ADDED = gql`
  subscription OnBookAdded {
    bookAdded {
      id
      title
      author { name }
    }
  }
`;

function LatestBook() {
  const { data, loading } = useSubscription(BOOK_ADDED);
  return <div>{data?.bookAdded?.title}</div>;
}

Common Mistakes

  • Using subscriptions for one-off data fetches instead of queries
  • Not handling reconnection and subscription re-establishment on the client
  • Publishing events without filtering for the intended recipients
  • Sending too much data per event, overwhelming WebSocket connections
  • Forgetting to unsubscribe when components unmount on the client

Practice

  1. Define a subscription for when a new comment is added to a post.
  2. Implement a pub/sub system that publishes order status updates.
  3. Write a client-side subscription that shows live stock price changes.
  4. Add filtering so users only receive notifications intended for them.
  5. Challenge: Build a real-time chat using subscriptions where each room has its own event channel.

FAQ

How do subscriptions work under the hood?

Subscriptions typically use WebSocket transport. The client sends a subscription query over WebSocket, and the server pushes data as events occur.

What is the difference between subscriptions and queries?

Queries return data once immediately. Subscriptions maintain an open connection and push data over time. Queries use HTTP, subscriptions use WebSocket.

Can I use subscriptions with serverless?

Serverless functions have limited support for persistent connections. Use services like AWS AppSync or Azure Functions with SignalR for serverless subscriptions.

How do I handle authentication for subscriptions?

Authenticate during the WebSocket upgrade handshake using connection params. Verify the token in the onConnect callback before establishing the subscription.

What is the payload size limit for subscriptions?

Subscription payloads are limited by WebSocket message size (typically 1MB). Keep payloads small and send notifications rather than full data objects.

Mini Project

Add subscriptions to your e-commerce schema: orderStatusChanged for real-time order tracking, newProductAlert for admin notifications when products are added, and lowStockWarning when inventory drops below a threshold.

What's Next

Next, you will learn about resolvers: how to implement the functions that fetch data for each field in your schema.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro