Debezium connector for PostgreSQL

Overview

PostgreSQL’s logical decoding feature was introduced in version 9.4. It is a mechanism that allows the extraction of the changes that were committed to the transaction log and the processing of these changes in a user-friendly manner with the help of an output plug-in. The output plug-in enables clients to consume the changes.

The PostgreSQL connector contains two main parts that work together to read and process database changes:

  • A logical decoding output plug-in. You might need to install the output plug-in that you choose to use. You must configure a replication slot that uses your chosen output plug-in before running the PostgreSQL server. The plug-in can be one of the following:

    • decoderbufs is based on Protobuf and maintained by the Debezium community.

    • wal2json is based on JSON and maintained by the wal2json community.

    • pgoutput is the standard logical decoding output plug-in in PostgreSQL 10+. It is maintained by the PostgreSQL community, and used by PostgreSQL itself for logical replication. This plug-in is always present so no additional libraries need to be installed. The Debezium connector interprets the raw replication event stream directly into change events.

  • Java code (the actual Kafka Connect connector) that reads the changes produced by the chosen logical decoding output plug-in. It uses PostgreSQL’s streaming replication protocol, by means of the PostgreSQL JDBC driver

The connector produces a change event for every row-level insert, update, and delete operation that was captured and sends change event records for each table in a separate Kafka topic. Client applications read the Kafka topics that correspond to the database tables of interest, and can react to every row-level event they receive from those topics.

PostgreSQL normally purges write-ahead log (WAL) segments after some period of time. This means that the connector does not have the complete history of all changes that have been made to the database. Therefore, when the PostgreSQL connector first connects to a particular PostgreSQL database, it starts by performing a consistent snapshot of each of the database schemas. After the connector completes the snapshot, it continues streaming changes from the exact point at which the snapshot was made. This way, the connector starts with a consistent view of all of the data, and does not omit any changes that were made while the snapshot was being taken.

The connector is tolerant of failures. As the connector reads changes and produces events, it records the WAL position for each event. If the connector stops for any reason (including communication failures, network problems, or crashes), upon restart the connector continues reading the WAL where it last left off. This includes snapshots. If the connector stops during a snapshot, the connector begins a new snapshot when it restarts.

The connector relies on and reflects the PostgreSQL logical decoding feature, which has the following limitations:

  • Logical decoding does not support DDL changes. This means that the connector is unable to report DDL change events back to consumers.

  • Logical decoding replication slots are supported on only primary servers. When there is a cluster of PostgreSQL servers, the connector can run on only the active primary server. It cannot run on hot or warm standby replicas. If the primary server fails or is demoted, the connector stops. After the primary server has recovered, you can restart the connector. If a different PostgreSQL server has been promoted to primary, adjust the connector configuration before restarting the connector.

Behavior when things go wrong describes what the connector does when there is a problem.

Debezium currently supports databases with UTF-8 character encoding only. With a single byte character encoding, it is not possible to correctly process strings that contain extended ASCII code characters.

How the connector works

To optimally configure and run a Debezium PostgreSQL connector, it is helpful to understand how the connector performs snapshots, streams change events, determines Kafka topic names, and uses metadata.

Snapshots

Most PostgreSQL servers are configured to not retain the complete history of the database in the WAL segments. This means that the PostgreSQL connector would be unable to see the entire history of the database by reading only the WAL. Consequently, the first time that the connector starts, it performs an initial consistent snapshot of the database. The default behavior for performing a snapshot consists of the following steps. You can change this behavior by setting the snapshot.mode connector configuration property to a value other than initial.

  1. Start a transaction with a SERIALIZABLE, READ ONLY, DEFERRABLE isolation level to ensure that subsequent reads in this transaction are against a single consistent version of the data. Any changes to the data due to subsequent INSERT, UPDATE, and DELETE operations by other clients are not visible to this transaction.

  2. Obtain an ACCESS SHARE MODE lock on each of the tables being tracked to ensure that no structural changes can occur to any of the tables while the snapshot is taking place. These locks do not prevent table INSERT, UPDATE and DELETE operations from taking place during the snapshot.

    This step is omitted when snapshot.mode is set to exported, which allows the connector to perform a lock-free snapshot.

  3. Read the current position in the server’s transaction log.

  4. Scan the database tables and schemas, generate a READ event for each row and write that event to the appropriate table-specific Kafka topic.

  5. Commit the transaction.

  6. Record the successful completion of the snapshot in the connector offsets.

If the connector fails, is rebalanced, or stops after Step 1 begins but before Step 6 completes, upon restart the connector begins a new snapshot. After the connector completes its initial snapshot, the PostgreSQL connector continues streaming from the position that it read in step 3. This ensures that the connector does not miss any updates. If the connector stops again for any reason, upon restart, the connector continues streaming changes from where it previously left off.

It is strongly recommended that you configure a PostgreSQL connector to set snapshot.mode to exported. The initial, initial only and always modes can lose a few events while a connector switches from performing the snapshot to streaming change event records when a database is under heavy load. This is a known issue and the affected snapshot modes will be reworked to use exported mode internally (DBZ-2337).

Table 1. Settings for snapshot.mode connector configuration property
SettingDescription

always

The connector always performs a snapshot when it starts. After the snapshot completes, the connector continues streaming changes from step 3 in the above sequence. This mode is useful in these situations:

  • It is known that some WAL segments have been deleted and are no longer available.

  • After a cluster failure, a new primary has been promoted. The always snapshot mode ensures that the connector does not miss any changes that were made after the new primary had been promoted but before the connector was restarted on the new primary.

never

The connector never performs snapshots. When a connector is configured this way, its behavior when it starts is as follows. If there is a previously stored LSN in the Kafka offsets topic, the connector continues streaming changes from that position. If no LSN has been stored, the connector starts streaming changes from the point in time when the PostgreSQL logical replication slot was created on the server. The never snapshot mode is useful only when you know all data of interest is still reflected in the WAL.

initial only

The connector performs a database snapshot and stops before streaming any change event records. If the connector had started but did not complete a snapshot before stopping, the connector restarts the snapshot process and stops when the snapshot completes.

exported

The connector performs a database snapshot based on the point in time when the replication slot was created. This mode is an excellent way to perform a snapshot in a lock-free way.

custom

The custom snapshot mode lets you inject your own implementation of the io.debezium.connector.postgresql.spi.Snapshotter interface. Set the snapshot.custom.class configuration property to the class on the classpath of your Kafka Connect cluster or included in the JAR if using the EmbeddedEngine. For more details, see custom snapshotter SPI.

Custom snapshotter SPI

For more advanced uses, you can provide an implementation of the io.debezium.connector.postgresql.spi.Snapshotter interface. This interface allows control of most of the aspects of how the connector performs snapshots. This includes whether or not to take a snapshot, the options for opening the snapshot transaction, and whether to take locks.

Following is the full API for the interface. All built-in snapshot modes implement this interface.

  1. /**
  2. * This interface is used to determine details about the snapshot process:
  3. *
  4. * Namely:
  5. * - Should a snapshot occur at all
  6. * - Should streaming occur
  7. * - What queries should be used to snapshot
  8. *
  9. * While many default snapshot modes are provided with Debezium,
  10. * a custom implementation of this interface can be provided by the implementor, which
  11. * can provide more advanced functionality, such as partial snapshots.
  12. *
  13. * Implementations must return true for either {@link #shouldSnapshot()} or {@link #shouldStream()}
  14. * or true for both.
  15. */
  16. @Incubating
  17. public interface Snapshotter {
  18. void init(PostgresConnectorConfig config, OffsetState sourceInfo,
  19. SlotState slotState);
  20. /**
  21. * @return true if the snapshotter should take a snapshot
  22. */
  23. boolean shouldSnapshot();
  24. /**
  25. * @return true if the snapshotter should stream after taking a snapshot
  26. */
  27. boolean shouldStream();
  28. /**
  29. * @return true if when creating a slot, a snapshot should be exported, which
  30. * can be used as an alternative to taking a lock
  31. */
  32. default boolean exportSnapshot() {
  33. return false;
  34. }
  35. /**
  36. * Generate a valid postgres query string for the specified table, or an empty {@link Optional}
  37. * to skip snapshotting this table (but that table will still be streamed from)
  38. *
  39. * @param tableId the table to generate a query for
  40. * @return a valid query string, or none to skip snapshotting this table
  41. */
  42. Optional<String> buildSnapshotQuery(TableId tableId);
  43. /**
  44. * Return a new string that set up the transaction for snapshotting
  45. *
  46. * @param newSlotInfo if a new slow was created for snapshotting, this contains information from
  47. * the `create_replication_slot` command
  48. */
  49. default String snapshotTransactionIsolationLevelStatement(SlotCreationResult newSlotInfo) {
  50. // we're using the same isolation level that pg_backup uses
  51. return "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE;";
  52. }
  53. /**
  54. * Returns a SQL statement for locking the given tables during snapshotting, if required by the specific snapshotter
  55. * implementation.
  56. */
  57. default Optional<String> snapshotTableLockingStatement(Duration lockTimeout, Set<TableId> tableIds) {
  58. String lineSeparator = System.lineSeparator();
  59. StringBuilder statements = new StringBuilder();
  60. statements.append("SET lock_timeout = ").append(lockTimeout.toMillis()).append(";").append(lineSeparator);
  61. // we're locking in ACCESS SHARE MODE to avoid concurrent schema changes while we're taking the snapshot
  62. // this does not prevent writes to the table, but prevents changes to the table's schema....
  63. // DBZ-298 Quoting name in case it has been quoted originally; it does not do harm if it has not been quoted
  64. tableIds.forEach(tableId -> statements.append("LOCK TABLE ")
  65. .append(tableId.toDoubleQuotedString())
  66. .append(" IN ACCESS SHARE MODE;")
  67. .append(lineSeparator));
  68. return Optional.of(statements.toString());
  69. }
  70. }

Streaming changes

The PostgreSQL connector typically spends the vast majority of its time streaming changes from the PostgreSQL server to which it is connected. This mechanism relies on PostgreSQL’s replication protocol. This protocol enables clients to receive changes from the server as they are committed in the server’s transaction log at certain positions, which are referred to as Log Sequence Numbers (LSNs).

Whenever the server commits a transaction, a separate server process invokes a callback function from the logical decoding plug-in. This function processes the changes from the transaction, converts them to a specific format (Protobuf or JSON in the case of Debezium plug-in) and writes them on an output stream, which can then be consumed by clients.

The Debezium PostgreSQL connector acts as a PostgreSQL client. When the connector receives changes it transforms the events into Debezium create, update, or delete events that include the LSN of the event. The PostgreSQL connector forwards these change events in records to the Kafka Connect framework, which is running in the same process. The Kafka Connect process asynchronously writes the change event records in the same order in which they were generated to the appropriate Kafka topic.

Periodically, Kafka Connect records the most recent offset in another Kafka topic. The offset indicates source-specific position information that Debezium includes with each event. For the PostgreSQL connector, the LSN recorded in each change event is the offset.

When Kafka Connect gracefully shuts down, it stops the connectors, flushes all event records to Kafka, and records the last offset received from each connector. When Kafka Connect restarts, it reads the last recorded offset for each connector, and starts each connector at its last recorded offset. When the connector restarts, it sends a request to the PostgreSQL server to send the events starting just after that position.

