PostgreSQL Migration Synchronization to Kafka
NineData data replication supports replicating data from PostgreSQL to Kafka, allowing enterprises to achieve efficient data migration and synchronization, ensuring that the data in the Kafka system is always up-to-date.
Background Information
Kafka, as a distributed streaming platform, is widely used for real-time data transmission and processing. PostgreSQL is a popular relational database management system, commonly used for storing structured data. In many application scenarios, synchronizing data from PostgreSQL to Kafka in real-time can improve data processing speed and scalability, providing support for enterprise data analysis, log processing, etc.
Prerequisites
The source and target data sources have been added to NineData. For instructions on how to add them, please refer to Create Data Source.
The target database type is Kafka 0.10 or above.
You must have the following permissions for the source data source:
Replication Type Permissions Full Replication CONNECT, SELECT Incremental Replication SUPERUSER For incremental replication, please open the
postgresql.conffile and configure the following parameters. If you cannot find the location of the file, you can execute theSHOW config_file;SQL command in the psql client to view it.- The
wal_levelparameter of the source data source must belogical. To confirm the current value, you can directly executeSHOW wal_levelin the client. - The
wal_sender_timeoutparameter of the source data source is set to0. This parameter is used to interrupt replication connections that have been stagnant for more than the specified number of milliseconds. The default value is 60000 milliseconds. Setting it to 0 will disable the timeout mechanism. To confirm the current value, you can directly executeSHOW wal_sender_timeoutin the client. - The
max_replication_slotsparameter of the source data source must be greater than1. This parameter specifies the maximum number of replication slots the server can support. The default value is 10. - The
max_wal_sendersparameter of the source data source must be greater than1. This parameter specifies the maximum number of concurrent connections. The default value is 10. To confirm the current value, you can directly executeSHOW max_wal_sendersin the client.
- The
Usage Limitations
- Before performing data synchronization, it is necessary to assess the performance of the source and target data sources, and it is recommended to perform data synchronization during off-peak business hours. Otherwise, the full data initialization will occupy a certain amount of read and write resources of the source and target data sources, leading to increased database load.
- It is necessary to ensure that each table in the synchronization object has a primary key or unique constraint, and the column names have uniqueness, otherwise, the same data may be synchronized repeatedly.
Operation Steps
NineData’s data replication product has been commercialized. You can still use 10 replication tasks for free, with the following considerations:
Among the 10 replication tasks, you can include 1 Incremental task, with a specification of Micro.
Tasks with a status of Terminated do not count towards the 10-task limit. If you have already created 10 replication tasks and want to create more, you can terminate previous replication tasks and then create new ones.
When creating replication tasks, you can only select the Spec you have purchased. Specifications that have not been purchased will be grayed out and cannot be selected. If you need to purchase additional specifications, please contact us through the customer service icon at the bottom right of the page.
Log in to the NineData Console.
In the left navigation pane, click Replication > Data Replication.
On the Replication page, click Create Replication in the upper-right corner.
On the Source & Target tab, configure the parameters in the following table, and click Next.
Parameter Description Name Enter a name for the data synchronization task. To make the task easier to find and manage later, use a meaningful name. Up to 64 characters are supported. Source The data source that contains the objects to synchronize. Target The data source that receives the synchronized objects. Kafka Topic Select the target Kafka Topic. Data from the source data source will be written to the specified Topic. Delivery Partition When delivering data to a Topic, you can specify the partition to which the data is delivered. - Deliver All to Partition 0: Deliver all data to the default partition 0.
- Deliver to different partition by the Hash value of [databaseName + tableName]: Hash data across different partitions. The system uses the hash value of the database name and table name to calculate the target partition, ensuring that data from the same table is delivered to the same partition during hash delivery.
Target Object Name Select the case conversion rule for object names after they are migrated from the source to the target. - Convert all to Lowercase: Regardless of the naming rule on the source, all target names are lowercase.
- Consistent with Source: Keep the naming rule of the source.
- Convert all to Uppercase: Regardless of the naming rule on the source, all target names are uppercase.
Type Select the replication type. - Full: Synchronize all objects and data from the source data source, namely full data replication.
- Incremental: After full synchronization is complete, perform incremental synchronization based on the logs of the source data source.
Incremental Started Required only when Type is Incremental. - From Started: Use the current replication task start time as the baseline for incremental replication.
- Customized Time: Select the point in time from which incremental replication starts. You can select a time zone based on the region of your business. If the configured time point is earlier than the current replication task start time and DDL operations occurred during that period, the replication task will fail.
Spec The specification of the replication task. A larger specification provides a higher replication rate. Hover over the icon to view the rate and configuration information of each specification. If you configure the data replication task before purchasing resources, you can select the required specification here. If you purchase resources before configuring the task, the system selects the specification chosen during resource purchase, and you cannot change it in the task configuration.
Target Table Exists Data (Required when Full is selected) - Pre-Check Error and Stop Task: Stop the task when data is detected in the target table during the precheck stage.
- Ignore existing target data and append to it.: When data is detected in the target table during the precheck stage, ignore that data and append other data.
- Clear target existing data before write: When data is detected in the target table during the precheck stage, delete that data and write it again.
Incremental data conflict handling strategy for target table (Required when Incremental is selected) - Runtime error: During incremental replication, report an error when target data already exists and wait for manual intervention.
- Do not update target data: During incremental replication, do not write data when target data already exists, and continue subsequent tasks.
- Update target data: During incremental replication, overwrite the target data when target data already exists.
On the Objects tab, configure the following parameters, and click Next.
Parameter Description Replication Objects Select the content to replicate. You can select All Objects to replicate all content in the source database, or select Customized Object, select the content to replicate in the Source Object list, and click > to add it to the Target Object list on the right. If you need to create multiple replication links with the same replication objects, you can create a configuration file and import it when creating a task. Click Import Config in the upper-right corner, click Download Template to download the configuration file template, edit the file, and then click Upload to upload it for batch import. Configuration file description:
Parameter Description source_table_nameThe source table name of the object to synchronize. destination_table_nameThe target table name that receives the synchronized object. source_schema_nameThe source schema name of the object to synchronize. destination_schema_nameThe target schema name that receives the synchronized object. source_database_nameThe source database name of the object to synchronize. target_database_nameThe target database name that receives the synchronized object. column_listThe list of columns to synchronize. extra_configurationAdditional configuration information. You can configure the following information here: column_rules: Defines column mappings and value rules. Field descriptions:column_name: Original column name.destination_column_name: Specifies the target column name.column_value: Specifies the column value, which can be an SQL function or a constant value.
filter_condition: Specifies row-level data filtering conditions. Only rows that meet the conditions are replicated.
tipThe following is an example of
extra_configuration:{
"extra_config":{
"column_rules":[
{
"column_name": "created_time", // Specifies the original column name to be mapped.
"destination_column_name": "migrated_time", // Maps the target column name to "migrated_time".
"column_value": "current_timestamp()" // Changes the column value to the current timestamp.
}
],
"filter_condition": "id != 0" // Only rows whose ID is not 0 are synchronized.
}
}For a complete example of the configuration file, see the downloaded template.
On the "Mapping" tab, you can separately configure each column to replicate to Kafka. By default, all columns of the selected table are replicated. If the source and target data sources are updated during mapping configuration, click Refresh Metadata in the upper-right corner of the page to refresh the source and target data source information. After completing the configuration, click Save and Pre-Check.
On the Pre-check tab, wait for the system to complete the precheck. After the precheck is passed, click Launch.
You can select Enable data consistency comparison. After the synchronization task is complete, a data consistency comparison task based on the source data source automatically starts to ensure data consistency between both ends. Based on the selected Type, Enable data consistency comparison starts at the following times:
- Full: Starts after full replication is complete.
- Full+Incremental, Incremental: Starts when incremental data is consistent with the source data source for the first time and Delay is 0 seconds. You can click View Details and view the synchronization delay on the Details page.

