All Products
Search
Document Center

ApsaraDB for ClickHouse:Migrate from self-managed to Cloud ClickHouse

Last Updated:Jul 02, 2026

Self-managed ClickHouse clusters often suffer from instability, poor scalability, difficult upgrades, and weak disaster recovery. As a result, more customers are migrating their self-managed ClickHouse clusters to a cloud PaaS service. This topic describes how to migrate from a self-managed ClickHouse cluster to an ApsaraDB for ClickHouse community-compatible edition cluster.

Prerequisites

  • Target cluster:

  • Self-managed cluster:

    • You need a database account and password.

    • The account must have read permissions on databases and tables, and permissions to execute SYSTEM commands.

  • The target cluster and the self-managed cluster must be able to communicate over the network.

    If the self-managed cluster and the target cluster are in the same VPC, you must also add the IP addresses of all nodes in the target cluster and the IPv4 CIDR block of its vSwitch to the self-managed cluster's whitelist.

    • To configure a whitelist for an ApsaraDB for ClickHouse cluster, see Configure a whitelist.

    • To configure a whitelist in a self-managed cluster, see the relevant product documentation.

    • To view the IP addresses of all nodes in the ApsaraDB for ClickHouse cluster, run SELECT * FROM system.clusters;.

    • To obtain the IPv4 CIDR block for the vSwitch of your ApsaraDB for ClickHouse cluster, follow these steps:

      1. In the ApsaraDB for ClickHouse console, go to the Cluster Information page of the target cluster. In the Network Information section, get the VSwitch ID.

      2. In the vSwitch list, use the Instance ID to find the target vSwitch and get its IPv4 CIDR.

    If your self-managed cluster and the target cluster are in different VPCs, or if the self-managed cluster is in a local data center or on another cloud platform, you must first establish network connectivity. For more information, see How do I establish a network connection between a target cluster and a data source?.

Migration validation

Before you start the data migration, we strongly recommend creating a test environment to validate business compatibility, performance, and the migration plan. After the validation is complete, you can perform the data migration in your production environment. This crucial step helps you identify and resolve potential issues early, ensuring a smooth migration and preventing disruption to your production environment.

  1. Create a migration task to migrate the data. For detailed steps, see this topic.

  2. For information about cloud migration compatibility, performance bottleneck analysis, and ensuring migration success, see Analysis and Solutions for Compatibility and Performance Bottlenecks in Migrating Self-Managed ClickHouse to the Cloud.

Choose a solution

Migration solution

Pros

Cons

Use cases

Console migration

Provides a visual interface. You do not need to manually migrate metadata.

Supports only full and incremental migration of the entire cluster. You cannot migrate specific databases, tables, or historical data.

Migrating an entire cluster.

Manual migration

Lets you control which databases and tables to migrate.

Involves complex steps and manual metadata migration.

  • Migrating specific databases and tables.

  • Cold data exceeds 1 TB.

  • Hot data exceeds 10 TB.

  • Migrating an entire cluster that does not meet the conditions for console migration.

Procedure

Console migration

Limits

The destination cluster must be running version 21.8 or later.

Notes

During migration

  • During migration, the merge process pauses in the destination cluster but continues in the self-managed cluster.

    Note

    If a migration task runs for a long time, excessive metadata can accumulate in the destination cluster. We recommend that migration tasks do not exceed 5 days in duration. Tasks that exceed 5 days are automatically canceled.

  • The destination cluster must be the default cluster. If your self-managed cluster uses a different name, the service automatically converts the cluster definition in distributed tables to default.

Migration scope

  • Supported objects

    • Databases, data dictionaries, and materialized views.

      • This service supports migrating data dictionaries created with SQL, but not those created with XML.

        To verify this, run the following statement: SELECT * FROM system.dictionaries WHERE (database = '') OR isNull(database);. If the statement returns any rows, this indicates you have data dictionaries created using XML.

      • When a data dictionary accesses an external service, ensure that the external service is available and that the cluster is added to its allowlist. If the data source for a data dictionary is an internal table in the current ClickHouse cluster and the HOST parameter in the definition is an IP address, access to the dictionary may fail after a migration due to an IP address change. You must reconfirm the HOST of the current ClickHouse cluster and manually create the data dictionary.

    • Table schemas: All table schemas except for Kafka and RabbitMQ engine tables.

    • Data: Incremental migration of data from MergeTree family tables.

  • Unsupported objects and data

    • Kafka and RabbitMQ engine tables, and their data.

    • Data from non-MergeTree tables, such as external tables and Log tables.

    Important

    You must manually migrate the unsupported items listed above.

  • Data volume limits

    • Cold data: Migrating cold data is slow. To prevent failures caused by long migration times, we recommend clearing cold data from your self-managed cluster to ensure the total volume does not exceed 1 TB.

    • Hot data: If the volume of hot data exceeds 10 TB, the migration task is likely to fail.

    If your data volume exceeds these limits, consider using the manual migration solution instead.

