๐
GraphQL Subscription
Real-time Events Based on GraphQL Schema
GraphQL Subscription is the third operation type in GraphQL alongside Query and Mutation. It uses WebSocket as its transport internally, and through the type system defined in the GraphQL schema, you can declaratively specify which events to subscribe to and which fields to receive.
Architecture Diagram
๐
Client
subscription {
messageAdded {
id
text
}
}
messageAdded {
id
text
}
}
โ subscription query
→
WebSocket
←
โฃ data push
๐ฅ๏ธ
GraphQL Server
โก register subscription
โข Mutation triggered
←
โ๏ธ
Mutation
Data change trigger
Flow Description
- Client sends subscription query (WebSocket connection)
- Server registers subscription for the event
- Another client/system changes data via Mutation
- Server pushes to subscribed clients in GraphQL format
How It Works
1
Client sends subscription query to server (WebSocket connection)
2
Server registers subscription for the event
3
Data change (Mutation) occurs on the server side
4
Server pushes data in GraphQL format to subscribed clients
Pros
- ✓ Type-safe real-time communication
- ✓ Selective subscription of only needed fields
- ✓ Integration with existing GraphQL schema
- ✓ Consistent development experience with Query/Mutation
Cons
- ✗ Additional abstraction layer on top of WebSocket
- ✗ High server implementation complexity
- ✗ Potential N+1 subscription problem
- ✗ Pub/Sub backend needed for scaling
Use Cases
Real-time comments/notifications
Order status tracking
Real-time sync in collaboration tools
GitHub's GraphQL API