The PostgreSQL connector retrieves schema information as part of the events sent by the logical decoding plug-in. However, the connector does not retrieve information about which columns compose the primary key. The connector obtains this information from the JDBC metadata (side channel). If the primary key definition of a table changes (by adding, removing or renaming primary key columns), there is a tiny period of time when the primary key information from JDBC is not synchronized with the change event that the logical decoding plug-in generates. During this tiny period, a message could be created with an inconsistent key structure. To prevent this inconsistency, update primary key structures as follows:

  1. Put the database or an application into a read-only mode.

  2. Let Debezium process all remaining events.

  3. Stop Debezium.

  4. Update the primary key definition in the relevant table.

  5. Put the database or the application into read/write mode.

  6. Restart Debezium.

PostgreSQL 10+ logical decoding support (pgoutput)

As of PostgreSQL 10+, there is a logical replication stream mode, called pgoutput that is natively supported by PostgreSQL. This means that a Debezium PostgreSQL connector can consume that replication stream without the need for additional plug-ins. This is particularly valuable for environments where installation of plug-ins is not supported or not allowed.

See Setting up PostgreSQL for more details.

Topics names

The PostgreSQL connector writes events for all insert, update, and delete operations on a single table to a single Kafka topic. By default, the Kafka topic name is serverName.schemaName.tableName where:

  • serverName is the logical name of the connector as specified with the database.server.name connector configuration property.

  • schemaName is the name of the database schema where the operation occurred.

  • tableName is the name of the database table in which the operation occurred.

For example, suppose that fulfillment is the logical server name in the configuration for a connector that is capturing changes in a PostgreSQL installation that has a postgres database and an inventory schema that contains four tables: products, products_on_hand, customers, and orders. The connector would stream records to these four Kafka topics:

  • fulfillment.inventory.products

  • fulfillment.inventory.products_on_hand

  • fulfillment.inventory.customers

  • fulfillment.inventory.orders

Now suppose that the tables are not part of a specific schema but were created in the default public PostgreSQL schema. The names of the Kafka topics would be:

  • fulfillment.public.products

  • fulfillment.public.products_on_hand

  • fulfillment.public.customers

  • fulfillment.public.orders

Meta information

In addition to a database change event, each record produced by a PostgreSQL connector contains some metadata. Metadata includes where the event occurred on the server, the name of the source partition and the name of the Kafka topic and partition where the event should go, for example:

  1. "sourcePartition": {
  2. "server": "fulfillment"
  3. },
  4. "sourceOffset": {
  5. "lsn": "24023128",
  6. "txId": "555",
  7. "ts_ms": "1482918357011"
  8. },
  9. "kafkaPartition": null
  • sourcePartition always defaults to the setting of the database.server.name connector configuration property.

  • sourceOffset contains information about the location of the server where the event occurred:

    • lsn represents the PostgreSQL Log Sequence Number or offset in the transaction log.

    • txId represents the identifier of the server transaction that caused the event.

    • ts_ms represents the server time at which the transaction was committed in the form of the number of milliseconds since the epoch.

  • kafkaPartition with a setting of null means that the connector does not use a specific Kafka partition. The PostgreSQL connector uses only one Kafka Connect partition and it places the generated events into one Kafka partition.

Transaction metadata

Debezium can generate events that represent transaction boundaries and that enrich data change event messages. For every transaction BEGIN and END, Debezium generates an event that contains the following fields:

  • status - BEGIN or END

  • id - string representation of unique transaction identifier

  • event_count (for END events) - total number of events emitted by the transaction

  • data_collections (for END events) - an array of pairs of data_collection and event_count that provides the number of events emitted by changes originating from given data collection

Example

  1. {
  2. "status": "BEGIN",
  3. "id": "571",
  4. "event_count": null,
  5. "data_collections": null
  6. }
  7. {
  8. "status": "END",
  9. "id": "571",
  10. "event_count": 2,
  11. "data_collections": [
  12. {
  13. "data_collection": "s1.a",
  14. "event_count": 1
  15. },
  16. {
  17. "data_collection": "s2.a",
  18. "event_count": 1
  19. }
  20. ]
  21. }

Transaction events are written to the topic named *database.server.name*.transaction.

Change data event enrichment

When transaction metadata is enabled the data message Envelope is enriched with a new transaction field. This field provides information about every event in the form of a composite of fields:

  • id - string representation of unique transaction identifier

  • total_order - absolute position of the event among all events generated by the transaction

  • data_collection_order - the per-data collection position of the event among all events that were emitted by the transaction

Following is an example of a message:

  1. {
  2. "before": null,
  3. "after": {
  4. "pk": "2",
  5. "aa": "1"
  6. },
  7. "source": {
  8. ...
  9. },
  10. "op": "c",
  11. "ts_ms": "1580390884335",
  12. "transaction": {
  13. "id": "571",
  14. "total_order": "1",
  15. "data_collection_order": "1"
  16. }
  17. }

Data change events

The Debezium PostgreSQL connector generates a data change event for each row-level INSERT, UPDATE, and DELETE operation. Each event contains a key and a value. The structure of the key and the value depends on the table that was changed.

Debezium and Kafka Connect are designed around continuous streams of event messages. However, the structure of these events may change over time, which can be difficult for consumers to handle. To address this, each event contains the schema for its content or, if you are using a schema registry, a schema ID that a consumer can use to obtain the schema from the registry. This makes each event self-contained.

The following skeleton JSON shows the basic four parts of a change event. However, how you configure the Kafka Connect converter that you choose to use in your application determines the representation of these four parts in change events. A schema field is in a change event only when you configure the converter to produce it. Likewise, the event key and event payload are in a change event only if you configure a converter to produce it. If you use the JSON converver and you configure it to produce all four basic change event parts, change events have this structure:

  1. {
  2. "schema": { (1)
  3. ...
  4. },
  5. "payload": { (2)
  6. ...
  7. },
  8. "schema": { (3)
  9. ...
  10. },
  11. "payload": { (4)
  12. ...
  13. },
  14. }
Table 2. Overview of change event basic content
ItemField nameDescription

1

schema

The first schema field is part of the event key. It specifies a Kafka Connect schema that describes what is in the event key’s payload portion. In other words, the first schema field describes the structure of the primary key, or the unique key if the table does not have a primary key, for the table that was changed.

It is possible to override the table’s primary key by setting the message.key.columns connector configuration property. In this case, the first schema field describes the structure of the key identified by that property.

2

payload

The first payload field is part of the event key. It has the structure described by the previous schema field and it contains the key for the row that was changed.

3

schema

The second schema field is part of the event value. It specifies the Kafka Connect schema that describes what is in the event value’s payload portion. In other words, the second schema describes the structure of the row that was changed. Typically, this schema contains nested schemas.

4

payload

The second payload field is part of the event value. It has the structure described by the previous schema field and it contains the actual data for the row that was changed.

By default behavior is that the connector streams change event records to topics with names that are the same as the event’s originating table.

Starting with Kafka 0.10, Kafka can optionally record the event key and value with the timestamp at which the message was created (recorded by the producer) or written to the log by Kafka.

The PostgreSQL connector ensures that all Kafka Connect schema names adhere to the Avro schema name format. This means that the logical server name must start with a Latin letter or an underscore, that is, a-z, A-Z, or . Each remaining character in the logical server name and each character in the schema and table names must be a Latin letter, a digit, or an underscore, that is, a-z, A-Z, 0-9, or \. If there is an invalid character it is replaced with an underscore character.

This can lead to unexpected conflicts if the logical server name, a schema name, or a table name contains invalid characters, and the only characters that distinguish names from one another are invalid and thus replaced with underscores.

Change event keys

For a given table, the change event’s key has a structure that contains a field for each column in the primary key of the table at the time the event was created. Alternatively, if the table has REPLICA IDENTITY set to FULL or USING INDEX there is a field for each unique key constraint.

Consider a customers table defined in the public database schema and the example of a change event key for that table.

Example table

  1. CREATE TABLE customers (
  2. id SERIAL,
  3. first_name VARCHAR(255) NOT NULL,
  4. last_name VARCHAR(255) NOT NULL,
  5. email VARCHAR(255) NOT NULL,
  6. PRIMARY KEY(id)
  7. );

Example change event key

If the database.server.name connector configuration property has the value PostgreSQL_server, every change event for the customers table while it has this definition has the same key structure, which in JSON looks like this:

  1. {
  2. "schema": { (1)
  3. "type": "struct",
  4. "name": "PostgreSQL_server.public.customers.Key", (2)
  5. "optional": false, (3)
  6. "fields": [ (4)
  7. {
  8. "name": "id",
  9. "index": "0",
  10. "schema": {
  11. "type": "INT32",
  12. "optional": "false"
  13. }
  14. }
  15. ]
  16. },
  17. "payload": { (5)
  18. "id": "1"
  19. },
  20. }
Table 3. Description of change event key
ItemField nameDescription

1

schema

The schema portion of the key specifies a Kafka Connect schema that describes what is in the key’s payload portion.

2

PostgreSQL_server.inventory.customers.Key

Name of the schema that defines the structure of the key’s payload. This schema describes the structure of the primary key for the table that was changed. Key schema names have the format connector-name.database-name.table-name.Key. In this example:

  • PostgreSQL_server is the name of the connector that generated this event.

  • public is the database that contains the table that was changed.

  • customers is the table that was updated.

3

optional

Indicates whether the event key must contain a value in its payload field. In this example, a value in the key’s payload is required. A value in the key’s payload field is optional when a table does not have a primary key.

4

fields

Specifies each field that is expected in the payload, including each field’s name, index, and schema.

5

payload

Contains the key for the row for which this change event was generated. In this example, the key, contains a single id field whose value is 1.

Although the column.blacklist and column.whitelist connector configuration properties allow you to capture only a subset of table columns, all columns in a primary or unique key are always included in the event’s key.

If the table does not have a primary or unique key, then the change event’s key is null. The rows in a table without a primary or unique key constraint cannot be uniquely identified.

Change event values

The value in a change event is a bit more complicated than the key. Like the key, the value has a schema section and a payload section. The schema section contains the schema that describes the Envelope structure of the payload section, including its nested fields. Change events for operations that create, update or delete data all have a value payload with an envelope structure.

Consider the same sample table that was used to show an example of a change event key:

  1. CREATE TABLE customers (
  2. id SERIAL,
  3. first_name VARCHAR(255) NOT NULL,
  4. last_name VARCHAR(255) NOT NULL,
  5. email VARCHAR(255) NOT NULL,
  6. PRIMARY KEY(id)
  7. );

The value portion of a change event for a change to this table varies according to the REPLICA IDENTITY setting and the operation that the event is for.

Replica identity

REPLICA IDENTITY is a PostgreSQL-specific table-level setting that determines the amount of information that is available to the logical decoding plug-in for UPDATE and DELETE events. More specifically, the setting of REPLICA IDENTITY controls what (if any) information is available for the previous values of the table columns involved, whenever an UPDATE or DELETE event occurs.

There are 4 possible values for REPLICA IDENTITY:

  • DEFAULT - The default behavior is that UPDATE and DELETE events contain the previous values for the primary key columns of a table if that table has a primary key. For an UPDATE event, only the primary key columns with changed values are present.

    If a table does not have a primary key, the connector does not emit UPDATE or DELETE events for that table. For a table without a primary key, the connector emits only create events. Typically, a table without a primary key is used for appending messages to the end of the table, which means that UPDATE and DELETE events are not useful.

  • NOTHING - Emitted events for UPDATE and DELETE operations do not contain any information about the previous value of any table column.

  • FULL - Emitted events for UPDATE and DELETE operations contain the previous values of all columns in the table.

  • INDEX index-name - Emitted events for UPDATE and DELETE operations contain the previous values of the columns contained in the specified index. UPDATE events also contain the indexed columns with the updated values.

