HomeBytesheetsRoadmapsUI TemplatesUI ToolsStack Discussion
9 Topics
Chapter•90 Minutes

Subscriptions & Real-Time GraphQL

Build real-time GraphQL features using subscriptions, understand WebSocket-based transport, event publishing, authorization, scaling, and production considerations.

What Are GraphQL Subscriptions?

Queries retrieve data and mutations change data. Subscriptions allow a client to receive data when a relevant event occurs.

A subscription is useful for features such as chat messages, live notifications, collaborative editing, order-status updates, dashboards, and real-time monitoring.

Unlike a normal request-response query, a subscription represents a long-lived relationship between a client and the server.

How Subscription Transport Works

GraphQL subscriptions commonly use a persistent transport such as WebSockets. The client establishes a connection and subscribes to one or more events. When an event is published, the server sends the corresponding GraphQL payload to subscribed clients.

The GraphQL subscription defines the shape of the data delivered to the client, while the underlying transport is responsible for maintaining communication.

Defining Subscription Fields

A subscription is declared in the GraphQL schema similarly to query and mutation root fields. The field represents an event stream rather than a single request.

For example, a messaging application might expose messageAdded, allowing clients to subscribe to new messages for a particular conversation.

Publish and Subscribe Architecture

A GraphQL subscription system usually separates event production from event delivery. Application code publishes an event when something meaningful happens. Subscription infrastructure then determines which connected clients should receive the event.

For a single server instance, an in-memory event mechanism may be sufficient for development. Production systems with multiple instances generally require a shared event or messaging infrastructure.

Subscription Resolver Example

A subscription resolver commonly connects a GraphQL subscription field to an event source. The exact implementation depends on the GraphQL server and subscription transport being used.

Subscription Schema and Resolver
const typeDefs = `
  type Message {
    id: ID!
    text: String!
  }

  type Subscription {
    messageAdded: Message!
  }
`;

const resolvers = {
  Subscription: {
    messageAdded: {
      subscribe: () => pubsub.asyncIterator(["MESSAGE_ADDED"])
    }
  }
};

await pubsub.publish("MESSAGE_ADDED", {
  messageAdded: newMessage
});
💡 The subscription resolver connects clients to an event source, while application code publishes a payload when a new message is created. Production implementations may use a distributed event system rather than an in-memory publisher.

Authenticating Subscription Connections

Subscription connections must be authenticated just like normal GraphQL operations. Authentication information may be supplied during the connection handshake or through the supported connection parameters of the transport library.

Authorization should also be evaluated when determining whether a client is allowed to subscribe to a particular resource. For example, a user should not receive messages from a private conversation simply because they know its ID.

Scaling Subscriptions Across Multiple Servers

A single-process subscription implementation becomes insufficient when clients are distributed across multiple application instances. One server may receive an event while the interested client is connected to another server.

A shared broker such as Redis, Kafka, or another messaging system can distribute events across instances. Load balancing and connection affinity may also matter depending on the subscription architecture.

Reconnects, Missed Events and Reliability

Real-time connections can fail because of network changes, browser sleep, server restarts, proxies, or temporary outages. A robust client should be prepared to reconnect.

Reconnection alone does not guarantee that no events are lost. If an application requires reliable event delivery, it may need event IDs, replay mechanisms, persisted events, or a query-based synchronization step after reconnecting.

Check Your Understanding

Test your understanding of GraphQL subscriptions.

Knowledge Check

Why can an in-memory subscription event system become problematic when an application is horizontally scaled?