0
0
GraphqlConceptBeginner · 3 min read

What is Subscription in GraphQL: Real-Time Data Explained

In GraphQL, a 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.

graphql
subscription OnNewMessage {
  newMessage {
    id
    content
    sender
  }
}
Output
{ "data": { "newMessage": { "id": "123", "content": "Hello!", "sender": "Alice" } } }
🎯

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.

Key Takeaways

GraphQL subscriptions provide real-time data updates by keeping a connection open.
They are perfect for apps needing live information like chats or notifications.
Subscriptions use protocols like WebSocket to push data instantly from server to client.
Unlike queries, subscriptions do not require repeated requests for new data.