create events

The following example shows the value portion of a change event that the connector generates for an operation that creates data in the customers table:

  1. {
  2. "schema": { (1)
  3. "type": "struct",
  4. "fields": [
  5. {
  6. "type": "struct",
  7. "fields": [
  8. {
  9. "type": "int32",
  10. "optional": false,
  11. "field": "id"
  12. },
  13. {
  14. "type": "string",
  15. "optional": false,
  16. "field": "first_name"
  17. },
  18. {
  19. "type": "string",
  20. "optional": false,
  21. "field": "last_name"
  22. },
  23. {
  24. "type": "string",
  25. "optional": false,
  26. "field": "email"
  27. }
  28. ],
  29. "optional": true,
  30. "name": "PostgreSQL_server.inventory.customers.Value", (2)
  31. "field": "before"
  32. },
  33. {
  34. "type": "struct",
  35. "fields": [
  36. {
  37. "type": "int32",
  38. "optional": false,
  39. "field": "id"
  40. },
  41. {
  42. "type": "string",
  43. "optional": false,
  44. "field": "first_name"
  45. },
  46. {
  47. "type": "string",
  48. "optional": false,
  49. "field": "last_name"
  50. },
  51. {
  52. "type": "string",
  53. "optional": false,
  54. "field": "email"
  55. }
  56. ],
  57. "optional": true,
  58. "name": "PostgreSQL_server.inventory.customers.Value",
  59. "field": "after"
  60. },
  61. {
  62. "type": "struct",
  63. "fields": [
  64. {
  65. "type": "string",
  66. "optional": false,
  67. "field": "version"
  68. },
  69. {
  70. "type": "string",
  71. "optional": false,
  72. "field": "connector"
  73. },
  74. {
  75. "type": "string",
  76. "optional": false,
  77. "field": "name"
  78. },
  79. {
  80. "type": "int64",
  81. "optional": false,
  82. "field": "ts_ms"
  83. },
  84. {
  85. "type": "boolean",
  86. "optional": true,
  87. "default": false,
  88. "field": "snapshot"
  89. },
  90. {
  91. "type": "string",
  92. "optional": false,
  93. "field": "db"
  94. },
  95. {
  96. "type": "string",
  97. "optional": false,
  98. "field": "schema"
  99. },
  100. {
  101. "type": "string",
  102. "optional": false,
  103. "field": "table"
  104. },
  105. {
  106. "type": "int64",
  107. "optional": true,
  108. "field": "txId"
  109. },
  110. {
  111. "type": "int64",
  112. "optional": true,
  113. "field": "lsn"
  114. },
  115. {
  116. "type": "int64",
  117. "optional": true,
  118. "field": "xmin"
  119. }
  120. ],
  121. "optional": false,
  122. "name": "io.debezium.connector.postgresql.Source", (3)
  123. "field": "source"
  124. },
  125. {
  126. "type": "string",
  127. "optional": false,
  128. "field": "op"
  129. },
  130. {
  131. "type": "int64",
  132. "optional": true,
  133. "field": "ts_ms"
  134. }
  135. ],
  136. "optional": false,
  137. "name": "PostgreSQL_server.inventory.customers.Envelope" (4)
  138. },
  139. "payload": { (5)
  140. "before": null, (6)
  141. "after": { (7)
  142. "id": 1,
  143. "first_name": "Anne",
  144. "last_name": "Kretchmar",
  145. "email": "annek@noanswer.org"
  146. },
  147. "source": { (8)
  148. "version": "1.2.5.Final",
  149. "connector": "postgresql",
  150. "name": "PostgreSQL_server",
  151. "ts_ms": 1559033904863,
  152. "snapshot": true,
  153. "db": "postgres",
  154. "schema": "public",
  155. "table": "customers",
  156. "txId": 555,
  157. "lsn": 24023128,
  158. "xmin": null
  159. },
  160. "op": "c", (9)
  161. "ts_ms": 1559033904863 (10)
  162. }
  163. }
Table 4. Descriptions of create event value fields
ItemField nameDescription

1

schema

The value’s schema, which describes the structure of the value’s payload. A change event’s value schema is the same in every change event that the connector generates for a particular table.

2

name

In the schema section, each name field specifies the schema for a field in the value’s payload.

PostgreSQL_server.inventory.customers.Value is the schema for the payload’s before and after fields. This schema is specific to the customers table.

Names of schemas for before and after fields are of the form logicalName.tableName.Value, which ensures that the schema name is unique in the database. This means that when using the Avro converter, the resulting Avro schema for each table in each logical source has its own evolution and history.

3

name

io.debezium.connector.postgresql.Source is the schema for the payload’s source field. This schema is specific to the PostgreSQL connector. The connector uses it for all events that it generates.

4

name

PostgreSQL_server.inventory.customers.Envelope is the schema for the overall structure of the payload, where PostgreSQL_server is the connector name, inventory is the database, and customers is the table.

5

payload

The value’s actual data. This is the information that the change event is providing.

It may appear that the JSON representations of the events are much larger than the rows they describe. This is because the JSON representation must include the schema and the payload portions of the message. However, by using the Avro converter, you can significantly decrease the size of the messages that the connector streams to Kafka topics.

6

before

An optional field that specifies the state of the row before the event occurred. When the op field is c for create, as it is in this example, the before field is null since this change event is for new content.

Whether or not this field is available is dependent on the REPLICA IDENTITY setting for each table.

7

after

An optional field that specifies the state of the row after the event occurred. In this example, the after field contains the values of the new row’s id, first_name, last_name, and email columns.

8

source

Mandatory field that describes the source metadata for the event. This field contains information that you can use to compare this event with other events, with regard to the origin of the events, the order in which the events occurred, and whether events were part of the same transaction. The source metadata includes:

  • Debezium version

  • Connector type and name

  • Database and table that contains the new row

  • Schema name

  • If the event was part of a snapshot

  • ID of the transaction in which the operation was performed

  • Offset of the operation in the database log

  • Timestamp for when the change was made in the database

9

op

Mandatory string that describes the type of operation that caused the connector to generate the event. In this example, c indicates that the operation created a row. Valid values are:

  • c = create

  • u = update

  • d = delete

  • r = read (applies to only snapshots)

10

ts_ms

Optional field that displays the time at which the connector processed the event. The time is based on the system clock in the JVM running the Kafka Connect task.

In the source object, ts_ms indicates the time that the change was made in the database. By comparing the value for payload.source.ts_ms with the value for payload.ts_ms, you can determine the lag between the source database update and Debezium.

update events

The value of a change event for an update in the sample customers table has the same schema as a create event for that table. Likewise, the event value’s payload has the same structure. However, the event value payload contains different values in an update event. Here is an example of a change event value in an event that the connector generates for an update in the customers table:

  1. {
  2. "schema": { ... },
  3. "payload": {
  4. "before": { // <1>
  5. "id": 1
  6. },
  7. "after": { // <2>
  8. "id": 1,
  9. "first_name": "Anne Marie",
  10. "last_name": "Kretchmar",
  11. "email": "annek@noanswer.org"
  12. },
  13. "source": { // <3>
  14. "version": "1.2.5.Final",
  15. "connector": "postgresql",
  16. "name": "PostgreSQL_server",
  17. "ts_ms": 1559033904863,
  18. "snapshot": null,
  19. "db": "postgres",
  20. "schema": "public",
  21. "table": "customers",
  22. "txId": 556,
  23. "lsn": 24023128,
  24. "xmin": null
  25. },
  26. "op": "u", // <4>
  27. "ts_ms": 1465584025523 // <5>
  28. }
  29. }
Table 5. Descriptions of update event value fields
ItemField nameDescription

1

before

An optional field that contains values that were in the row before the database commit. In this example, only the primary key column, id, is present because the table’s REPLICA IDENTITY setting is, by default, DEFAULT. + For an update event to contain the previous values of all columns in the row, you would have to change the customers table by running ALTER TABLE customers REPLICA IDENTITY FULL.

2

after

An optional field that specifies the state of the row after the event occurred. In this example, the first_name value is now Anne Marie.

3

source

Mandatory field that describes the source metadata for the event. The source field structure has the same fields as in a create event, but some values are different. The source metadata includes:

  • Debezium version

  • Connector type and name

  • Database and table that contains the new row

  • Schema name

  • If the event was part of a snapshot

  • ID of the transaction in which the operation was performed

  • Offset of the operation in the database log

  • Timestamp for when the change was made in the database

4

op

Mandatory string that describes the type of operation. In an update event value, the op field value is u, signifying that this row changed because of an update.

5

ts_ms

Optional field that displays the time at which the connector processed the event. The time is based on the system clock in the JVM running the Kafka Connect task.

In the source object, ts_ms indicates the time that the change was made in the database. By comparing the value for payload.source.ts_ms with the value for payload.ts_ms, you can determine the lag between the source database update and Debezium.

Updating the columns for a row’s primary/unique key changes the value of the row’s key. When a key changes, Debezium outputs three events: a DELETE event and a tombstone event with the old key for the row, followed by an event with the new key for the row. Details are in the next section.

Primary key updates

An UPDATE operation that changes a row’s primary key field(s) is known as a primary key change. For a primary key change, in place of sending an UPDATE event record, the connector sends a DELETE event record for the old key and a CREATE event record for the new (updated) key. These events have the usual structure and content, and in addition, each one has a message header related to the primary key change:

  • The DELETE event record has __debezium.newkey as a message header. The value of this header is the new primary key for the updated row.

  • The CREATE event record has __debezium.oldkey as a message header. The value of this header is the previous (old) primary key that the updated row had.

delete events

The value in a delete change event has the same schema portion as create and update events for the same table. The payload portion in a delete event for the sample customers table looks like this:

  1. {
  2. "schema": { ... },
  3. "payload": {
  4. "before": { (1)
  5. "id": 1
  6. },
  7. "after": null, (2)
  8. "source": { (3)
  9. "version": "1.2.5.Final",
  10. "connector": "postgresql",
  11. "name": "PostgreSQL_server",
  12. "ts_ms": 1559033904863,
  13. "snapshot": null,
  14. "db": "postgres",
  15. "schema": "public",
  16. "table": "customers",
  17. "txId": 556,
  18. "lsn": 46523128,
  19. "xmin": null
  20. },
  21. "op": "d", (4)
  22. "ts_ms": 1465581902461 (5)
  23. }
  24. }
Table 6. Descriptions of delete event value fields
ItemField nameDescription

1

before

Optional field that specifies the state of the row before the event occurred. In a delete event value, the before field contains the values that were in the row before it was deleted with the database commit.

In this example, the before field contains only the primary key column because the table’s REPLICA IDENTITY setting is DEFAULT.

2

after

Optional field that specifies the state of the row after the event occurred. In a delete event value, the after field is null, signifying that the row no longer exists.

3

source

Mandatory field that describes the source metadata for the event. In a delete event value, the source field structure is the same as for create and update events for the same table. Many source field values are also the same. In a delete event value, the ts_ms and lsn field values, as well as other values, might have changed. But the source field in a delete event value provides the same metadata:

  • Debezium version

  • Connector type and name

  • Database and table that contains the new row

  • Schema name

  • If the event was part of a snapshot

  • ID of the transaction in which the operation was performed

  • Offset of the operation in the database log

  • Timestamp for when the change was made in the database