Cluster impact

  • Self-managed cluster:

    • Reading data from the self-managed cluster increases its CPU and memory usage.

    • DDL operations are not allowed.

  • Destination cluster:

    • Writing data to the destination cluster increases its CPU and memory usage.

    • DDL operations are not allowed on the databases and tables being migrated.

    • This restriction does not apply to other databases and tables.

    • The merge process is stopped only for the databases and tables being migrated.

    • The cluster restarts before the migration task begins.

    • After the migration is complete, the cluster performs frequent merge operations. This increases I/O usage and can lead to higher business request latency. Plan for the potential impact of this increased latency. You must calculate the specific duration of the merge operations. For instructions, see Calculate the merge time after migration.

Procedure

Step 1: Check the cluster and enable system tables

Before migrating data, modify the config.xml file in your self-managed cluster to enable incremental migration. The required modifications depend on whether the system.part_log and system.query_log tables are enabled.

If system tables are not enabled

If you have not enabled system.part_log and system.query_log, add the following configurations to the config.xml file.

system.part_log

<part_log>
    <database>system</database>
    <table>part_log</table>
    <partition_by>event_date</partition_by>
    <order_by>event_time</order_by>
    <ttl>event_date + INTERVAL 15 DAY DELETE</ttl>
    <flush_interval_milliseconds>7500</flush_interval_milliseconds>
</part_log>

system.query_log

<query_log>
    <database>system</database>
    <table>query_log</table>
    <partition_by>event_date</partition_by>
    <order_by>event_time</order_by>
    <ttl>event_date + INTERVAL 15 DAY DELETE</ttl>
    <flush_interval_milliseconds>7500</flush_interval_milliseconds>
</query_log>

If system tables are enabled

  1. Ensure the configurations of system.part_log and system.query_log in the config.xml file match the following content. Inconsistencies may cause the data migration to fail or proceed slowly.

    system.part_log

    <part_log>
        <database>system</database>
        <table>part_log</table>
        <partition_by>event_date</partition_by>
        <order_by>event_time</order_by>
        <ttl>event_date + INTERVAL 15 DAY DELETE</ttl>
        <flush_interval_milliseconds>7500</flush_interval_milliseconds>
    </part_log>

    system.query_log

    <query_log>
        <database>system</database>
        <table>query_log</table>
        <partition_by>event_date</partition_by>
        <order_by>event_time</order_by>
        <ttl>event_date + INTERVAL 15 DAY DELETE</ttl>
        <flush_interval_milliseconds>7500</flush_interval_milliseconds>
    </query_log>
  2. After modifying the configuration, run the drop table system.part_log and drop table system.query_log statements. Inserting data into a business table automatically recreates the system.part_log and system.query_log tables.

Step 2: Configure destination cluster compatibility

Configure the destination cluster to be compatible with the self-managed cluster. This step minimizes the application changes required after migration.

  1. Obtain and compare the version numbers of the destination cluster and the self-managed cluster.

    Log on to the destination cluster and the self-managed cluster and run the following statement on each to obtain their version numbers. For more information about how to log on to ApsaraDB for ClickHouse, see Connect to a database.

    SELECT version();
  2. If the versions differ, log on to the destination cluster and set the compatibility parameter to match the version of the self-managed cluster. This ensures that their features are as consistent as possible. The following is an example:

    SET GLOBAL compatibility = '22.8';

Step 3: (Optional) Enable the MaterializedMySQL engine

If your self-managed cluster contains tables that use the MaterializedMySQL engine, run the following statement to enable this engine.

SET GLOBAL allow_experimental_database_materialized_mysql = 1;
Note

The ClickHouse community no longer maintains the MaterializedMySQL engine. After migrating to the cloud, we recommend using Data Transmission Service (DTS) to synchronize MySQL data.

Because the MaterializedMySQL engine is unmaintained, Data Transmission Service (DTS) uses ReplacingMergeTree tables instead of MaterializedMySQL tables when it synchronizes MySQL data to ApsaraDB for ClickHouse. For more information, see MaterializedMySQL compatibility.

For more information about using DTS to migrate MySQL data to ApsaraDB for ClickHouse, see the following topics:

Step 4: Record and clean up Kafka/RabbitMQ engine tables

Before starting the migration, record the definitions of all Kafka/RabbitMQ engine tables and their downstream materialized views in the self-managed cluster, handle implicit tables, and then delete these tables to avoid migration errors.

  1. Log on to the self-managed cluster and query all Kafka and RabbitMQ engine tables along with their downstream dependencies.

    /*
    create_table_query: table definition
    dependencies_database: database of the table that depends on this table
    dependencies_table: table that depends on this table
    From dependencies_database and dependencies_table, you can identify the materialized views that depend on Kafka/RabbitMQ tables
    */
    SELECT * FROM system.tables WHERE engine IN ('RabbitMQ', 'Kafka');
  2. View the materialized view definition to check whether its target table is an implicit table.

    /*
    View the materialized view definition.
    If the target table of the materialized view is an implicit table, pay special attention:
    Dropping the materialized view will also drop the implicit table, causing data loss.
    Example: If CREATE MATERIALIZED VIEW [db.]table_name [TO[db.]name] does not specify TO,
    the system automatically creates an implicit table, possibly in the format '.inner_id.<TABLE_UUID>' or '.inner.<TABLE>'
    */
    SELECT * FROM system.tables WHERE database='<DATABASE>' AND name = '<MATERIALIZED_VIEW_NAME>';
  3. If the target table of a materialized view is an implicit table, RENAME the target table to a new name to prevent data loss when the materialized view is dropped later.

    -- Rename the implicit target table to a new name to protect data
    RENAME TABLE <DATABASE>.`.inner_id.<TABLE_UUID>` TO <DATABASE>.<new_target_table_name>;
  4. Delete the Kafka/RabbitMQ engine tables and their downstream materialized views.

    -- Drop materialized views first
    DROP TABLE <DATABASE>.<MATERIALIZED_VIEW_NAME>;
    -- Then drop Kafka/RabbitMQ engine tables
    DROP TABLE <DATABASE>.<KAFKA_OR_RABBITMQ_TABLE_NAME>;
