API Fundamentals Course
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?

Flash Cards

Question

Which protocol?

Click to reveal answer
Answer

WebSockets.

Question

Difference?

Click to reveal answer
Answer

A Query is a one-time HTTP request. The server answers and hangs up. A Subscription opens a permanent connection, and the server can send multiple answers over time whenever a specific event occurs.