API Fundamentals
/Advanced
GraphQL Subscriptions
Definition
A GraphQL feature that allows the server to push real-time updates to the client. It maintains a persistent connection (usually WebSockets) rather than a typical request-response cycle.
Explain Like I'm New
A Query is asking 'Did I get any new messages?' (You have to keep asking). A Subscription is giving the server your phone number and saying 'Call me instantly the second a new message arrives.'
Real World Example
A live sports score app. Instead of the phone refreshing every 5 seconds, the app creates a Subscription for `matchScore(id: 123)`. Whenever the backend updates the score in the database, it instantly pushes the new score down the WebSocket to the phone.
Common Use Cases
- •Real-time chat apps
- •Live dashboards
- •Notifications
Terminal Output
bash / terminal
/*
GraphQL Subscription Example
*/
subscription OnNewMessageReceived($roomId: ID!) {
# This block will execute and push data to the client
# EVERY TIME a new message is added to this room!
messageAdded(roomId: $roomId) {
id
text
sender {
username
}
timestamp
}
}
// In a React app using Apollo Client, this would automatically
// trigger a UI re-render the millisecond someone types a message.
Interview Questions
basic
- What underlying network protocol do GraphQL Subscriptions typically use to maintain a live connection?
intermediate
- How does a Subscription differ from a standard Query?