Debezium Format

Changelog-Data-Capture Format Format: Serialization Schema Format: Deserialization Schema

Debezium is a CDC (Changelog Data Capture) tool that can stream changes in real-time from MySQL, PostgreSQL, Oracle, Microsoft SQL Server and many other databases into Kafka. Debezium provides a unified format schema for changelog and supports to serialize messages using JSON and Apache Avro.

Flink supports to interpret Debezium JSON and Avro messages as INSERT/UPDATE/DELETE messages into Flink SQL system. This is useful in many cases to leverage this feature, such as

  • synchronizing incremental data from databases to other systems
  • auditing logs
  • real-time materialized views on databases
  • temporal join changing history of a database table and so on.

Flink also supports to encode the INSERT/UPDATE/DELETE messages in Flink SQL as Debezium JSON or Avro messages, and emit to external systems like Kafka. However, currently Flink can’t combine UPDATE_BEFORE and UPDATE_AFTER into a single UPDATE message. Therefore, Flink encodes UPDATE_BEFORE and UDPATE_AFTER as DELETE and INSERT Debezium messages.

Dependencies

Debezium Avro

In order to use the Debezium format the following dependencies are required for both projects using a build automation tool (such as Maven or SBT) and SQL Client with SQL JAR bundles.

Maven dependencySQL Client
  1. <dependency>
  2. <groupId>org.apache.flink</groupId>
  3. <artifactId>flink-avro-confluent-registry</artifactId>
  4. <version>1.18.1</version>
  5. </dependency>
Copied to clipboard!
Download

Debezium Json

In order to use the Debezium format the following dependencies are required for both projects using a build automation tool (such as Maven or SBT) and SQL Client with SQL JAR bundles.

Maven dependencySQL Client
  1. <dependency>
  2. <groupId>org.apache.flink</groupId>
  3. <artifactId>flink-json</artifactId>
  4. <version>1.18.1</version>
  5. </dependency>
Copied to clipboard!
Built-in

Note: please refer to Debezium documentation about how to setup a Debezium Kafka Connect to synchronize changelog to Kafka topics.

How to use Debezium format

Debezium provides a unified format for changelog, here is a simple example for an update operation captured from a MySQL products table in JSON format:

  1. {
  2. "before": {
  3. "id": 111,
  4. "name": "scooter",
  5. "description": "Big 2-wheel scooter",
  6. "weight": 5.18
  7. },
  8. "after": {
  9. "id": 111,
  10. "name": "scooter",
  11. "description": "Big 2-wheel scooter",
  12. "weight": 5.15
  13. },
  14. "source": {...},
  15. "op": "u",
  16. "ts_ms": 1589362330904,
  17. "transaction": null
  18. }

Note: please refer to Debezium documentation about the meaning of each fields.

The MySQL products table has 4 columns (id, name, description and weight). The above JSON message is an update change event on the products table where the weight value of the row with id = 111 is changed from 5.18 to 5.15. Assuming this messages is synchronized to Kafka topic products_binlog, then we can use the following DDL to consume this topic and interpret the change events.

  1. CREATE TABLE topic_products (
  2. -- schema is totally the same to the MySQL "products" table
  3. id BIGINT,
  4. name STRING,
  5. description STRING,
  6. weight DECIMAL(10, 2)
  7. ) WITH (
  8. 'connector' = 'kafka',
  9. 'topic' = 'products_binlog',
  10. 'properties.bootstrap.servers' = 'localhost:9092',
  11. 'properties.group.id' = 'testGroup',
  12. -- using 'debezium-json' as the format to interpret Debezium JSON messages
  13. -- please use 'debezium-avro-confluent' if Debezium encodes messages in Avro format
  14. 'format' = 'debezium-json'
  15. )

In some cases, users may setup the Debezium Kafka Connect with the Kafka configuration 'value.converter.schemas.enable' enabled to include schema in the message. Then the Debezium JSON message may look like this:

  1. {
  2. "schema": {...},
  3. "payload": {
  4. "before": {
  5. "id": 111,
  6. "name": "scooter",
  7. "description": "Big 2-wheel scooter",
  8. "weight": 5.18
  9. },
  10. "after": {
  11. "id": 111,
  12. "name": "scooter",
  13. "description": "Big 2-wheel scooter",
  14. "weight": 5.15
  15. },
  16. "source": {...},
  17. "op": "u",
  18. "ts_ms": 1589362330904,
  19. "transaction": null
  20. }
  21. }