4

op

Mandatory string that describes the type of operation. The op field value is d, signifying that this row was deleted.

5

ts_ms

Optional field that displays the time at which the connector processed the event. The time is based on the system clock in the JVM running the Kafka Connect task.

In the source object, ts_ms indicates the time that the change was made in the database. By comparing the value for payload.source.ts_ms with the value for payload.ts_ms, you can determine the lag between the source database update and Debezium.

A delete change event record provides a consumer with the information it needs to process the removal of this row.

For a consumer to be able to process a delete event generated for a table that does not have a primary key, set the table’s REPLICA IDENTITY to FULL. When a table does not have a primary key and the table’s REPLICA IDENTITY is set to DEFAULT or NOTHING, a delete event has no before field.

PostgreSQL connector events are designed to work with Kafka log compaction. Log compaction enables removal of some older messages as long as at least the most recent message for every key is kept. This lets Kafka reclaim storage space while ensuring that the topic contains a complete data set and can be used for reloading key-based state.

Tombstone events

When a row is deleted, the delete event value still works with log compaction, because Kafka can remove all earlier messages that have that same key. However, for Kafka to remove all messages that have that same key, the message value must be null. To make this possible, the PostgreSQL connector follows a delete event with a special tombstone event that has the same key but a null value.

Data type mappings

The PostgreSQL connector represents changes to rows with events that are structured like the table in which the row exists. The event contains a field for each column value. How that value is represented in the event depends on the PostgreSQL data type of the column. This section describes these mappings.

Basic types

The following table describes how the connector maps basic PostgreSQL data types to a literal type and a semantic type in event fields.

  • literal type describes how the value is literally represented using Kafka Connect schema types: INT8, INT16, INT32, INT64, FLOAT32, FLOAT64, BOOLEAN, STRING, BYTES, ARRAY, MAP, and STRUCT.

  • semantic type describes how the Kafka Connect schema captures the meaning of the field using the name of the Kafka Connect schema for the field.

Table 7. Mappings for PostgreSQL basic data types
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

BOOLEAN

BOOLEAN

n/a

BIT(1)

BOOLEAN

n/a

BIT( > 1)

BYTES

io.debezium.data.Bits

The length schema parameter contains an integer that represents the number of bits. The resulting byte[] contains the bits in little-endian form and is sized to contain the specified number of bits. For example, numBytes = n/8 + (n % 8 == 0 ? 0 : 1) where n is the number of bits.

BIT VARYING[(M)]

BYTES

io.debezium.data.Bits

The length schema parameter contains an integer that represents the number of bits (2^31 - 1 in case no length is given for the column). The resulting byte[] contains the bits in little-endian form and is sized based on the content. The specified size (M) is stored in the length parameter of the io.debezium.data.Bits type.

SMALLINT, SMALLSERIAL

INT16

n/a

INTEGER, SERIAL

INT32

n/a

BIGINT, BIGSERIAL

INT64

n/a

REAL

FLOAT32

n/a

DOUBLE PRECISION

FLOAT64

n/a

CHAR[(M)]

STRING

n/a

VARCHAR[(M)]

STRING

n/a

CHARACTER[(M)]

STRING

n/a

CHARACTER VARYING[(M)]

STRING

n/a

TIMESTAMPTZ, TIMESTAMP WITH TIME ZONE

STRING

io.debezium.time.ZonedTimestamp

A string representation of a timestamp with timezone information, where the timezone is GMT.

TIMETZ, TIME WITH TIME ZONE

STRING

io.debezium.time.ZonedTime

A string representation of a time value with timezone information, where the timezone is GMT.

INTERVAL [P]

INT64

io.debezium.time.MicroDuration
(default)

The approximate number of microseconds for a time interval using the 365.25 / 12.0 formula for days per month average.

INTERVAL [P]

STRING

io.debezium.time.Interval
(when interval.handling.mode is set to string)

The string representation of the interval value that follows the pattern P<years>Y<months>M<days>DT<hours>H<minutes>M<seconds>S, for example, P1Y2M3DT4H5M6.78S.

BYTEA

BYTES or STRING

n/a

Either the raw bytes (the default), a base64-encoded string, or a hex-encoded string, based on the connector’s binary handling mode setting.

JSON, JSONB

STRING

io.debezium.data.Json

Contains the string representation of a JSON document, array, or scalar.

XML

STRING

io.debezium.data.Xml

Contains the string representation of an XML document.

UUID

STRING

io.debezium.data.Uuid

Contains the string representation of a PostgreSQL UUID value.

POINT

STRUCT

io.debezium.data.geometry.Point

Contains a structure with two FLOAT64 fields, (x,y). Each field represents the coordinates of a geometric point.

LTREE

STRING

io.debezium.data.Ltree

Contains the string representation of a PostgreSQL LTREE value.

CITEXT

STRING

n/a

INET

STRING

n/a

INT4RANGE

STRING

n/a

Range of integer.

INT8RANGE

STRING

n/a

Range of bigint.

NUMRANGE

STRING

n/a

Range of numeric.

TSRANGE

STRING

n/a

Contains the string representation of a timestamp range without a time zone.

TSTZRANGE

STRING

n/a

Contains the string representation of a timestamp range with the local system time zone.

DATERANGE

STRING

n/a

Contains the string representation of a date range. It always has an exclusive upper-bound.

ENUM

STRING

io.debezium.data.Enum

Contains the string representation of the PostgreSQL ENUM value. The set of allowed values is maintained in the allowed schema parameter.

Temporal types

Other than PostgreSQL’s TIMESTAMPTZ and TIMETZ data types, which contain time zone information, how temporal types are mapped depends on the value of the time.precision.mode connector configuration property. The following sections describe these mappings:

time.precision.mode=adaptive

When the time.precision.mode property is set to adaptive, the default, the connector determines the literal type and semantic type based on the column’s data type definition. This ensures that events exactly represent the values in the database.

Table 8. Mappings when time.precision.mode is adaptive
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

DATE

INT32

io.debezium.time.Date

Represents the number of days since the epoch.

TIME(1), TIME(2), TIME(3)

INT32

io.debezium.time.Time

Represents the number of milliseconds past midnight, and does not include timezone information.

TIME(4), TIME(5), TIME(6)

INT64

io.debezium.time.MicroTime

Represents the number of microseconds past midnight, and does not include timezone information.

TIMESTAMP(1), TIMESTAMP(2), TIMESTAMP(3)

INT64

io.debezium.time.Timestamp

Represents the number of milliseconds since the epoch, and does not include timezone information.

TIMESTAMP(4), TIMESTAMP(5), TIMESTAMP(6), TIMESTAMP

INT64

io.debezium.time.MicroTimestamp

Represents the number of microseconds since the epoch, and does not include timezone information.

time.precision.mode=adaptive_time_microseconds

When the time.precision.mode configuration property is set to adaptive_time_microseconds, the connector determines the literal type and semantic type for temporal types based on the column’s data type definition. This ensures that events exactly represent the values in the database, except all TIME fields are captured as microseconds.

Table 9. Mappings when time.precision.mode is adaptive_time_microseconds
PostgreSQL Data TypeLiteral type (schema type)Semantic type (schema name)Notes

DATE

INT32

io.debezium.time.Date

Represents the number of days since epoch.

TIME([P])

INT64

io.debezium.time.MicroTime

Represents the time value in microseconds and does not include timezone information. PostgreSQL allows precision P to be in the range 0-6 to store up to microsecond precision.

TIMESTAMP(1) , TIMESTAMP(2), TIMESTAMP(3)

INT64

io.debezium.time.Timestamp

Represents the number of milliseconds past epoch, and does not include timezone information.

TIMESTAMP(4) , TIMESTAMP(5), TIMESTAMP(6), TIMESTAMP

INT64

io.debezium.time.MicroTimestamp

Represents the number of microseconds past epoch, and does not include timezone information.

time.precision.mode=connect

When the time.precision.mode configuration property is set to connect, the connector uses Kafka Connect logical types. This may be useful when consumers can handle only the built-in Kafka Connect logical types and are unable to handle variable-precision time values. However, since PostgreSQL supports microsecond precision, the events generated by a connector with the connect time precision mode results in a loss of precision when the database column has a fractional second precision value that is greater than 3.

Table 10. Mappings when time.precision.mode is connect
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

DATE

INT32

org.apache.kafka.connect.data.Date

Represents the number of days since epoch.

TIME([P])

INT64

org.apache.kafka.connect.data.Time

Represents the number of milliseconds since midnight, and does not include timezone information. PostgreSQL allows P to be in the range 0-6 to store up to microsecond precision, though this mode results in a loss of precision when P is greater than 3.

TIMESTAMP([P])

INT64

org.apache.kafka.connect.data.Timestamp

Represents the number of milliseconds since the epoch, and does not include timezone information. PostgreSQL allows P to be in the range 0-6 to store up to microsecond precision, though this mode results in a loss of precision when P is greater than 3.

TIMESTAMP type

The TIMESTAMP type represents a timestamp without time zone information. Such columns are converted into an equivalent Kafka Connect value based on UTC. For example, the TIMESTAMP value “2018-06-20 15:13:16.945104” is represented by an io.debezium.time.MicroTimestamp with the value “1529507596945104” when time.precision.mode is not set to connect.

The timezone of the JVM running Kafka Connect and Debezium does not affect this conversion.

Decimal types

The setting of the PostgreSQL connector configuration property, decimal.handling.mode determines how the connector maps decimal types.

When the decimal.handling.mode property is set to precise, the connector uses the Kafka Connect org.apache.kafka.connect.data.Decimal logical type for all DECIMAL and NUMERIC columns. This is the default mode.

Table 11. Mappings when decimal.handling.mode is precise
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

NUMERIC[(M[,D])]

BYTES

org.apache.kafka.connect.data.Decimal

The scale schema parameter contains an integer representing how many digits the decimal point was shifted.

DECIMAL[(M[,D])]

BYTES

org.apache.kafka.connect.data.Decimal

The scale schema parameter contains an integer representing how many digits the decimal point was shifted.

There is an exception to this rule. When the NUMERIC or DECIMAL types are used without scale constraints, the values coming from the database have a different (variable) scale for each value. In this case, the connector uses io.debezium.data.VariableScaleDecimal, which contains both the value and the scale of the transferred value.

Table 12. Mappings of decimal types when there are no scale constraints
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

NUMERIC

STRUCT

io.debezium.data.VariableScaleDecimal

Contains a structure with two fields: scale of type INT32 that contains the scale of the transferred value and value of type BYTES containing the original value in an unscaled form.

DECIMAL

STRUCT

io.debezium.data.VariableScaleDecimal

Contains a structure with two fields: scale of type INT32 that contains the scale of the transferred value and value of type BYTES containing the original value in an unscaled form.

When the decimal.handling.mode property is set to double, the connector represents all DECIMAL and NUMERIC values as Java double values and encodes them as shown in the following table.

Table 13. Mappings when decimal.handling.mode is double
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

NUMERIC[(M[,D])]

FLOAT64

DECIMAL[(M[,D])]

FLOAT64

The last possible setting for the decimal.handling.mode configuration property is string. In this case, the connector represents DECIMAL and NUMERIC values as their formatted string representation, and encodes them as shown in the following table.

Table 14. Mappings when decimal.handling.mode is string
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

NUMERIC[(M[,D])]

STRING

