
Amazon Redshift is a managed AWS data warehouse that stores tables in columnar format and runs SQL queries in parallel across compute nodes. It removes the need to operate database servers, but it bills per node-hour or per Redshift Processing Unit (RPU) hour plus managed storage, and it ties your data and queries to AWS.
ClickHouse is an open-source, column-oriented analytics database, released under the Apache License 2.0, that compresses each column and runs each query on all shards in parallel. ClickHouse uses its own SQL dialect, so table definitions and some functions need translation. The Altinity Kubernetes Operator for ClickHouse manages the servers, shards, replicas, and the ClickHouse Keeper coordination service as Kubernetes resources, so you keep the data on volumes that you control and pay for the underlying compute and storage.
This article explains how to deploy ClickHouse as an alternative to Amazon Redshift. It covers a ClickHouse cluster with two shards and two replicas per shard on Kubernetes, TLS access through a load balancer, block storage volumes, nightly backups to S3-compatible object storage with a restore test, optional monitoring with Prometheus and Grafana, and the migration of existing Redshift tables, queries, and applications.
The following table maps Redshift concepts to their ClickHouse equivalents.
The deployment places ClickHouse on the data nodes and every supporting service on the system nodes:
clickhouse-backup sidecar. The loss of one node leaves every shard available.Before you begin:
clickhouse-data with four nodes of 8 vCPUs and 32 GB of memory, and clickhouse-system with three nodes of 4 vCPUs and 8 GB of memory. The cluster needs a Container Storage Interface (CSI) driver for block storage volumes and a cloud controller that provisions load balancers for LoadBalancer services.22 from your workstation IP address only.clickhouse-backups, and note its endpoint hostname, access key, and secret key.kubectl on a Linux workstation, configure it to access the cluster, and confirm that kubectl get nodes lists all seven nodes with the Ready status.curl, openssl, and Helm 3.8 or later on the workstation.~/clickhouse-k8s directory on the workstation and run every command in this article from it.curl -4 -s https://ifconfig.me.UNLOAD to write to an Amazon S3 bucket, and an access key with read access to that bucket.Every workload selects its nodes by a pool label. The data nodes also get a soft taint that steers unrelated pods to the system nodes without blocking the CSI node plugins.
Label the data nodes.
Label the system nodes.
Add the soft taint to the data nodes.
Verify the labels.
The CLICKHOUSE-POOL column shows data for the four clickhouse-data nodes and system for the three clickhouse-system nodes.
Verify the taints.
The four data nodes show PreferNoSchedule, and the three system nodes show <none>.
The labels belong to the nodes, not to the node pools. Run the steps in this section again after every Kubernetes upgrade, node repair, or pool resize, or pods meant for new nodes stay Pending.
Each component gets its own namespace, and three priority classes evict monitoring first and ClickHouse last. The storage class provisions NVMe block storage volumes in place of Redshift Managed Storage.
Create a manifest file named 00-base.yaml.
Add the following content to the file.
Save and close the file.
The provisioner and parameters values match the CSI driver of the tested cluster. On another cluster, replace them with the values of its block storage CSI driver.
Apply the manifest.
Verify the storage class.
The output shows the Retain reclaim policy and the WaitForFirstConsumer binding mode.
The following steps generate random passwords and store them in Kubernetes secrets. ClickHouse receives only the SHA-256 hashes of its passwords.
Generate the ClickHouse admin and backup passwords and store them, together with their SHA-256 hashes, in the clickhouse-credentials secret.
Create a random password for the operator's own ClickHouse account. The Helm chart default is public.
Store the object storage keys for the backup sidecars. Replace OBJECT_STORAGE_ACCESS_KEY and OBJECT_STORAGE_SECRET_KEY with the keys of your object storage service.
List the secrets in the clickhouse namespace.
The output lists the clickhouse-backup-s3, clickhouse-credentials, and clickhouse-operator-password secrets.
The cert-manager add-on issues and renews the TLS certificates that ClickHouse serves. Two controller and two webhook replicas keep it available during node drains.
Create a values file named cert-manager.values.yaml.
Add the following content to the file.
Save and close the file.
Install cert-manager version v1.21.0.
List the cert-manager pods.
All five pods are Running: two controller replicas, two webhook replicas, and one CA injector.
ClickHouse serves a certificate signed by a private certificate authority (CA) that cert-manager creates. The CA key never rotates, so clients keep trusting renewed server certificates.
Create a manifest file named 10-tls-issuers.yaml.
Add the following content to the file.
Save and close the file.
Apply the manifest.
Wait until the CA certificate is ready.
Create a manifest file named 11-server-cert.yaml.
Add the following content to the file. The load balancer IP address is added to the certificate after the load balancer exists.
Save and close the file.
Apply the manifest.
Wait until the server certificate is ready.
The Altinity operator turns ClickHouse and Keeper installation resources into StatefulSets, services, and configuration. The following steps install the operator and its custom resource definitions (CRDs).
Create a values file named clickhouse-operator.values.yaml.
Add the following content to the file.
Save and close the file.
In the above values file:
crdHook.enabled: false: Skips the chart hook that installs the CRDs. The next steps apply them from the pinned chart instead.reconcile.host.wait.replicas.all: true: Makes the operator wait for replication to catch up before it restarts the next server.Add the Altinity Helm repository.
Update the Helm repositories.
Download the operator chart to apply its CRDs from the pinned version.
Apply the CRDs.
Install the operator with the password from the clickhouse-operator-password secret.
List the pods in the clickhouse namespace.
The output lists one clickhouse-operator-altinity-clickhouse-operator-... pod with 2/2 containers in the Running state.
ClickHouse Keeper stores replication metadata and coordinates the statements that run on every server. Three replicas on separate system nodes keep a quorum when one node fails or is drained.
Create a manifest file named 20-keeper.yaml.
Add the following content to the file.
Save and close the file.
In the above manifest:
pdbMaxUnavailable: 1 and podAntiAffinity: Place each replica on a different node and allow only one down at a time, so two replicas always form a quorum.resources: Sets the memory request equal to the limit to protect Keeper from eviction.Apply the manifest.
Wait until the operator reports the Keeper installation as complete. This step takes 2 to 5 minutes.
List the Keeper pods and their nodes.
The three chk-keeper-keeper-0-N-0 pods run on different clickhouse-system nodes.
Wait until all three Keeper pods are ready.
The output reports condition met for each of the three pods.
Each ClickHouse pod runs a backup sidecar that uploads backups to object storage, in place of Redshift automated snapshots. A nightly CronJob backs up one replica per shard, and a second CronJob reloads renewed TLS certificates. Create this configuration before the cluster, or the ClickHouse pods fail with CreateContainerConfigError.
Create a manifest file named 40-backup.yaml.
Add the following content to the file. Replace S3_HOSTNAME with the endpoint hostname of your object storage service.
Save and close the file.
In the above manifest:
S3_PATH: Stores the backups of each shard in its own folder of the bucket.BACKUPS_TO_KEEP_REMOTE: Keeps 21 backups per shard.FULL_EVERY_DAYS: Takes a full backup when the newest full backup is older than seven days, and an incremental backup otherwise.--async_insert=0 and < /dev/null: Stop the client from reading the shard list as insert data.grep -q 'BACKUP OK': Fails the job when the script is empty or incomplete.schedule and timeZone: Run the backup every night at 1:30 a.m. UTC. Change both to match your maintenance window.Apply the manifest.
Create a manifest file named 41-cert-reload.yaml.
Add the following content to the file. The job makes every ClickHouse server reload the renewed certificate without a restart.
Save and close the file.
Apply the manifest.
List the CronJobs.
The output lists the clickhouse-backup CronJob with the 30 1 * * * schedule and the clickhouse-cert-reload CronJob with the 15 4 * * * schedule.
The ClickHouseInstallation resource describes the whole cluster: shards, replicas, pod placement, the backup sidecar, TLS, users, and the load balancer. An internal service serves applications inside the Kubernetes cluster.
Create a manifest file named 30-clickhouse.yaml.
Add the following content to the file. Replace ALLOWED_IP with the public IP address of your workstation that you noted in the prerequisites.
Save and close the file.
In the above manifest:
serviceTemplate: public-lb: Replaces the operator's default service with a load balancer that forwards only port 9440.service.beta.kubernetes.io/vultr-loadbalancer-*: Configure the load balancer of the tested cluster with TCP forwarding, health checks, and a source allowlist. On another cluster, use the annotations of its cloud controller, or spec.loadBalancerSourceRanges.vultr-loadbalancer-firewall-rules: Allows port 9440 only from ALLOWED_IP. Separate several sources with ;, such as 198.51.100.25/32,9440;203.0.113.0/24,9440.admin/networks/ip and backup/networks/ip: Accept these users from any address, because the load balancer allowlist and the node firewall restrict access.secret: auto: "true": Creates a shared inter-server secret, so distributed queries run on remote shards as the original user.resources: Sets requests equal to limits for the Guaranteed quality-of-service class.openSSL.client: Applies only to TLS connections between ClickHouse pods.storageManagement: Lets the operator grow volumes online.shardsCount and replicasCount: Create four ClickHouse pods named chi-analytics-main-SHARD-REPLICA-0.Apply the manifest.
Create a manifest file named 31-clickhouse-internal.yaml for the in-cluster service.
Add the following content to the file.
Save and close the file.
Apply the manifest.
Wait until the operator reports the cluster as complete. This step takes a few minutes.
List the ClickHouse pods and their nodes.
Each chi-analytics-main-* pod runs on a different clickhouse-data node, and the READY column shows true,true.
Clients that connect by IP address verify that the address appears in the server certificate. The following steps add the load balancer address to the certificate.
Display the public IP address of the load balancer.
The output is a single address, such as 192.0.2.10. If the output is empty, wait one minute and run the command again.
Open the server certificate manifest.
Add the load balancer IP address under ipAddresses, below 127.0.0.1. Replace LB_IP with the load balancer IP address.
Save and close the file.
Apply the manifest to make cert-manager issue a new certificate that includes the address.
Verify that the renewed certificate contains the address.
The output ends with an IP Address entry that matches the load balancer IP address. If it is missing, wait a few seconds and run the command again.
Wait 90 seconds for Kubernetes to deliver the renewed certificate files to the ClickHouse pods.
Start a certificate reload job from the reload CronJob.
Wait until the job completes.
Clients outside the cluster connect through the load balancer, in place of the Redshift endpoint.
Export the CA certificate to a file.
Verify the TLS handshake and the certificate. Replace LB_IP with the load balancer IP address.
The output is Verify return code: 0 (ok).
Download the single-binary ClickHouse client to the working directory.
The script downloads the latest ClickHouse build as a binary named clickhouse. The client can be newer than the 26.8.15.10 server and still connects to it.
Create the client configuration file clickhouse-client.xml. Replace LB_IP with the load balancer IP address.
Store the admin password in a shell variable.
Run a query through the load balancer.
The output shows the server version, 26.8.15.10, and the name of the pod that answered, such as chi-analytics-main-1-0-0.
The following checks confirm the cluster layout, Keeper connectivity, replication, the disruption budgets, the backup sidecars, and the public access rules.
Define a shell function named ch that runs a query in the first ClickHouse pod. Run the remaining sections in the same terminal.
Display the shards and replicas of the main cluster.
The output lists shards 1 and 2 with replicas 1 and 2 each, and 0 in the errors_count column for every host.
Verify that ClickHouse reaches Keeper.
The output is a number greater than 0, such as 2.
Create a demo database on every server.
The output lists one line per server with 0 in the third column.
Create a replicated local table and a Distributed table that shards rows by a hash of the id column.
Insert 1 million rows through the Distributed table.
Wait until every replica has copied the rows.
Count the rows on each server.
Both replicas of each shard report the same row count, and the two shards together hold 1,000,000 rows. The shard macro numbers the shards from 0.
Drop the demo database.
List the PodDisruptionBudgets.
The output lists the chi-analytics-main and chk-keeper-keeper budgets, each with 1 in the ALLOWED DISRUPTIONS column.
Verify that the backup sidecar answers through the system.backup_list table.
The output is 0 before the first backup. An error means that the sidecar is not running.
Verify that the load balancer rejects the plaintext ports. Replace LB_IP with the load balancer IP address.
The output reports both ports as closed.
Verify that ClickHouse rejects a wrong password.
The output is Authentication failed.
Display the node port of the load balancer service.
The output is a port number between 30000 and 32767.
List the nodes with their public IP addresses in the EXTERNAL-IP column.
Verify that the node port is not reachable directly on a node. Replace NODE_IP with the EXTERNAL-IP of any node and NODE_PORT with the port from the previous step.
The output closed confirms that clients reach ClickHouse only through the load balancer. If the output is open, confirm that the node firewall has the SSH rule from the prerequisites, wait 2 minutes, and run the check again.
This section runs a backup on demand, then drops and restores a test database, the equivalent of restoring a table from a Redshift snapshot.
The CronJob runs every night, and a job created from it runs the same script immediately.
Define a shell function named cb that runs clickhouse-backup in the sidecar of a pod and hides its informational log lines. No output means success.
Start a backup job from the backup CronJob.
Wait until the job completes. The first full backup takes longer as the data grows.
Display the job log.
The log shows an uploaded line for a full backup of each shard, such as shard0-full-TIMESTAMP, and ends with BACKUP OK.
List the backups of each shard in object storage.
The output lists one shard0-full-... and one shard1-full-... backup.
The test records a checksum of a test database, backs it up, drops it, restores it, and compares the checksum.
The test drops the drill database on every server. Run it only against the test database.
Create the drill database.
Create the replicated local table.
Create the Distributed table.
Insert 1 million rows.
Store the row count and a checksum of every row in a shell variable.
The output prints BEFORE: followed by the row count, 1000000, and the checksum of the table.
Start a backup job.
Wait until the job completes.
Display the job log.
The log shows uploaded lines for incremental backups, such as shard0-incr-TIMESTAMP, and ends with BACKUP OK.
Store the names of the two new backups in shell variables.
The output prints S0= and S1= followed by the name of the new backup of each shard, such as shard0-incr-TIMESTAMP.
Drop the drill database on every server. Run this step only when both backup names in the previous output are set.
Restore the schema on both replicas of each shard.
Restore the data of each shard on its first replica.
The output can include an already exists will try to resume download warning, which is expected.
Wait until the second replicas have copied the restored data.
Compare the restored rows with the checksum from before the backup.
The output ends with PASS: restored data is identical.
Delete the local backup copies that the restore downloaded on every replica.
Drop the drill database.
Delete the finished backup and certificate reload jobs. The backups stay in object storage.
To restore a production database, follow the same order. Omit --tables to restore every database, and add --rm to replace existing tables.
The operator applies manifest changes one server at a time, so every shard stays available. To add capacity, add and label data nodes, then raise replicasCount or shardsCount in 30-clickhouse.yaml and apply the manifest. A new shard receives new rows, but ClickHouse does not move existing rows to it. To grow the volumes, raise the storage request under volumeClaimTemplates and apply the manifest.
Replace or add nodes: Run the steps in Label the Nodes again after every Kubernetes upgrade, node repair, or pool resize.
Change the allowed source address: Edit the vultr-loadbalancer-firewall-rules value in 30-clickhouse.yaml, apply the manifest, and set the same value on the service. Replace ALLOWED_IP with the new source address.
Upgrade ClickHouse: Change 26.8.15.10 to a newer 26.8 patch release in 20-keeper.yaml, 30-clickhouse.yaml, 40-backup.yaml, and 41-cert-reload.yaml. Apply 20-keeper.yaml first, then the other three files.
Create application tables the same way as the demo table in Verify the Deployment: a ReplicatedMergeTree local table and a Distributed table on top, both with ON CLUSTER 'main'. Send inserts in batches of thousands of rows, or enable async_insert for clients that send small batches.
A migration translates each table definition, copies the data through object storage, rewrites Redshift-specific SQL, and moves applications. A phased cutover keeps Redshift as a fallback.
Recreate each Redshift table as a ReplicatedMergeTree local table and a Distributed table, both with ON CLUSTER 'main', as in Verify the Deployment. Run SHOW TABLE schema_name.table_name in Redshift to get each CREATE TABLE statement, then translate it with the following rules:
sales.orders keeps its name.SMALLINT, INTEGER, and BIGINT become Int16, Int32, and Int64. DECIMAL(p, s) becomes Decimal(p, s), and REAL and DOUBLE PRECISION become Float32 and Float64.CHAR and VARCHAR become String, or LowCardinality(String) for columns with few distinct values, such as status codes or country names. BOOLEAN becomes Bool.DATE becomes Date32, which covers the years 1900 to 2299. TIMESTAMP becomes DateTime64(6), which keeps microseconds, and TIMESTAMPTZ becomes DateTime64(6, 'UTC'). Check for dates outside the supported range before you load them.SUPER becomes JSON, and VARBYTE and GEOMETRY become String. HLLSKETCH has no equivalent, so compute distinct counts with uniq.NULL unless its type is wrapped in Nullable. Use Nullable only where NULL carries meaning.DISTKEY(column) becomes the sharding key cityHash64(column) of the Distributed table, and DISTSTYLE EVEN becomes rand(). A table with DISTSTYLE ALL, usually a small dimension table, becomes a ReplicatedMergeTree table whose Keeper path omits the {shard} macro, so all four servers hold a full copy, or a dictionary for key-value lookups. For tables with DISTSTYLE AUTO, the diststyle column of the SVV_TABLE_INFO view shows the style that Redshift chose.Distributed table with the local table of the other side, so each shard joins its own rows. Otherwise, use GLOBAL JOIN, which sends the right-hand table to every shard.SORTKEY(a, b) becomes ORDER BY (a, b). For an interleaved sort key, put the most common filter columns in ORDER BY and add data-skipping indexes for the others.ENCODE clauses. ClickHouse compresses every column with LZ4 unless the column sets a codec, such as CODEC(ZSTD(3)) for long text or CODEC(Delta, ZSTD) for timestamps.PRIMARY KEY is a prefix of the sorting key, not a uniqueness rule. Generate IDENTITY values in the application or with generateSnowflakeID().UPDATE, DELETE, or MERGE statements becomes a ReplicatedReplacingMergeTree table, which keeps the newest version of each row. Query it with FINAL when results must not contain older versions.The Redshift UNLOAD command exports each table to Parquet files in Amazon S3, and the ClickHouse s3 table function loads them. The ClickHouse postgresql table function does not work with Redshift.
The following example copies the sales.orders table after you create it in ClickHouse as described in Schema Migration.
Export the table from Redshift to Parquet files. Replace BUCKET and PREFIX with the Amazon S3 bucket and folder for the export, and ROLE_ARN with the Amazon Resource Name (ARN) of the IAM role that authorizes UNLOAD.
Redshift writes one or more Parquet files per slice under the PREFIX/ folder.
Copy the Parquet files from Amazon S3 to your object storage service with an S3-compatible copy tool, such as rclone. To read the files directly from Amazon S3 instead, skip the copy and use the regional URL https://BUCKET.s3.REGION.amazonaws.com/PREFIX/*.parquet with an AWS access key in the next step.
Load the files into ClickHouse through the Distributed table. Replace S3_HOSTNAME with the endpoint hostname of your object storage service, BUCKET and PREFIX with the location of the files, and S3_ACCESS_KEY and S3_SECRET_KEY with keys that can read the bucket.
Count the loaded rows and compare the result with SELECT COUNT(*) FROM sales.orders in Redshift.
Plan for the following behavior during the copy:
UNLOAD exports the rows that the table holds when the query starts. Rows written after that reach ClickHouse through the dual writes in Data Migration Strategy.UNLOAD competes with other queries. Export large tables outside peak hours or one month at a time.UNLOAD with PARTITION BY removes the partition columns from the files unless you add the INCLUDE option.UNLOAD writes GEOMETRY, VARBYTE, and HLLSKETCH columns only to CSV, so export those tables in a separate CSV UNLOAD.system.parts. AWS bills reads from outside AWS as data transfer out.Joins, window functions, and common table expressions usually need only small changes. Check each query for the following differences:
GETDATE() becomes now(), NVL(a, b) becomes ifNull(a, b) or COALESCE(a, b), LISTAGG(column, ',') becomes arrayStringConcat(groupArray(column), ','), and APPROXIMATE COUNT(DISTINCT column) becomes uniq(column). DATEDIFF and DATE_TRUNC become dateDiff and dateTrunc, which take the unit as a string, such as 'day'.2 for 5 / 2, and ClickHouse returns 2.5. Use intDiv(5, 2) where a query depends on integer results.NULL. Set join_use_nulls = 1 in the settings profile of the application user to return NULL, as Redshift does.PREPARE with typed query parameters, such as {customer_id:UInt64}.VACUUM and ANALYZE jobs. ClickHouse merges data parts in the background.Each application, dashboard, and data pipeline needs a new driver and new connection settings:
CLUSTER_NAME.ID.REGION.redshift.amazonaws.com on port 5439, with the load balancer IP address on port 9440 for clients outside the Kubernetes cluster. Applications inside the Kubernetes cluster connect to clickhouse-internal.clickhouse.svc.cluster.local on port 9000 or 9440.9440. HTTP-based drivers, such as JDBC, ODBC, and clickhouse-connect, need https_port: 8443 in 30-clickhouse.yaml and port 8443 on the load balancer and its allowlist.clickhouse-ca.crt from Connect to ClickHouse over TLS, and keep certificate verification enabled.admin user for administration only.The admin user creates ClickHouse users, roles, and grants with SQL statements:
CREATE USER ... IDENTIFIED WITH sha256_password.CREATE ROLE and assigned with GRANT role_name TO user_name.GRANT SELECT ON ALL TABLES IN SCHEMA sales becomes GRANT SELECT ON sales.*, and column-level grants keep their form, such as GRANT SELECT(id, amount) ON sales.orders. A user that queries a Distributed table also needs SELECT on its local table, because the other shards run the query as the same user.CREATE ROW POLICY and a USING condition for each role. Redshift masking policies have no equivalent, so grant access to a view that returns masked values instead.CREATE SETTINGS PROFILE sets limits such as max_memory_usage, max_execution_time, and max_threads, and CREATE QUOTA limits the queries, errors, or rows read per user over an interval.CREATE USER, CREATE ROLE, CREATE ROW POLICY, CREATE SETTINGS PROFILE, CREATE QUOTA, and GRANT statement with ON CLUSTER 'main'.For tables that keep receiving data during the migration:
COPY loads the same files into ClickHouse with the s3 table function, or with an S3Queue table that picks up new files as they arrive.system.query_log table, or in the Altinity ClickHouse Operator Dashboard if you configured the optional monitoring.The following items require attention during the migration:
insert_quorum = 2 on inserts that must reach both replicas before they return.The following table lists common problems, their causes, and their resolutions.
You have successfully deployed a ClickHouse cluster with two shards and two replicas per shard on Kubernetes as an alternative to Amazon Redshift, with TLS access through a load balancer, block storage volumes, and nightly backups that pass a restore test. To add capacity, add replicas or shards in the cluster manifest, and to move existing workloads, follow Migrate from Amazon Redshift to ClickHouse. For more information, visit the ClickHouse documentation and the Altinity Kubernetes Operator for ClickHouse documentation.
0 Comments
Be the first to comment and share your perspective with the community.