Important

Make sure to save all recorded DDL statements. You will need them to rebuild these tables on both the self-managed cluster and the destination cluster later. If you performed a RENAME operation, use the TO clause pointing to the renamed target table when rebuilding the materialized view. For more information, see CREATE MATERIALIZED VIEW.

Step 5: Create a data migration task

  1. Log on to the ApsaraDB for ClickHouse console.

  2. On the Clusters page, select Clusters of Community-compatible Edition and click the ID of the destination cluster.

  3. In the left-side navigation pane, choose Data Migration and Synchronization > Migration from ClickHouse.

  4. On the migration task page, click Create Migration Task.

    1. Configure the source and destination instances.

      Configure the following settings and click Test Connectivity and Proceed.

      Note

      If the connection test is successful, proceed to the next step. If the connection test fails, reconfigure the source and destination instances based on the prompts.

      image

      Source cluster parameters

      Parameter

      Description

      Example

      Source Access Method

      Select Express Connect, VPN Gateway, Smart Access Gateway, or Self-managed ClickHouse Clusters on an ECS Instance.

      Express Connect, VPN Gateway, Smart Access Gateway, or Self-managed ClickHouse Clusters on an ECS Instance

      Cluster Name

      The name of the source cluster.

      The name can contain only digits and lowercase letters.

      source

      Source Cluster Name

      Run SELECT * FROM system.clusters; to obtain the Source Cluster Name.

      default

      VPC IP Address

      The IP address and PORT (TCP address) of each shard in the cluster, separated by commas.

      Important

      You cannot use the VPC domain name or SLB address of an ApsaraDB for ClickHouse cluster.

      Format: IP:PORT,IP:PORT,......

      The method to obtain the cluster IP address and PORT varies depending on the data migration scenario.

      Cross-account or cross-region migration

      You can use the following SQL statement to obtain the IP address and PORT of the self-managed cluster:

      SELECT shard_num, replica_num, host_address as ip, port FROM system.clusters WHERE cluster = 'default' and replica_num = 1;

      Here, replica_num=1 selects the first replica set. You can also choose other replica sets or select one replica from each shard.

      Non-Alibaba Cloud ClickHouse migration

      If the IP address cannot be easily mapped to Alibaba Cloud, you can use the following SQL statement to obtain the IP address and PORT of the self-managed cluster:

      SELECT shard_num, replica_num, host_address as ip, port FROM system.clusters WHERE cluster = '<cluster_name>' and replica_num = 1;

      The parameters are described as follows:

      • cluster_name: the name of the destination cluster.

      • replica_num=1 selects the first replica set. You can also choose other replica sets or select one replica from each shard.

      If the IP address and port are mapped to Alibaba Cloud through network translation, you must configure the corresponding mapped IP address and port.

      192.168.0.5:9000,192.168.0.6:9000

      Database Account

      The database account of the source cluster.

      test

      Database Password

      The password for the database account of the source cluster.

      test******

      Destination cluster parameters

      Parameter

      Description

      Example

      Database Account

      The database account of the destination cluster.

      test

      Database Password

      The password for the database account of the destination cluster.

      test******

    2. Confirm the migration content.

      Carefully review the information about the data to be migrated on the page, and then click Next: Pre-detect and Start Synchronization.

    3. The system runs a precheck on the migration link in the background and starts the task.

      The system runs an Instance Status Detection, a Storage Space Detection, and a Local Table and Distributed Table Detection on the source and destination clusters.

      • If the precheck is successful:

        The following figure shows the page that appears after a successful precheck.

        image

        1. Carefully review how the data migration process affects the instances.

        2. Click Completed.

          Important
          • After you click Complete, the system creates and starts the task, and its status changes to Running. You can view the task in the task list.

          • After creating the task, you must monitor it. In the final stage of the migration, you must stop write operations to the self-managed cluster and migrate the remaining database and table schemas. For more information, see Monitor the migration task and stop writes to the self-managed cluster.

      • If the precheck fails: Follow the instructions in the error message and run the data migration task again. The following table describes the precheck items and their requirements. For more information about precheck error messages and their solutions, see Migration precheck errors and solutions.

        Check item

        Requirement

        Instance Status Detection

        The data migration task cannot start if management tasks (such as scale-out, upgrade, or downgrade) are running on the source or destination cluster.

        Storage Space Detection

        The available storage space of the destination cluster must be at least 1.2 times the used storage space of the self-managed cluster.

        Local Table and Distributed Table Detection

        If a local table in the self-managed cluster does not have a corresponding distributed table or has more than one distributed table, the check fails. To resolve this, delete the redundant distributed tables or create a unique distributed table for the local table.