In order to interpret such messages, you need to add the option 'debezium-json.schema-include' = 'true' into above DDL WITH clause (false by default). Usually, this is not recommended to include schema because this makes the messages very verbose and reduces parsing performance.

After registering the topic as a Flink table, then you can consume the Debezium messages as a changelog source.

  1. -- a real-time materialized view on the MySQL "products"
  2. -- which calculate the latest average of weight for the same products
  3. SELECT name, AVG(weight) FROM topic_products GROUP BY name;
  4. -- synchronize all the data and incremental changes of MySQL "products" table to
  5. -- Elasticsearch "products" index for future searching
  6. INSERT INTO elasticsearch_products
  7. SELECT * FROM topic_products;

Available Metadata

The following format metadata can be exposed as read-only (VIRTUAL) columns in a table definition.

Attention Format metadata fields are only available if the corresponding connector forwards format metadata. Currently, only the Kafka connector is able to expose metadata fields for its value format.

KeyData TypeDescription
schemaSTRING NULLJSON string describing the schema of the payload. Null if the schema is not included in the Debezium record.
ingestion-timestampTIMESTAMP_LTZ(3) NULLThe timestamp at which the connector processed the event. Corresponds to the ts_ms field in the Debezium record.
source.timestampTIMESTAMP_LTZ(3) NULLThe timestamp at which the source system created the event. Corresponds to the source.ts_ms field in the Debezium record.
source.databaseSTRING NULLThe originating database. Corresponds to the source.db field in the Debezium record if available.
source.schemaSTRING NULLThe originating database schema. Corresponds to the source.schema field in the Debezium record if available.
source.tableSTRING NULLThe originating database table. Corresponds to the source.table or source.collection field in the Debezium record if available.
source.propertiesMAP<STRING, STRING> NULLMap of various source properties. Corresponds to the source field in the Debezium record.

The following example shows how to access Debezium metadata fields in Kafka:

  1. CREATE TABLE KafkaTable (
  2. origin_ts TIMESTAMP(3) METADATA FROM 'value.ingestion-timestamp' VIRTUAL,
  3. event_time TIMESTAMP(3) METADATA FROM 'value.source.timestamp' VIRTUAL,
  4. origin_database STRING METADATA FROM 'value.source.database' VIRTUAL,
  5. origin_schema STRING METADATA FROM 'value.source.schema' VIRTUAL,
  6. origin_table STRING METADATA FROM 'value.source.table' VIRTUAL,
  7. origin_properties MAP<STRING, STRING> METADATA FROM 'value.source.properties' VIRTUAL,
  8. user_id BIGINT,
  9. item_id BIGINT,
  10. behavior STRING
  11. ) WITH (
  12. 'connector' = 'kafka',
  13. 'topic' = 'user_behavior',
  14. 'properties.bootstrap.servers' = 'localhost:9092',
  15. 'properties.group.id' = 'testGroup',
  16. 'scan.startup.mode' = 'earliest-offset',
  17. 'value.format' = 'debezium-json'
  18. );

Format Options

Flink provides debezium-avro-confluent and debezium-json formats to interpret Avro or Json messages produced by Debezium. Use format debezium-avro-confluent to interpret Debezium Avro messages and format debezium-json to interpret Debezium Json messages.

Debezium Avro

OptionRequiredDefaultTypeDescription
format
required(none)StringSpecify what format to use, here should be ‘debezium-avro-confluent’.
debezium-avro-confluent.basic-auth.credentials-source
optional(none)StringBasic auth credentials source for Schema Registry
debezium-avro-confluent.basic-auth.user-info
optional(none)StringBasic auth user info for schema registry
debezium-avro-confluent.bearer-auth.credentials-source
optional(none)StringBearer auth credentials source for Schema Registry
debezium-avro-confluent.bearer-auth.token
optional(none)StringBearer auth token for Schema Registry
debezium-avro-confluent.properties
optional(none)MapProperties map that is forwarded to the underlying Schema Registry. This is useful for options that are not officially exposed via Flink config options. However, note that Flink options have higher precedence.
debezium-avro-confluent.ssl.keystore.location
optional(none)StringLocation / File of SSL keystore
debezium-avro-confluent.ssl.keystore.password
optional(none)StringPassword for SSL keystore
debezium-avro-confluent.ssl.truststore.location
optional(none)StringLocation / File of SSL truststore
debezium-avro-confluent.ssl.truststore.password
optional(none)StringPassword for SSL truststore
debezium-avro-confluent.schema
optional(none)StringThe schema registered or to be registered in the Confluent Schema Registry. If no schema is provided Flink converts the table schema to avro schema. The schema provided must match the Debezium schema which is a nullable record type including fields ‘before’, ‘after’, ‘op’.
debezium-avro-confluent.subject
optional(none)StringThe Confluent Schema Registry subject under which to register the schema used by this format during serialization. By default, ‘kafka’ and ‘upsert-kafka’ connectors use ‘<topic_name>-value’ or ‘<topic_name>-key’ as the default subject name if this format is used as the value or key format. But for other connectors (e.g. ‘filesystem’), the subject option is required when used as sink.
debezium-avro-confluent.url
required(none)StringThe URL of the Confluent Schema Registry to fetch/register schemas.

