What is Subscription in GraphQL: Real-Time Data Explained
subscription is a way to get real-time updates from the server. It keeps a connection open so the server can send new data instantly when something changes, unlike queries that fetch data once.How It Works
Think of a GraphQL subscription like a live radio broadcast. Instead of calling the station every time you want to hear a song, you tune in once and listen as new songs play. Similarly, a subscription opens a continuous connection between your app and the server.
This connection uses a protocol like WebSocket, allowing the server to push updates immediately when data changes. Your app listens and reacts to these updates without asking repeatedly.
This is different from a query, which is like calling a restaurant to ask if your order is ready — you get an answer once and then hang up. Subscriptions keep the line open for ongoing updates.
Example
This example shows a simple GraphQL subscription that listens for new messages in a chat app.
subscription OnNewMessage {
newMessage {
id
content
sender
}
}When to Use
Use GraphQL subscriptions when your app needs to show live data updates without the user refreshing or asking again. Common cases include:
- Chat applications showing new messages instantly
- Live sports scores or stock prices updating in real time
- Notifications or alerts that appear as soon as they happen
Subscriptions improve user experience by delivering fresh data automatically.
Key Points
- Subscriptions keep a connection open for real-time data.
- They use WebSocket or similar protocols for pushing updates.
- Ideal for live feeds like chat, notifications, or live scores.
- Different from queries that fetch data once.