Step 6: Assess migration feasibility

If the write speed of the source cluster is less than 20 MB/s, you can skip this step.

If the write speed of the source cluster is greater than 20 MB/s, you must check the actual write speed of the destination cluster to assess the feasibility of the migration. A successful migration requires the destination cluster's write speed to keep pace with the source cluster's. Follow these steps:

  1. View the TairPDBShardingIOBandwidth of the destination cluster to determine its actual write speed. For information on how to view TairPDBShardingIOBandwidth, see View cluster monitoring data.

  2. Compare the write speeds of the destination and source clusters.

    1. If the write speed of the destination cluster is greater than that of the source cluster: The migration is likely to succeed. Continue to Step 7.

    2. If the write speed of the destination cluster is less than that of the source cluster: The migration is likely to fail. We recommend that you cancel the migration task and use manual migration.

Step 7: Monitor migration and stop writes

  1. Log on to the ApsaraDB for ClickHouse console.

  2. On the Community Edition Instances list, click the ID of the destination cluster.

  3. In the navigation pane, click Data Migration and Synchronization > Migration from ClickHouse.

  4. On the instance migration list page, you can:

    • View the status and running stage of the migration task.

      Important
      • When the running stage reaches Data Migration (i.e., table schema migration is complete), immediately proceed to Step 8 to rebuild Kafka/RabbitMQ engine tables on the self-managed cluster and resume incremental data ingestion.

      • Closely monitor the Running Information of the target task. Based on the estimated remaining time in the Running Information column, follow Step 9 to stop writes to the self-managed cluster and handle Kafka and RabbitMQ engine tables.

    • In the Actions column, click View Details to open the task details page. The task details page contains the following information:

      Note

      If the migration task is finished (its status is Completed or Canceled), the content on the View Details page is cleared. You can view the list of migrated table schemas on the destination cluster by running the following SQL statement:

      SELECT `database`, `name`, `engine_full` FROM `system`.`tables` WHERE `database` NOT IN ('system', 'INFORMATION_SCHEMA', 'information_schema');
      • All migrated table schemas and their migration status.

      • All migrated database schemas and their migration status.

      • All error messages for failed database and table migrations.

    The following table describes the migration task statuses.

    Task status

    Description

    Running

    Preparing the environment and resources for the migration.

    Initializing

    Initializing the migration task.

    Configuration Migration

    Migrating the cluster configuration.

    Schema Migration

    Migrating all databases, MergeTree family tables, and Distributed tables.

    Data Migration

    Incrementally migrating data from MergeTree family tables.

    Other Schema Migration

    Migrating the schemas of materialized views and non-MergeTree tables.

    Data Check

    Checking if the data volume of the completed tables in the destination cluster is consistent with the data volume in the self-managed cluster. If they are inconsistent, the task might fail. We recommend that you restart the migration.

    Post-migration Configuration

    Configuring system settings for the destination cluster, such as cleaning up migration resources and re-enabling writes to the source instance.

    Completed

    The migration task is complete.

    Canceled

    The migration task is canceled.

Step 8: Rebuild Kafka/RabbitMQ engine tables on the self-managed cluster

After the migration task enters the data migration phase (i.e., table schema migration is complete), use the previously saved DDL statements to rebuild the Kafka/RabbitMQ engine tables and their downstream materialized views on the self-managed cluster. Once rebuilt, incremental data resumes flowing and is automatically synchronized to the destination cluster.

Important

If you performed a RENAME operation on implicit target tables earlier, use the TO clause pointing to the renamed target table when rebuilding the materialized view.

-- Rebuild Kafka/RabbitMQ engine tables on the self-managed cluster
CREATE TABLE <DATABASE>.<KAFKA_OR_RABBITMQ_TABLE_NAME> (...)
ENGINE = Kafka/RabbitMQ
SETTINGS ...;
-- Rebuild materialized view (pointing to the renamed target table)
CREATE MATERIALIZED VIEW <DATABASE>.<MATERIALIZED_VIEW_NAME> TO <DATABASE>.<new_target_table_name>
AS SELECT ... FROM <DATABASE>.<KAFKA_OR_RABBITMQ_TABLE_NAME>;

Step 9: Stop writes and perform cutover

