Subscriptions in GraphQL — Complete Guide
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
- Define a subscription for when a new comment is added to a post.
- Implement a pub/sub system that publishes order status updates.
- Write a client-side subscription that shows live stock price changes.
- Add filtering so users only receive notifications intended for them.
- Challenge: Build a real-time chat using subscriptions where each room has its own event channel.
FAQ
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