DECIMAL[(M[,D])]

STRING

PostgreSQL supports NaN (not a number) as a special value to be stored in DECIMAL/NUMERIC values when the setting of decimal.handling.mode is string or double. In this case, the connector encodes NaN as either Double.NaN or the string constant NAN.

HSTORE type

When the hstore.handling.mode connector configuration property is set to json (the default), the connector represents HSTORE values as string representations of JSON values and encodes them as shown in the following table. When the hstore.handling.mode property is set to map, the connector uses the MAP schema type for HSTORE values.

Table 15. Mappings for HSTORE data type
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

HSTORE

STRING

io.debezium.data.Json

Example: output representation using the JSON converter is {\”key\” : \”val\”}

HSTORE

MAP

Example: output representation using the JSON converter is {“key” : “val”}

Domain types

PostgreSQL supports user-defined types that are based on other underlying types. When such column types are used, Debezium exposes the column’s representation based on the full type hierarchy.

Capturing changes in columns that use PostgreSQL domain types requires special consideration. When a column is defined to contain a domain type that extends one of the default database types and the domain type defines a custom length or scale, the generated schema inherits that defined length or scale.

When a column is defined to contain a domain type that extends another domain type that defines a custom length or scale, the generated schema does not inherit the defined length or scale because that information is not available in the PostgreSQL driver’s column metadata.

Network address types

PostgreSQL has data types that can store IPv4, IPv6, and MAC addresses. It is better to use these types instead of plain text types to store network addresses. Network address types offer input error checking and specialized operators and functions.

Table 16. Mappings for network address types
PostgreSQL data typeLiteral type (schema type)Semantic type (schema name)Notes

INET

STRING

IPv4 and IPv6 networks

CIDR

STRING

IPv4 and IPv6 hosts and networks

MACADDR

STRING

MAC addresses

MACADDR8

STRING

MAC addresses in EUI-64 format

PostGIS types

The PostgreSQL connector supports all PostGIS data types.

Table 17. Mappings of PostGIS data types
PostGIS data typeLiteral type (schema type)Semantic type (schema name)Notes

GEOMETRY
(planar)

STRUCT

io.debezium.data.geometry.Geometry

Contains a structure with two fields:

  • srid (INT32) - Spatial Reference System Identifier that defines what type of geometry object is stored in the structure.

  • wkb (BYTES) - A binary representation of the geometry object encoded in the Well-Known-Binary format.

GEOGRAPHY
(spherical)

STRUCT

io.debezium.data.geometry.Geography

Contains a structure with two fields:

  • srid (INT32) - Spatial Reference System Identifier that defines what type of geography object is stored in the structure.

  • wkb (BYTES) - A binary representation of the geometry object encoded in the Well-Known-Binary format.

Toasted values

PostgreSQL has a hard limit on the page size. This means that values that are larger than around 8 KBs need to be stored by using link::https://www.postgresql.org/docs/current/storage-toast.html\[TOAST storage]. This impacts replication messages that are coming from the database. Values that were stored by using the TOAST mechanism and that have not been changed are not included in the message, unless they are part of the table’s replica identity. There is no safe way for Debezium to read the missing value out-of-bands directly from the database, as this would potentially lead to race conditions. Consequently, Debezium follows these rules to handle toasted values:

  • Tables with REPLICA IDENTITY FULL - TOAST column values are part of the before and after fields in change events just like any other column.

  • Tables with REPLICA IDENTITY DEFAULT - When receiving an UPDATE event from the database, any unchanged TOAST column value that is not part of the replica identity is not contained in the event. Similarly, when receiving a DELETE event, no TOAST columns, if any, are in the before field. As Debezium cannot safely provide the column value in this case, the connector returns a placeholder value as defined by the connector configuration property, toasted.value.placeholder.

There is a problem related to Amazon RDS instances. The wal2json plug-in has evolved over the time and there were releases that provided out-of-band toasted values. Amazon supports different versions of the plug-in for different PostgreSQL versions. See Amazon’s documentation to obtain version to version mapping. For consistent toasted values handling:

  • Use the pgoutput plug-in for PostgreSQL 10+ instances.

  • Set include-unchanged-toast=0 for older versions of the wal2json plug-in by using the slot.stream.params configuration option.

Set up

Before using the PostgreSQL connector to monitor the changes committed on a PostgreSQL server, decide which logical decoding plug-in you intend to use. If you plan not to use the native pgoutput logical replication stream support, then you must install the logical decoding plug-in into the PostgreSQL server. Afterward, enable a replication slot, and configure a user with sufficient privileges to perform the replication.

If your database is hosted by a service such as Heroku Postgres you might be unable to install the plug-in. If so, and if you are using PostgreSQL 10+, you can use the pgoutput decoder support to capture changes in your database. If that is not an option, you are unable to use Debezium with your database.

PostgreSQL in the Cloud

PostgreSQL on Amazon RDS

It is possible to capture changes in a PostgreSQL database that is running in Amazon RDS. To do this:

  • Set the instance parameter rds.logical_replication to 1.

  • Verify that the wal_level parameter is set to logical by running the query SHOW wal_level as the database master user. This might not be the case in multi-zone replication setups. You cannot set this option manually. It is automatically changed when the rds.logical_replication parameter is set to 1. If the wal_level is not logical after the change above, it is probably because the instance has to be restarted due to the parameter group change. This happens according to your maintenance window or you can do it manually.

  • Set the Debezium plugin.name parameter to wal2json. You can skip this on PostgreSQL 10+ if you plan to use pgoutput logical replication stream support.

  • Use the database master account for replication as RDS currently does not support setting of REPLICATION privilege for another account.

Ensure that you use the latest versions of PostgreSQL 9.6, 10 or 11 on Amazon RDS. Otherwise, older versions of the wal2json plug-in might be installed. See the official documentation for the exact wal2json versions installed on Amazon RDS. In the case of an older version, replication messages received from the database might not contain complete information about type constraints such as length or scale or NULL/NOT NULL. This might cause creation of messages with an inconsistent schema for a short period of time when there are changes to a column’s definition.

As of January 2019, the following PostgreSQL versions on RDS come with an up-to-date version of wal2json and thus should be used:

  • PostgreSQL 9.6: 9.6.10 and newer

  • PostgreSQL 10: 10.5 and newer

  • PostgreSQL 11: any version

PostgreSQL on Azure

It is possible to use Debezium with Azure Database for PostgreSQL, which has support for the wal2json and pgoutput plug-ins, both of which are supported by Debezium as well.

Set the Azure replication support to logical. You can use the Azure CLI or the Azure Portal to configure this. For example, to use the Azure CLI, here are the az postgres server commands that you need to execute:

  1. az postgres server configuration set --resource-group mygroup --server-name myserver --name azure.replication_support --value logical
  2. az postgres server restart --resource-group mygroup --name myserver

While using the pgoutput plug-in, it is recommended that you configure filtered as the publication.autocreate.mode. If you use all_tables, which is the default value for publication.autocreate.mode, and the publication is not found, the connector tries to create one by using CREATE PUBLICATION <publication_name> FOR ALL TABLES;, but this fails due to lack of permissions.

Installing the logical decoding output plug-in

See Logical Decoding Output Plug-in Installation for PostgreSQL for more detailed instructions for setting up and testing logical decoding plug-ins.

As of Debezium 0.10, the connector supports PostgreSQL 10+ logical replication streaming by using pgoutput. This means that a logical decoding output plug-in is no longer necessary and changes can be emitted directly from the replication stream by the connector.

As of PostgreSQL 9.4, the only way to read changes to the write-ahead-log is to install a logical decoding output plug-in. Plug-ins are written in C, compiled, and installed on the machine that runs the PostgreSQL server. Plug-ins use a number of PostgreSQL specific APIs, as described by the PostgreSQL documentation.

The PostgreSQL connector works with one of Debezium’s supported logical decoding plug-ins to encode the changes in either Protobuf format or JSON format. See the documentation for your chosen plug-in to learn more about the plug-in’s requirements, limitations, and how to compile it.

For simplicity, Debezium also provides a Docker image based on a vanilla PostgreSQL server image on top of which it compiles and installs the plug-ins. You can use this image as an example of the detailed steps required for the installation.

The Debezium logical decoding plug-ins have been installed and tested on only Linux machines. For Windows and other operating systems, different installation steps might be required.

Plug-in differences

Plug-in behavior is not completely the same for all cases. These differences have been identified:

  • The wal2json plug-in is not able to process quoted identifiers (issue).

  • The wal2json and decoderbufs plug-ins emit events for tables without primary keys.

  • The wal2json plug-in does not support special values, such as NaN or infinity, for floating point types.

  • The wal2json plug-in should be used with the schema.refresh.mode connector configuration property set to columns_diff_exclude_unchanged_toast. Otherwise, when receiving a change event for a row that contains an unchanged TOAST column, no field for that column is contained in the emitted change event’s after field. This is because wal2json plug-in messages do not contain a field for such a column.

    The requirement for adding this is tracked under the wal2json issue 98. See the documentation of columns_diff_exclude_unchanged_toast further below for implications of using it.

  • The pgoutput plug-in does not emit all events for tables without primary keys. It emits only events for INSERT operations.

All up-to-date differences are tracked in a test suite Java class.

Configuring the PostgreSQL server

If you are using one of the supported logical decoding plug-ins, that is, not pgoutput, and it has been installed, configure the PostgreSQL server as follows:

  1. To load the plug-in at startup, add the following to the postgresql.conf file::

    1. # MODULES
    2. shared_preload_libraries = 'decoderbufs,wal2json' (1)
    1instructs the server to load the decoderbufs and wal2json logical decoding plug-ins at startup. The names of the plug-ins are set in the Protobuf and wal2json make files.
  2. To configure the replication slot regardless of the decoder being used, specify the following in the postgresql.conf file:

    1. # REPLICATION
    2. wal_level = logical (1)
    3. max_wal_senders = 1 (2)
    4. max_replication_slots = 1 (3)
    1instructs the server to use logical decoding with the write-ahead log.
    2instructs the server to use a maximum of 1 separate process for processing WAL changes.
    3instructs the server to allow a maximum of 1 replication slot to be created for streaming WAL changes.

Debezium uses PostgreSQL’s logical decoding, which uses replication slots. Replication slots are guaranteed to retain all WAL segments required for Debezium even during Debezium outages. For this reason, it is important to closely monitor replication slots to avoid too much disk consumption and other conditions that can happen such as catalog bloat if a replication slot stays unused for too long. For more information, see the PostgreSQL streaming replication documentation.

If you are working with a synchronous_commit setting other than on, the recommendation is to set wal_writer_delay to a value such as 10 milliseconds to achieve a low latency of change events. Otherwise, its default value is applied, which adds a latency of about 200 milliseconds.

Setting up permissions

Setting up a PostgreSQL server to run a Debezium connector requires a database user who can perform replications. Replication can be performed only by a database user who has appropriate permissions and only for a configured number of hosts. Also, you must configure the PostgreSQL server to allow replication to take place between the server machine and the host on which the PostgreSQL connector is running.

Prerequisites

  • PostgreSQL administrative permissions.

