Customize CDC subscriptions

This is the documentation of the GraphQL Library version 6. For the long-term support (LTS) version 5, refer to GraphQL Library version 5 LTS.

GraphQL subscriptions to Neo4j use Change Data Capture (CDC). Its behavior can be configured by passing an instance of Neo4jGraphQLSubscriptionsCDCEngine.

Neo4jGraphQLSubscriptionsCDCEngine

By default, the GraphQL library uses the same driver passed to Neo4jGraphQL to poll for events every second. This behavior can be changed by creating a custom instance of Neo4jGraphQLSubscriptionsCDCEngine.

The following options can be passed to the constructor:

  • driver: The driver to be used for CDC queries.

  • pollTime: The interval, in milliseconds, between queries to CDC. Defaults to 1000ms. Note that poll time is the period between a finished request and the start of the next. The actual time it takes for CDC events to trigger the subscription also depends on your network.

  • queryConfig: An object with the driver query options to be passed to CDC requests. Use the db field to define the target database for CDC.

For example:

import { Neo4jGraphQL, Neo4jGraphQLSubscriptionsCDCEngine } from '@neo4j/graphql';

const engine = new Neo4jGraphQLSubscriptionsCDCEngine({
    driver,
    pollTime: 5000
})

const neoSchema = new Neo4jGraphQL({
    typeDefs,
    driver,
    features: {
        subscriptions: engine,
        queryConfig: {
             database: "neo4j",
        }
    },
});

Listen to subscription events

The class Neo4jGraphQLSubscriptionsCDCEngine exposes the events property, an instance of EventEmitter, which emits an event for each CDC event. This is useful for scenarios such as forwarding CDC events to an external queue for processing.

It is generally recommended to use CDC directly, outside of the GraphQL library, for event listening.

To listen to GraphQL subscription events, use the .on method on the events property:

engine.events.on("create", (payload) => {
    console.log("Node Created!", payload)
});

The following CDC-triggered events can be listened to:

  • create: A node has been created.

  • update: A node has been updated.

  • delete: A node has been deleted.

Event payload

Each event includes a JSON payload with event details:

  • event: The event type, matching the listener event name.

  • typename: The GraphQL type name.

  • properties: Contains old and new objects representing node properties before and after the mutation. These may be undefined if the node did not exist before or after the mutation.

  • id: The node ID (not exposed through the GraphQL API).

  • timestamp: The timestamp of the mutation that triggered the event.

For example, a node creation event would look like this:

{
    event: 'create',
    typename: 'Movie',
    properties: { old: undefined, new: { title: 'The Matrix' } },
    id: '4:70bade62-2121-4808-9348-3ab77859e164:510',
    timestamp: 1739286926054
}