Debezium Json

OptionRequiredDefaultTypeDescription
format
required(none)StringSpecify what format to use, here should be ‘debezium-json’.
debezium-json.schema-include
optionalfalseBooleanWhen setting up a Debezium Kafka Connect, users may enable a Kafka configuration ‘value.converter.schemas.enable’ to include schema in the message. This option indicates whether the Debezium JSON message includes the schema or not.
debezium-json.ignore-parse-errors
optionalfalseBooleanSkip fields and rows with parse errors instead of failing. Fields are set to null in case of errors.
debezium-json.timestamp-format.standard
optional‘SQL’StringSpecify the input and output timestamp format. Currently supported values are ‘SQL’ and ‘ISO-8601’:
  • Option ‘SQL’ will parse input timestamp in “yyyy-MM-dd HH:mm:ss.s{precision}” format, e.g ‘2020-12-30 12:13:14.123’ and output timestamp in the same format.
  • Option ‘ISO-8601’will parse input timestamp in “yyyy-MM-ddTHH:mm:ss.s{precision}” format, e.g ‘2020-12-30T12:13:14.123’ and output timestamp in the same format.
debezium-json.map-null-key.mode
optional‘FAIL’StringSpecify the handling mode when serializing null keys for map data. Currently supported values are ‘FAIL’, ‘DROP’ and ‘LITERAL’:
  • Option ‘FAIL’ will throw exception when encountering map with null key.
  • Option ‘DROP’ will drop null key entries for map data.
  • Option ‘LITERAL’ will replace null key with string literal. The string literal is defined by debezium-json.map-null-key.literal option.
debezium-json.map-null-key.literal
optional‘null’StringSpecify string literal to replace null key when ‘debezium-json.map-null-key.mode’ is LITERAL.
debezium-json.encode.decimal-as-plain-number
optionalfalseBooleanEncode all decimals as plain numbers instead of possible scientific notations. By default, decimals may be written using scientific notation. For example, 0.000000027 is encoded as 2.7E-8 by default, and will be written as 0.000000027 if set this option to true.

Caveats

Duplicate change events

Under normal operating scenarios, the Debezium application delivers every change event exactly-once. Flink works pretty well when consuming Debezium produced events in this situation. However, Debezium application works in at-least-once delivery if any failover happens. See more details about delivery guarantee from Debezium documentation. That means, in the abnormal situations, Debezium may deliver duplicate change events to Kafka and Flink will get the duplicate events. This may cause Flink query to get wrong results or unexpected exceptions. Thus, it is recommended to set job configuration table.exec.source.cdc-events-duplicate to true and define PRIMARY KEY on the source in this situation. Framework will generate an additional stateful operator, and use the primary key to deduplicate the change events and produce a normalized changelog stream.

Consuming data produced by Debezium Postgres Connector

If you are using Debezium Connector for PostgreSQL to capture the changes to Kafka, please make sure the REPLICA IDENTITY configuration of the monitored PostgreSQL table has been set to FULL which is by default DEFAULT. Otherwise, Flink SQL currently will fail to interpret the Debezium data.

In FULL strategy, the UPDATE and DELETE events will contain the previous values of all the table’s columns. In other strategies, the “before” field of UPDATE and DELETE events will only contain primary key columns or null if no primary key. You can change the REPLICA IDENTITY by running ALTER TABLE <your-table-name> REPLICA IDENTITY FULL. See more details in Debezium Documentation for PostgreSQL REPLICA IDENTITY.

Data Type Mapping

Currently, the Debezium format uses JSON and Avro format for serialization and deserialization. Please refer to JSON Format documentation and [Confluent Avro Format documentation]({< ref “docs/connectors/table/formats/avro-confluent” >}}#data-type-mapping) for more details about the data type mapping.