Data Transmission Service (DTS) supports two-way data synchronization between two PostgreSQL databases, such as databases on an ApsaraDB RDS for PostgreSQL instance and self-managed PostgreSQL databases. This feature is applicable to scenarios such as active geo-redundancy (unit-based) and geo-disaster recovery. This topic describes how to configure two-way data synchronization between ApsaraDB RDS for PostgreSQL instances. You can also follow the procedure to configure data synchronization tasks for self-managed PostgreSQL databases.

Prerequisites

Limits

Note By default, DTS disables FOREIGN KEY constraints for the destination database in a data synchronization task. Therefore, the cascade and delete operations of the source database are not synchronized to the destination database.
Category Description
Limits on the source and destination databases
  • The tables to be synchronized must have PRIMARY KEY or UNIQUE constraints, and all fields must be unique. Otherwise, the destination database may contain duplicate data records.
  • If you select tables as the objects to be synchronized and you want to edit tables (such as renaming tables or columns), up to 1,000 tables can be synchronized in a single data synchronization task. If you run a task to be synchronized more than 1,000 tables, a request error occurs. In this case, we recommend that you split the tables and configure multiple tasks to synchronize the tables, or configure a task to synchronize the entire database.
  • The following requirements for write-ahead logging (WAL) logs must be met:
    • The value of the wal_level parameter must be set to logical.
    • If you perform only incremental data synchronization, the WAL logs of the source database must be stored for more than 24 hours. If you perform both full data synchronization and incremental data synchronization, the WAL logs of the source database must be stored for at least seven days. After full data synchronization is completed, you can set the retention period to more than 24 hours. Otherwise, DTS may fail to obtain the WAL logs and the task may fail. In exceptional circumstances, data inconsistency or loss may occur. Make sure that you set the retention period of WAL logs based on the preceding requirements. Otherwise, the Service Level Agreement (SLA) of DTS does not guarantee service reliability or performance.

  • If you want to perform a primary/secondary switchover on the source ApsaraDB RDS for PostgreSQL instance, the Logical Replication Slot Failover feature must be enabled. This prevents logical subscriptions from being interrupted and ensures that your data synchronization task can run as expected. For more information, see Logical Replication Slot Failover.

Other limits
  • You can configure data synchronization tasks only in the China (Hangzhou), China (Shanghai), and China (Qingdao) region.
  • A single data synchronization task can synchronize data from only one database. To synchronize data from multiple databases, you must create a data synchronization task for each database.
  • If the schema is selected as the object to be synchronized, you must execute the ALTER TABLE schema.table REPLICA IDENTITY FULL;statement in the destination table before the data synchronization starts. This ensures data consistency. When you execute this statement, we recommend that you do not lock the table. Otherwise, a deadlock occurs.
    Note
    • Replace the schema and table in the preceding sample statement with the actual schema name and table name.
    • We recommend that you perform this operation during off-peak hours.
  • DTS does not check the validity of metadata such as sequences. You must manually check the validity of metadata.
  • After your workloads are switched to the destination database, newly written sequences do not increment from the maximum value of the sequences in the source database. Therefore, you must query the maximum value of the sequences in the source database before you switch your workloads to the destination database. Then, you must specify the queried maximum value as the starting value of the sequences in the destination database. You can run the following statements to query the maximum value of the sequences in the source database:
    do language plpgsql $$
    declare
      nsp name;
      rel name;
      val int8;
    begin
      for nsp,rel in select nspname,relname from pg_class t2 , pg_namespace t3 where t2.relnamespace=t3.oid and t2.relkind='S'
      loop
        execute format($_$select last_value from %I.%I$_$, nsp, rel) into val;
        raise notice '%',
        format($_$select setval('%I.%I'::regclass, %s);$_$, nsp, rel, val+1);
      end loop;
    end;
    $$;
  • DTS creates the following temporary tables in the source database to obtain the DDL statements of incremental data, the schemas of incremental tables, and the heartbeat information. During data synchronization, do not delete temporary tables in the source database. Otherwise, exceptions occur. After the DTS instance is released, temporary tables are automatically deleted.

    public.DTS_PG_CLASS, public.DTS_PG_ATTRIBUTE, public.DTS_PG_TYPE, public.DTS_PG_ENUM, public.DTS_POSTGRES_HEARTBEAT, public.DTS_DDL_COMMAND, and public.DTS_ARGS_SESSION.

  • To ensure that the latency of data synchronization is accurate, DTS adds a heartbeat table to the source database. The name of the heartbeat table is dts_postgres_heartbeat.
  • During data synchronization, DTS creates a replication slot for the source database. The replication slot is prefixed with dts_sync_. DTS automatically clears historical replication slots every 90 minutes to reduce storage usage.
    Note
    • After the DTS instance is released, the replication slot is automatically deleted. If you modify the password of the source database or delete the IP address whitelist of DTS, the replication slot cannot be automatically deleted. In this case, you must delete the replication slot in the source database to prevent it from piling up.
    • If the data synchronization task is released or fails, DTS automatically clears the replication slot. If a primary/secondary switchover is performed on the source ApsaraDB RDS for PostgreSQL instance, you must log on to the secondary database to clear the replication slot.
    Replication slot information
  • Before you synchronize data, evaluate the impact of data synchronization on the performance of the source and destination databases. We recommend that you synchronize data during off-peak hours. During full data synchronization, DTS uses read and write resources of the source and destination databases. This may increase the loads of the database servers.
  • During full data synchronization, concurrent INSERT operations cause fragmentation in the tables of the destination database. Therefore, after full data synchronization is completed, the size of the used tablespace of the destination database is larger than that of the source database.
  • We recommend that you do not use gh-ost or pt-online-schema-change to perform DDL operations on source tables during data synchronization. Otherwise, data synchronization may fail.
  • If you use only DTS to write data to the destination database, you can use DMS to perform online DDL operations on source tables during data synchronization. For more information, see Change schemas without locking tables.
  • During data synchronization, we recommend that you use only DTS to write data to the destination database. This prevents data inconsistency between the source and destination databases. If you use tools other than DTS to write data to the destination database, data loss may occur in the destination database when you use DMS to perform online DDL operations.
  • If you perform both full data synchronization and incremental data synchronization and the tables to be synchronized in the source database contain foreign keys, triggers, or event triggers (PostgreSQL V11.5 and later), the session_replication_role parameter in the destination database must be set to replica. After the data synchronization task is released, you can change the value of the session_replication_role parameter back to origin.