Procedure

  1. To give replication permissions to a user, define a PostgreSQL role that has at least the REPLICATION and LOGIN permissions. For example:

    1. CREATE ROLE name REPLICATION LOGIN;

    By default, superusers have both of the above roles.

  2. Configure the PostgreSQL server to allow replication to take place between the server machine and the host on which the PostgreSQL connector is running.

    pg_hba.conf file example:

    1. local replication <youruser> trust (1)
    2. host replication <youruser> 127.0.0.1/32 trust (2)
    3. host replication <youruser> ::1/128 trust (3)
    1Instructs the server to allow replication for <youruser> locally, that is, on the server machine.
    2Instructs the server to allow <youruser> on localhost to receive replication changes using IPV4.
    3Instructs the server to allow <youruser> on localhost to receive replication changes using IPV6.

For more information about network masks, see the PostgreSQL documentation.

Supported PostgreSQL topologies

The PostgreSQL connector can be used with a standalone PostgreSQL server or with a cluster of PostgreSQL servers.

As mentioned in the beginning, PostgreSQL (for all versions ⇐ 12) supports logical replication slots on only primary servers. This means that a replica in a PostgreSQL cluster cannot be configured for logical replication, and consequently that the Debezium PostgreSQL connector can connect and communicate with only the primary server. Should this server fail, the connector stops. When the cluster is repaired, if the original primary server is once again promoted to primary, you can retart the connector. However, if a different PostgreSQL server with the plug-in and proper configuration is promoted to primary, you must change the connector configuration to point to the new primary server and then you can restart the connector.

WAL disk space consumption

In certain cases, it is possible for PostgreSQL disk space consumed by WAL files to spike or increase out of usual proportions. There are several possible reasons for this situation:

  • The LSN up to which the connector has received data is available in the confirmed_flush_lsn column of the server’s pg_replication_slots view. Data that is older than this LSN is no longer available, and the database is responsible for reclaiming the disk space.

    Also in the pg_replication_slots view, the restart_lsn column contains the LSN of the oldest WAL that the connector might require. If the value for confirmed_flush_lsn is regularly increasing and the value of restart_lsn lags then the database needs to reclaim the space.

    The database typically reclaims disk space in batch blocks. This is expected behavior and no action by a user is necessary.

  • There are many updates in a database that is being tracked but only a tiny number of updates are related to the table(s) and schema(s) for which the connector is capturing changes. This situation can be easily solved with periodic heartbeat events. Set the heartbeat.interval.ms connector configuration property.

  • The PostgreSQL instance contains multiple databases and one of them is a high-traffic database. Debezium captures changes in another database that is low-traffic in comparison to the other database. Debezium then cannot confirm the LSN as replication slots work per-database and Debezium is not invoked. As WAL is shared by all databases, the amount used tends to grow until an event is emitted by the database for which Debezium is capturing changes. To overcome this, it is necessary to:

    • Enable periodic heartbeat record generation with the heartbeat.interval.ms connector configuration property.

    • Regularly emit change events from the database for which Debezium is capturing changes.

      In the case of wal2json decoder plug-in, it is sufficient to generate empty events. This can be achieved for example by truncating an empty temporary table. For other decoder plug-ins, the recommendation is to create a supplementary table for which Debezium is not capturing changes.

    A separate process would then periodically update the table by either inserting a new row or repeatedly updating the same row. PostgreSQL then invokes Debezium, which confirms the latest LSN and allows the database to reclaim the WAL space. This task can be automated by means of the heartbeat.action.query connector configuration property.

For users on AWS RDS with PostgreSQL, a situation similar to the high traffic/low traffic scenario can occur in an idle environment. AWS RDS causes writes to its own system tables to be invisible to clients on a frequent basis (5 minutes). Again, regularly emitting events solves the problem.

Deployment

With Zookeeper, Kafka, and Kafka Connect installed, the remaining tasks to deploy a Debezium PostgreSQL connector are to download the connector’s plug-in archive, extract the JAR files into your Kafka Connect environment, and add the directory with the JAR files to Kafka Connect’s plugin.path. You then need to restart your Kafka Connect process to pick up the new JAR files.

If you are working with immutable containers, see Debezium’s Container images for Zookeeper, Kafka, PostgreSQL and Kafka Connect with the PostgreSQL connector already installed and ready to run. You can also run Debezium on Kubernetes and OpenShift.

Connector configuration example

Following is an example of the configuration for a PostgreSQL connector that connects to a PostgreSQL server on port 5432 at 192.168.99.100, whose logical name is fullfillment. Typically, you configure the Debezium PostgreSQL connector in a .json file using the configuration properties available for the connector.

You can choose to produce events for a subset of the schemas and tables. Optionally, ignore, mask, or truncate columns that are sensitive, too large, or not needed.

  1. {
  2. "name": "inventory-connector", (1)
  3. "config": {
  4. "connector.class": "io.debezium.connector.postgresql.PostgresConnector", (2)
  5. "database.hostname": "192.168.99.100", (3)
  6. "database.port": "5432", (4)
  7. "database.user": "postgres", (5)
  8. "database.password": "postgres", (6)
  9. "database.dbname" : "postgres", (7)
  10. "database.server.name": "fullfillment", (8)
  11. "table.whitelist": "public.inventory" (9)
  12. }
  13. }
1The name of the connector when registered with a Kafka Connect service.
2The name of this PostgreSQL connector class.
3The address of the PostgreSQL server.
4The port number of the PostgreSQL server.
5The name of the PostgreSQL user that has the required privileges.
6The password for the PostgreSQL user that has the required privileges.
7The name of the PostgreSQL database to connect to
8The logical name of the PostgreSQL server/cluster, which forms a namespace and is used in all the names of the Kafka topics to which the connector writes, the Kafka Connect schema names, and the namespaces of the corresponding Avro schema when the Avro converter is used.
9A list of all tables hosted by this server that this connector will monitor. This is optional, and there are other properties for listing the schemas and tables to include or exclude from monitoring.

See the complete list of PostgreSQL connector properties that can be specified in these configurations.

You can send this configuration with a POST command to a running Kafka Connect service. The service records the configuration and starts the connector task that connects to the PostgreSQL database and streams change event records to Kafka topics.

Adding connector configuration

To start running a PostgreSQL connector, create a connector configuration and add the configuration to your Kafka Connect cluster.

Prerequisites

Procedure

  1. Create a configuration for the PostgreSQL connector.

  2. Use the Kafka Connect REST API to add that connector configuration to your Kafka Connect cluster.

Results

When the connector starts, it performs a consistent snapshot of the PostgreSQL server databases that the connector is configured for. The connector then starts generating data change events for row-level operations and streaming change event records to Kafka topics.

Monitoring

The Debezium PostgreSQL connector provides two types of metrics that are in addition to the built-in support for JMX metrics that Zookeeper, Kafka, and Kafka Connect provide.

  • Snapshot metrics provide information about connector operation while performing a snapshot.

  • Streaming metrics provide information about connector operation when the connector is capturing changes and streaming change event records.

Debezium monitoring documentation provides details for how to expose these metrics by using JMX.

Snapshot metrics

The MBean is debezium.postgres:type=connector-metrics,context=snapshot,server=*<database.server.name>*.

AttributesTypeDescription

LastEvent

string

The last snapshot event that the connector has read.

MilliSecondsSinceLastEvent

long

The number of milliseconds since the connector has read and processed the most recent event.

TotalNumberOfEventsSeen

long

The total number of events that this connector has seen since last started or reset.

NumberOfEventsFiltered

long

The number of events that have been filtered by whitelist or blacklist filtering rules configured on the connector.

MonitoredTables

string[]

The list of tables that are monitored by the connector.

QueueTotalCapacity

int

The length the queue used to pass events between the snapshotter and the main Kafka Connect loop.

QueueRemainingCapacity

int

The free capacity of the queue used to pass events between the snapshotter and the main Kafka Connect loop.

TotalTableCount

int

The total number of tables that are being included in the snapshot.

RemainingTableCount

int

The number of tables that the snapshot has yet to copy.

SnapshotRunning

boolean

Whether the snapshot was started.

SnapshotAborted

boolean

Whether the snapshot was aborted.

SnapshotCompleted

boolean

Whether the snapshot completed.

SnapshotDurationInSeconds

long

The total number of seconds that the snapshot has taken so far, even if not complete.

RowsScanned

Map<String, Long>

Map containing the number of rows scanned for each table in the snapshot. Tables are incrementally added to the Map during processing. Updates every 10,000 rows scanned and upon completing a table.

Streaming metrics

The MBean is debezium.postgres:type=connector-metrics,context=streaming,server=*<database.server.name>*.

AttributesTypeDescription

LastEvent

string

The last streaming event that the connector has read.

MilliSecondsSinceLastEvent

long

The number of milliseconds since the connector has read and processed the most recent event.

TotalNumberOfEventsSeen

long

The total number of events that this connector has seen since last started or reset.

NumberOfEventsFiltered

long

The number of events that have been filtered by whitelist or blacklist filtering rules configured on the connector.

MonitoredTables

string[]

The list of tables that are monitored by the connector.

QueueTotalCapacity

int

The length the queue used to pass events between the streamer and the main Kafka Connect loop.

QueueRemainingCapacity

int

The free capacity of the queue used to pass events between the streamer and the main Kafka Connect loop.

Connected

boolean

Flag that denotes whether the connector is currently connected to the database server.

MilliSecondsBehindSource

long

The number of milliseconds between the last change event’s timestamp and the connector processing it. The values will incoporate any differences between the clocks on the machines where the database server and the connector are running.

NumberOfCommittedTransactions

long

The number of processed transactions that were committed.

SourceEventPosition

Map<String, String>

The coordinates of the last received event.

LastTransactionId

string

Transaction identifier of the last processed transaction.

Connector configuration properties

The Debezium PostgreSQL connector has many configuration properties that you can use to achieve the right connector behavior for your application. Many properties have default values. Information about the properties is organized as follows:

The following configuration properties are required unless a default value is available.

Table 18. Required connector configuration properties
PropertyDefaultDescription

Unique name for the connector. Attempting to register again with the same name will fail. This property is required by all Kafka Connect connectors.

The name of the Java class for the connector. Always use a value of io.debezium.connector.postgresql.PostgresConnector for the PostgreSQL connector.

1

The maximum number of tasks that should be created for this connector. The PostgreSQL connector always uses a single task and therefore does not use this value, so the default is always acceptable.

decoderbufs

The name of the PostgreSQL logical decoding plug-in installed on the PostgreSQL server.

Supported values are decoderbufs, wal2json, wal2jsonrds, wal2json_streaming, wal2json_rds_streaming and pgoutput.

If you are using a wal2json plug-in and transactions are very large, the JSON batch event that contains all transaction changes might not fit into the hard-coded memory buffer, which has a size of 1 GB. In such cases, switch to a streaming plug-in, by setting the plugin-name property to wal2json_streaming or wal2json_rds_streaming. With a streaming plug-in, PostgreSQL sends the connector a separate message for each change in a transaction.

debezium

The name of the PostgreSQL logical decoding slot that was created for streaming changes from a particular plug-in for a particular database/schema. The server uses this slot to stream events to the Debezium connector that you are configuring.

Slot names must conform to PostgreSQL replication slot naming rules, which state: “Each replication slot has a name, which can contain lower-case letters, numbers, and the underscore character.”

false

Whether or not to delete the logical replication slot when the connector stops in a graceful, expected way. The default behavior is that the replication slot remains configured for the connector when the connector stops. When the connector restarts, having the same replication slot enables the connector to start processing where it left off.

Set to true in only testing or development environments. Dropping the slot allows the database to discard WAL segments. When the connector restarts it performs a new snapshot or it can continue from a persistent offset in the Kafka Connect offsets topic.

