Chapter 2. Debezium Connector for PostgreSQL
Debezium’s PostgreSQL Connector can monitor and record row-level changes in the schemas of a PostgreSQL database.
The first time it connects to a PostgreSQL server/cluster, it reads a consistent snapshot of all of the schemas. When that snapshot is complete, the connector continuously streams the changes that were committed to PostgreSQL 9.6 or later and generates corresponding insert, update and delete events. All of the events for each table are recorded in a separate Kafka topic, where they can be easily consumed by applications and services.
2.1. Overview
PostgreSQL’s logical decoding feature was first introduced in version 9.4 and is a mechanism which allows the extraction of the changes which were committed to the transaction log and the processing of these changes in a user-friendly manner via the help of an output plugin. This output plugin must be installed prior to running the PostgreSQL server and enabled together with a replication slot in order for clients to be able to consume the changes.
PostgreSQL connector contains two different parts which work together in order to be able to read and process server changes:
- A logical decoding output plugin, which has to be installed and configured in the PostgreSQL server.
- Java code (the actual Kafka Connect connector) which reads the changes produced by the plugin, using PostgreSQL’s streaming replication protocol, via the PostgreSQL JDBC driver
The connector then produces a change event for every row-level insert, update, and delete operation that was received, recording all the change events for each table in a separate Kafka topic. Your client applications read the Kafka topics that correspond to the database tables they’re interested in following, and react to every row-level event it sees in those topics.
PostgreSQL normally purges WAL segments after some period of time. This means that the connector won’t 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, we start with a consistent view of all of the data, yet continue reading without having lost any of the changes made while the snapshot was taking place.
The connector is also tolerant of failures. As the connector reads changes and produces events, it records the position in the write-ahead log with each event. If the connector stops for any reason (including communication failures, network problems, or crashes), upon restart it simply continues reading the WAL where it last left off. This includes snapshots: if the snapshot was not completed when the connector is stopped, upon restart it will begin a new snapshot.
2.1.1. Logical decoding output plugin
The pgoutput
logical decoder is the only supported logical decoder in the Tecnhology Preview release of Debezium.
pgoutput
, the standard logical decoding plug-in in PostgreSQL 10+, is maintained by the Postgres community, and is also used by Postgres for logical replication. The pgoutput
plug-in is always present, meaning that no additional libraries must be installed, and the connector will interpret the raw replication event stream into change events directly.
The connector’s functionality relies on PostgreSQL’s logical decoding feature. Please be aware of the following limitations which are also reflected by the connector:
- 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 only supported on
primary
servers: this means that when there is a cluster of PostgreSQL servers, the connector can only run on the activeprimary
server. It cannot run onhot
orwarm
standby replicas. If theprimary
server fails or is demoted, the connector will stop. Once theprimary
has recovered the connector can simply be restarted. If a different PostgreSQL server has been promoted toprimary
, the connector configuration must be adjusted before the connector is restarted. Make sure you read more about how the connector behaves when things go wrong.
Debezium currently supports only databases with UTF-8 character encoding. With a single byte character encoding it is not possible to correctly process strings containing extended ASCII code characters.
2.2. Setting up PostgreSQL
This release of Debezium only supports the native pgoutput logical replication stream. To set up PostgreSQL using pgoutput, you will need to enable a replication slot, and configure a user with sufficient privileges to perform the replication.
2.2.1. Configuring the replication slot
PostgreSQL’s logical decoding uses replication slots.
First, you configure the replication slot:
postgresql.conf
wal_level=logical max_wal_senders=1 max_replication_slots=1
-
wal_level
tells the server to use logical decoding with the write-ahead log -
max_wal_senders
tells the server to use a maximum of 1 separate processes for processing WAL changes -
max_replication_slots
tells the server to allow a maximum of 1 replication slots to be created for streaming WAL changes
Replication slots are guaranteed to retain all WAL required for Debezium even during Debezium outages. It is important for this reason 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, refer to the the Postgres documentation.
We recommend reading and understanding the WAL configuration documentation regarding the mechanics and configuration of the PostgreSQL write-ahead log.
2.2.2. Setting up Permissions
Next, configure a database user who can perform replications.
Replication can only be performed by a database user that has appropriate permissions and only for a configured number of hosts.
In order to give a user replication permissions, define a PostgreSQL role that has at least the REPLICATION
and LOGIN
permissions. For example:
CREATE ROLE name REPLICATION LOGIN;
Superusers have by default both of the above roles.
Finally, 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
local replication <youruser> trust 1 host replication <youruser> 127.0.0.1/32 trust 2 host replication <youruser> ::1/128 trust 3
See the PostgreSQL documentation for more information on network masks.
2.2.3. WAL Disk Space Consumption
In certain cases, it is possible that PostgreSQL disk space consumed by WAL files either experiences spikes or increases out of usual proportions. There are three potential reasons that explain the situation:
-
Debezium regularly confirms LSN of processed events to the database. This is visible as
confirmed_flush_lsn
in thepg_replication_slots
slots table. The database is responsible for reclaiming the disk space and the WAL size can be calculated fromrestart_lsn
of the same table. So if theconfirmed_flush_lsn
is regularly increasing andrestart_lsn
lags then the database does need to reclaim the space. Disk space is usually reclaimed in batch blocks so this is expected behaviour and no action on a user’s side is necessary. -
There are many updates in a monitored database but only a minuscule amount relates to the monitored table(s) and/or schema(s). This situation can be easily solved by enabling periodic heartbeat events using
heartbeat.interval.ms
configuration option. - The PostgreSQL instance contains multiple databases where one of them is a high-traffic database. Debezium monitors another database that is low-traffic in comparison to the other one. Debezium then cannot confirm the LSN as replication slots work per-database and Debezium is not invoked. As WAL is shared by all databases it tends to grow until an event is emitted by the database monitored by Debezium.
To overcome the third cause it is necessary to
-
enable periodic heartbeat record generation using the
heartbeat.interval.ms
configuration option - regularly emit change events from the database tracked by Debezium
A separate process would then periodically update the table (either inserting a new event or updating the same row all over). PostgreSQL then will invoke Debezium which will confirm the latest LSN and allow the database to reclaim the WAL space.
For users on AWS RDS with Postgres, a similar situation to the third cause may occur on an idle environment, since AWS RDS makes writes to its own system tables not visible to the useres on a frequent basis (5 minutes). Again regularly emitting events will solve the problem.
2.2.4. How the PostgreSQL connector works
2.2.4.1. Snapshots
Most PostgreSQL servers are configured to not retain the complete history of the database in the WAL segments, so the PostgreSQL connector would be unable to see the entire history of the database by simply reading the WAL. So, by default the connector will upon first startup perform an initial consistent snapshot of the database. Each snapshot consists of the following steps (when using the builtin snapshot modes, custom snapshot modes may override this):
-
Start a transaction with a SERIALIZABLE, READ ONLY, DEFERRABLE isolation level to ensure that all subsequent reads within this transaction are done against a single consistent version of the data. Any changes to the data due to subsequent
INSERT
,UPDATE
, andDELETE
operations by other clients will not be visible to this transaction. -
Obtain a
ACCESS SHARE MODE
lock on each of the monitored tables to ensure that no structural changes can occur to any of the tables while the snapshot is taking place. Note that these locks do not prevent tableINSERTS
,UPDATES
andDELETES
from taking place during the operation. This step is omitted when using the exported snapshot mode to allow for a lock-free snapshots. - Read the current position in the server’s transaction log.
-
Scan all of the database tables and schemas, and generate a
READ
event for each row and write that event to the appropriate table-specific Kafka topic. - Commit the transaction.
- 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 will begin a new snapshot. Once the connector does complete its initial snapshot, the PostgreSQL connector then continues streaming from the position read during step 3, ensuring that it does not miss any updates. If the connector stops again for any reason, upon restart it will simply continue streaming changes from where it previously left off.
A second snapshot mode allows the connector to perform snapshots always. This behavior tells the connector to always perform a snapshot when it starts up, and after the snapshot completes to continue streaming changes from step 3 in the above sequence. This mode can be used in cases when it’s known that some WAL segments have been deleted and are no longer available, or in case of a cluster failure after a new primary has been promoted so that the connector doesn’t miss out on any potential changes that could’ve taken place after the new primary had been promoted but before the connector was restarted on the new primary.
The third snapshot mode instructs the connector to never performs snapshots. When a new connector is configured this way, if will either continue streaming changes from a previous stored offset or it will start from the point in time when the PostgreSQL logical replication slot was first created on the server. Note that this mode is useful only when you know all data of interest is still reflected in the WAL.
The fourth snapshot mode, initial only, will perform a database snapshot and then stop before streaming any other changes. If the connector had started but did not complete a snapshot before stopping, the connector will restart the snapshot process and stop once the snapshot completes.
The fifth snapshot mode, exported, will perform 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.
2.2.4.2. Streaming Changes
The PostgreSQL connector will typically spend 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 where the client can receive changes from the server as they are committed in the server’s transaction log at certain positions (also known as Log Sequence Numbers
or in short LSNs).
Whenever the server commits a transaction, a separate server process invokes a callback function from the logical decoding plugin. This function processes the changes from the transaction, converts them to a specific format (Protobuf or JSON in the case of Debezium plugin) and writes them on an output stream which can then be consumed by clients.
The PostgreSQL connector acts as a PostgreSQL client, and when it receives these changes it transforms the events into Debezium create, update, or delete events that include the LSN position of the event. The PostgreSQL connector forwards these change events to the Kafka Connect framework (running in the same process), which then asynchronously writes them in the same order to the appropriate Kafka topic. Kafka Connect uses the term offset for the source-specific position information that Debezium includes with each event, and Kafka Connect periodically records the most recent offset in another Kafka topic.
When Kafka Connect gracefully shuts down, it stops the connectors, flushes all events to Kafka, and records the last offset received from each connector. Upon restart, Kafka Connect reads the last recorded offset for each connector, and starts the connector from that point. The PostgreSQL connector uses the LSN recorded in each change event as the offset, so that upon restart the connector requests the PostgreSQL server send it the events starting just after that position.
The PostgreSQL connector retrieves the schema information as part of the events sent by the logical decoder plug-in. The only exception is the information about which columns compose the primary key, as this information is obtained from the JDBC metadata (side channel). If the primary key definition of a table changes (by adding, removing or renaming PK columns), then there exists a slight risk of an unfortunate timing when the primary key information from JDBC will not be synchronized with the change data in the logical decoding event and a small amount of messages will be created with an inconsistent key structure. If this happens then a restart of the connector and a reprocessing of the messages will fix the issue. To prevent the issue completely it is recommended to synchronize updates to the primary key structure with Debezium roughly using following sequence of operations:
- Put the database or an application into a read-only mode
- Let Debezium process all remaining events
- Stop Debezium
- Update the primary key definition
- Put the database or the application into read/write state and start Debezium again
2.2.4.3. PostgreSQL 10+ Logical Decoding Support (pgoutput)
As of PostgreSQL 10+, a new logical replication stream mode was introduced, called pgoutput. This logical replication stream mode is natively supported by PostgreSQL, which means that this connector can consume that replication stream without the need for additional plug-ins being installed. This is particularly valuable for environments where installation of plug-ins isn’t supported or allowed.
See Setting up PostgreSQL for more details.
2.2.4.4. 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
configuration property, schemaName is the name of the database schema where the operation occurred, and tableName is the name of the database table on which the operation occurred.
For example, consider a PostgreSQL installation with a postgres
database and an inventory
schema that contains four tables: products
, products_on_hand
, customers
, and orders
. If the connector monitoring this database were given a logical server name of fulfillment
, then the connector would produce events on these four Kafka topics:
-
fulfillment.inventory.products
-
fulfillment.inventory.products_on_hand
-
fulfillment.inventory.customers
-
fulfillment.inventory.orders
If on the other hand the tables were not part of a specific schema but rather created in the default public
PostgreSQL schema, then the name of the Kafka topics would be:
-
fulfillment.public.products
-
fulfillment.public.products_on_hand
-
fulfillment.public.customers
-
fulfillment.public.orders
2.2.4.5. Meta Information
Each record
produced by the PostgreSQL connector has, in addition to the database event, some meta-information about 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 be placed:
"sourcePartition": { "server": "fulfillment" }, "sourceOffset": { "lsn": "24023128", "txId": "555", "ts_ms": "1482918357011" }, "kafkaPartition": null
The PostgreSQL connector uses only 1 Kafka Connect partition and it places the generated events into 1 Kafka partition. Therefore, the name of the sourcePartition
will always default to the name of the database.server.name
configuration property, while the kafkaPartition
has the value null
which means that the connector does not use a specific Kafka partition.
The sourceOffset
portion of the message contains information about the location of the server where the event occurred:
-
lsn
represents the PostgreSQL log sequence number oroffset
in the transaction log -
txId
represents the identifier of the server transaction which caused the event -
ts_ms
represents the number of microseconds since Unix Epoch as the server time at which the transaction was committed
2.2.4.6. Events
All data change events produced by the PostgreSQL connector have a key and a value, although the structure of the key and value depend on the table from which the change events originated (see Topic names).
Starting with Kafka 0.10, Kafka can optionally record with the message key and value 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 are valid Avro schema names. This means that the logical server name must start with Latin letters or an underscore (e.g., [a-z,A-Z,_]), and the remaining characters in the logical server name and all characters in the schema and table names must be Latin letters, digits, or an underscore (e.g., [a-z,A-Z,0-9,\_]). If not, then all invalid characters will automatically be replaced with an underscore character.
This can lead to unexpected conflicts when the logical server name, schema names, and table names contain other characters, and the only distinguishing characters between table full names are invalid and thus replaced with underscores.
Debezium and Kafka Connect are designed around continuous streams of event messages, and the structure of these events may change over time. This could be difficult for consumers to deal with, so to make it easy Kafka Connect makes each event self-contained. Every message key and value has two parts: a schema and payload. The schema describes the structure of the payload, while the payload contains the actual data.
2.2.4.6.1. Change Event’s Key
For a given table, the change event’s key will have a structure that contains a field for each column in the primary key (or unique key constraint with REPLICA IDENTITY
set to FULL
or USING INDEX
on the table) of the table at the time the event was created.
Consider a customers
table defined in the public
database schema:
CREATE TABLE customers ( id SERIAL, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, PRIMARY KEY(id) );
If the database.server.name
configuration property has the value PostgreSQL_server
, every change event for the customers
table while it has this definition will feature the same key structure, which in JSON looks like this:
{ "schema": { "type": "struct", "name": "PostgreSQL_server.public.customers.Key", "optional": false, "fields": [ { "name": "id", "index": "0", "schema": { "type": "INT32", "optional": "false" } } ] }, "payload": { "id": "1" }, }
The schema
portion of the key contains a Kafka Connect schema describing what is in the key portion, and in our case that means that the payload
value is not optional, is a structure defined by a schema named PostgreSQL_server.public.customers.Key
, and has one required field named id
of type int32
. If we look at the value of the key’s payload
field, we’ll see that it is indeed a structure (which in JSON is just an object) with a single id
field, whose value is 1
.
Therefore, we interpret this key as describing the row in the public.customers
table (output from the connector named PostgreSQL_server
) whose id
primary key column had a value of 1
.
Although the column.blacklist
configuration property allows you to remove columns from the event values, 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 will be null. This makes sense since the rows in a table without a primary or unique key constraint cannot be uniquely identified.
2.2.4.6.2. Change Event’s Value
The value of the change event message is a bit more complicated. Like the message key, it has a schema section and payload section. The payload section of every change event value produced by the PostgreSQL connector has an envelope structure with the following fields:
-
op
is a mandatory field that contains a string value describing the type of operation. Values for the PostgreSQL connector arec
for create (or insert),u
for update,d
for delete, andr
for read (in the case of a snapshot). -
before
is an optional field that if present contains the state of the row before the event occurred. The structure will be described by thePostgreSQL_server.public.customers.Value
Kafka Connect schema, which thePostgreSQL_server
connector uses for all rows in thepublic.customers
table.
Whether or not this field is available is highly dependent on the REPLICA IDENTITY setting for each table
-
after
is an optional field that if present contains the state of the row after the event occurred. The structure is described by the samePostgreSQL_server.public.customers.Value
Kafka Connect schema used inbefore
. -
source
is a mandatory field that contains a structure describing the source metadata for the event, which in the case of PostgreSQL contains several fields: the Debezium version, the connector name, the name of the affected database, schema and table, whether the event is part of an ongoing snapshot or not and the same fields from the record’s meta information section -
ts_ms
is optional and if present contains the time (using the system clock in the JVM running the Kafka Connect task) at which the connector processed the event.
And of course, the schema portion of the event message’s value contains a schema that describes this envelope structure and the nested fields within it.
2.2.4.6.3. Replica Identity
REPLICA IDENTITY is a PostgreSQL specific table-level setting which determines the amount of information that is available to logical decoding
in case of UPDATE
and DELETE
events. More specifically, this controls what (if any) information is available regarding the previous values of the table columns involved, whenever one of the aforementioned events occur.
There are 4 possible values for REPLICA IDENTITY
:
-
DEFAULT -
UPDATE
andDELETE
events will only contain the previous values for the primary key columns of a table, in case ofUPDATE
only the primary columns with changed values are present -
NOTHING -
UPDATE
andDELETE
events will not contain any information about the previous value on any of the table columns -
FULL -
UPDATE
andDELETE
events will contain the previous values of all the table’s columns -
INDEX
index name
-UPDATE
andDELETE
events will contain the previous values of the columns contained in the index definition namedindex name
, in case ofUPDATE
only the indexed columns with changed values are present
2.2.4.6.4. Create Events
Let’s look at what a create event value might look like for our customers
table:
{ "schema": { "type": "struct", "fields": [ { "type": "struct", "fields": [ { "type": "int32", "optional": false, "field": "id" }, { "type": "string", "optional": false, "field": "first_name" }, { "type": "string", "optional": false, "field": "last_name" }, { "type": "string", "optional": false, "field": "email" } ], "optional": true, "name": "PostgreSQL_server.inventory.customers.Value", "field": "before" }, { "type": "struct", "fields": [ { "type": "int32", "optional": false, "field": "id" }, { "type": "string", "optional": false, "field": "first_name" }, { "type": "string", "optional": false, "field": "last_name" }, { "type": "string", "optional": false, "field": "email" } ], "optional": true, "name": "PostgreSQL_server.inventory.customers.Value", "field": "after" }, { "type": "struct", "fields": [ { "type": "string", "optional": false, "field": "version" }, { "type": "string", "optional": false, "field": "connector" }, { "type": "string", "optional": false, "field": "name" }, { "type": "int64", "optional": false, "field": "ts_ms" }, { "type": "boolean", "optional": true, "default": false, "field": "snapshot" }, { "type": "string", "optional": false, "field": "db" }, { "type": "string", "optional": false, "field": "schema" }, { "type": "string", "optional": false, "field": "table" }, { "type": "int64", "optional": true, "field": "txId" }, { "type": "int64", "optional": true, "field": "lsn" }, { "type": "int64", "optional": true, "field": "xmin" } ], "optional": false, "name": "io.debezium.connector.postgresql.Source", "field": "source" }, { "type": "string", "optional": false, "field": "op" }, { "type": "int64", "optional": true, "field": "ts_ms" } ], "optional": false, "name": "PostgreSQL_server.inventory.customers.Envelope" }, "payload": { "before": null, "after": { "id": 1, "first_name": "Anne", "last_name": "Kretchmar", "email": "annek@noanswer.org" }, "source": { "version": "1.0.3.Final", "connector": "postgresql", "name": "PostgreSQL_server", "ts_ms": 1559033904863, "snapshot": true, "db": "postgres", "schema": "public", "table": "customers", "txId": 555, "lsn": 24023128, "xmin": null }, "op": "c", "ts_ms": 1559033904863 } }
If we look at the schema
portion of this event’s value, we can see the schema for the envelope, the schema for the source
structure (which is specific to the PostgreSQL connector and reused across all events), and the table-specific schemas for the before
and after
fields.
The names of the schemas for the before
and after
fields are of the form logicalName.schemaName.tableName.Value, and thus are entirely independent from all other schemas for all other tables.
This means that when using the Avro Converter, the resulting Avro schemas for each table in each logical source have their own evolution and history.
If we look at the payload
portion of this event’s value, we can see the information in the event, namely that it is describing that the row was created (since op=c
), and that the after
field value contains the values of the new inserted row’s' id
, first_name
, last_name
, and email
columns.
It may appear that the JSON representations of the events are much larger than the rows they describe. This is true, because the JSON representation must include the schema and the payload portions of the message.
It is possible and even recommended to use the Avro Converter to dramatically decrease the size of the actual messages written to the Kafka topics.
2.2.4.6.5. Update Events
The value of an update change event on this table will actually have the exact same schema, and its payload will be structured the same but will hold different values. Here’s an example:
{ "schema": { ... }, "payload": { "before": { "id": 1 }, "after": { "id": 1, "first_name": "Anne Marie", "last_name": "Kretchmar", "email": "annek@noanswer.org" }, "source": { "version": "1.0.3.Final", "connector": "postgresql", "name": "PostgreSQL_server", "ts_ms": 1559033904863, "snapshot": null, "db": "postgres", "schema": "public", "table": "customers", "txId": 556, "lsn": 24023128, "xmin": null }, "op": "u", "ts_ms": 1465584025523 } }
When we compare this to the value in the insert event, we see a couple of differences in the payload
section:
-
The
op
field value is nowu
, signifying that this row changed because of an update -
The
before
field now has the state of the row with the values before the database commit, but only for the primary key columnid
. This is because the REPLICA IDENTITY which is by defaultDEFAULT
.
Should we want to see the previous values of all the columns for the row, we would have to change the customers
table first by running ALTER TABLE customers REPLICA IDENTITY FULL
-
The
after
field now has the updated state of the row, and here was can see that thefirst_name
value is nowAnne Marie
. -
The
source
field structure has the same fields as before, but the values are different since this event is from a different position in the WAL. -
The
ts_ms
shows the timestamp that Debezium processed this event.
There are several things we can learn by just looking at this payload
section. We can compare the before
and after
structures to determine what actually changed in this row because of the commit. The source
structure tells us information about PostgreSQL’s record of this change (providing traceability), but more importantly this has information we can compare to other events in this and other topics to know whether this event occurred before, after, or as part of the same PostgreSQL commit as other events.
When the columns for a row’s primary/unique key are updated, the value of the row’s key has changed so Debezium will output three events: a DELETE
event and tombstone event with the old key for the row, followed by an INSERT
event with the new key for the row.
2.2.4.6.6. Delete Events
So far we’ve seen samples of create and update events. Now, let’s look at the value of a delete event for the same table. Once again, the schema
portion of the value will be exactly the same as with the create and update events:
{ "schema": { ... }, "payload": { "before": { "id": 1 }, "after": null, "source": { "version": "1.0.3.Final", "connector": "postgresql", "name": "PostgreSQL_server", "ts_ms": 1559033904863, "snapshot": null, "db": "postgres", "schema": "public", "table": "customers", "txId": 556, "lsn": 46523128, "xmin": null }, "op": "d", "ts_ms": 1465581902461 } }
If we look at the payload
portion, we see a number of differences compared with the create or update event payloads:
-
The
op
field value is nowd
, signifying that this row was deleted -
The
before
field now has the state of the row that was deleted with the database commit. Again this only contains the primary key column due to the REPLICA IDENTITY setting -
The
after
field is null, signifying that the row no longer exists -
The
source
field structure has many of the same values as before, except thets_ms
,lsn
andtxId
fields have changed -
The
ts_ms
shows the timestamp that Debezium processed this event.
This event gives a consumer all kinds of information that it can use to process the removal of this row.
Please pay attention to the tables without PK, any delete messages from such table with REPLICA IDENTITY DEFAULT will have no before
part (because they have no PK which is the only field for the default identity level) and therefore will be skipped as totally empty. To be able to process messages from tables without PK set REPLICA IDENTITY to FULL level.
The PostgreSQL connector’s events are designed to work with Kafka log compaction, which allows for the removal of some older messages as long as at least the most recent message for every key is kept. This allows Kafka to reclaim storage space while ensuring the topic contains a complete dataset and can be used for reloading key-based state.
When a row is deleted, the delete event value listed above still works with log compaction, since Kafka can still remove all earlier messages with that same key. But only if the message value is null
will Kafka know that it can remove all messages with that same key. To make this possible, the PostgreSQL connector always follows the delete event with a special tombstone event that has the same key but null
value.
2.2.4.7. Data Types
As described above, the PostgreSQL connector represents the changes to rows with events that are structured like the table in which the row exist. The event contains a field for each column value, and how that value is represented in the event depends on the PostgreSQL data type of the column. This section describes this mapping.
The following table describes how the connector maps each of the PostgreSQL data types to a literal type and semantic type within the events' fields.
Here, the literal type describes how the value is literally represented using Kafka Connect schema types, namely INT8
, INT16
, INT32
, INT64
, FLOAT32
, FLOAT64
, BOOLEAN
, STRING
, BYTES
, ARRAY
, MAP
, and STRUCT
.
The 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.
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
| n/a | |
|
| n/a | |
|
|
|
The |
|
| n/a | |
|
| n/a | |
|
| n/a | |
|
| n/a | |
|
| n/a | |
|
| n/a | |
|
| n/a | |
|
| n/a | |
|
| n/a | |
|
|
| A string representation of a timestamp with timezone information, where the timezone is GMT |
|
|
| A string representation of a time value with timezone information, where the timezone is GMT |
|
|
|
The approximate number of microseconds for a time interval using the |
|
|
|
The string representation of the interval value that follows pattern |
|
| n/a | |
|
|
| Contains the string representation of a JSON document, array, or scalar. |
|
|
| Contains the string representation of an XML document |
|
|
| Contains the string representation of a PostgreSQL UUID value |
|
|
|
Contains a structure with 2 |
|
|
| Contains the string representation of a PostgreSQL LTREE value |
|
| n/a | |
|
| n/a | |
|
| n/a | Range of integer |
|
| n/a | Range of bigint |
|
| n/a | Range of numeric |
|
| n/a | Contains the string representation of timestamp range without time zone. |
|
| n/a | Contains the string representation of a timestamp range with (local system) time zone. |
|
| n/a | Contains the string representation of a date range. It always has an exclusive upper-bound. |
|
|
|
Contains the string representation of the PostgreSQL ENUM value. The set of allowed values are maintained in the schema parameter named |
Other data type mappings are described in the following sections.
2.2.4.7.1. Temporal Values
Other than PostgreSQL’s TIMESTAMPTZ
and TIMETZ
data types (which contain time zone information), the other temporal types depend on the value of the time.precision.mode
configuration property. When the time.precision.mode
configuration property is set to adaptive
(the default), then the connector will determine the literal type and semantic type for the temporal types based on the column’s data type definition so that events exactly represent the values in the database:
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
| Represents the number of days since epoch. |
|
|
| Represents the number of milliseconds past midnight, and does not include timezone information. |
|
|
| Represents the number of microseconds past midnight, and does not include timezone information. |
|
|
| Represents the number of milliseconds past epoch, and does not include timezone information. |
|
|
| Represents the number of microseconds past epoch, and does not include timezone information. |
When the time.precision.mode
configuration property is set to adaptive_time_microseconds
, then the connector will determine the literal type and semantic type for the temporal types based on the column’s data type definition so that events exactly represent the values in the database, except that all TIME fields will be captured as microseconds:
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
| Represents the number of days since epoch. |
|
|
|
Represents the time value in microseconds and does not include timezone information. PostgreSQL allows precision |
|
|
| Represents the number of milliseconds past epoch, and does not include timezone information. |
|
|
| Represents the number of microseconds past epoch, and does not include timezone information. |
When the time.precision.mode
configuration property is set to connect
, then the connector will use the predefined Kafka Connect logical types. This may be useful when consumers only know about the built-in Kafka Connect logical types and are unable to handle variable-precision time values. On the other hand, since PostgreSQL supports microsecond precision, the events generated by a connector with the connect
time precision mode will result in a loss of precision when the database column has a fractional second precision value greater than 3:
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
| Represents the number of days since epoch. |
|
|
|
Represents the number of milliseconds since midnight, and does not include timezone information. PostgreSQL allows |
|
|
|
Represents the number of milliseconds since epoch, and does not include timezone information. PostgreSQL allows |
2.2.4.7.2. TIMESTAMP
values
The TIMESTAMP
type represents a timestamp without time zone information. Such columns are converted into an equivalent Kafka Connect value based on UTC. So for instance the TIMESTAMP
value "2018-06-20 15:13:16.945104" will be represented by a io.debezium.time.MicroTimestamp
with the value "1529507596945104" (assuming time.precision.mode
is not set to connect
).
Note that the timezone of the JVM running Kafka Connect and Debezium does not affect this conversion.
2.2.4.7.3. Decimal Values
When decimal.handling.mode
configuration property is set to precise
, then the connector will use the predefined Kafka Connect org.apache.kafka.connect.data.Decimal
logical type for all DECIMAL
and NUMERIC
columns. This is the default mode.
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
|
The |
|
|
|
The |
There is an exception to this rule. When the NUMERIC
or DECIMAL
types are used without any scale constraints then it means that the values coming from the database have a different (variable) scale for each value. In this case a type io.debezium.data.VariableScaleDecimal
is used and it contains both value and scale of the transferred value.
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
|
Contains a structure with two fields: |
|
|
|
Contains a structure with two fields: |
However, when decimal.handling.mode
configuration property is set to double
, then the connector will represent all DECIMAL
and NUMERIC
values as Java double values and encodes them as follows:
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
| ||
|
|
The last option for decimal.handling.mode
configuration property is string
. In this case the connector will represent all DECIMAL
and NUMERIC
values as their formatted string representation and encodes them as follows:
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
| ||
|
|
PostgreSQL supports NaN
(not a number) special value to be stored in the DECIMAL
/NUMERIC
values. Only string
and double
modes are able to handle such values encoding them as either Double.NaN
or string constant NAN
.
2.2.4.7.4. HStore Values
When hstore.handling.mode
configuration property is set to json
(the default), the connector will represent all HSTORE
values as string-ified JSON values and encode them as follows:
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
|
Example: output representation using the JSON converter is |
When hstore.handling.mode
configuration property is set to map
, then the connector will use the MAP
schema type for all HSTORE
columns.
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
Example: output representation using the JSON converter is |
2.2.4.8. PostgreSQL Domain Types
PostgreSQL also supports the notion of user-defined types that are based upon other underlying types. When such column types are used, Debezium exposes the column’s representation based on the full type hierarchy.
Special consideration should be taken when monitoring columns that use domain types.
When a column is defined using a domain type that extends one of the default database types and the domain type defines a custom length/scale, the generated schema will inherit that defined length/scale.
When a column is defined using a domain type that extends another domain type that defines a custom length/scale, the generated schema will not inherit the defined length/scale because the PostgreSQL driver’s column metadata implementation.
2.2.4.8.1. Network Address Types
PostgreSQL also have data types that can store IPv4, IPv6, and MAC addresses. It is better to use these instead of plain text types to store network addresses, because these types offer input error checking and specialized operators and functions.
PostgreSQL Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
| IPv4 and IPv6 networks | |
|
| IPv4 and IPv6 hosts and networks | |
|
| MAC addresses | |
|
| MAC addresses in EUI-64 format |
2.2.4.8.2. PostGIS Types
The PostgreSQL connector also has full support for all of the PostGIS data types
PostGIS Data Type | Literal type (schema type) | Semantic type (schema name) | Notes |
---|---|---|---|
|
|
|
Contains a structure with 2 fields
|
|
|
|
Contains a structure with 2 fields
|
2.2.4.8.3. Toasted values
PostgreSQL has a hard limit on the page size. This means that values larger than ca. 8 KB need to be stored using TOAST storage. This impacts replication messages coming from database, as the values that were stored using the TOAST mechanism and 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 database, as this would lead into race conditions potentially. Debezium thus follows these rules to handle the toasted values:
-
tables with
REPLICA IDENTITY FULL
: TOAST column values are part of thebefore
andafter
blocks of change events as any other column -
tables with
REPLICA IDENTITY DEFAULT
: when receiving anUPDATE
event from the database, any unchanged TOAST column value which is not part of the replica identity will not be part of that event; similarly, when receiving aDELETE
event, any such TOAST column will not be part of thebefore
block. As Debezium cannot safely provide the column value in this case, it returns a placeholder value defined in configuration optiontoasted.value.placeholder
.
There is a specific problem related to Amazon RDS instances. wal2json
plugin has evolved over the time and there were releases that provided out-of-band toasted values. Amazon supports different versions of the plugin for different PostgreSQL versions. Please consult Amazon’s documentation to obtain version to version mapping. For consistent toasted values handling we recommend to
-
use
pgoutput
plugin for PostgreSQL 10+ instances -
set
include-unchanged-toast=0
for older versions ofwal2json
plugin usingslot.stream.params
configuration option
2.3. Deploying the PostgreSQL Connector
Installing the PostgreSQL connector is a simple process whereby you only need to download the JAR, extract it to your Kafka Connect environment, and ensure the plugin’s parent directory is specified in your Kafka Connect environment.
Prerequisites
- You have Zookeeper, Kafka, and Kafka Connect installed.
- You have PostgreSQL installed and setup.
Procedure
- Download the Debezium PostgreSQL connector.
- Extract the files into your Kafka Connect environment.
Add the plugin’s parent directory to your Kafka Connect plugin path:
plugin.path=/kafka/connect
The above example assumes you have extracted the Debezium PostgreSQL connector to the /kafka/connect/Debezium-connector-postgresql
path.
- Restart your Kafka Connect process. This ensures the new JARs are picked up.
Additional resources
For more information on the deployment process, and deploying connectors with AMQ Streams, refer to the Debezium installation guides.
2.3.1. Example Configuration
To use the connector to produce change events for a particular PostgreSQL server or cluster:
- Install the logical decoding plugin
- Configure the PostgreSQL server to support logical replication
- Create a configuration file for the PostgreSQL connector.
When the connector starts, it will grab a consistent snapshot of the databases in your PostgreSQL server and start streaming changes, producing events for every inserted, updated, and deleted row. You can also 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.
Following is an example of the configuration for a PostgreSQL connector that monitors a PostgreSQL server at port 5432 on 192.168.99.100, which we logically name fullfillment
. Typically, you configure the Debezium PostgreSQL connector in a .yaml
file using the configuration properties available for the connector.
apiVersion: kafka.strimzi.io/v1beta1 kind: KafkaConnector metadata: name: inventory-connector 1 labels: strimzi.io/cluster: my-connect-cluster spec: class: io.debezium.connector.postgresql.PostgresConnector tasksMax: 1 2 config: 3 database.hostname: postgresqldb 4 database.port: 5432 database.user: debezium database.password: dbz database.dbname: postgres database.server.name: fullfillment 5 database.whitelist: public.inventory 6
- 1
- The name of the connector.
- 2
- Only one task should operate at any one time. Because the PostgreSQL connector reads the PostgreSQL server’s
binlog
, using a single connector task ensures proper order and event handling. The Kafka Connect service uses connectors to start one or more tasks that do the work, and it automatically distributes the running tasks across the cluster of Kafka Connect services. If any of the services stop or crash, those tasks will be redistributed to running services. - 3
- The connector’s configuration.
- 4
- The database host, which is the name of the container running the PostgreSQL server (
postgresqldb
). - 5
- A unique server name. The server name is the logical identifier for the PostgreSQL server or cluster of servers. This name will be used as the prefix for all Kafka topics.
- 6
- Only changes in the
public.inventory
database will be detected.
See the complete list of connector properties that can be specified in these configurations.
This configuration can be sent via POST to a running Kafka Connect service, which will then record the configuration and start up the one connector task that will connect to the PostgreSQL database and record events to Kafka topics.
2.3.2. Monitoring
Kafka, Zookeeper, and Kafka Connect all have built-in support for JMX metrics. The PostgreSQL connector also publishes a number of metrics about the connector’s activities that can be monitored through JMX. The connector has two types of metrics. Snapshot metrics help you monitor the snapshot activity and are available when the connector is performing a snapshot. Streaming metrics help you monitor the progress and activity while the connector processes the logical replication stream.
2.3.2.1. Snapshot Metrics
2.3.2.1.1. MBean: debezium.postgres:type=connector-metrics,context=snapshot,server=<database.server.name>
Attribute Name | Type | Description |
---|---|---|
|
| The last snapshot event that the connector has read. |
|
| The number of milliseconds since the connector has read and processed the most recent event. |
|
| The total number of events that this connector has seen since last started or reset. |
|
| The number of events that have been filtered by whitelist or blacklist filtering rules configured on the connector. |
|
| The list of tables that are monitored by the connector. |
|
| The length of the queue used to pass events between the snapshotter and the main Kafka Connect loop. |
|
| The free capacity of the queue used to pass events between the snapshotter and the main Kafka Connect loop. |
|
| The total number of tables that are being included in the snapshot. |
|
| The number of tables that the snapshot has yet to copy. |
|
| Whether the snapshot was started. |
|
| Whether the snapshot was aborted. |
|
| Whether the snapshot completed. |
|
| The total number of seconds that the snapshot has taken so far, even if not complete. |
|
| 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. |
2.3.2.2. Streaming Metrics
2.3.2.2.1. MBean: debezium.postres:type=connector-metrics,context=streaming,server=<database.server.name>
Attribute Name | Type | Description |
---|---|---|
|
| The last streaming event that the connector has read. |
|
| The number of milliseconds since the connector has read and processed the most recent event. |
|
| The total number of events that this connector has seen since last started or reset. |
|
| The number of events that have been filtered by whitelist or blacklist filtering rules configured on the connector. |
|
| The list of tables that are monitored by the connector. |
|
| The length of the queue used to pass events between the streamer and the main Kafka Connect loop. |
|
| The free capacity of the queue used to pass events between the streamer and the main Kafka Connect loop. |
|
| Flag that denotes whether the connector is currently connected to the database server. |
|
| The number of milliseconds between the last change event’s timestamp and the connector processing it. The values will incorporate any differences between the clocks on the machines where the database server and the connector are running. |
|
| The number of processed transactions that were committed. |
|
| The coordinates of the last received event. |
|
| Transaction identifier of the last processed transaction. |
2.3.3. Connector Properties
The following configuration properties are required unless a default value is available.
Property | Default | Description |
---|---|---|
| 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 | |
|
| 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. |
|
|
The name of the Postgres logical decoding plugin installed on the server. The only supported value is
When the processed transactions are very large it is possible that the |
|
| The name of the Postgres logical decoding slot created for streaming changes from a plugin and database instance. Values must conform to Postgres replication slot naming rules which state: "Each replication slot has a name, which can contain lower-case letters, numbers, and the underscore character." |
|
|
Whether or not to drop the logical replication slot when the connector finishes orderly. Should only be set to |
|
|
The name of the PostgreSQL publication created created for streaming changes when using This publication is created at start-up if it does not already exist to include all tables. Debezium will then use its own white-/blacklist filtering capabilities to limit change events to the specific tables of interest if configured. Note the connector user must have superuser permissions in order to create this publication, so it is usually preferable to create the publication upfront. If the publication already exists (either for all tables or configured with a subset of tables), Debezium will instead use the publication as defined. |
| IP address or hostname of the PostgreSQL database server. | |
|
| Integer port number of the PostgreSQL database server. |
| Name of the PostgreSQL database to use when 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/cluster being monitored. The logical name should be unique across all other connectors, since it is used as a prefix for all Kafka topic names coming from this connector. Only alphanumeric characters and underscores should be used. | |
|
An optional comma-separated list of regular expressions that match schema names to be monitored; any schema name not included in the whitelist will be excluded from monitoring. By default all non-system schemas will be monitored. May not be used with | |
|
An optional comma-separated list of regular expressions that match schema names to be excluded from monitoring; any schema name not included in the blacklist will be monitored, with the exception of system schemas. May not be used with | |
|
An optional comma-separated list of regular expressions that match fully-qualified table identifiers for tables to be monitored; any table not included in the whitelist will be excluded from monitoring. Each identifier is of the form schemaName.tableName. By default the connector will monitor every non-system table in each monitored schema. May not be used with | |
|
An optional comma-separated list of regular expressions that match fully-qualified table identifiers for tables to be excluded from monitoring; any table not included in the blacklist will be monitored. Each identifier is of the form schemaName.tableName. May not be used with | |
| An optional comma-separated list of regular expressions that match the fully-qualified names of columns that should be excluded from change event message values. Fully-qualified names for columns are of the form schemaName.tableName.columnName | |
|
|
Time, date, and timestamps can be represented with different kinds of precision, including: |
|
|
Specifies how the connector should handle values for |
|
|
Specifies how the connector should handle values for |
|
|
Specifies how the connector should handle values for |
|
|
Whether to use an encrypted connection to the PostgreSQL server. Options include: disable (the default) to use an unencrypted connection ; require to use a secure (encrypted) connection, and fail if one cannot be established; verify-ca like |
| The path to the file containing the SSL Certificate for the client. See the PostgreSQL documentation for more information. | |
| The path to the file containing 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 | |
| The path to the file containing the root certificate(s) against which the server is validated. See the PostgreSQL documentation for more information. | |
| Enable TCP keep-alive probe to verify that database connection is still alive. (enabled by default). See the PostgreSQL documentation for more information. | |
|
|
Controls whether a tombstone event should be generated after a delete event. |
| n/a | An optional comma-separated list of regular expressions that match the fully-qualified names of character-based columns whose values should be truncated in the change event message values if the field values are longer than the specified number of characters. Multiple properties with different lengths can be used in a single configuration, although in each the length must be a positive integer. Fully-qualified names for columns are of the form databaseName.tableName.columnName, or databaseName.schemaName.tableName.columnName. |
| n/a |
An optional comma-separated list of regular expressions that match the fully-qualified names of character-based columns whose values should be replaced in the change event message values with a field value consisting of the specified number of asterisk ( |
| n/a |
An optional comma-separated list of regular expressions that match the fully-qualified names of columns whose original type and length should be added as a parameter to the corresponding field schemas in the emitted change messages. The schema parameters |
| empty string |
A semi-colon list of regular expressions that match fully-qualified tables and columns to map a primary key. |
The following advanced configuration properties have good defaults that will work in most situations and therefore rarely need to be specified in the connector’s configuration.
Property | Default | Description |
---|---|---|
|
| Specifies the criteria for running a snapshot upon startup of the connector. The default is initial, and specifies the connector can run a snapshot only when no offsets have been recorded for the logical server name. The always option specifies that the connector run a snapshot each time on startup. The never option specifies that the connect should never use snapshots and that upon first startup with a logical server name the connector should read from either from where it last left off (last LSN position) or start from the beginning from the point of the view of the logical replication slot. The initial_only option specifies that the connector should only take an initial snapshot and then stop, without processing any subsequent changes. The exported option specifies that the database snapshot will be based on the point in time when the replication slot was created and is an excellent way to perform the snapshot in a lock-free way. |
|
| Positive integer value that specifies the maximum amount of time (in milliseconds) to wait to obtain table locks when performing a snapshot. If table locks cannot be acquired in this time interval, the snapshot will fail. See snapshots |
|
Controls which rows from tables will be included in snapshot. | |
|
|
Specifies how the connector should react to exceptions during processing of events. |
|
| Positive integer value that specifies the maximum size of the blocking queue into which change events received via streaming replication are placed before they are written to Kafka. This queue can provide backpressure when, for example, writes to Kafka are slower or if Kafka is not available. |
|
| Positive integer value that specifies the maximum size of each batch of events that should be processed during each iteration of this connector. |
|
| Positive integer value that specifies the number of milliseconds the connector should wait during each iteration for new change events to appear. Defaults to 1000 milliseconds, or 1 second. |
|
|
When Debezium meets a field whose data type is unknown, then by default the field is omitted from the change event and a warning is logged. In some cases it may be preferable though to include the field and send it downstream to clients in the opaque binary representation so the clients will decode it themselves. Set to Note The clients risk backward compatibility issues. Not only may the database specific binary representation change between releases, but also when the datatype is supported by Debezium eventually, it will be sent downstream in a logical type, requiring adjustments by consumers. In general, when encountering unsupported data types, please file a feature request so that support can be added. |
| A semicolon separated list of SQL statements to be executed when a JDBC connection (not the transaction log reading connection) to the database is established. Use doubled semicolon (';;') to use a semicolon as a character and not as a delimiter. Note The connector may establish JDBC connections at its own discretion, so this should typically be used for configuration of session parameters only, but not for executing DML statements. | |
|
|
Controls how frequently heartbeat messages are sent. |
|
|
Controls the naming of the topic to which heartbeat messages are sent. |
|
| Specify the conditions that trigger a refresh of the in-memory schema for a table.
This setting can improve connector performance significantly if there are frequently-updated tables that have TOASTed data that are rarely part of these updates. However, it is possible for the in-memory schema to become outdated if TOASTable columns are dropped from the table. |
|
An interval in milli-seconds that the connector should wait before taking a snapshot after starting up; | |
|
| Specifies the maximum number of rows that should be read in one go from each table while taking a snapshot. The connector will read the table contents in multiple batches of this size. Defaults to 10240. |
|
Optional list of parameters to be passed to the configured logical decoding plug-in. For example, | |
|
| Whether field names will be sanitized to adhere to Avro naming requirements. See Avro naming for more details. |
| 6 | How many times to retry connecting to a replication slot when an attempt fails. |
| 10000 (10 seconds) | The number of milli-seconds to wait between retry attempts when the connector fails to connect to a replication slot. |
|
|
Specify the constant that will be provided by Debezium to indicate that the original value is a toasted value not provided by the database. If starts with |
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.)
2.4. PostgreSQL common issues
Debezium is a distributed system that captures all changes in multiple upstream databases, and will never miss or lose an event. Of course, when the system is operating nominally or being administered carefully, then Debezium provides exactly once delivery of every change event. However, if a fault does happen then the system will still not lose any events, although while it is recovering from the fault it may repeat some change events. Thus, 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.
2.4.1. Configuration and Startup Errors
The connector will fail upon startup, report an error/exception in the log, and stop running when the connector’s configuration is invalid, when the connector cannot successfully connect to PostgreSQL using the specified connectivity parameters, or when the connector is restarting from a previously-recorded position in the PostgreSQL WAL (via the LSN value) and PostgreSQL no longer has that history available.
In these cases, the error will have more details about the problem and possibly a suggested work around. The connector can be restarted when the configuration has been corrected or the PostgreSQL problem has been addressed.
2.4.3. Cluster Failures
As of 12
, PostgreSQL allows logical replication slots only on primary servers, which means that a PostgreSQL connector can only be pointed to the active primary of a database cluster. Also replication slots themselves are not propagated to replicas. If the primary node goes down, only after a new primary has been promoted (with the logical decoding plugin installed) and a replication slot has been created there, the connector can be restarted and pointed to the new server.
There are some really important caveats to failovers, and you should pause Debezium until you can verify that you have a replication slot intact which has not lost data. After a failover, you will miss change events unless your administration of failovers includes a process to recreate the Debezium replication slot before the application is allowed to write to the new primary. You also may need to verify in a failover situation that Debezium was able to read all changes in the slot before the old primary failed.
One reliable method of recovering and verifying any lost changes (yet administratively difficult) is to recover a backup of your failed primary to the point immediately before it failed, which would allow you to inspect the replication slot for any unconsumed changes. In any case, it is crucial that you recreate the replication slot on the new primary prior to allowing writes to it.
2.4.4. Kafka Connect Process Stops Gracefully
If Kafka Connect is being run in distributed mode, and a Kafka Connect process is stopped gracefully, then prior to shutdown of that processes Kafka Connect will migrate all of the process' connector tasks to another Kafka Connect process in that group, and the new connector tasks will pick up exactly where the prior tasks left off. There will be a short delay in processing while the connector tasks are stopped gracefully and restarted on the new processes.
2.4.5. Kafka Connect Process Crashes
If the Kafka Connector process stops unexpectedly, then any connector tasks it was running will obviously terminate without recording their most recently-processed offsets. When Kafka Connect is being run in distributed mode, it will restart those connector tasks on other processes. However, the PostgreSQL connectors will resume from the last offset recorded by the earlier processes, which means that the new replacement tasks may generate some of the same change events that were processed just prior to the crash. The number of duplicate events will depend on the offset flush period and the volume of data changes just before the crash.
Because there is a chance that some events may be duplicated during a recovery from failure, consumers should always anticipate some events may be duplicated. Debezium changes are idempotent, so a sequence of events always results in the same state.
Debezium also includes with each change event message the 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 position) to know whether they have already seen a particular event.
2.4.7. Connector Is Stopped for a Duration
If the connector is gracefully stopped, the database can continue to be used and any new changes will be recorded in the PostgreSQL WAL. When the connector is restarted, it will resume streaming changes where it last left off, recording change events for all of the changes that were made while the connector was stopped.
A properly configured Kafka cluster is able to handle massive throughput. Kafka Connect is written with Kafka best practices, and given enough resources will also be able to handle very large numbers of database change events. Because of this, when a connector has been restarted after a while, it is very likely to catch up with the database, though how quickly will depend upon the capabilities and performance of Kafka and the volume of changes being made to the data in PostgreSQL.