Special cases If the source instance is an ApsaraDB RDS for PostgreSQL instance, take note of the following limits:

During data synchronization, do not modify the endpoint and zone of the ApsaraDB RDS for PostgreSQL instance. Otherwise, the data synchronization task fails.

Billing

Synchronization type Task configuration fee
Schema synchronization and full data synchronization Free of charge.
Incremental data synchronization Charged. For more information, see Pricing.

Supported synchronization topologies

DTS supports two-way data synchronization only between two PostgreSQL databases. DTS does not support two-way data synchronization between multiple PostgreSQL databases.

Conflict detection

To ensure data consistency, make sure that data records with the same primary key, business primary key, or unique key are updated only on one of the synchronization nodes. If data records are updated on both nodes, DTS responds to conflicts based on the conflict resolution policy that you specify for the data synchronization task.

DTS checks and fixes conflicts to maximize the stability of two-way synchronization instances. DTS can detect the following types of conflicts:
  • Uniqueness conflicts caused by INSERT operations

    INSERT operations that do not comply with the uniqueness constraint cannot be synchronized. For example, if a record with the same primary key value is inserted into the two synchronization nodes at almost the same time, one of the inserted records fails to be synchronized. The synchronization fails because a record with the same primary key value already exists in the other node.

  • Inconsistent records caused by UPDATE operations
    • If the records to be updated do not exist in the destination instance, DTS converts the UPDATE operation into an INSERT operation. However, uniqueness conflicts may occur.
    • The primary keys or unique keys of the records to be inserted may conflict with those of existing records in the destination instance.
  • Non-existent records to be deleted

    The records to be deleted do not exist in the destination instance. In this case, DTS ignores the DELETE operation regardless of the conflict resolution policy that you specify.

Notice
  • During two-way synchronization, the system time of the source and destination instances may be different. Synchronization latency may occur. For these reasons, DTS cannot guarantee that the conflict detection mechanism can prevent all data conflicts. To perform two-way synchronization, make sure that records with the same primary key, business primary key, or unique key are updated only on one of the synchronization nodes.
  • DTS provides conflict resolution policies to prevent conflicts that may occur during data synchronization. You can select a conflict resolution policy when you configure two-way data synchronization.

SQL operations that can be synchronized

Operation type SQL statement
DML INSERT, UPDATE, and DELETE