When the estimated remaining migration time is less than 10 minutes or the migration progress reaches 99%, perform the following cutover steps:

  1. Stop business writes. On the self-managed cluster, delete the previously rebuilt Kafka/RabbitMQ engine tables and their downstream materialized views.

    -- Drop materialized views first
    DROP TABLE <DATABASE>.<MATERIALIZED_VIEW_NAME>;
    -- Then drop Kafka/RabbitMQ engine tables
    DROP TABLE <DATABASE>.<KAFKA_OR_RABBITMQ_TABLE_NAME>;
  2. Wait for the migration progress to reach 100% and the migration to complete fully.

  3. Connect to the destination cluster and use the previously saved DDL statements to rebuild the Kafka/RabbitMQ engine tables and their downstream materialized views.

    Important

    If you performed a RENAME operation on implicit target tables earlier, use the TO clause pointing to the renamed target table when rebuilding the materialized view.

    -- Rebuild Kafka/RabbitMQ engine tables on the destination cluster
    CREATE TABLE <DATABASE>.<KAFKA_OR_RABBITMQ_TABLE_NAME> (...)
    ENGINE = Kafka/RabbitMQ
    SETTINGS ...;
    -- Rebuild materialized view (pointing to the renamed target table)
    CREATE MATERIALIZED VIEW <DATABASE>.<MATERIALIZED_VIEW_NAME> TO <DATABASE>.<new_target_table_name>
    AS SELECT ... FROM <DATABASE>.<KAFKA_OR_RABBITMQ_TABLE_NAME>;
  4. Verify that the data pipeline on the destination cluster is working properly and data is flowing in normally.

Step 10: Complete migration

After stopping writes to the self-managed cluster, you can Complete the task. This step migrates the remaining data, performs a data volume check, and migrates the remaining database and table schemas. You can view the migrated content in the task details.

Important
  • If the data check fails, the migration task remains in the data volume check phase. We recommend canceling the migration and creating a new migration task. For more information about canceling a migration task, see Other operations.

  • A long data migration can cause excessive metadata to accumulate in the destination cluster. We recommend that migration tasks do not exceed 5 days in duration. Tasks that exceed 5 days are automatically canceled.

  1. Log on to the ApsaraDB for ClickHouse console.

  2. On the Clusters page, select Clusters of Community-compatible Edition, and click the ID of the destination cluster.

  3. In the left-side navigation pane, click Data Migration and Synchronization > Migration from ClickHouse.

  4. For the target migration task, click Complete Migration in the Actions column.

  5. In the Complete Migration dialog box, click OK.

Step 11: Migrate data for non-MergeTree tables

The migration task migrates only the table schema of non-MergeTree tables (such as external tables and Log tables), creating them in the destination cluster without any business data. You must migrate the business data manually. Follow these steps:

  1. Log on to the self-managed cluster and run the following statement to identify the non-MergeTree tables that require data migration.

    SELECT
        `database` AS database_name,
        `name` AS table_name,
        `engine`
    FROM `system`.`tables`
    WHERE (`engine` NOT LIKE '%MergeTree%') AND (`engine` != 'Distributed') AND (`engine` != 'MaterializedView') AND (`engine` NOT IN ('Kafka', 'RabbitMQ')) AND (`database` NOT IN ('system', 'INFORMATION_SCHEMA', 'information_schema')) AND (`database` NOT IN (
        SELECT `name`
        FROM `system`.`databases`
        WHERE `engine` IN ('MySQL', 'MaterializedMySQL', 'MaterializeMySQL', 'Lazy', 'PostgreSQL', 'MaterializedPostgreSQL', 'SQLite')
    ))
  2. Log on to the destination cluster and use the remote function to migrate the table data. For detailed instructions, see Migrate data using the remote function.

Other operations

When a migration task completes, its Migration Status changes to Completed. The task list does not update immediately, so refresh the page periodically to view the latest status.

Actions

Description

Impact

Scenario

Cancel Migration

Forcibly cancels the task and skips the data volume check, without migrating the remaining database and table schemas.

  • The migration is forcibly terminated. The database and table schemas on the destination instance may be incomplete and unusable.

  • Before restarting the migration, you must clear the migrated data from the destination cluster to prevent data duplication.

Use this option when the migration adversely affects your self-managed cluster and you need to restore write operations immediately.

Stop Migration

Stops data migration immediately but completes the migration of the remaining database and table schemas. The data volume check is skipped.

The data migration will be incomplete, but the database and table schemas on the destination instance will be complete.

Use this option to test a partially migrated dataset without interrupting writes to the self-managed cluster.

Stop migration

  1. Log on to the ApsaraDB for ClickHouse console.

  2. On the Clusters page, select Clusters of Community-compatible Edition, and then click the target cluster ID.

  3. In the left-side navigation pane, choose Data Migration and Synchronization > Migration from ClickHouse.

  4. In the Actions column for the target migration task, click Stop Migration.

  5. In the Stop Migration dialog box, click OK.

Cancel migration

  1. Log on to the ApsaraDB for ClickHouse console.

  2. On the Clusters page, select Clusters of Community-compatible Edition, and then click the target cluster ID.

  3. In the left-side navigation pane, choose Data Migration and Synchronization > Migration from ClickHouse.

  4. In the Actions column for the target migration task, click Cancel Migration.

  5. In the Cancel Migration dialog box, click OK.

Manual migration

Method 1: Use the BACKUP and RESTORE commands

For more information, see Use the BACKUP and RESTORE commands to back up and restore data.