dbz_publication

The name of the PostgreSQL publication created for streaming changes when using pgoutput.

This publication is created at start-up if it does not already exist and it includes all tables. Debezium then applies its own whitelist/blacklist filtering, if configured, to limit the publication to change events for the specific tables of interest. The connector user must have superuser permissions to create this publication, so it is usually preferable to create the publication before starting the connector for the first time.

If the publication already exists, either for all tables or configured with a subset of tables, Debezium uses the publication as it is defined.

IP address or hostname of the PostgreSQL database server.

5432

Integer port number of the PostgreSQL database server.

Name of the PostgreSQL database user for connecting to the PostgreSQL database server.

Password to use when connecting to the PostgreSQL database server.

The name of the PostgreSQL database from which to stream the changes.

Logical name that identifies and provides a namespace for the particular PostgreSQL database server or cluster in which Debezium is capturing changes. Only alphanumeric characters and underscores should be used in the database server logical name. The logical name should be unique across all other connectors, since it is used as a topic name prefix for all Kafka topics that receive records from this connector.

An optional, comma-separated list of regular expressions that match names of schemas for which you want to capture changes. Any schema name not included in the whitelist is excluded from having its changes captured. By default, all non-system schemas have their changes captured. Do not also set the schema.blacklist property.

An optional, comma-separated list of regular expressions that match names of schemas for which you do not want to capture changes. Any schema whose name is not included in the blacklist has its changes captured, with the exception of system schemas. Do not also set the schema.whitelist property.

An optional, comma-separated list of regular expressions that match fully-qualified table identifiers for tables whose changes you want to capture. Any table not included in the whitelist does not have its changes captured. Each identifier is of the form schemaName.tableName. By default, the connector captures changes in every non-system table in each schema whose changes are being captured. Do not also set the table.blacklist property.

An optional, comma-separated list of regular expressions that match fully-qualified table identifiers for tables whose changes you do not want to capture. Any table not included in the blacklist has it changes captured. Each identifier is of the form schemaName.tableName. Do not also set the table.whitelist property.

An optional, comma-separated list of regular expressions that match the fully-qualified names of columns that should be included in change event record values. Fully-qualified names for columns are of the form schemaName.tableName.columnName. Do not also set the column.blacklist property.

An optional, comma-separated list of regular expressions that match the fully-qualified names of columns that should be excluded from change event record values. Fully-qualified names for columns are of the form schemaName.tableName.columnName. Do not also set the column.whitelist property.

adaptive

Time, date, and timestamps can be represented with different kinds of precision:

adaptive captures the time and timestamp values exactly as in the database using either millisecond, microsecond, or nanosecond precision values based on the database column’s type.

adaptive_time_microseconds captures the date, datetime and timestamp values exactly as in the database using either millisecond, microsecond, or nanosecond precision values based on the database column’s type. An exception is TIME type fields, which are always captured as microseconds.

connect always represents time and timestamp values by using Kafka Connect’s built-in representations for Time, Date, and Timestamp, which use millisecond precision regardless of the database columns’ precision. See temporal values.

precise

Specifies how the connector should handle values for DECIMAL and NUMERIC columns:

precise represents values by using java.math.BigDecimal to represent values in binary form in change events.

double represents values by using double values, which might result in a loss of precision but which is easier to use.

string encodes values as formatted strings, which are easy to consume but semantic information about the real type is lost. See Decimal types.

map

Specifies how the connector should handle values for hstore columns:

map represents values by using MAP.

json represents values by using json string. This setting encodes values as formatted strings such as {“key” : “val”}. See PostgreSQL HSTORE type.

numeric

Specifies how the connector should handle values for interval columns:

numeric represents intervals using approximate number of microseconds.

string represents intervals exactly by using the string pattern representation P<years>Y<months>M<days>DT<hours>H<minutes>M<seconds>S. For example: P1Y2M3DT4H5M6.78S. See PostgreSQL basic types.

disable

Whether to use an encrypted connection to the PostgreSQL server. Options include:

disable uses an unencrypted connection.

require uses a secure (encrypted) connection, and fails if one cannot be established.

verify-ca behaves like require but also verifies the server TLS certificate against the configured Certificate Authority (CA) certificates, or fails if no valid matching CA certificates are found.

verify-full behaves like verify-ca but also verifies that the server certificate matches the host to which the connector is trying to connect. See the PostgreSQL documentation for more information.

The path to the file that contains the SSL certificate for the client. See the PostgreSQL documentation for more information.

The path to the file that contains the SSL private key of the client. See the PostgreSQL documentation for more information.

The password to access the client private key from the file specified by database.sslkey. See the PostgreSQL documentation for more information.

The path to the file that contains the root certificate(s) against which the server is validated. See the PostgreSQL documentation for more information.

true

Enable TCP keep-alive probe to verify that the database connection is still alive. See the PostgreSQL documentation for more information.

true

Controls whether a tombstone event should be generated after a delete event.

true - delete operations are represented by a delete event and a subsequent tombstone event.

false - only a delete event is sent.

After a delete operation, emitting a tombstone event enables Kafka to delete all change event records that have the same key as the deleted row.

n/a

An optional, comma-separated list of regular expressions that match the fully-qualified names of character-based columns. Fully-qualified names for columns are of the form schemaName.tableName.columnName. In change event records, values in these columns are truncated if they are longer than the number of characters specified by length in the property name. You can specify multiple properties with different lengths in a single configuration. Length must be a positive integer, for example, column.truncate.to.20.chars.

n/a

An optional, comma-separated list of regular expressions that match the fully-qualified names of character-based columns. Fully-qualified names for columns are of the form schemaName.tableName.columnName. In change event values, the values in the specified table columns are replaced with length number of asterisk (*) characters. You can specify multiple properties with different lengths in a single configuration. Length must be a positive integer or zero. When you specify zero, the connector replaces a value with an empty string.

n/a

An optional, comma-separated list of regular expressions that match the fully-qualified names of character-based columns. Fully-qualified names for columns are of the form schemaName.tableName.columnName. In change event values, the values in the specified columns are replaced with pseudonyms.

A pseudonym consists of the hashed value that results from applying the specifed hashAlgorithm and salt. Based on the hash function that is used, referential integrity is kept while column values are replaced with pseudonyms. Supported hash functions are described in the MessageDigest section of the Java Cryptography Architecture Standard Algorithm Name Documentation.

If necessary, the pseudonym is automatically shortened to the length of the column. You can specify multiple properties with different hash algorithms and salts in a single configuration. In the following example, CzQMA0cB5K is a randomly selected salt.

column.mask.hash.SHA-256.with.salt.CzQMA0cB5K =inventory.orders.customerName,inventory.shipment.customerName

Depending on the hashAlgorithm used, the salt selected, and the actual data set, the resulting masked data set might not be completely masked.

n/a

An optional, comma-separated list of regular expressions that match the fully-qualified names of columns. Fully-qualified names for columns are of the form databaseName.tableName.columnName, or databaseName.schemaName.tableName.columnName.

For each specified column, the connector adds the column’s original type and original length as parameters to the corresponding field schemas in the emitted change records. The following added schema parameters propagate the original type name and also the original length for variable-width types:

debezium.source.column.type + debezium.source.column.length + debezium.source.column.scale

This property is useful for properly sizing corresponding columns in sink databases.

n/a

An optional, comma-separated list of regular expressions that match the database-specific data type name for some columns. Fully-qualified data type names are of the form databaseName.tableName.typeName, or databaseName.schemaName.tableName.typeName.

For these data types, the connector adds parameters to the corresponding field schemas in emitted change records. The added parameters specify the original type and length of the column:

debezium.source.column.type + debezium.source.column.length + debezium.source.column.scale

These parameters propagate a column’s original type name and length, for variable-width types, respectively. This property is useful for properly sizing corresponding columns in sink databases.

See the list of PostgreSQL-specific data type names.

empty string

A semicolon separated list of tables with regular expressions that match table column names. The connector maps values in matching columns to key fields in change event records that it sends to Kafka topics. This is useful when a table does not have a primary key, or when you want to order change event records in a Kafka topic according to a field that is not a primary key.

Separate entries with semicolons. Insert a colon between the fully-qualified table name and its regular expression. The format is:

schema-name.table-name:_regexp;…​

For example,

schemaA.table_a:regex_1;schemaB.table_b:regex_2;schemaC.table_c:regex_3

If table_a has a an id column, and regex_1 is ^i (matches any column that starts with i), the connector maps the value in table_a‘s id column to a key field in change events that the connector sends to Kafka.

all_tables

Applies only when streaming changes by using the pgoutput plug-in. The setting determines how creation of a publication should work. Possible settings are:

all_tables - If a publication exists, the connector uses it. If a publication does not exist, the connector creates a publication for all tables in the database for which the connector is capturing changes. This requires that the database user who has permission to perform replications also has permission to create a publication. This is granted with CREATE PUBLICATION <publication_name> FOR ALL TABLES;.

disabled - The connector does not attempt to create a publication. A database administrator or the user configured to perform replications must have created the publication before running the connector. If the connector cannot find the publication, the connector throws an exception and stops.

filtered - If a publication exists, the connector uses it. If no publication exists, the connector creates a new publication for tables that match the current filter configuration as specified by the database.exclude.list, database.include.list, table.exclude.list, and table.include.list connector configuration properties. For example: CREATE PUBLICATION <publication_name> FOR TABLE <tbl1, tbl2, tbl3>.

bytes

Specifies how binary (bytea) columns should be represented in change events:

bytes represents binary data as byte array.

base64 represents binary data as base64-encoded strings.

hex represents binary data as hex-encoded (base16) strings.

The following advanced configuration properties have defaults that work in most situations and therefore rarely need to be specified in the connector’s configuration.

Table 19. Advanced connector configuration properties
PropertyDefaultDescription

initial

Specifies the criteria for performing a snapshot when the connector starts:

initial - The connector performs a snapshot only when no offsets have been recorded for the logical server name.

always - The connector performs a snapshot each time the connector starts.

never - The connector never performs snapshots. When a connector is configured this way, its behavior when it starts is as follows. If there is a previously stored LSN in the Kafka offsets topic, the connector continues streaming changes from that position. If no LSN has been stored, the connector starts streaming changes from the point in time when the PostgreSQL logical replication slot was created on the server. The never snapshot mode is useful only when you know all data of interest is still reflected in the WAL.

initial_only - The connector performs an initial snapshot and then stops, without processing any subsequent changes.

exported - The connector performs a snapshot based on the point in time when the replication slot was created. This is an excellent way to perform the snapshot in a lock-free way.

custom - The connector performs a snapshot according to the setting for the snapshot.custom.class property, which is a custom implementation of the io.debezium.connector.postgresql.spi.Snapshotter interface.

Thereference table for snapshot mode settings has more details.

A full Java class name that is an implementation of the io.debezium.connector.postgresql.spi.Snapshotter interface. Required when the snapshot.mode property is set to custom. See custom snapshotter SPI.

10000

Positive integer value that specifies the maximum amount of time (in milliseconds) to wait to obtain table locks when performing a snapshot. If the connector cannot acquire table locks in this time interval, the snapshot fails. How the connector performs snapshots provides details.

Controls which table rows are included in snapshots. This property affects snapshots only. It does not affect events that are generated by the logical decoding plug-in. Specify a comma-separated list of fully-qualified table names in the form databaseName.tableName.

