About Change Data Capture (CDC) workflows with Apache Cassandra® and Apache Pulsar™
Change Data Capture (CDC) is a design pattern used in software development to capture and propagate changes made to data in a system. The CDC pattern is commonly used in real-time data streaming applications to enable near-real-time processing of data changes. In a typical CDC implementation, a change to a row of data (insert, update, delete) is detected and recorded. The change (or mutation) is made available to downstream systems as an event for further processing. This allows applications to react quickly to changes in the data while not adding unneeded load on the data store, enabling real-time data processing and analytics.
Before learning the specifics of CDC, you must first understand the components needed to complete a CDC workflow.
Apache Pulsar™ source connectors
Source connectors in Apache Pulsar are responsible for ingesting data from external sources into the Pulsar system. They can be used to collect data from a variety of sources including databases, message queues, and file systems. When the source connector "sees" data, it streams the data to a Pulsar topic. This enables users to easily integrate data from disparate sources into their Pulsar-based applications. Source connectors make it easy to ingest, process, and analyze large volumes of data from a variety of sources into Pulsar.
Pulsar offers extensible APIs where developers can use a defined interface to develop their own connector. The interface takes much of the boilerplate burdens away from a developer and gets them right to the purpose of the connector. Creating a connector means adding in the know-how to work with data from the source and adapt it to produce a compliant message with the Pulsar client.
As explained later in this guide, among the processes needed to capture change data, the DataStax Cassandra Source Connector for Apache Pulsar™ (CSC for Pulsar) is critical. This is one of many available source connectors for Pulsar, but is specifically designed to work with Cassandra and its CDC features.
To run a source connector, you provide configuration about what data is selected, how to connect with the upstream system, and the destination topic for the new message. The source connector takes care of producing the message. Pulsar source connectors run as Pulsar functions within the cluster, so many of the features of functions apply, such as the number of instances to run and how to configure the function instance running environment. Metrics and logs for a source connector are automatically made a part of the cluster.
Monitor source connectors
Monitoring a source connector includes two areas: health and performance. Every connector in Pulsar emits basic metrics about its health, including stats like the number of records received from the source, and the number of messages written to the destination topic. Connectors also emit debugging metrics like the number of exceptions thrown by the source. Performance metrics include health metrics as well as specific knowledge about the source. Refer to the Pulsar connectors metrics documentation for a complete list and explanation of metrics.
Source connector logs
Most Pulsar source connectors emit logs that show lifecycle events as well as custom events specific to the connector type. All logs are handled the same way core cluster logs are handled. By default, they are written to the console and collected by log4j destinations. If you are using function workers, you can access log files on their disk. Refer to Pulsar’s connector debugging guide for more information.
Pulsar schemas and the schema registry
The Apache Pulsar schema registry is a feature of a Pulsar cluster that manages the schemas of messages sent and received on Pulsar topics. In Pulsar, messages are stored as bytes. Schemas provide a way to serialize and deserialize messages with a particular structure or type, allowing for interoperability between different systems.
The schema registry in Pulsar stores and manages schema definitions for all message types sent and received in Pulsar. The schema registry enforces schema compatibility rules, such as requiring a producer to send messages that conform to a certain schema, or rejecting messages that don’t match the schema.
Schemas follow a primitive or complex type. Primitive schemas are simple data types like bool, int, string, and float. Because Pulsar is written in Java, that is where the primitives are based. When a different client runtime is used, a conversion might need to occur. Refer to the Pulsar primitive types table for a full reference.
Complex schemas introduce a more structured way of messaging. The two types of complex messages are KeyValue and Struct. KeyValue is JSON formatted text that offers a separation of custom labels and their values. Struct is a custom class definition set as Avro, Json, or Protobuf.
KeyValue offers an interesting way to encode a message called "Separated". This option separates a message key and the message payload. This in turn has the option to store message key information as a different data type than the message payload. It also offers special compression capabilities. CDC takes advantage of separating KeyValue messages when it produces both the event and data topic.
Namespace schema configurations
In the context of CDC there are a few schema configurations of note. All of these are specific to the namespace where the event and data topics are logically located.
- schema-compatibility-strategy
-
This setting instructs the Pulsar broker how to handle new schemas introduced to existing topics by producers. This is relevant to CDC when a table’s design is changed. For example, if a new column is added, the registered schema is changed to include that new value. The chosen schema-compatibility-strategy decides if the namespace allows this. If schema validations are enabled, this option decides what strategy is used. Pulsar’s default strategy is "FULL" which means existing optional table columns can be modified. Learn more about the different types of strategies in the Pulsar docs.
- allow-auto-update-schema
-
Given the compatibility strategy, this setting is a flag that determines if an update to the schema is generally allowed. CDC sets this to
trueso changes in a table’s design can automatically propagate to the topic. - schema-autoupdate-strategy
-
When auto update is enabled (set to
true) this setting directs the Broker how to ensure consumers of a topic are able to process messages. If a consumer attempts to connect with a schema that doesn’t match the current schema, this strategy decides if it is allowed to receive messages. CDC sets this to 'BACKWARDTRANSITIVE', which means if optional table columns have been added or a column has been removed, the old schema is allowed. - schema-validation-enforce
-
This flag limits how producers and consumers are allowed to be configured. When enabled (
true) producer and consumer clients must have a schema set before sending the message. When disabled (false) Pulsar allows producers and consumers without a set schema to send or receive messages. CDC disables (false) this option, so producers and consumers don’t have to know the message schema ahead of time.
The DataStax Change Agent for Apache Cassandra® and DataStax Cassandra Source Connector for Apache Pulsar™
The Change Agent for Cassandra is a process running on each node in a Cassandra cluster that watches for data changes on tables that have enabled the CDC feature. Using Cassandra’s commitlog_sync option, the agent periodically syncs a separate log in a special "cdc_raw" directory. Each log entry is a CDC event. The Change Agent for Cassandra creates a new event message containing the row coordinates of the changed data and produces the message to a downstream Pulsar cluster.
In Pulsar, each table that has CDC enabled also has a corresponding DataStax CSC for Pulsar. This is unlike the Change Agent for Cassandra where the process runs on each Cassandra node, keeping a log of all table changes. Each table-specific Cassandra source connector subscribes to the events topic the agent is producing messages to. When the connector "sees" a message for its table, it uses the row coordinates within the message to retrieve the mutated data from Cassandra and create a new message with the specifics. That new message is written to a data topic where others can subscribe and receive CDC messages.
Event deduplication
A particular advantage in the DataStax CSC for Pulsar is its deduplication feature. Pulsar’s built-in deduplication capabilities aren’t used in the message flow because CDC needs a finer grain control to detect duplicates. As the Change Agent for Cassandra discovers a new commit log, an authentic identifier is created using the MD5 hash algorithm. That key identifier is added to the event message.
When message consumers, like the DataStax CSC for Pulsar, connect to the event topic, they establish a subscription type. Pulsar has four types of subscriptions: Exclusive, shared, failover, and key_shared. In a typical CDC flow, the Cassandra source connector has multiple instances running in parallel. When multiple consumers are a part of a key_shared subscription, Pulsar delivers a duplicate hash key to the same consumer no matter how many times it’s sent.
When a Cassandra cluster has multiple hosts (with multiple commit logs), and they all use the same mutation to calculate the same hash key, then the same consumer always receives it. Each Cassandra source connector keeps a cache of hashes it has seen and ensures duplicates are dropped before producing the data message.
Learn more about Pulsar’s key_shared subscription type in the Pulsar documentation.
Understand the CDC workflow
Now that you understand the different components used in the CDC pattern, the following steps summarize a generic CDC workflow, including configuring the workflow and producing messages:
-
Create a Pulsar tenant to hold CDC messages with the following namespace and topics:
-
Create a namespace or use the default namespace.
-
Create a topic for event messages.
-
Create a topic for data messages.
-
-
Start the Cassandra source connector in Pulsar by setting the destination topic (the data messages topic), the event topic, and Cassandra connection info, along with other settings.
-
Configure the Cassandra change agent with a working directory, Pulsar service URL, and other settings in the Cassandra node. A restart is required.
-
Create a Cassandra table and enable CDC.
-
Insert a row of data into the table to produce messages.
From here the following sequence occurs:
-
The change agent detects a mutation to the table, and then it writes a log.
-
The log is converted to an event message, and then it is written to the events topic.
-
The source connector completes the flow by producing a final change message to the data topic.
-
Cassandra table schema evolution with CDC
This section describes how table schema changes are handled in the Apache Cassandra® Connector for Apache Pulsar™.
Message schema translation
The message schema is of particular importance in completing the CDC pattern. Initially, it is set to match the Cassandra table’s schema as closely as possible, but some data types aren’t known in Pulsar (or more accurately, not known in Avro). To overcome this, there are adaptations performed when the DataStax CSC for Pulsar builds the Pulsar message. Some types aren’t compatible and cannot be adapted. In this case, those columns of data are dropped while creating the Pulsar message.
To better understand how exactly the Change Agent for Cassandra constructs the event message, here is the pseudo code of how the schema is created:
org.apache.pulsar.common.schema.SchemaType.AVRO GenericRecord = all key fields in the Cassandra table
org.apache.cassandra.schema TableMetadata = convert a log entry to a mutation instance
Schema<KeyValue<byte[], MutationValue>> keyValueSchema = Schema.KeyValue(
(convert GenericRecord to byte[]),
(set TableMetadata to SchemaType.AVRO),
KeyValueEncodingType.SEPARATED
);
Notice the two types used in KeyValue. The byte array is an Avro-encoded record that documents the table’s primary key(s). The MutationValue is an extended Avro record that has direction on what changed and how to get its specifics.
CDC sets the initial topic schema on the first change it detects. Once the initial topic schema has been set, an ideal path has been established to create change data events in Pulsar.
Inevitably, table designs change: Columns are added, updated, or removed. When these changes occur, the components that are part of the CDC flow must adapt to preserve the ideal path of event data. This can become quite a complex set of decisions and as such, there are specific changes a CDC flow can tolerate before the flow needs to be recreated entirely.
Here is a summary of how the data message schema is created:
-
Receive GenericRecord event message of type KeyValue.
-
Use a Cassandra client to query for row data.
-
Convert data as GenericRecord of type KeyValue and return.
-
The connector interface produces a new message to the destination topic.
Add a table column
This is the easiest of scenarios for table design change.
Assuming the new column’s data type is compatible with the source connector, a new schema replaces the existing and message compatibility is retained.
Note that because the schema auto-update compatibility strategy is set to BACKWARD_TRANSITIVE, the new column must be optional, which is the default of any non-primary-key column.
For example:
ALTER TABLE [keyspace_name.] table_name ADD some-column text;
Update a table column
Altering a table column includes renaming a column or changing a column’s type. Assuming the new column’s data type is compatible with the source connector, a new schema replaces the existing schema and message compatibility is retained. Once a table has been created, a table’s primary key(s) cannot be modified. This fits well with the CDC pattern.
While technically updating columns is possible when CDC is enabled, it isn’t recommended. Instead, changes to a Cassandra table should be additive only. If you are familiar with data migrations, this concept is the same.
To change the name or type of table column, add a new column. The resulting event messages have a reference to both columns, and you can handle this migration downstream.
Note that this recommendation assumes a schema compatibility strategy of BACKWARD_TRANSITIVE.
If you are using a different schema compatibility strategy, table updates are handled differently.
Remove a table column
Removing a table column is a standard command in CQL. The resulting CDC data messages won’t include that data anymore.
For example:
ALTER TABLE [keyspace_name.] table_name DROP some-column;
Consume change data with Apache Pulsar™
This section describes how to consume change data with Apache Pulsar™.
Pulsar clients
Each client handles message consumption a little differently but there is one overall pattern to follow. As covered in the previous sections, a CDC message arrives as an Avro GenericRecord of type KeyValue. Typically, the first step is to separate the key and value portions of the message. You can find the Cassandra table’s key fields in the key of the record and the change data in the value portion of the record. Both of which are Avro records themselves. From there you’ll want to deserialize the Avro record and extract the interesting info.
The following example projects demonstrate implementations for each runtime consuming messages from a CDC data topic.
These examples are stored in the astra-streaming-examples repository, but they aren’t specific to Astra Streaming.
You can use these examples to consume CDC data topics in your own Cassandra/Pulsar clusters.
Pulsar functions
It is very common to have a function consuming the CDC data. Functions usually perform additional processing on the data and pass it to another topic. Similar to a client consumer, it needs to deserialize the message data.
The following example functions consume messages from the CDC data topic.
These examples are stored in the astra-streaming-examples repository, but they aren’t specific to Astra Streaming.
You can use these examples for functions for your own Cassandra/Pulsar clusters.