Method 2: Use the INSERT FROM SELECT statement

Step 1: Migrate metadata

Migrating ClickHouse metadata is primarily about migrating the table creation DDL.

If you need to install the clickhouse-client tool, ensure its version matches that of the destination ApsaraDB for ClickHouse instance. You can find the download link at clickhouse-client.

  1. View the list of databases in the self-managed cluster.

    clickhouse-client --host="<old host>" --port="<old port>" --user="<old user name>" --password="<old password>" --query="SHOW databases"  > database.list

    Parameters:

    Parameter

    Description

    old host

    The address of the self-managed cluster.

    old port

    The port of the self-managed cluster.

    old user name

    The account used to log on to the self-managed cluster. The account must have DML read/write permissions, settings permissions, and DDL permissions.

    old password

    The password for the account.

    Note

    The system database is a system database and does not require migration. Filter it out.

  2. View the list of tables in the self-managed cluster.

    clickhouse-client --host="<old host>" --port="<old port>" --user="<old user name>" --password="<old password>" --query="SHOW tables from <database_name>"  > table.list

    Parameters:

    Parameter

    Description

    database_name

    The database name.

    Alternatively, you can query all database and table names directly from the system tables.

    SELECT DISTINCT database, name FROM system.tables WHERE database != 'system';
    Note

    If a queried table name starts with .inner., it is an internal representation of a materialized view and does not require migration. Filter it out.

  3. Export the table creation DDL for all tables in a specific database from the self-managed cluster.

    clickhouse-client --host="<old host>" --port="<old port>" --user="<old user name>" --password="<old password>" --query="SELECT concat(create_table_query, ';') FROM system.tables WHERE database='<database_name>' FORMAT TabSeparatedRaw" > tables.sql
  4. Import the table creation DDL into the destination ApsaraDB for ClickHouse instance.

    Note

    Before importing the table creation DDL, you must create the corresponding database in the ApsaraDB for ClickHouse instance.

    clickhouse-client --host="<new host>" --port="<new port>" --user="<new user name>" --password="<new password>"  -d '<database_name>'  --multiquery < tables.sql

    Parameters:

    Parameter

    Description

    new host

    The address of the destination ApsaraDB for ClickHouse instance.

    new port

    The port of the destination ApsaraDB for ClickHouse instance.

    new user name

    The account used to log on to the destination ApsaraDB for ClickHouse instance. The account must have DML read/write permissions, settings permissions, and DDL permissions.

    new password

    The password for the account.

Step 2: Migrate data

Remote function

  1. (Optional) When you migrate data to an ApsaraDB for ClickHouse instance, consider adjusting the network_compression_method parameter to reduce network traffic.

    • To temporarily modify the network_compression_method in the destination ApsaraDB for ClickHouse instance, run the following command.

    • SET network_compression_method = 'ZSTD';
    • To view the value of the network_compression_method parameter in the destination ApsaraDB for ClickHouse instance, run the following command.

    • SELECT * FROM system.settings WHERE name = 'network_compression_method';
  2. On the destination ApsaraDB for ClickHouse instance, run the following SQL statement to migrate data.

    INSERT INTO <new_database>.<new_table> 
    SELECT * 
    FROM remote('<old_endpoint>', <old_database>.<old_table>, '<username>', '<password>') 
    [WHERE _partition_id = '<partition_id>']
    SETTINGS max_execution_time = 0, max_bytes_to_read = 0, log_query_threads = 0, max_result_rows = 0, min_insert_block_size_rows = 4294967296, min_insert_block_size_bytes = 1073741824;
    Note

    For version 20.8, first use the remoteRaw function for data migration. If the migration fails, you can request a minor version upgrade.

    INSERT INTO <new_database>.<new_table> 
    SELECT * 
    FROM remoteRaw('<old_endpoint>', <old_database>.<old_table>, '<username>', '<password>')
    [WHERE _partition_id = '<partition_id>']
    SETTINGS max_execution_time = 0, max_bytes_to_read = 0, log_query_threads = 0, max_result_rows = 0, min_insert_block_size_rows = 4294967296, min_insert_block_size_bytes = 1073741824;

    Parameters:

    Important

    Use the _partition_id parameter to filter data. This reduces resource usage.

    (Optional) To obtain the partition_id and the number of parts, query them from the system.parts table by running the following SQL statement.

    SELECT partition_id, count(*) AS part_count from clusterAllReplicas(default, system, parts) WHERE `database` = '<old_database>' AND `table` = '<old_table>' GROUP BY partition_id ;

    Parameter

    Description

    new_database

    The database name in the destination ApsaraDB for ClickHouse instance.

    new_table

    The table name in the destination ApsaraDB for ClickHouse instance.

    old_endpoint

    The endpoint of the source instance.

    Self-managed ClickHouse

    Endpoint format: IP address of a source instance node:port.

    Important

    The port must be the TCP port.

    ApsaraDB for ClickHouse

    Use the VPC internal endpoint of the source instance, not the public endpoint.

    Important

    Ports 3306 and 9000 are fixed values.

    • Community Edition instance:

      • Endpoint format: VPC internal address:3306.

      • Example: cc-2zeqhh5v7y6q*****.clickhouse.ads.aliyuncs.com:3306

    • Enterprise instance:

      • Endpoint format: VPC internal address:9000.

      • Example: cc-bp1anv7jo84ta*****clickhouse.clickhouseserver.rds.aliyuncs.com:9000

    old_database

    The database name of the self-managed cluster.

    old_table

    The table name of the self-managed cluster.

    username

    The account for the self-managed cluster.

    password

    The password for the self-managed cluster account.

    max_execution_time

    The maximum execution time for a query. Set to 0 for no time limit.

    max_bytes_to_read

    The maximum number of bytes that a query can read from the source data. Set to 0 for no limit.

    log_query_threads

    Specifies whether to log thread information during query execution. Set to 0 to disable logging.

    max_result_rows

    The maximum number of rows in the query result. Set to 0 for no limit.

    min_insert_block_size_rows

    The minimum number of rows per data part in a single write. Set to 4294967296 (maximum) to disable the row limit. This setting works together with min_insert_block_size_bytes to prevent excessive small parts.

    min_insert_block_size_bytes

    The minimum size in bytes per data part in a single write. Set to 1073741824 (1 GB) to prevent excessive small parts and avoid the "Too many partitions for a single INSERT block" error.

    _partition_id

    The data partition ID.