If the precheck fails, click Details in the Actions column on the right of the failed check item, troubleshoot the cause, manually fix the issue, and then click Check Again to run the precheck again until it passes.
Check items whose Result is Warning can be fixed or ignored depending on the situation.
On the Launch page, the Launch Successfully prompt appears, indicating that the synchronization task has started. You can then perform the following operations:
Click View Details to view the execution status of each stage of the synchronization task.
Click Back to list to return to the Replication task list page.
View Synchronization Results
Log in to the NineData Console.
Click on Replication > Data Replication in the left navigation bar.
On the Replication page, click the ID of the target synchronization task to open the Details page, the page description is as follows.

No. Feature Description 1 Synchronization Delay The data synchronization delay between the source and target data sources, 0 seconds indicates no delay between the two ends, meaning that the data on the Kafka side has currently caught up with the source side. 2 Configure Alerts After configuring alerts, the system will notify you through the method you choose when the task fails. For more information, please refer to Operations Monitoring Introduction. 3 More - Pause: Pause the task, only tasks with the status Running are selectable.
- Terminate: End tasks that are not completed or listening (i.e., in incremental synchronization), after terminating the task, it cannot be restarted, please operate with caution.
- Delete: Delete the task, the task cannot be recovered after deletion, please operate with caution.
4 Full Replication (Displayed in scenarios including full replication) Display the progress and detailed information of full replication. - Click on the Monitor on the right side of the page: View various monitoring metrics during the full replication process. During the full replication process, you can also click on the Flow Control Settings on the right side of the monitoring metrics page to limit the rate of writing to the target data source per second. The unit is MB/S.
- Click on the Log on the right side of the page: View the execution logs of full replication.
- Click on the
icon on the right side of the page: View the latest information.
5 Incremental Replication (Displayed in scenarios including incremental replication) Display various monitoring metrics for incremental replication. - Click on the Flow Control Settings on the right side of the page: Limit the rate of writing to the target data source per second. The unit is rows/second.
- Click on the Log on the right side of the page: View the execution logs of incremental replication.
- Click on the
icon on the right side of the page: View the latest information.
6 Modify Object Display the modification records of the synchronization object. - Click on the Modify Objects on the right side of the page to configure the synchronization object.
- Click on the
icon on the right side of the page: View the latest information.
7 Expand Display detailed information of the current replication task, including Type, Replication Objects, Started, etc.
Appendix 1: Data Format Description
The data migrated from PostgreSQL to Kafka will be stored in JSON format. The system will equally divide the data in PostgreSQL into multiple JSON objects, with each JSON representing a message (Message).
- Full replication phase: The number of PostgreSQL data rows stored in a single message is determined by the message.max.bytesmessage.max.bytes is the maximum message size allowed in the Kafka cluster, with a default value of
1000000bytes (i.e., 1MB). You can adjust this value by modifying themessage.max.bytesparameter in the Kafka configuration file, which will allow more PostgreSQL data rows to be stored in each message. Please note that since Kafka needs to allocate memory space for each message, setting this value too high may lead to decreased Kafka cluster performance. parameter. - Incremental replication phase: A single message stores one line of PostgreSQL data.
| Field | Field Type | Field Description | Field Example |
|---|---|---|---|
| serverId | STRING | Message ownership data source information, format: <connection address:port>. | "serverId":"47.98.224.21:3307" |
| id | LONG | The Record id of the message. This field is globally incremented and is used as the basis for determining message duplicate consumption. | "Id":156 |
| es | INT | Represented by Unix timestamp, different task stages represent different meanings:
| "es":1668650385 |
| ts | INT | The time when more data is delivered to Kafka, represented by Unix timestamp. | "ts":1668651053 |
| isDdl | BOOLEAN | Whether the data is DDL, values:
| "is_ddl":true |
| type | STRING | The type of data, values:
| "type":"INIT" |
| database | STRING | The database to which the data belongs. | "database":"database_name" |
| table | STRING | The table to which the data belongs. If the DDL statement corresponds to a non-table object, this field takes the value null. | "table":"table_name" |
| mysqlType | JSON | Reserved field, no need to pay attention. | "mysqlType": null |
| sqlType | JSON | The data types of each field in the source PostgreSQL. | "sqlType": {"id": "NUMBER","shipping_type":"varchar2(50)"} |
| pkNames | ARRAY | The names of the primary keys (Primary Key) corresponding to the records (Record) in the Binlog. Values:
| "pkNames": ["id", "uid"] |
| data | ARRAY[JSON] | The data from PostgreSQL delivered to Kafka, stored in a JSON format array.
| "data": [{ "name": "jl", "phone": "(737)1234787", "email": "caicai@yahoo.edu", "address": "zhejiang", "country": "china" }] |
| old | ARRAY[JSON] | Records the details of the incremental replication from PostgreSQL to Kafka.
For other operations, the value of this field is null. | "old": [{ "name": "someone", "phone": "(737)1234787", "email": "someone@example.com", "address": "somewhere", "country": "china" }] |
| sql | STRING | If the current data is an incremental DDL operation, it records the corresponding SQL statement. For other operations, the value of this field is null. | "sql":"create table sbtest1(id int primary key,name varchar(20))" |
Appendix 2: Pre-Check Item List
| Check Item | Check Content |
|---|---|
| Source datasource connection check | Check the status of the gateway of the source datasource, database connectable, and verify the username and password |
| Target datasource connection check | Check the status of the gateway of the target datasource, database connectable, and verify the username and password |
| Source databse privilege check | Check whether the account privileges of the source database meet the requirements |
| Target databse privilege check | Checking Kafka account's access permission to Topic |
| Target database data existence check | Check if there is existing data in the topic |
| Check wal_ Level | Check if the wal_level of the source datasource is set to logical |
| Check max_wal_senders | Check whether max_wal_senders meets wal sender requirements |
| Check max_replication_slots | Check whether max_replication_slots meets replication slot requirements |