Course contentsShow
← System Design
Lesson 1915 of 1,91945. API Design and VersioningFree lesson

GraphQL Subscriptions for Real-Time Data

Implementing persistent connections for push-based updates using GraphQL subscriptions over WebSockets.

GraphQL Subscriptions for Real-Time Data

What you'll learn: How to implement persistent connections for push-based real-time updates using GraphQL subscriptions over WebSockets.

The Problem with Polling

With standard GraphQL queries (or REST), clients must repeatedly poll the server to check for new data. This wastes bandwidth, adds latency, and doesn't scale well when thousands of clients want real-time updates.

How GraphQL Subscriptions Work

GraphQL subscriptions establish a persistent, bidirectional connection between client and server—typically using WebSockets. Instead of the client asking "anything new?" every second, the server pushes updates automatically when data changes.

Think of it like subscribing to a YouTube channel: instead of checking manually every day for new videos, you get a notification pushed to you instantly when one appears.

Subscription Definition

In your GraphQL schema, subscriptions are defined alongside queries and mutations:

type Subscription {
  messageAdded(channelId: ID!): Message
  orderStatusChanged(orderId: ID!): Order
}

When a client subscribes, they open a WebSocket connection and register interest in specific events. The server maintains this connection and streams updates as they occur.

Architecture Pattern

  1. Client initiates: Opens WebSocket, sends subscription request
  2. Server registers: Maps subscription to event stream (e.g., Redis pub/sub, message queue)
  3. Event occurs: Backend mutation triggers event
  4. Server pushes: Resolver sends update through WebSocket to all subscribed clients
  5. Connection persists: Stays open until client disconnects or unsubscribes

This complements your existing resolver architecture—mutations trigger events, subscriptions deliver them.

Key Takeaway: GraphQL subscriptions enable efficient real-time data delivery by maintaining persistent WebSocket connections that push updates from server to client, eliminating the need for wasteful polling while building on your existing schema and resolver patterns.