File export and import

Export data from the self-managed cluster database to a file and then import the file into the destination ApsaraDB for ClickHouse instance.

  • CSV export and import
    1. Export data from the self-managed cluster database to a CSV file.

      clickhouse-client --host="<old host>" --port="<old port>" --user="<old user name>" --password="<old password>"  --query="select * from <database_name>.<table_name> FORMAT CSV"  > table.csv
    2. Import the CSV file into the destination ApsaraDB for ClickHouse instance.

      clickhouse-client --host="<new host>" --port="<new port>" --user="<new user name>" --password="<new password>"  --query="insert into <database_name>.<table_name> FORMAT CSV"  < table.csv
  • Stream with a Linux pipe
    clickhouse-client --host="<old host>" --port="<old port>" --user="<user name>" --password="<password>"  --query="select * from <database_name>.<table_name> FORMAT CSV" | 
    clickhouse-client --host="<new host>" --port="<new port>" --user="<user name>" --password="<password>"   --query="INSERT INTO <database_name>.<table_name> FORMAT CSV"

Migration check errors and solutions

Error message

Description

Solution

Missing unique distributed table or sharding_key not set.

A local table in the self-managed cluster is missing a unique distributed table.

Create a corresponding distributed table for the local table in the self-managed cluster.

The corresponding distributed table is not unique.

A local table in the self-managed cluster corresponds to multiple distributed tables.

Delete the redundant distributed tables on the self-managed cluster and keep only one.

MergeTree table on a multi-replica cluster.

The self-managed cluster is a multi-replica cluster but contains a non-replicated table. Migration is not supported because the data is inconsistent across replicas.

Why are non-replicated tables not allowed when you scale or migrate multi-replica instances?

Data reserved table on destination cluster.

The table to be migrated already exists and contains data on the destination cluster.

Delete the corresponding table from the destination cluster.

Columns of distributed table and local table conflict

The columns of the distributed table and the local table in the self-managed cluster are inconsistent.

Rebuild the distributed table on the self-managed cluster to ensure that its schema is consistent with the local table.

Insufficient storage space.

The destination cluster has insufficient storage space.

Increase the disk storage space of the destination cluster. Ensure that the destination cluster's total storage space is at least 1.2 times the self-managed cluster's used space. For more information, see Vertical and horizontal scaling of community-compatible clusters.

Missing system table.

A system table is missing from the self-managed cluster.

Modify the config.xml configuration file of the self-managed cluster to create the required system tables. For more information, see Step 1: Check the self-managed cluster and enable system tables.

The table is incomplete across different nodes.

The table is missing on some nodes.

Create tables with the same name on different shards. For an inner table of a materialized view, rename the inner table, and then rebuild the materialized view to point to the renamed table. For more information, see The inner table of a materialized view is inconsistent across shards.

Calculating post-migration merge time

After migration, the destination cluster temporarily performs frequent merge operations. This increases I/O usage and can cause higher latency for service requests. If your services are sensitive to read and write latency, consider upgrading the instance type and ESSD performance level to shorten this period of high I/O usage. For more information, see Vertical scaling, scale-out, and scale-in of community-compatible clusters.

Use the following formulas to calculate the merge time after migration:

Note

These formulas apply to both single-replica and master-replica clusters.

  • Estimated total time for frequent merge operations = MAX(hot data merge time, cold data merge time)

    • Hot data merge time = amount of hot data on a single node * 2 / MIN(instance type bandwidth, disk bandwidth * n)

    • Cold data merge time = (amount of cold data / number of nodes) / MIN(instance type bandwidth, OSS read bandwidth) + (amount of cold data / number of nodes) / MIN(instance type bandwidth, OSS write bandwidth)

