0
0
GraphqlConceptBeginner · 3 min read

When to Use Subscription in GraphQL: Real-Time Data Explained

Use subscription in GraphQL when you need real-time updates from the server to the client. It keeps a live connection open to push data instantly, unlike queries that fetch data once. This is ideal for live feeds, notifications, or any data that changes frequently.
⚙️

How It Works

Think of a subscription like a live phone call between your app and the server. Instead of asking for information once and hanging up, your app stays connected and listens for new data. When the server has an update, it speaks immediately, and your app hears it right away.

This is different from a normal query, which is like sending a letter and waiting for a reply. Subscriptions use a special connection (usually WebSocket) that stays open, so updates flow instantly without asking again.

💻

Example

This example shows a GraphQL subscription that listens for new messages in a chat app. When a new message arrives, the server sends it to the client immediately.

graphql
subscription {
  newMessage {
    id
    content
    sender
    timestamp
  }
}
Output
{ "data": { "newMessage": { "id": "123", "content": "Hello!", "sender": "Alice", "timestamp": "2024-06-01T12:00:00Z" } } }
🎯

When to Use

Use subscription when your app needs to show data that changes often without the user refreshing or asking again. Common cases include:

  • Live chat messages or comments
  • Real-time notifications or alerts
  • Stock prices or sports scores updating live
  • Collaborative editing where multiple users see changes instantly

If your data updates rarely or can be fetched on demand, a simple query or mutation is enough.

Key Points

  • Subscriptions keep a live connection open to push updates instantly.
  • They are best for real-time data that changes frequently.
  • Use them for live chats, notifications, and dynamic feeds.
  • They require WebSocket or similar protocols to work.
  • Not suitable for one-time data fetches; use queries instead.

Key Takeaways

Use GraphQL subscriptions to get real-time updates from the server.
Subscriptions keep a live connection open, unlike queries that fetch once.
Ideal for live chats, notifications, and any frequently changing data.
They require WebSocket or similar technology to maintain the connection.
For static or rarely changing data, use queries instead of subscriptions.