Procedure

  1. Purchase an instance for two-way data synchronization. For more information, see Purchase a DTS instance.
    Notice On the buy page, set both Source Instance and Destination Instance to PostgreSQL and set Synchronization Topology to Two-way Synchronization.
  2. Go to the Data Synchronization page of the new DTS console.
    Note You can also log on to the Data Management console. In the top navigation bar, click DTS. Then, in the left-side navigation pane, choose DTS (DTS) > Data Synchronization.
  3. In the upper-left corner of the page, select the region where the destination instance resides.
  4. Find the data synchronization instance and click Configure Task in the Actions column of the first data synchronization task.
  5. Click Create Task. On the page that appears, configure the source and destination databases.
    Warning After you select the source and destination instances, we recommend that you read the Limits displayed in the upper part of the page. This ensures that you create and run the data synchronization task.
    Section Parameter Description
    N/A Task Name

    The task name that DTS automatically generates. We recommend that you specify a descriptive name that makes it easy to identify the task. You do not need to use a unique task name.

    Source Database Database Type Select PostgreSQL.
    Access Method Select Alibaba Cloud Instance.
    Instance Region The source region that you selected on the buy page. You cannot change the value of this parameter.
    Instance ID Select the ID of the source ApsaraDB RDS for PostgreSQL instance.
    Database Name Enter the name of the source database in the ApsaraDB RDS for PostgreSQL instance.
    Database Account Enter the privileged account of the ApsaraDB RDS for PostgreSQL instance. The account must be the owner of the database. For more information about how to create an account on an ApsaraDB RDS for PostgreSQL instance and grant permissions to this account, see Create an account on an ApsaraDB RDS for PostgreSQL instance and Create a database on an ApsaraDB RDS for PostgreSQL instance.
    Database Password

    The password of the database account.

    Destination Database Database Type Select PostgreSQL.
    Access Method Select Alibaba Cloud Instance.
    Instance Region The destination region that you selected on the buy page. You cannot change the value of this parameter.
    Instance ID Select the ID of the destination ApsaraDB RDS for PostgreSQL instance.
    Database Name Enter the name of the destination database in the ApsaraDB RDS for PostgreSQL instance.
    Database Account Enter the privileged account of the ApsaraDB RDS for PostgreSQL instance. The account must be the owner of the database. For more information about how to create an account on an ApsaraDB RDS for PostgreSQL instance and grant permissions to this account, see Create an account on an ApsaraDB RDS for PostgreSQL instance and Create a database on an ApsaraDB RDS for PostgreSQL instance.
    Database Password

    The password of the database account.

  6. In the lower part of the page, click Test Connectivity and Proceed.
    Note
    • You do not need to modify the security settings for ApsaraDB instances (such as ApsaraDB RDS for MySQL and ApsaraDB for MongoDB) and ECS-hosted databases. DTS automatically adds the CIDR blocks of DTS servers to the whitelists of ApsaraDB instances or the security group rules of ECS instances. For more information, see Add the CIDR blocks of DTS servers to the security settings of on-premises databases.
    • After data synchronization is complete, we recommend that you remove the CIDR blocks of DTS servers from the whitelists or security groups.
  7. Select the objects to migrate.
    • Basic Settings
      Parameter Description
      Task Stages

      Incremental Data Synchronization is selected by default. You must also select Schema Synchronization and Full Data Synchronization. After the precheck is complete, DTS synchronizes the historical data of selected objects from the source instance to the destination cluster. The historical data is the basis for subsequent incremental synchronization.

      Processing Mode of Conflicting Tables
      • Precheck and Report Errors: checks whether the destination database contains tables that have the same names as tables in the source database. If the source and destination databases do not contain identical table names, the precheck is passed. Otherwise, an error is returned during the precheck and the data synchronization task cannot be started.

        Note You can use the object name mapping feature to rename the tables that are migrated to the destination database. You can use this feature if the source and destination databases contain identical table names and the tables in the destination database cannot be deleted or renamed. For more information, see Map object names.
      • Ignore Errors and Proceed: skips the precheck for identical table names in the source and destination databases.
        Warning If you select Ignore Errors and Proceed, data inconsistency may occur and your business may be exposed to potential risks.
        • If the source and destination databases have the same schema, and a data record has the same primary key as an existing data record in the destination database:
          • During full data synchronization, DTS does not synchronize the data record to the destination database. The existing data record in the destination database is retained.
          • During incremental data synchronization, DTS synchronizes the data record to the destination database. The existing data record in the destination database is overwritten.
        • If the source and destination databases have different schemas, initial data synchronization may fail. In this case, only part of the columns are synchronized, or the data synchronization task fails.
      Conflict Resolution Policy If you encounter the conflicts described in Conflict detection, select a conflict resolution policy based on your business needs.
      • TaskFailed

        If a conflict occurs during data synchronization, an error is reported and the task exits. The task fails and you must manually resume the task.

      • Ignore

        If a conflict occurs during data synchronization, the synchronization task ignores the current statement and the task continues. The conflicting records in the destination database are used.

      • Overwrite

        If a conflict occurs during data synchronization, the conflicting records in the destination database are overwritten.

      Select Objects

      Select one or more objects from the Source Objects section and click the Rightwards arrow icon to add the objects to the Selected Objects section.

      Note You can select columns, tables, or schemas as objects to synchronize.
      Rename Databases and Tables
      • To rename an object in the destination instance, right-click the object in the Selected Objects section. For more information, see Map the name of a single object.
      • To rename multiple objects at a time in the destination instance, click Batch Edit in the upper-right corner of the Selected Objects section. For more information, see Map multiple object names at a time.
      Filter data

      You can specify WHERE conditions to filter data. For more information, see Use SQL conditions to filter data.

      Select the SQL operations to be synchronized In the Selected Objects section, right-click an object. In the dialog box that appears, select the SQL operations that you want to synchronize.
    • Advanced Settings
      Parameter Description
      Capitalization of Object Names in Destination Instance This parameter is set to DTS default policy. In this scenario, you cannot change the capitalization of object names in the destination database. For two-way data synchronization between PostgreSQL databases, all object names in the destination database are in lowercase. For more information, see Specify the capitalization of object names in the destination instance.
      Retry Time for Failed Connection
      Specifies the retry time range for failed connections. Valid values: 10 to 1440. Unit: minutes. Default value: 120. We recommend that you set the retry time range to more than 30 minutes. If DTS reconnects to the source and destination databases within the specified time range, DTS resumes the data synchronization task. Otherwise, the data synchronization task fails.
      Note
      • If an instance serves as the source or destination database of multiple data synchronization tasks, the less value that is specified for the instance takes precedence.
      • When DTS retries a connection, you are charged for the DTS instance. We recommend that you specify the retry time range based on your business needs. You can also release the DTS instance at your earliest opportunity after the source and destination instances are released.
  8. Click Next: Save Task Settings and Precheck in the lower part of the page.
    Note
    • Before you can start the data synchronization task, DTS performs a precheck. You can start the data synchronization task only after the task passes the precheck.
    • If the task fails to pass the precheck, you can click the Info icon icon next to each failed item to view details.
      • After you troubleshoot the issues based on the causes, you can run a precheck again.
      • If you do not need to troubleshoot the issues, you can ignore failed items and run a precheck again.
  9. Wait until the Success Rate becomes 100%. Then, click Back.
  10. The data synchronization task in the forward direction starts. You can view the progress of the task in the task list.
  11. Wait until initial synchronization is completed and the data synchronization task in the forward direction is in the Running state. You can view the status of the data synchronization task on the Data Synchronization page.
  12. Find the data synchronization task in the reverse direction and click Configure Task.
  13. On the Create Task page, configure the source and destination databases, as described in Step 5.
    Notice When you configure the data synchronization task in the reverse direction, you must select the correct source and destination instances. The source instance in the reverse direction corresponds to the destination instance in the forward direction. The destination instance in the reverse direction corresponds to the source instance in the forward direction. You must also make sure that the parameter settings such as the database name, account, and password are consistent.
  14. Select the objects to migrate., as described in Step 7. We recommend that you specify the same settings. The following table provides additional description.
    Basic Settings
    Parameter Description
    Processing Mode of Conflicting Tables When DTS checks for conflicting tables in the reverse direction, the tables that have been synchronized to the destination instance are ignored.
    Select Objects We recommend that you select the same objects for the forward and reverse directions.

    You can also add or delete objects based on your business requirements.

    Rename Databases and Tables We recommend that you do not use this feature when you configure the task in the reverse direction. Otherwise, data inconsistency may occur.
  15. Click Next: Save Task Settings and Precheck in the lower part of the page.
    Note
    • Before you can start the data synchronization task, DTS performs a precheck. You can start the data synchronization task only after the task passes the precheck.
    • If the task fails to pass the precheck, you can click the Info icon icon next to each failed item to view details.
      • After you troubleshoot the issues based on the causes, you can run a precheck again.
      • If you do not need to troubleshoot the issues, you can ignore failed items and run a precheck again.
  16. Wait until the Success Rate becomes 100%. Then, click Back.
  17. After the second data synchronization task is configured, wait until both tasks are in the Running state. The two-way data synchronization tasks are configured.