The following list describes the parameters used in the formulas:

  • Amount of hot data on a single node: You can view this value in the Disk Usage - Single-Node Statistics row. For more information, see View cluster monitoring information.

  • Instance type bandwidth

    Note

    These bandwidth values are not absolute and vary depending on the machine types used by the ApsaraDB for ClickHouse backend. The values provided are minimums and for reference only.

    Specification

    Bandwidth (MB/s)

    Standard 8-core 32 GB

    250

    Standard 16-core 64 GB

    375

    Standard 24-core 96 GB

    500

    Standard 32-core 128 GB

    625

    Standard 64-core 256 GB

    1250

    Standard 80-core 384 GB

    2000

    Standard 104-core 384 GB

    2000

  • Disk bandwidth: Find this value in the Maximum throughput per disk (MB/s) row of the ESSD performance level table.

  • n: The number of disks on a single node. Run the following command to get this value: SELECT count() FROM system.disks WHERE type = 'local';

  • Amount of cold data: You can view this value in the clickhouse_cold_storage_data row. For more information, see View cluster monitoring information.

  • Number of nodes: The number of nodes in the cluster. Run the following command to get this value: SELECT count() FROM system.clusters WHERE cluster = 'default' and replica_num=1;

  • OSS read bandwidth: Find this value in the Total Intranet and Internet Download Bandwidth column of the OSS bandwidth table.

  • OSS write bandwidth: Find this value in the Total Intranet and Internet Upload Bandwidth column of the OSS bandwidth table.

FAQ

  • Q: How do I resolve the "Too many partitions for single INSERT block (more than 100)" error?

    A: This error occurs because a single INSERT operation exceeds the max_partitions_per_insert_block limit, which is 100 by default. In ClickHouse, each write operation creates a data part, and a partition can contain one or more data parts. If a single INSERT operation writes data to too many partitions, it creates an excessive number of data parts. This can significantly degrade merge and query performance. ClickHouse imposes this limit to prevent performance degradation.

    To resolve this issue, you can adjust the number of partitions or modify the max_partitions_per_insert_block parameter.

    • Adjust the table schema and partitioning method, or avoid inserting data into too many different partitions in a single operation.

    • If you must insert data into many partitions at once, you can raise the limit by modifying the max_partitions_per_insert_block parameter. The syntax is as follows:

      SET GLOBAL ON cluster DEFAULT max_partitions_per_insert_block = XXX;
      Note

      The ClickHouse community recommends using the default value of 100. Do not set this value too high, because it may degrade performance. After the batch data import, we recommend that you reset the value to its default.

  • Q: Why does the connection from my destination ApsaraDB for ClickHouse instance to my self-managed ClickHouse database fail?

    A: This issue occurs if your self-managed ClickHouse database is behind a firewall or uses a whitelist. To resolve this, add the IPv4 CIDR block of the vSwitch for the ApsaraDB for ClickHouse cluster to the whitelist of your self-managed database. For information about how to obtain the IPv4 CIDR block of the vSwitch for the ApsaraDB for ClickHouse cluster, see View IPv4 CIDR block.

  • Q: When I scale or migrate a multi-replica instance, why are non-Replicated tables not allowed? If they exist, how do I resolve this issue?

    A: The reason for this restriction and the solution are as follows:

    • Reason: A multi-replica instance requires Replicated tables to synchronize data between replicas. Without Replicated tables, the multi-replica setup is ineffective. The migration tool randomly selects one replica as the data source and migrates its data to the destination instance.

      If non-Replicated tables exist, data is not synchronized between replicas, meaning each replica holds isolated data. Because the migration tool migrates from only one replica, this process causes data loss. For example, as shown in the following figure, the MergeTree table on replica 0 (r0) contains data 1, 2, and 3. The MergeTree table on replica 1 (r1) contains data 4 and 5. If the migration tool selects r0 as the source, only data 1, 2, and 3 are migrated to the destination instance.

      image
    • Solution: If you can delete the non-Replicated tables in the source instance, we recommend doing so. Otherwise, you must replace the non-Replicated tables with Replicated tables. Follow these steps:

      1. Log on to the source instance.

      2. Create a Replicated table. The table schema must be identical to the non-Replicated table that you want to replace, except for the engine.

      3. Manually migrate data from the non-Replicated table to the new Replicated table. The migration statement is as follows:

        Important

        You must perform this migration for each replica. For example, you must run the statement on both r0 and r1.

        You can get the node IP address for the statement by running SELECT * FROM system.clusters;.

        INSERT INTO <destination_database>.<new_replicated_table> 
        SELECT * 
        FROM remote('<node_IP_address>:3003', '<source_database>', '<non_replicated_table_to_replace>', '<username>', '<password>')
        [WHERE _partition_id = '<partition_id>']
        SETTINGS max_execution_time = 0, max_bytes_to_read = 0, log_query_threads = 0, min_insert_block_size_rows = 4294967296, min_insert_block_size_bytes = 1073741824;
      4. Swap the names of the non-Replicated table and the Replicated table.

      EXCHANGE TABLES <source_database>.<non_replicated_table_to_replace> AND <destination_database>.<new_replicated_table> ON CLUSTER default;