For each table that you specify, also specify another configuration property: snapshot.select.statement.overrides.DB_NAME.TABLE_NAME, for example: snapshot.select.statement.overrides.customers.orders. Set this property to a SELECT statement that obtains only the rows that you want in the snapshot. When the connector performs a snapshot, it executes this SELECT statement to retrieve data from that table.

A possible use case for setting these properties is large, append-only tables. You can specify a SELECT statement that sets a specific point for where to start a snapshot, or where to resume a snapshot if a previous snapshot was interrupted.

fail

Specifies how the connector should react to exceptions during processing of events:

fail propagates the exception, indicates the offset of the problematic event, and causes the connector to stop.

warn logs the offset of the problematic event, skips that event, and continues processing.

skip skips the problematic event and continues processing.

20240

Positive integer value for the maximum size of the blocking queue. The connector places change events received from streaming replication in the blocking queue before writing them to Kafka. This queue can provide backpressure when, for example, writing records to Kafka is slower that it should be or Kafka is not available.

10240

Positive integer value that specifies the maximum size of each batch of events that the connector processes.

1000

Positive integer value that specifies the number of milliseconds the connector should wait for new change events to appear before it starts processing a batch of events. Defaults to 1000 milliseconds, or 1 second.

false

Specifies connector behavior when the connector encounters a field whose data type is unknown. The default behavior is that the connector omits the field from the change event and logs a warning.

Set this property to true if you want the change event to contain an opaque binary representation of the field. This lets consumers decode the field. You can control the exact representation by setting the binary handling mode property.

Consumers risk backward compatibility issues when include.unknown.datatypes is set to true. Not only may the database-specific binary representation change between releases, but if the data type is eventually supported by Debezium, the data type will be sent downstream in a logical type, which would require adjustments by consumers. In general, when encountering unsupported data types, create a feature request so that support can be added.

A semicolon separated list of SQL statements that the connector executes when it establishes a JDBC connection to the database. To use a semicolon as a character and not as a delimiter, specify two consecutive semicolons, ;;.

The connector may establish JDBC connections at its own discretion. Consequently, this property is useful for configuration of session parameters only, and not for executing DML statements.

The connector does not execute these statements when it creates a connection for reading the transaction log.

0

Controls how frequently the connector sends heartbeat messages to a Kafka topic. The default behavior is that the connector does not send heartbeat messages.

Heartbeat messages are useful for monitoring whether the connector is receiving change events from the database. Heartbeat messages might help decrease the number of change events that need to be re-sent when a connector restarts. To send heartbeat messages, set this property to a positive integer, which indicates the number of milliseconds between heartbeat messages.

Heartbeat messages are needed when there are many updates in a database that is being tracked but only a tiny number of updates are related to the table(s) and schema(s) for which the connector is capturing changes. In this situation, the connector reads from the database transaction log as usual but rarely emits change records to Kafka. This means that no offset updates are committed to Kafka and the connector does not have an opportunity to send the latest retrieved LSN to the database. The database retains WAL files that contain events that have already been processed by the connector. Sending heartbeat messages enables the connector to send the latest retrieved LSN to the database, which allows the database to reclaim disk space being used by no longer needed WAL files.

debezium-heartbeat

Controls the name of the topic to which the connector sends heartbeat messages. The topic name has this pattern:

<heartbeat.topics.prefix>.<server.name>

For example, if the database server name is fullfillment, the default topic name is debezium-heartbeat.fulfillment.

Specifies a query that the connector executes on the source database when the connector sends a heartbeat message.

This is useful for resolving the situation described in WAL disk space consumption, where capturing changes from a low-traffic database on the same host as a high-traffic database prevents Debezium from processing WAL records and thus acknowledging WAL positions with the database. To address this situation, create a heartbeat table in the low-traffic database, and set this property to a statement that inserts records into that table, for example:

INSERT INTO test_heartbeat_table (text) VALUES (‘test_heartbeat’)

This allows the connector to receive changes from the low-traffic database and acknowledge their LSNs, which prevents unbounded WAL growth on the database host.

columns_diff

Specify the conditions that trigger a refresh of the in-memory schema for a table.

columns_diff is the safest mode. It ensures that the in-memory schema stays in sync with the database table’s schema at all times.

columns_diff_exclude_unchanged_toast instructs the connector to refresh the in-memory schema cache if there is a discrepancy with the schema derived from the incoming message, unless unchanged TOASTable data fully accounts for the discrepancy.

This setting can significantly improve connector performance if there are frequently-updated tables that have TOASTed data that are rarely part of updates. However, it is possible for the in-memory schema to become outdated if TOASTable columns are dropped from the table.

An interval in milliseconds that the connector should wait before performing a snapshot when the connector starts. If you are starting multiple connectors in a cluster, this property is useful for avoiding snapshot interruptions, which might cause re-balancing of connectors.

10240

During a snapshot, the connector reads table content in batches of rows. This property specifies the maximum number of rows in a batch.

Semicolon separated list of parameters to pass to the configured logical decoding plug-in. For example, add-tables=public.table,public.table2;include-lsn=true.

If you are using the wal2json plug-in, this property is useful for enabling server-side table filtering. Allowed values depend on the configured plug-in.

true if connector configuration sets the key.converter or value.converter property to the Avro converter.

false if not.

Indicates whether field names are sanitized to adhere to Avro naming requirements.

6

If connecting to a replication slot fails, this is the maximum number of consecutive attempts to connect.

10000 (10 seconds)

The number of milliseconds to wait between retry attempts when the connector fails to connect to a replication slot.

__debezium_unavailable_value

Specifies the constant that the connector provides to indicate that the original value is a toasted value that is not provided by the database. If the setting of toasted.value.placeholder starts with the hex: prefix it is expected that the rest of the string represents hexadecimally encoded octets. See toasted values for additional details.

false

Determines whether the connector generates events with transaction boundaries and enriches change event envelopes with transaction metadata. Specify true if you want the connector to do this. See Transaction metadata for details.

Pass-through connector configuration properties

The connector also supports pass-through configuration properties that are used when creating the Kafka producer and consumer.

Be sure to consult the Kafka documentation for all of the configuration properties for Kafka producers and consumers. The PostgreSQL connector does use the new consumer configuration properties.

Behavior when things go wrong

Debezium is a distributed system that captures all changes in multiple upstream databases; it never misses or loses an event. When the system is operating normally or being managed carefully then Debezium provides exactly once delivery of every change event record.

If a fault does happen then the system does not lose any events. However, while it is recovering from the fault, it might repeat some change events. In these abnormal situations, Debezium, like Kafka, provides at least once delivery of change events.

The rest of this section describes how Debezium handles various kinds of faults and problems.

Configuration and startup errors

In the following situations, the connector fails when trying to start, reports an error/exception in the log, and stops running:

  • The connector’s configuration is invalid.

  • The connector cannot successfully connect to PostgreSQL by using the specified connection parameters.

  • The connector is restarting from a previously-recorded position in the PostgreSQL WAL (by using the LSN) and PostgreSQL no longer has that history available.

In these cases, the error message has details about the problem and possibly a suggested workaround. After you correct the configuration or address the PostgreSQL problem, restart the connector.

PostgreSQL becomes unavailable

When the connector is running, the PostgreSQL server that it is connected to could become unavailable for any number of reasons. If this happens, the connector fails with an error and stops. When the server is available again, restart the connector.

The PostgreSQL connector externally stores the last processed offset in the form of a PostgreSQL LSN. After a connector restarts and connects to a server instance, the connector communicates with the server to continue streaming from that particular offset. This offset is available as long as the Debezium replication slot remains intact. Never drop a replication slot on the primary server or you will lose data. See the next section for failure cases in which a slot has been removed.

Cluster failures

As of release 12, PostgreSQL allows logical replication slots only on primary servers. This means that you can point a Debezium PostgreSQL connector to only the active primary server of a database cluster. Also, replication slots themselves are not propagated to replicas. If the primary server goes down, a new primary must be promoted.

The new primary must have the logical decoding plug-in installed and a replication slot that is configured for use by the plug-in and the database for which you want to capture changes. Only then can you point the connector to the new server and restart the connector.

There are important caveats when failovers occur and you should pause Debezium until you can verify that you have an intact replication slot that has not lost data. After a failover:

  • There must be a process that re-creates the Debezium replication slot before allowing the application to write to the new primary. This is crucial. Without this process, your application can miss change events.

  • You might need to verify that Debezium was able to read all changes in the slot before the old primary failed.

One reliable method of recovering and verifying whether any changes were lost is to recover a backup of the failed primary to the point immediately before it failed. While this can be administratively difficult, it allows you to inspect the replication slot for any unconsumed changes.

There are discussions in the PostgreSQL community around a feature called failover slots that would help mitigate this problem, but as of PostgreSQL 12, they have not been implemented. However, there is active development for PostgreSQL 13 to support logical decoding on standbys, which is a major requirement to make failover possible. You can find more about this in this 0w50sRagcs+jrktBXuJAWGZQdSTMa57CCY+Dh-xbg@mail.gmail.com">community thread.

More about the concept of failover slots is in this blog post.

Kafka Connect process stops gracefully

Suppose that Kafka Connect is being run in distributed mode and a Kafka Connect process is stopped gracefully. Prior to shutting down that process, Kafka Connect migrates the process’s connector tasks to another Kafka Connect process in that group. The new connector tasks start processing exactly where the prior tasks stopped. There is a short delay in processing while the connector tasks are stopped gracefully and restarted on the new processes.

Kafka Connect process crashes

If the Kafka Connector process stops unexpectedly, any connector tasks it was running terminate without recording their most recently processed offsets. When Kafka Connect is being run in distributed mode, Kafka Connect restarts those connector tasks on other processes. However, PostgreSQL connectors resume from the last offset that was recorded by the earlier processes. This means that the new replacement tasks might generate some of the same change events that were processed just prior to the crash. The number of duplicate events depends on the offset flush period and the volume of data changes just before the crash.

Because there is a chance that some events might be duplicated during a recovery from failure, consumers should always anticipate some duplicate events. Debezium changes are idempotent, so a sequence of events always results in the same state.

In each change event record, Debezium connectors insert source-specific information about the origin of the event, including the PostgreSQL server’s time of the event, the ID of the server transaction, and the position in the write-ahead log where the transaction changes were written. Consumers can keep track of this information, especially the LSN, to determine whether an event is a duplicate.

Kafka becomes unavailable

As the connector generates change events, the Kafka Connect framework records those events in Kafka by using the Kafka producer API. Periodically, at a frequency that you specify in the Kafka Connect configuration, Kafka Connect records the latest offset that appears in those change events. If the Kafka brokers become unavailable, the Kafka Connect process that is running the connectors repeatedly tries to reconnect to the Kafka brokers. In other words, the connector tasks pause until a connection can be re-established, at which point the connectors resume exactly where they left off.

Connector is stopped for a duration

If the connector is gracefully stopped, the database can continue to be used. Any changes are recorded in the PostgreSQL WAL. When the connector restarts, it resumes streaming changes where it left off. That is, it generates change event records for all database changes that were made while the connector was stopped.

A properly configured Kafka cluster is able to handle massive throughput. Kafka Connect is written according to Kafka best practices, and given enough resources a Kafka Connect connector can also handle very large numbers of database change events. Because of this, after being stopped for a while, when a Debezium connector restarts, it is very likely to catch up with the database changes that were made while it was stopped. How quickly this happens depends on the capabilities and performance of Kafka and the volume of changes being made to the data in PostgreSQL.