---
title: How to Deploy ClickHouse as a Self-Hosted Amazon Redshift Alternative
url: https://docs.vultr.com/how-to-deploy-clickhouse-as-a-self-hosted-amazon-redshift-alternative
description: Deploy a sharded, replicated ClickHouse cluster on Vultr Kubernetes as an Amazon Redshift alternative, with TLS, block storage, backups, and Redshift migration.
publish_date: 2026-12-04T19:47:25.821706Z
last_updated: 2026-12-04T20:12:49.633130Z
author: Vijay  Srinivas P
header_image: https://assets.vultrdevrel.com/docs-main-doc-assets-1/2696/17e5736e-7819-4f79-b87a-3df27a9478a9.png
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

[Amazon Redshift](https://aws.amazon.com/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](https://clickhouse.com/) 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.

## Understanding ClickHouse Architecture

The following table maps Redshift concepts to their ClickHouse equivalents.

| Amazon Redshift | ClickHouse Equivalent | Description |
|---|---|---|
| Provisioned cluster with a leader node and compute nodes, or a Serverless workgroup | The `main` cluster with two shards of two replicas each, defined in a `ClickHouseInstallation` resource | Runs each query on one replica of every shard in parallel. The server that receives a query merges the results, so no separate leader node exists. |
| Distribution styles `KEY`, `EVEN`, and `ALL` | Sharding key of a `Distributed` table, such as `cityHash64(user_id)` or `rand()` | Places each row on a shard by the hash of a column, like `KEY`, or at random, like `EVEN`. [Schema Migration](#schema-migration) covers `ALL`. |
| Compound and interleaved sort keys | `ORDER BY` key of a `ReplicatedMergeTree` table | Skips blocks of rows that a filter on the key excludes. Interleaved keys have no equivalent. |
| `COPY` and `UNLOAD` with Amazon S3, and Redshift Spectrum | `s3`, `iceberg`, and `deltaLake` table functions | Reads and writes Parquet, CSV, and other formats in S3-compatible storage, and queries Apache Iceberg or Delta Lake tables in place. |
| Workload management (WLM) queues and query monitoring rules | Settings profiles and quotas | Limits the memory, run time, threads, and query count of each user. |
| Database users, groups, roles, and IAM authentication | ClickHouse users, roles, row policies, and `GRANT` statements | Grants privileges per database, table, or column. IAM authentication has no equivalent. |
| Automated and manual snapshots | `clickhouse-backup` sidecars that upload to S3-compatible object storage | Takes a weekly full backup and nightly incremental backups of each shard, and keeps 21 backups per shard. |
| Amazon CloudWatch metrics and query monitoring | Prometheus, Alertmanager, and Grafana with the Altinity dashboards | Collects server, Keeper, and backup metrics, evaluates alert rules, and shows query statistics. This article installs them as an optional step. |

The deployment places ClickHouse on the data nodes and every supporting service on the system nodes:

* **Data node pool:** Four ClickHouse pods, one per node, each with a `clickhouse-backup` sidecar. The loss of one node leaves every shard available.
* **System node pool:** Three ClickHouse Keeper replicas on separate nodes, the Altinity operator, cert-manager, the scheduled backup job, and the optional Prometheus, Alertmanager, and Grafana.
* **Load balancer:** Forwards only the TLS port from allowlisted source addresses.
* **Block storage:** One NVMe volume per ClickHouse server and per Keeper replica.
* **Object storage:** Holds the nightly backups.

![Clients connect over TLS on port 9440 through a load balancer to a ClickHouse cluster of two shards with two replicas each on Kubernetes, coordinated by three ClickHouse Keeper replicas. Volumes are on block storage, and backup sidecars upload nightly backups to S3-compatible object storage.](https://assets.vultrdevrel.com/docs-main-doc-assets-1/2696/7b2c11a7-0048-4fd3-83f8-98092e8115cf.png)

## Prerequisites

Before you begin:

* Have access to a [Kubernetes cluster](https://docs.vultr.com/products/compute/kubernetes/provisioning) with two node pools: `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](https://docs.vultr.com/products/storage/block-storage) volumes and a cloud controller that provisions [load balancers](https://docs.vultr.com/products/network/load-balancer) for `LoadBalancer` services.
* Apply a [firewall](https://docs.vultr.com/products/network/firewall-groups/management/rules) to the cluster nodes with one inbound rule that accepts SSH on TCP port `22` from your workstation IP address only.
* Have access to an [S3-compatible object storage](https://docs.vultr.com/products/storage/object-storage/provisioning) service with a bucket named `clickhouse-backups`, and note its endpoint hostname, access key, and secret key.
* Install `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.
* Install `curl`, `openssl`, and Helm 3.8 or later on the workstation.
* Create the `~/clickhouse-k8s` directory on the workstation and run every command in this article from it.
* Note the public IPv4 address of the workstation, for example from the output of `curl -4 -s https://ifconfig.me`.
* (Optional) Have access to the Amazon Redshift cluster or Redshift Serverless workgroup that you plan to migrate, with an [IAM role that authorizes `UNLOAD`](https://docs.aws.amazon.com/redshift/latest/mgmt/copy-unload-iam-role.html) to write to an Amazon S3 bucket, and an access key with read access to that bucket.

## Label the Nodes

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.

1. Label the data nodes.

    ```console
    $ kubectl get nodes -o name | grep clickhouse-data- | xargs -I{} kubectl label {} clickhouse-pool=data --overwrite
    ```

1. Label the system nodes.

    ```console
    $ kubectl get nodes -o name | grep clickhouse-system- | xargs -I{} kubectl label {} clickhouse-pool=system --overwrite
    ```

1. Add the soft taint to the data nodes.

    ```console
    $ kubectl taint nodes -l clickhouse-pool=data dedicated=clickhouse-data:PreferNoSchedule --overwrite
    ```

1. Verify the labels.

    ```console
    $ kubectl get nodes -L clickhouse-pool
    ```

    The `CLICKHOUSE-POOL` column shows `data` for the four `clickhouse-data` nodes and `system` for the three `clickhouse-system` nodes.

1. Verify the taints.

    ```console
    $ kubectl get nodes -o custom-columns='NAME:.metadata.name,TAINTS:.spec.taints[*].effect'
    ```

    The four data nodes show `PreferNoSchedule`, and the three system nodes show `<none>`.

> [!IMPORTANT]
> 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`.

## Create Namespaces, Priority Classes, and a Storage Class

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.

1. Create a manifest file named `00-base.yaml`.

    ```console
    $ nano 00-base.yaml
    ```

1. Add the following content to the file.

    ```yaml
    apiVersion: v1
    kind: Namespace
    metadata:
      name: clickhouse
      labels:
        app.kubernetes.io/part-of: clickhouse-platform
    ---
    apiVersion: v1
    kind: Namespace
    metadata:
      name: cert-manager
      labels:
        app.kubernetes.io/part-of: clickhouse-platform
    ---
    apiVersion: v1
    kind: Namespace
    metadata:
      name: monitoring
      labels:
        app.kubernetes.io/part-of: clickhouse-platform
    ---
    apiVersion: scheduling.k8s.io/v1
    kind: PriorityClass
    metadata:
      name: clickhouse-critical
    value: 1000000
    globalDefault: false
    description: "ClickHouse servers and Keeper. Data path, never preempted by anything else here."
    ---
    apiVersion: scheduling.k8s.io/v1
    kind: PriorityClass
    metadata:
      name: clickhouse-platform
    value: 100000
    globalDefault: false
    description: "Operator, cert-manager and backup jobs. Needed for changes and recovery, not for queries."
    ---
    apiVersion: scheduling.k8s.io/v1
    kind: PriorityClass
    metadata:
      name: monitoring
    value: 10000
    globalDefault: false
    description: "Prometheus, Alertmanager, Grafana and exporters. First to go under pressure."
    ---
    apiVersion: storage.k8s.io/v1
    kind: StorageClass
    metadata:
      name: clickhouse-nvme-retain
    provisioner: block.csi.vultr.com
    parameters:
      storage_type: "block"
      disk_type: "nvme"
    reclaimPolicy: Retain
    allowVolumeExpansion: true
    volumeBindingMode: WaitForFirstConsumer
    ```

    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](https://docs.vultr.com/products/storage/block-storage) CSI driver.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 00-base.yaml
    ```

1. Verify the storage class.

    ```console
    $ kubectl get sc clickhouse-nvme-retain
    ```

    The output shows the `Retain` reclaim policy and the `WaitForFirstConsumer` binding mode.

## Create the Secrets

The following steps generate random passwords and store them in Kubernetes secrets. ClickHouse receives only the SHA-256 hashes of its passwords.

1. Generate the ClickHouse `admin` and `backup` passwords and store them, together with their SHA-256 hashes, in the `clickhouse-credentials` secret.

    ```console
    $ ADMIN_PW=$(openssl rand -hex 16) && BACKUP_PW=$(openssl rand -hex 16) && \
      kubectl -n clickhouse create secret generic clickhouse-credentials \
        --from-literal=admin-password="$ADMIN_PW" \
        --from-literal=admin-password-sha256="$(printf '%s' "$ADMIN_PW" | sha256sum | cut -d' ' -f1)" \
        --from-literal=backup-password="$BACKUP_PW" \
        --from-literal=backup-password-sha256="$(printf '%s' "$BACKUP_PW" | sha256sum | cut -d' ' -f1)"
    ```

1. Create a random password for the operator's own ClickHouse account. The Helm chart default is public.

    ```console
    $ kubectl -n clickhouse create secret generic clickhouse-operator-password --from-literal=password="$(openssl rand -hex 16)"
    ```

1. 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.

    ```console
    $ kubectl -n clickhouse create secret generic clickhouse-backup-s3 --from-literal=S3_ACCESS_KEY=OBJECT_STORAGE_ACCESS_KEY --from-literal=S3_SECRET_KEY=OBJECT_STORAGE_SECRET_KEY
    ```

1. List the secrets in the `clickhouse` namespace.

    ```console
    $ kubectl -n clickhouse get secrets
    ```

    The output lists the `clickhouse-backup-s3`, `clickhouse-credentials`, and `clickhouse-operator-password` secrets.

## Install cert-manager

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.

1. Create a values file named `cert-manager.values.yaml`.

    ```console
    $ nano cert-manager.values.yaml
    ```

1. Add the following content to the file.

    ```yaml
    crds:
      enabled: true

    global:
      priorityClassName: clickhouse-platform

    replicaCount: 2
    podDisruptionBudget:
      enabled: true
      minAvailable: 1
    nodeSelector:
      clickhouse-pool: system
    resources:
      requests: { cpu: 20m, memory: 64Mi }
      limits: { memory: 256Mi }

    webhook:
      replicaCount: 2
      podDisruptionBudget:
        enabled: true
        minAvailable: 1
      nodeSelector:
        clickhouse-pool: system
      resources:
        requests: { cpu: 10m, memory: 32Mi }
        limits: { memory: 128Mi }

    cainjector:
      replicaCount: 1
      nodeSelector:
        clickhouse-pool: system
      resources:
        requests: { cpu: 10m, memory: 64Mi }
        limits: { memory: 256Mi }

    startupapicheck:
      nodeSelector:
        clickhouse-pool: system
    ```

    Save and close the file.

1. Install cert-manager version `v1.21.0`.

    ```console
    $ helm upgrade --install cert-manager oci://quay.io/jetstack/charts/cert-manager --version v1.21.0 -n cert-manager -f cert-manager.values.yaml --wait --timeout 10m
    ```

1. List the cert-manager pods.

    ```console
    $ kubectl -n cert-manager get pods
    ```

    All five pods are `Running`: two controller replicas, two webhook replicas, and one CA injector.

## Create the Certificate Authority and Server Certificate

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.

1. Create a manifest file named `10-tls-issuers.yaml`.

    ```console
    $ nano 10-tls-issuers.yaml
    ```

1. Add the following content to the file.

    ```yaml
    apiVersion: cert-manager.io/v1
    kind: Issuer
    metadata:
      name: selfsigned-bootstrap
      namespace: clickhouse
    spec:
      selfSigned: {}
    ---
    apiVersion: cert-manager.io/v1
    kind: Certificate
    metadata:
      name: clickhouse-ca
      namespace: clickhouse
    spec:
      isCA: true
      commonName: clickhouse-k8s-ca
      secretName: clickhouse-ca
      duration: 87600h # 10 years
      privateKey:
        algorithm: RSA
        size: 2048
        rotationPolicy: Never
      issuerRef:
        name: selfsigned-bootstrap
        kind: Issuer
    ---
    apiVersion: cert-manager.io/v1
    kind: Issuer
    metadata:
      name: clickhouse-ca
      namespace: clickhouse
    spec:
      ca:
        secretName: clickhouse-ca
    ```

    Save and close the file.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 10-tls-issuers.yaml
    ```

1. Wait until the CA certificate is ready.

    ```console
    $ kubectl -n clickhouse wait certificate/clickhouse-ca --for=condition=Ready --timeout=180s
    ```

1. Create a manifest file named `11-server-cert.yaml`.

    ```console
    $ nano 11-server-cert.yaml
    ```

1. Add the following content to the file. The load balancer IP address is added to the certificate after the load balancer exists.

    ```yaml
    apiVersion: cert-manager.io/v1
    kind: Certificate
    metadata:
      name: clickhouse-server
      namespace: clickhouse
    spec:
      secretName: clickhouse-tls
      duration: 8760h    # 1 year
      renewBefore: 720h  # renewed 30 days before expiry
      privateKey:
        algorithm: RSA
        size: 2048
        encoding: PKCS8
        rotationPolicy: Always
      usages: ["server auth", "digital signature", "key encipherment"]
      commonName: clickhouse-analytics.clickhouse.svc.cluster.local
      issuerRef:
        name: clickhouse-ca
        kind: Issuer
      dnsNames:
        - localhost
        - clickhouse-analytics
        - clickhouse-analytics.clickhouse
        - clickhouse-analytics.clickhouse.svc
        - clickhouse-analytics.clickhouse.svc.cluster.local
        - clickhouse-internal
        - clickhouse-internal.clickhouse
        - clickhouse-internal.clickhouse.svc
        - clickhouse-internal.clickhouse.svc.cluster.local
        - "*.clickhouse.svc.cluster.local"
        # - clickhouse.example.com      # <- your DNS name, if any
      ipAddresses:
        - 127.0.0.1
        # Add the load balancer IP address here after the load balancer exists.
    ```

    Save and close the file.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 11-server-cert.yaml
    ```

1. Wait until the server certificate is ready.

    ```console
    $ kubectl -n clickhouse wait certificate/clickhouse-server --for=condition=Ready --timeout=180s
    ```

## Install the Altinity Operator

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).

1. Create a values file named `clickhouse-operator.values.yaml`.

    ```console
    $ nano clickhouse-operator.values.yaml
    ```

1. Add the following content to the file.

    ```yaml
    nodeSelector:
      clickhouse-pool: system

    crdHook:
      enabled: false

    operator:
      priorityClassName: clickhouse-platform
      resources:
        requests: { cpu: 100m, memory: 128Mi }
        limits: { memory: 512Mi }

    metrics:
      enabled: true
      resources:
        requests: { cpu: 50m, memory: 128Mi }
        limits: { memory: 512Mi }

    dashboards:
      enabled: true
      additionalLabels:
        grafana_dashboard: "1"
      annotations:
        grafana_folder: ClickHouse

    configs:
      files:
        config.yaml:
          reconcile:
            host:
              wait:
                replicas:
                  all: true
    ```

    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.

1. Add the Altinity Helm repository.

    ```console
    $ helm repo add altinity https://helm.altinity.com
    ```

1. Update the Helm repositories.

    ```console
    $ helm repo update
    ```

1. Download the operator chart to apply its CRDs from the pinned version.

    ```console
    $ helm pull altinity/altinity-clickhouse-operator --version 0.27.3 --untar -d chop
    ```

1. Apply the CRDs.

    ```console
    $ kubectl apply --server-side --force-conflicts -f chop/altinity-clickhouse-operator/crds/
    ```

1. Install the operator with the password from the `clickhouse-operator-password` secret.

    ```console
    $ helm upgrade --install clickhouse-operator altinity/altinity-clickhouse-operator --version 0.27.3 -n clickhouse --skip-crds -f clickhouse-operator.values.yaml --set-string secret.password="$(kubectl -n clickhouse get secret clickhouse-operator-password -o jsonpath='{.data.password}' | base64 -d)" --wait --timeout 10m
    ```

1. List the pods in the `clickhouse` namespace.

    ```console
    $ kubectl -n clickhouse get pods
    ```

    The output lists one `clickhouse-operator-altinity-clickhouse-operator-...` pod with `2/2` containers in the `Running` state.

## Deploy ClickHouse Keeper

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.

1. Create a manifest file named `20-keeper.yaml`.

    ```console
    $ nano 20-keeper.yaml
    ```

1. Add the following content to the file.

    ```yaml
    apiVersion: clickhouse-keeper.altinity.com/v1
    kind: ClickHouseKeeperInstallation
    metadata:
      name: keeper
      namespace: clickhouse
    spec:
      defaults:
        templates:
          podTemplate: keeper
          dataVolumeClaimTemplate: keeper-data
      configuration:
        clusters:
          - name: keeper
            pdbMaxUnavailable: 1
            layout:
              replicasCount: 3
        settings:
          logger/level: information
          logger/console: "true"
          prometheus/endpoint: /metrics
          prometheus/port: "7000"
          prometheus/metrics: "true"
          prometheus/events: "true"
          prometheus/asynchronous_metrics: "true"
      templates:
        podTemplates:
          - name: keeper
            metadata:
              labels:
                app.kubernetes.io/name: clickhouse-keeper
                app.kubernetes.io/part-of: clickhouse-platform
            spec:
              priorityClassName: clickhouse-critical
              affinity:
                nodeAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                    nodeSelectorTerms:
                      - matchExpressions:
                          - key: clickhouse-pool
                            operator: In
                            values: ["system"]
                podAntiAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                    - labelSelector:
                        matchLabels:
                          app.kubernetes.io/name: clickhouse-keeper
                      topologyKey: kubernetes.io/hostname
              containers:
                - name: clickhouse-keeper
                  image: clickhouse/clickhouse-keeper:26.8.15.10
                  ports:
                    - name: metrics
                      containerPort: 7000
                  resources:
                    requests: { cpu: 500m, memory: 2Gi }
                    limits: { cpu: "2", memory: 2Gi }
        volumeClaimTemplates:
          - name: keeper-data
            reclaimPolicy: Retain
            spec:
              storageClassName: clickhouse-nvme-retain
              accessModes: ["ReadWriteOnce"]
              resources:
                requests:
                  storage: 10Gi
    ```

    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.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 20-keeper.yaml
    ```

1. Wait until the operator reports the Keeper installation as complete. This step takes 2 to 5 minutes.

    ```console
    $ kubectl -n clickhouse wait chk/keeper --for=jsonpath='{.status.status}'=Completed --timeout=15m
    ```

1. List the Keeper pods and their nodes.

    ```console
    $ kubectl -n clickhouse get pods -l app.kubernetes.io/name=clickhouse-keeper -o custom-columns='POD:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName'
    ```

    The three `chk-keeper-keeper-0-N-0` pods run on different `clickhouse-system` nodes.

1. Wait until all three Keeper pods are ready.

    ```console
    $ kubectl -n clickhouse wait pod -l app.kubernetes.io/name=clickhouse-keeper --for=condition=Ready --timeout=5m
    ```

    The output reports `condition met` for each of the three pods.

## Configure Scheduled Backups

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`.

1. Create a manifest file named `40-backup.yaml`.

    ```console
    $ nano 40-backup.yaml
    ```

1. Add the following content to the file. Replace `S3_HOSTNAME` with the endpoint hostname of your object storage service.

    ```yaml
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: clickhouse-backup-config
      namespace: clickhouse
    data:
      LOG_LEVEL: "info"
      ALLOW_EMPTY_BACKUPS: "true"
      API_LISTEN: "0.0.0.0:7171"
      API_CREATE_INTEGRATION_TABLES: "true"
      BACKUPS_TO_KEEP_REMOTE: "21"
      REMOTE_STORAGE: "s3"
      S3_ENDPOINT: "https://S3_HOSTNAME"
      S3_BUCKET: "clickhouse-backups"
      S3_REGION: "us-east-1"
      S3_PATH: "backup/shard-{shard}"
      S3_FORCE_PATH_STYLE: "true"
      S3_ACL: "private"
      UPLOAD_CONCURRENCY: "4"
      DOWNLOAD_CONCURRENCY: "4"
    ---
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: clickhouse-backup-script
      namespace: clickhouse
    data:
      backup.sh: |
        #!/usr/bin/env bash
        set -uo pipefail

        CLUSTER="${CH_CLUSTER:-main}"
        SEED="${CH_SEED_HOST:-clickhouse-internal}"
        FULL_DAYS="${FULL_EVERY_DAYS:-7}"
        WAIT_MAX="${MAX_WAIT_SECONDS:-14400}"
        STAMP="$(date -u +%Y%m%dT%H%M%SZ)"

        log() { echo "$(date -u +%FT%TZ) $*"; }
        ch() { # <host> <query>
          clickhouse-client --host "$1" --port 9000 \
            --user "$BACKUP_USER" --password "$BACKUP_PASSWORD" \
            --connect_timeout 10 --receive_timeout 300 --async_insert=0 --query "$2" < /dev/null
        }

        if ! SHARDS="$(ch "$SEED" "
            SELECT shard_num, arrayStringConcat(arraySort(groupArray(host_name)), ' ')
            FROM system.clusters WHERE cluster = '${CLUSTER}'
            GROUP BY shard_num ORDER BY shard_num
            FORMAT TabSeparatedRaw")" || [[ -z "$SHARDS" ]]; then
          log "ERROR: cannot read cluster '${CLUSTER}' layout through ${SEED}"
          exit 1
        fi

        declare -A HOST CMD NAME
        FAILED=0

        while IFS=$'\t' read -r shard_num hosts; do
          picked=""
          for h in $hosts; do
            if ch "$h" "SELECT count() FROM system.backup_list FORMAT Null" >/dev/null 2>&1; then
              picked="$h"; break
            fi
          done
          if [[ -z "$picked" ]]; then
            log "ERROR: cluster shard ${shard_num}: no replica with a working backup sidecar (${hosts})"
            FAILED=1; continue
          fi

          tag="shard$(ch "$picked" "SELECT getMacro('shard') FORMAT TabSeparatedRaw")"
          last="$(ch "$picked" "
            SELECT name FROM system.backup_list
            WHERE location = 'remote' AND name LIKE '${tag}-%' AND desc NOT LIKE 'broken%'
            ORDER BY created DESC LIMIT 1 FORMAT TabSeparatedRaw")"
          recent_full="$(ch "$picked" "
            SELECT count() FROM system.backup_list
            WHERE location = 'remote' AND name LIKE '${tag}-full-%' AND desc NOT LIKE 'broken%'
              AND created > now() - INTERVAL ${FULL_DAYS} DAY FORMAT TabSeparatedRaw")"

          if [[ -z "$last" || "${recent_full:-0}" == "0" ]]; then
            name="${tag}-full-${STAMP}"; cmd="create_remote ${name}"
          else
            name="${tag}-incr-${STAMP}"; cmd="create_remote --diff-from-remote=${last} ${name}"
          fi

          log "${tag} on ${picked}: ${cmd}"
          if ! ch "$picked" "INSERT INTO system.backup_actions(command) VALUES('${cmd}')"; then
            log "ERROR: ${tag}: could not start backup on ${picked}"
            FAILED=1; continue
          fi
          HOST[$shard_num]="$picked"; CMD[$shard_num]="$cmd"; NAME[$shard_num]="$name"
        done <<< "$SHARDS"

        for s in "${!HOST[@]}"; do
          h="${HOST[$s]}"; c="${CMD[$s]}"; waited=0; status="in progress"
          while [[ "$status" == "in progress" && $waited -lt $WAIT_MAX ]]; do
            sleep 15; waited=$((waited + 15))
            status="$(ch "$h" "SELECT status FROM system.backup_actions
                                WHERE command = '${c}' ORDER BY start DESC LIMIT 1
                                FORMAT TabSeparatedRaw" 2>/dev/null || echo "in progress")"
          done
          if [[ "$status" == "success" ]]; then
            log "${NAME[$s]} uploaded"
            ch "$h" "INSERT INTO system.backup_actions(command) VALUES('delete local ${NAME[$s]}')" || true
          else
            log "ERROR: ${NAME[$s]} on ${h} ended with status '${status}'"
            ch "$h" "SELECT start, finish, status, error FROM system.backup_actions
                     WHERE command = '${c}' ORDER BY start DESC LIMIT 1 FORMAT Vertical" || true
            FAILED=1
          fi
        done

        if [[ $FAILED -ne 0 ]]; then log "BACKUP FAILED"; exit 1; fi
        log "BACKUP OK (${STAMP})"
    ---
    apiVersion: batch/v1
    kind: CronJob
    metadata:
      name: clickhouse-backup
      namespace: clickhouse
      labels:
        app.kubernetes.io/name: clickhouse-backup
        app.kubernetes.io/part-of: clickhouse-platform
    spec:
      schedule: "30 1 * * *"
      timeZone: "Etc/UTC"
      concurrencyPolicy: Forbid
      startingDeadlineSeconds: 3600
      successfulJobsHistoryLimit: 3
      failedJobsHistoryLimit: 3
      jobTemplate:
        spec:
          backoffLimit: 1
          activeDeadlineSeconds: 18000
          template:
            metadata:
              labels:
                app.kubernetes.io/name: clickhouse-backup-job
            spec:
              restartPolicy: Never
              priorityClassName: clickhouse-platform
              nodeSelector:
                clickhouse-pool: system
              securityContext:
                runAsNonRoot: true
                runAsUser: 101
                runAsGroup: 101
              containers:
                - name: backup
                  image: clickhouse/clickhouse-server:26.8.15.10
                  command:
                    - /bin/bash
                    - -c
                    - |
                      grep -q 'BACKUP OK' /scripts/backup.sh || { echo "ERROR: /scripts/backup.sh is empty or incomplete. Re-apply the clickhouse-backup-script ConfigMap."; exit 1; }
                      exec /bin/bash /scripts/backup.sh
                  env:
                    - name: HOME
                      value: /tmp
                    - name: CH_CLUSTER
                      value: main
                    - name: FULL_EVERY_DAYS
                      value: "7"
                    - name: BACKUP_USER
                      value: backup
                    - name: BACKUP_PASSWORD
                      valueFrom:
                        secretKeyRef:
                          name: clickhouse-credentials
                          key: backup-password
                  resources:
                    requests: { cpu: 50m, memory: 128Mi }
                    limits: { memory: 512Mi }
                  volumeMounts:
                    - name: script
                      mountPath: /scripts
                      readOnly: true
              volumes:
                - name: script
                  configMap:
                    name: clickhouse-backup-script
                    defaultMode: 0555
    ```

    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.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 40-backup.yaml
    ```

1. Create a manifest file named `41-cert-reload.yaml`.

    ```console
    $ nano 41-cert-reload.yaml
    ```

1. Add the following content to the file. The job makes every ClickHouse server reload the renewed certificate without a restart.

    ```yaml
    apiVersion: batch/v1
    kind: CronJob
    metadata:
      name: clickhouse-cert-reload
      namespace: clickhouse
      labels:
        app.kubernetes.io/name: clickhouse-cert-reload
        app.kubernetes.io/part-of: clickhouse-platform
    spec:
      schedule: "15 4 * * *"
      timeZone: "Etc/UTC"
      concurrencyPolicy: Forbid
      successfulJobsHistoryLimit: 1
      failedJobsHistoryLimit: 3
      jobTemplate:
        spec:
          backoffLimit: 2
          activeDeadlineSeconds: 600
          template:
            spec:
              restartPolicy: Never
              priorityClassName: clickhouse-platform
              nodeSelector:
                clickhouse-pool: system
              securityContext:
                runAsNonRoot: true
                runAsUser: 101
                runAsGroup: 101
              containers:
                - name: reload
                  image: clickhouse/clickhouse-server:26.8.15.10
                  command:
                    - /bin/bash
                    - -ec
                    - |
                      clickhouse-client --host clickhouse-internal --port 9000 \
                        --user backup --password "$BACKUP_PASSWORD" \
                        --query "SYSTEM RELOAD CONFIG ON CLUSTER 'main'"
                  env:
                    - name: HOME
                      value: /tmp
                    - name: BACKUP_PASSWORD
                      valueFrom:
                        secretKeyRef:
                          name: clickhouse-credentials
                          key: backup-password
                  resources:
                    requests: { cpu: 10m, memory: 64Mi }
                    limits: { memory: 256Mi }
    ```

    Save and close the file.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 41-cert-reload.yaml
    ```

1. List the CronJobs.

    ```console
    $ kubectl -n clickhouse get cronjobs
    ```

    The output lists the `clickhouse-backup` CronJob with the `30 1 * * *` schedule and the `clickhouse-cert-reload` CronJob with the `15 4 * * *` schedule.

## Deploy the ClickHouse Cluster

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.

1. Create a manifest file named `30-clickhouse.yaml`.

    ```console
    $ nano 30-clickhouse.yaml
    ```

1. Add the following content to the file. Replace `ALLOWED_IP` with the public IP address of your workstation that you noted in the [prerequisites](#prerequisites).

    ```yaml
    apiVersion: clickhouse.altinity.com/v1
    kind: ClickHouseInstallation
    metadata:
      name: analytics
      namespace: clickhouse
    spec:
      defaults:
        templates:
          podTemplate: clickhouse
          dataVolumeClaimTemplate: data
          serviceTemplate: public-lb
        storageManagement:
          provisioner: Operator
          reclaimPolicy: Retain

      configuration:
        zookeeper:
          keeper:
            name: keeper

        users:
          admin/password_sha256_hex:
            valueFrom:
              secretKeyRef:
                name: clickhouse-credentials
                key: admin-password-sha256
          admin/networks/ip:
            - "0.0.0.0/0"
            - "::/0"
          admin/profile: default
          admin/quota: default
          admin/access_management: 1
          admin/named_collection_control: 1
          admin/show_named_collections: 1
          backup/password_sha256_hex:
            valueFrom:
              secretKeyRef:
                name: clickhouse-credentials
                key: backup-password-sha256
          backup/networks/ip:
            - "0.0.0.0/0"
            - "::/0"
          backup/profile: default
          backup/quota: default

        settings:
          tcp_port_secure: 9440
          prometheus/endpoint: /metrics
          prometheus/port: 9363
          prometheus/metrics: true
          prometheus/events: true
          prometheus/asynchronous_metrics: true

        files:
          tls.crt:
            valueFrom:
              secretKeyRef:
                name: clickhouse-tls
                key: tls.crt
          tls.key:
            valueFrom:
              secretKeyRef:
                name: clickhouse-tls
                key: tls.key
          ca.crt:
            valueFrom:
              secretKeyRef:
                name: clickhouse-tls
                key: ca.crt
          openssl.xml: |
            <clickhouse>
              <openSSL>
                <server>
                  <certificateFile>/etc/clickhouse-server/secrets.d/tls.crt/clickhouse-tls/tls.crt</certificateFile>
                  <privateKeyFile>/etc/clickhouse-server/secrets.d/tls.key/clickhouse-tls/tls.key</privateKeyFile>
                  <caConfig>/etc/clickhouse-server/secrets.d/ca.crt/clickhouse-tls/ca.crt</caConfig>
                  <loadDefaultCAFile>false</loadDefaultCAFile>
                  <verificationMode>none</verificationMode>
                  <cacheSessions>true</cacheSessions>
                  <disableProtocols>sslv2,sslv3,tlsv1,tlsv1_1</disableProtocols>
                  <preferServerCiphers>true</preferServerCiphers>
                </server>
                <client>
                  <caConfig>/etc/clickhouse-server/secrets.d/ca.crt/clickhouse-tls/ca.crt</caConfig>
                  <loadDefaultCAFile>false</loadDefaultCAFile>
                  <verificationMode>relaxed</verificationMode>
                  <cacheSessions>true</cacheSessions>
                  <disableProtocols>sslv2,sslv3,tlsv1,tlsv1_1</disableProtocols>
                  <preferServerCiphers>true</preferServerCiphers>
                  <invalidCertificateHandler>
                    <name>AcceptCertificateHandler</name>
                  </invalidCertificateHandler>
                </client>
              </openSSL>
            </clickhouse>

        clusters:
          - name: main
            secret:
              auto: "true"
            pdbMaxUnavailable: 1
            layout:
              shardsCount: 2
              replicasCount: 2

      templates:
        podTemplates:
          - name: clickhouse
            metadata:
              labels:
                app.kubernetes.io/name: clickhouse
                app.kubernetes.io/component: server
                app.kubernetes.io/part-of: clickhouse-platform
            spec:
              priorityClassName: clickhouse-critical
              terminationGracePeriodSeconds: 120
              securityContext:
                runAsUser: 101
                runAsGroup: 101
                fsGroup: 101
                fsGroupChangePolicy: OnRootMismatch
              affinity:
                nodeAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                    nodeSelectorTerms:
                      - matchExpressions:
                          - key: clickhouse-pool
                            operator: In
                            values: ["data"]
                podAntiAffinity:
                  requiredDuringSchedulingIgnoredDuringExecution:
                    - labelSelector:
                        matchLabels:
                          app.kubernetes.io/name: clickhouse
                          app.kubernetes.io/component: server
                      topologyKey: kubernetes.io/hostname
              tolerations:
                - key: dedicated
                  operator: Equal
                  value: clickhouse-data
                  effect: PreferNoSchedule
              containers:
                - name: clickhouse
                  image: clickhouse/clickhouse-server:26.8.15.10
                  ports:
                    - name: tcp-secure
                      containerPort: 9440
                    - name: metrics
                      containerPort: 9363
                  resources:
                    requests: { cpu: "6", memory: "24Gi" }
                    limits: { cpu: "6", memory: "24Gi" }

                - name: clickhouse-backup
                  image: altinity/clickhouse-backup:2.8.0
                  imagePullPolicy: IfNotPresent
                  args: ["server"]
                  envFrom:
                    - configMapRef:
                        name: clickhouse-backup-config
                    - secretRef:
                        name: clickhouse-backup-s3
                  env:
                    - name: CLICKHOUSE_USERNAME
                      value: backup
                    - name: CLICKHOUSE_PASSWORD
                      valueFrom:
                        secretKeyRef:
                          name: clickhouse-credentials
                          key: backup-password
                  ports:
                    - name: backup-api
                      containerPort: 7171
                  resources:
                    requests: { cpu: 500m, memory: 1Gi }
                    limits: { cpu: 500m, memory: 1Gi }

        volumeClaimTemplates:
          - name: data
            reclaimPolicy: Retain
            spec:
              storageClassName: clickhouse-nvme-retain
              accessModes: ["ReadWriteOnce"]
              resources:
                requests:
                  storage: 100Gi

        serviceTemplates:
          - name: public-lb
            generateName: clickhouse-{chi}
            metadata:
              annotations:
                service.beta.kubernetes.io/vultr-loadbalancer-protocol: "tcp"
                service.beta.kubernetes.io/vultr-loadbalancer-firewall-rules: "ALLOWED_IP/32,9440"
                service.beta.kubernetes.io/vultr-loadbalancer-node-count: "3"
                service.beta.kubernetes.io/vultr-loadbalancer-vpc: "false"
                service.beta.kubernetes.io/vultr-loadbalancer-label: "clickhouse-analytics"
                service.beta.kubernetes.io/vultr-loadbalancer-healthcheck-protocol: "tcp"
                service.beta.kubernetes.io/vultr-loadbalancer-healthcheck-check-interval: "10"
                service.beta.kubernetes.io/vultr-loadbalancer-healthcheck-unhealthy-threshold: "3"
                service.beta.kubernetes.io/vultr-loadbalancer-healthcheck-healthy-threshold: "2"
            spec:
              type: LoadBalancer
              ports:
                - name: tcp-secure
                  port: 9440
                  targetPort: 9440
    ```

    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](https://docs.vultr.com/products/network/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`.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 30-clickhouse.yaml
    ```

1. Create a manifest file named `31-clickhouse-internal.yaml` for the in-cluster service.

    ```console
    $ nano 31-clickhouse-internal.yaml
    ```

1. Add the following content to the file.

    ```yaml
    apiVersion: v1
    kind: Service
    metadata:
      name: clickhouse-internal
      namespace: clickhouse
      labels:
        app.kubernetes.io/name: clickhouse
        app.kubernetes.io/part-of: clickhouse-platform
    spec:
      type: ClusterIP
      selector:
        app.kubernetes.io/name: clickhouse
        app.kubernetes.io/component: server
      ports:
        - name: http
          port: 8123
          targetPort: 8123
        - name: tcp
          port: 9000
          targetPort: 9000
        - name: tcp-secure
          port: 9440
          targetPort: 9440
    ```

    Save and close the file.

1. Apply the manifest.

    ```console
    $ kubectl apply -f 31-clickhouse-internal.yaml
    ```

1. Wait until the operator reports the cluster as complete. This step takes a few minutes.

    ```console
    $ kubectl -n clickhouse wait chi/analytics --for=jsonpath='{.status.status}'=Completed --timeout=40m
    ```

1. List the ClickHouse pods and their nodes.

    ```console
    $ kubectl -n clickhouse get pods -l app.kubernetes.io/name=clickhouse -o custom-columns='POD:.metadata.name,READY:.status.containerStatuses[*].ready,NODE:.spec.nodeName'
    ```

    Each `chi-analytics-main-*` pod runs on a different `clickhouse-data` node, and the `READY` column shows `true,true`.

## Add the Load Balancer IP Address to the Certificate

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.

1. Display the public IP address of the load balancer.

    ```console
    $ kubectl -n clickhouse get svc clickhouse-analytics -o jsonpath='{.status.loadBalancer.ingress[0].ip}{"\n"}'
    ```

    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.

1. Open the server certificate manifest.

    ```console
    $ nano 11-server-cert.yaml
    ```

1. Add the load balancer IP address under `ipAddresses`, below `127.0.0.1`. Replace `LB_IP` with the load balancer IP address.

    ```yaml
      ipAddresses:
        - 127.0.0.1
        - LB_IP
    ```

    Save and close the file.

1. Apply the manifest to make cert-manager issue a new certificate that includes the address.

    ```console
    $ kubectl apply -f 11-server-cert.yaml
    ```

1. Verify that the renewed certificate contains the address.

    ```console
    $ kubectl -n clickhouse get secret clickhouse-tls -o jsonpath='{.data.tls\.crt}' | base64 -d | openssl x509 -noout -ext subjectAltName
    ```

    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.

1. Wait 90 seconds for Kubernetes to deliver the renewed certificate files to the ClickHouse pods.

    ```console
    $ sleep 90
    ```

1. Start a certificate reload job from the reload CronJob.

    ```console
    $ kubectl -n clickhouse create job cert-reload-now --from=cronjob/clickhouse-cert-reload
    ```

1. Wait until the job completes.

    ```console
    $ kubectl -n clickhouse wait job/cert-reload-now --for=condition=Complete --timeout=180s
    ```

## Connect to ClickHouse over TLS

Clients outside the cluster connect through the load balancer, in place of the Redshift endpoint.

1. Export the CA certificate to a file.

    ```console
    $ kubectl -n clickhouse get secret clickhouse-tls -o jsonpath='{.data.ca\.crt}' | base64 -d > clickhouse-ca.crt
    ```

1. Verify the TLS handshake and the certificate. Replace `LB_IP` with the load balancer IP address.

    ```console
    $ openssl s_client -connect LB_IP:9440 -CAfile clickhouse-ca.crt -verify_ip LB_IP </dev/null 2>/dev/null | grep 'Verify return code'
    ```

    The output is `Verify return code: 0 (ok)`.

1. Download the single-binary ClickHouse client to the working directory.

    ```console
    $ curl https://clickhouse.com/ | sh
    ```

    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.

1. Create the client configuration file `clickhouse-client.xml`. Replace `LB_IP` with the load balancer IP address.

    ```console
    $ cat > clickhouse-client.xml <<EOF
    <config>
      <host>LB_IP</host>
      <port>9440</port>
      <secure>true</secure>
      <user>admin</user>
      <openSSL>
        <client>
          <caConfig>$(realpath clickhouse-ca.crt)</caConfig>
          <loadDefaultCAFile>false</loadDefaultCAFile>
          <verificationMode>strict</verificationMode>
        </client>
      </openSSL>
    </config>
    EOF
    ```

1. Store the `admin` password in a shell variable.

    ```console
    $ export ADMIN_PW=$(kubectl -n clickhouse get secret clickhouse-credentials -o jsonpath='{.data.admin-password}' | base64 -d)
    ```

1. Run a query through the load balancer.

    ```console
    $ ./clickhouse client --config-file clickhouse-client.xml --password "$ADMIN_PW" --query "SELECT version(), hostName()"
    ```

    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`.

## Verify the Deployment

The following checks confirm the cluster layout, Keeper connectivity, replication, the disruption budgets, the backup sidecars, and the public access rules.

1. Define a shell function named `ch` that runs a query in the first ClickHouse pod. Run the remaining sections in the same terminal.

    ```console
    $ ch() { kubectl -n clickhouse exec chi-analytics-main-0-0-0 -c clickhouse -- clickhouse-client -q "$1"; }
    ```

1. Display the shards and replicas of the `main` cluster.

    ```console
    $ ch "SELECT shard_num, replica_num, host_name, errors_count FROM system.clusters WHERE cluster = 'main' FORMAT PrettyCompact"
    ```

    The output lists shards `1` and `2` with replicas `1` and `2` each, and `0` in the `errors_count` column for every host.

1. Verify that ClickHouse reaches Keeper.

    ```console
    $ ch "SELECT count() AS keeper_nodes FROM system.zookeeper WHERE path = '/'"
    ```

    The output is a number greater than `0`, such as `2`.

1. Create a `demo` database on every server.

    ```console
    $ ch "CREATE DATABASE IF NOT EXISTS demo ON CLUSTER 'main'"
    ```

    The output lists one line per server with `0` in the third column.

1. Create a replicated local table and a `Distributed` table that shards rows by a hash of the `id` column.

    ```console
    $ ch "CREATE TABLE IF NOT EXISTS demo.events_local ON CLUSTER 'main' (id UInt64, event_time DateTime, event_type LowCardinality(String)) ENGINE = ReplicatedMergeTree ORDER BY (event_type, id)"
    $ ch "CREATE TABLE IF NOT EXISTS demo.events ON CLUSTER 'main' AS demo.events_local ENGINE = Distributed('main', 'demo', 'events_local', cityHash64(id))"
    ```

1. Insert 1 million rows through the `Distributed` table.

    ```console
    $ ch "INSERT INTO demo.events SELECT number, now() - number, ['view', 'click', 'purchase'][number % 3 + 1] FROM numbers(1000000) SETTINGS distributed_foreground_insert = 1"
    ```

1. Wait until every replica has copied the rows.

    ```console
    $ ch "SYSTEM SYNC REPLICA ON CLUSTER 'main' demo.events_local"
    ```

1. Count the rows on each server.

    ```console
    $ ch "SELECT getMacro('shard') AS shard, hostName() AS host, count() AS rows FROM clusterAllReplicas('main', demo.events_local) GROUP BY shard, host ORDER BY shard, host FORMAT PrettyCompact"
    ```

    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`.

1. Drop the `demo` database.

    ```console
    $ ch "DROP DATABASE demo ON CLUSTER 'main' SYNC"
    ```

1. List the PodDisruptionBudgets.

    ```console
    $ kubectl -n clickhouse get pdb
    ```

    The output lists the `chi-analytics-main` and `chk-keeper-keeper` budgets, each with `1` in the `ALLOWED DISRUPTIONS` column.

1. Verify that the backup sidecar answers through the `system.backup_list` table.

    ```console
    $ ch "SELECT count() FROM system.backup_list"
    ```

    The output is `0` before the first backup. An error means that the sidecar is not running.

1. Verify that the load balancer rejects the plaintext ports. Replace `LB_IP` with the load balancer IP address.

    ```console
    $ for port in 8123 9000; do timeout 5 bash -c "</dev/tcp/LB_IP/$port" 2>/dev/null && echo "$port open" || echo "$port closed"; done
    ```

    The output reports both ports as `closed`.

1. Verify that ClickHouse rejects a wrong password.

    ```console
    $ ./clickhouse client --config-file clickhouse-client.xml --password wrong-password -q "SELECT 1" 2>&1 | grep -o 'Authentication failed' | head -1
    ```

    The output is `Authentication failed`.

1. Display the node port of the load balancer service.

    ```console
    $ kubectl -n clickhouse get svc clickhouse-analytics -o jsonpath='{.spec.ports[0].nodePort}{"\n"}'
    ```

    The output is a port number between `30000` and `32767`.

1. List the nodes with their public IP addresses in the `EXTERNAL-IP` column.

    ```console
    $ kubectl get nodes -o wide
    ```

1. 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.

    ```console
    $ timeout 5 bash -c "</dev/tcp/NODE_IP/NODE_PORT" 2>/dev/null && echo open || echo closed
    ```

    The output `closed` confirms that clients reach ClickHouse only through the load balancer. If the output is `open`, confirm that the node [firewall](https://docs.vultr.com/products/network/firewall-groups/management/rules) has the SSH rule from the prerequisites, wait 2 minutes, and run the check again.

## Back Up the Cluster and Test a Restore

This section runs a backup on demand, then drops and restores a test database, the equivalent of restoring a table from a Redshift snapshot.

### Run a Backup

The CronJob runs every night, and a job created from it runs the same script immediately.

1. 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.

    ```console
    $ cb() { kubectl -n clickhouse exec "$1" -c clickhouse-backup -- clickhouse-backup "${@:2}" 2>&1 | grep -v ' INF ' || true; }
    ```

1. Start a backup job from the backup CronJob.

    ```console
    $ kubectl -n clickhouse create job backup-first --from=cronjob/clickhouse-backup
    ```

1. Wait until the job completes. The first full backup takes longer as the data grows.

    ```console
    $ kubectl -n clickhouse wait job/backup-first --for=condition=Complete --timeout=30m
    ```

1. Display the job log.

    ```console
    $ kubectl -n clickhouse logs job/backup-first
    ```

    The log shows an `uploaded` line for a full backup of each shard, such as `shard0-full-TIMESTAMP`, and ends with `BACKUP OK`.

1. List the backups of each shard in object storage.

    ```console
    $ cb chi-analytics-main-0-0-0 list remote
    $ cb chi-analytics-main-1-0-0 list remote
    ```

    The output lists one `shard0-full-...` and one `shard1-full-...` backup.

### Test a Restore

The test records a checksum of a test database, backs it up, drops it, restores it, and compares the checksum.

> [!WARNING]
> The test drops the `drill` database on every server. Run it only against the test database.

1. Create the `drill` database.

    ```console
    $ ch "CREATE DATABASE IF NOT EXISTS drill ON CLUSTER 'main'"
    ```

1. Create the replicated local table.

    ```console
    $ ch "CREATE TABLE IF NOT EXISTS drill.t_local ON CLUSTER 'main' (id UInt64, v String) ENGINE = ReplicatedMergeTree ORDER BY id"
    ```

1. Create the `Distributed` table.

    ```console
    $ ch "CREATE TABLE IF NOT EXISTS drill.t ON CLUSTER 'main' AS drill.t_local ENGINE = Distributed('main', 'drill', 't_local', cityHash64(id))"
    ```

1. Insert 1 million rows.

    ```console
    $ ch "INSERT INTO drill.t SELECT number, toString(rand()) FROM numbers(1000000) SETTINGS distributed_foreground_insert = 1"
    ```

1. Store the row count and a checksum of every row in a shell variable.

    ```console
    $ BEFORE=$(ch "SELECT count(), sum(cityHash64(*)) FROM drill.t") && echo "BEFORE: $BEFORE"
    ```

    The output prints `BEFORE:` followed by the row count, `1000000`, and the checksum of the table.

1. Start a backup job.

    ```console
    $ kubectl -n clickhouse create job backup-drill --from=cronjob/clickhouse-backup
    ```

1. Wait until the job completes.

    ```console
    $ kubectl -n clickhouse wait job/backup-drill --for=condition=Complete --timeout=30m
    ```

1. Display the job log.

    ```console
    $ kubectl -n clickhouse logs job/backup-drill
    ```

    The log shows `uploaded` lines for incremental backups, such as `shard0-incr-TIMESTAMP`, and ends with `BACKUP OK`.

1. Store the names of the two new backups in shell variables.

    ```console
    $ S0=$(kubectl -n clickhouse logs job/backup-drill | grep ' uploaded' | grep -o 'shard0-[a-z]*-[0-9TZ]*') && S1=$(kubectl -n clickhouse logs job/backup-drill | grep ' uploaded' | grep -o 'shard1-[a-z]*-[0-9TZ]*') && echo "S0=$S0 S1=$S1"
    ```

    The output prints `S0=` and `S1=` followed by the name of the new backup of each shard, such as `shard0-incr-TIMESTAMP`.

1. Drop the `drill` database on every server. Run this step only when both backup names in the previous output are set.

    ```console
    $ ch "DROP DATABASE drill ON CLUSTER 'main' SYNC"
    ```

1. Restore the schema on both replicas of each shard.

    ```console
    $ for p in 0-0 0-1; do cb chi-analytics-main-$p-0 restore_remote --schema --tables='drill.*' "$S0"; done
    $ for p in 1-0 1-1; do cb chi-analytics-main-$p-0 restore_remote --schema --tables='drill.*' "$S1"; done
    ```

1. Restore the data of each shard on its first replica.

    ```console
    $ cb chi-analytics-main-0-0-0 restore_remote --data --tables='drill.*' "$S0"
    $ cb chi-analytics-main-1-0-0 restore_remote --data --tables='drill.*' "$S1"
    ```

    The output can include an `already exists will try to resume download` warning, which is expected.

1. Wait until the second replicas have copied the restored data.

    ```console
    $ ch "SYSTEM SYNC REPLICA ON CLUSTER 'main' drill.t_local"
    ```

1. Compare the restored rows with the checksum from before the backup.

    ```console
    $ AFTER=$(ch "SELECT count(), sum(cityHash64(*)) FROM drill.t") && echo "AFTER: $AFTER" && [ "$BEFORE" = "$AFTER" ] && echo "PASS: restored data is identical"
    ```

    The output ends with `PASS: restored data is identical`.

1. Delete the local backup copies that the restore downloaded on every replica.

    ```console
    $ for p in 0-0 0-1; do cb chi-analytics-main-$p-0 delete local "$S0"; done
    $ for p in 1-0 1-1; do cb chi-analytics-main-$p-0 delete local "$S1"; done
    ```

1. Drop the `drill` database.

    ```console
    $ ch "DROP DATABASE drill ON CLUSTER 'main' SYNC"
    ```

1. Delete the finished backup and certificate reload jobs. The backups stay in object storage.

    ```console
    $ kubectl -n clickhouse delete job backup-first backup-drill cert-reload-now
    ```

To restore a production database, follow the same order. Omit `--tables` to restore every database, and add `--rm` to replace existing tables.

??? note "Monitor the Cluster with Prometheus and Grafana (Optional)"

    Prometheus, Alertmanager, and Grafana replace the Amazon CloudWatch metrics and alarms of Redshift.

    ### Install the Monitoring Stack

    The kube-prometheus-stack Helm chart installs Prometheus, Alertmanager, Grafana, and the Prometheus Operator on the system nodes.

    1. Create the Grafana administrator credentials.

        ```console
        $ kubectl -n monitoring create secret generic grafana-admin --from-literal=admin-user=admin --from-literal=admin-password="$(openssl rand -hex 16)"
        ```

    1. Create a values file named `kube-prometheus-stack.values.yaml`.

        ```console
        $ nano kube-prometheus-stack.values.yaml
        ```

    1. Add the following content to the file.

        ```yaml
        crds:
          enabled: true

        kubeEtcd:
          enabled: false
        kubeControllerManager:
          enabled: false
        kubeScheduler:
          enabled: false
        kubeProxy:
          enabled: false
        defaultRules:
          rules:
            etcd: false
            kubeControllerManager: false
            kubeSchedulerAlerting: false
            kubeSchedulerRecording: false
            kubeProxy: false

        prometheusOperator:
          nodeSelector:
            clickhouse-pool: system
          resources:
            requests: { cpu: 50m, memory: 128Mi }
            limits: { memory: 384Mi }
          admissionWebhooks:
            patch:
              nodeSelector:
                clickhouse-pool: system

        prometheus:
          prometheusSpec:
            replicas: 1
            nodeSelector:
              clickhouse-pool: system
            priorityClassName: monitoring
            scrapeInterval: 30s
            evaluationInterval: 30s
            retention: 15d
            resources:
              requests: { cpu: 300m, memory: 1Gi }
              limits: { cpu: 1500m, memory: 3Gi }
            ruleSelectorNilUsesHelmValues: false
            serviceMonitorSelectorNilUsesHelmValues: false
            podMonitorSelectorNilUsesHelmValues: false
            probeSelectorNilUsesHelmValues: false
            storageSpec:
              volumeClaimTemplate:
                spec:
                  storageClassName: vultr-block-storage
                  accessModes: ["ReadWriteOnce"]
                  resources:
                    requests:
                      storage: 40Gi

        alertmanager:
          alertmanagerSpec:
            nodeSelector:
              clickhouse-pool: system
            priorityClassName: monitoring
            resources:
              requests: { cpu: 20m, memory: 64Mi }
              limits: { memory: 128Mi }
          # Alerts are only useful if they reach someone. Uncomment and fill in one
          # receiver (Slack shown), then run the helm upgrade command again.
          # config:
          #   route:
          #     receiver: team
          #     group_by: [alertname, namespace, shard]
          #     routes:
          #       - matchers: ['alertname = "Watchdog"']
          #         receiver: "null"
          #       - matchers: ['alertname = "InfoInhibitor"']
          #         receiver: "null"
          #   receivers:
          #     - name: "null"
          #     - name: team
          #       slack_configs:
          #         - api_url: https://hooks.slack.com/services/SLACK_WEBHOOK_PATH
          #           channel: "#clickhouse-alerts"
          #           send_resolved: true

        grafana:
          nodeSelector:
            clickhouse-pool: system
          priorityClassName: monitoring
          resources:
            requests: { cpu: 50m, memory: 192Mi }
            limits: { memory: 512Mi }
          admin:
            existingSecret: grafana-admin
            userKey: admin-user
            passwordKey: admin-password
          persistence:
            enabled: true
            storageClassName: vultr-block-storage
            size: 10Gi
          deploymentStrategy:
            type: Recreate
          sidecar:
            dashboards:
              enabled: true
              label: grafana_dashboard
              labelValue: "1"
              searchNamespace: ALL
              folderAnnotation: grafana_folder
              provider:
                foldersFromFilesStructure: true

        kube-state-metrics:
          nodeSelector:
            clickhouse-pool: system
          priorityClassName: monitoring
          metricLabelsAllowlist:
            - nodes=[clickhouse-pool]
          resources:
            requests: { cpu: 20m, memory: 64Mi }
            limits: { memory: 256Mi }

        prometheus-node-exporter:
          priorityClassName: monitoring
          resources:
            requests: { cpu: 20m, memory: 32Mi }
            limits: { memory: 96Mi }
        ```

        Save and close the file.

        In the above values file:

        * `kubeEtcd`, `kubeControllerManager`, `kubeScheduler`, and `kubeProxy`: Disable scrapes of the managed control plane.
        * `storageClassName: vultr-block-storage`: Replace it with the default storage class from `kubectl get sc`.
        * `*SelectorNilUsesHelmValues: false`: Makes Prometheus load PodMonitors, ServiceMonitors, and alert rules from every namespace.
        * `metricLabelsAllowlist`: Exports the `clickhouse-pool` node label for the `NodeMissingPoolLabel` alert.

    1. Add the Prometheus community Helm repository.

        ```console
        $ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
        ```

    1. Update the Helm repositories.

        ```console
        $ helm repo update
        ```

    1. Install the chart. The `retentionSize` value keeps the 40 GiB Prometheus volume from filling up.

        ```console
        $ helm upgrade --install kube-prometheus-stack prometheus-community/kube-prometheus-stack --version 94.4.2 -n monitoring -f kube-prometheus-stack.values.yaml --set prometheus.prometheusSpec.retentionSize=34GB --wait --timeout 15m
        ```

    1. List the monitoring pods and the nodes they run on.

        ```console
        $ kubectl -n monitoring get pods -o wide
        ```

        All pods are `Running`.

    ### Enable the Chart Metrics

    The cert-manager and operator ServiceMonitors need the CRDs that the monitoring stack installs.

    1. Enable the cert-manager ServiceMonitor.

        ```console
        $ helm upgrade cert-manager oci://quay.io/jetstack/charts/cert-manager --version v1.21.0 -n cert-manager --reuse-values --set prometheus.servicemonitor.enabled=true --wait --timeout 10m
        ```

    1. Enable the operator ServiceMonitor.

        ```console
        $ helm upgrade clickhouse-operator altinity/altinity-clickhouse-operator --version 0.27.3 -n clickhouse --skip-crds --reuse-values --set serviceMonitor.enabled=true --wait --timeout 10m
        ```

    1. List the ServiceMonitors.

        ```console
        $ kubectl get servicemonitors -A | grep -E 'cert-manager|clickhouse-operator'
        ```

        The output lists one ServiceMonitor in the `cert-manager` namespace and one in the `clickhouse` namespace.

    ### Configure Metrics and Alerts

    The alert rules cover shard availability, replication, disks, node labels, Keeper quorum, backups, and certificates.

    1. Create a manifest file named `50-monitoring.yaml`.

        ```console
        $ nano 50-monitoring.yaml
        ```

    1. Add the following content to the file.

        ```yaml
        apiVersion: monitoring.coreos.com/v1
        kind: PodMonitor
        metadata:
          name: clickhouse-server
          namespace: clickhouse
        spec:
          selector:
            matchLabels:
              app.kubernetes.io/name: clickhouse
              app.kubernetes.io/component: server
          podMetricsEndpoints:
            - port: metrics
              path: /metrics
              interval: 30s
            - port: backup-api
              path: /metrics
              interval: 60s
        ---
        apiVersion: monitoring.coreos.com/v1
        kind: PodMonitor
        metadata:
          name: clickhouse-keeper
          namespace: clickhouse
        spec:
          selector:
            matchLabels:
              app.kubernetes.io/name: clickhouse-keeper
          podMetricsEndpoints:
            - portNumber: 7000
              path: /metrics
              interval: 30s
        ---
        apiVersion: monitoring.coreos.com/v1
        kind: PrometheusRule
        metadata:
          name: clickhouse-platform
          namespace: clickhouse
        spec:
          groups:
            - name: clickhouse.availability
              rules:
                - alert: ClickHouseShardDown
                  expr: |
                    sum by (shard) (
                      label_replace(kube_pod_status_ready{namespace="clickhouse",condition="true",pod=~"chi-analytics-main-[0-9]+-[0-9]+-0"},
                                    "shard", "$1", "pod", "chi-analytics-main-([0-9]+)-[0-9]+-0")
                    ) == 0
                  for: 2m
                  labels: { severity: critical }
                  annotations:
                    summary: "Shard {{ $labels.shard }} has no ready replica"
                    description: "Every replica of shard {{ $labels.shard }} is down. Distributed queries and inserts for that shard fail."
                - alert: ClickHouseShardDegraded
                  expr: |
                    count by (shard) (
                      label_replace(kube_pod_status_ready{namespace="clickhouse",condition="true",pod=~"chi-analytics-main-[0-9]+-[0-9]+-0"},
                                    "shard", "$1", "pod", "chi-analytics-main-([0-9]+)-[0-9]+-0"))
                    -
                    sum by (shard) (
                      label_replace(kube_pod_status_ready{namespace="clickhouse",condition="true",pod=~"chi-analytics-main-[0-9]+-[0-9]+-0"},
                                    "shard", "$1", "pod", "chi-analytics-main-([0-9]+)-[0-9]+-0"))
                    > 0
                  for: 10m
                  labels: { severity: warning }
                  annotations:
                    summary: "Shard {{ $labels.shard }} is running without full redundancy"
                    description: "A replica of shard {{ $labels.shard }} has not been ready for 10 minutes. One more failure takes the shard down."
                - alert: ClickHouseReadonlyReplica
                  expr: max by (pod) (ClickHouseMetrics_ReadonlyReplica{namespace="clickhouse"}) > 0
                  for: 5m
                  labels: { severity: critical }
                  annotations:
                    summary: "{{ $labels.pod }} has read-only replicated tables"
                    description: "Replicated tables on {{ $labels.pod }} are read-only, usually because the pod lost its Keeper session. Inserts to them fail."
                - alert: ClickHouseReplicationLag
                  expr: max by (pod) (ClickHouseAsyncMetrics_ReplicasMaxAbsoluteDelay{namespace="clickhouse"}) > 300
                  for: 10m
                  labels: { severity: warning }
                  annotations:
                    summary: "{{ $labels.pod }} is {{ $value | humanizeDuration }} behind"
                    description: "Replication delay above 5 minutes for 10 minutes. Reads from this replica return stale data."
                - alert: ClickHouseOOMKilled
                  expr: |
                    (max by (pod, container) (kube_pod_container_status_last_terminated_reason{namespace="clickhouse",reason="OOMKilled"}) == 1)
                    and on (pod, container)
                    (increase(kube_pod_container_status_restarts_total{namespace="clickhouse"}[1h]) > 0)
                  labels: { severity: warning }
                  annotations:
                    summary: "{{ $labels.container }} in {{ $labels.pod }} was OOM-killed"
                    description: "Check the queries running at the time (system.query_log) or give the pod more memory."
                - alert: ClickHouseMemoryNearLimit
                  expr: |
                    max by (pod, container) (container_memory_working_set_bytes{namespace="clickhouse",container=~"clickhouse|clickhouse-keeper"})
                    /
                    max by (pod, container) (kube_pod_container_resource_limits{namespace="clickhouse",resource="memory",container=~"clickhouse|clickhouse-keeper"})
                    > 0.95
                  for: 15m
                  labels: { severity: warning }
                  annotations:
                    summary: "{{ $labels.container }} in {{ $labels.pod }} uses {{ $value | humanizePercentage }} of its memory limit"

            - name: clickhouse.storage
              rules:
                - alert: ClickHouseTooManyParts
                  expr: max by (pod) (ClickHouseAsyncMetrics_MaxPartCountForPartition{namespace="clickhouse"}) > 300
                  for: 15m
                  labels: { severity: warning }
                  annotations:
                    summary: "{{ $labels.pod }} has a partition with {{ $value }} parts"
                    description: "Inserts are too small or too frequent and merges cannot keep up. ClickHouse starts delaying, then rejecting, inserts. Batch inserts or use async_insert."
                - alert: ClickHouseRejectedInserts
                  expr: sum by (pod) (increase(ClickHouseProfileEvents_RejectedInserts{namespace="clickhouse"}[10m])) > 0
                  labels: { severity: critical }
                  annotations:
                    summary: "{{ $labels.pod }} is rejecting inserts (too many parts)"
                - alert: ClickHouseVolumeLow
                  expr: |
                    kubelet_volume_stats_available_bytes{namespace="clickhouse"}
                    / kubelet_volume_stats_capacity_bytes{namespace="clickhouse"} < 0.20
                  for: 15m
                  labels: { severity: warning }
                  annotations:
                    summary: "Volume {{ $labels.persistentvolumeclaim }} has {{ $value | humanizePercentage }} free"
                    description: "Merges need free space (up to the size of the largest part). Grow the disk: raise the storage request in 30-clickhouse.yaml and apply it."
                - alert: ClickHouseVolumeCritical
                  expr: |
                    kubelet_volume_stats_available_bytes{namespace="clickhouse"}
                    / kubelet_volume_stats_capacity_bytes{namespace="clickhouse"} < 0.10
                  for: 5m
                  labels: { severity: critical }
                  annotations:
                    summary: "Volume {{ $labels.persistentvolumeclaim }} has {{ $value | humanizePercentage }} free"

            - name: clickhouse.nodes
              rules:
                - alert: NodeMissingPoolLabel
                  expr: |
                    count(kube_node_info) - count(kube_node_labels{label_clickhouse_pool=~"data|system"}) > 0
                  for: 10m
                  labels: { severity: warning }
                  annotations:
                    summary: "{{ $value }} node(s) without the clickhouse-pool label"
                    description: "Label the node with clickhouse-pool=data or clickhouse-pool=system."

            - name: clickhouse.keeper
              rules:
                - alert: KeeperReplicaDown
                  expr: |
                    count(kube_pod_status_ready{namespace="clickhouse",condition="true",pod=~"chk-keeper-.+"})
                    - sum(kube_pod_status_ready{namespace="clickhouse",condition="true",pod=~"chk-keeper-.+"}) > 0
                  for: 5m
                  labels: { severity: warning }
                  annotations:
                    summary: "A Keeper replica is not ready"
                    description: "Keeper still has quorum with 2 of 3, but one more failure makes every replicated table read-only."
                - alert: KeeperQuorumLost
                  expr: sum(kube_pod_status_ready{namespace="clickhouse",condition="true",pod=~"chk-keeper-.+"}) < 2
                  for: 1m
                  labels: { severity: critical }
                  annotations:
                    summary: "Keeper has lost quorum"
                    description: "Fewer than 2 of 3 Keeper replicas are ready. Replicated tables are read-only and ON CLUSTER DDL is blocked."

            - name: clickhouse.backup
              rules:
                - alert: ClickHouseBackupNotRecent
                  expr: time() - kube_cronjob_status_last_successful_time{namespace="clickhouse",cronjob="clickhouse-backup"} > 108000
                  for: 15m
                  labels: { severity: critical }
                  annotations:
                    summary: "No successful ClickHouse backup in the last 30 hours"
                    description: "Check: kubectl -n clickhouse get jobs; kubectl -n clickhouse logs job/<latest backup job>"
                - alert: ClickHouseBackupNeverSucceeded
                  expr: absent(kube_cronjob_status_last_successful_time{namespace="clickhouse",cronjob="clickhouse-backup"})
                  for: 30h
                  labels: { severity: critical }
                  annotations:
                    summary: "The backup CronJob has never completed successfully"
                - alert: ClickHouseBackupJobFailed
                  expr: |
                    (kube_job_status_failed{namespace="clickhouse",job_name=~".*backup.*"} > 0)
                    and on (namespace, job_name)
                    (time() - kube_job_status_start_time{namespace="clickhouse"} < 86400)
                  labels: { severity: warning }
                  annotations:
                    summary: "Backup job {{ $labels.job_name }} failed"
                    description: "kubectl -n clickhouse logs job/{{ $labels.job_name }}"
                - alert: ClickHouseBackupSidecarDown
                  expr: up{namespace="clickhouse",container="clickhouse-backup"} == 0
                  for: 10m
                  labels: { severity: warning }
                  annotations:
                    summary: "Backup sidecar in {{ $labels.pod }} is not responding"
                    description: "The CronJob falls back to the other replica of the shard, but fix this before both go down."

            - name: clickhouse.tls
              rules:
                - alert: ClickHouseCertificateExpiring
                  expr: certmanager_certificate_expiration_timestamp_seconds{name=~"clickhouse-.*"} - time() < 1209600
                  for: 1h
                  labels: { severity: warning }
                  annotations:
                    summary: "Certificate {{ $labels.name }} expires in less than 14 days"
                    description: "cert-manager should have renewed it 30 days before expiry. Check: kubectl -n clickhouse describe certificate {{ $labels.name }}"
                - alert: ClickHouseCertificateNotReady
                  expr: certmanager_certificate_ready_status{name=~"clickhouse-.*",condition="False"} == 1
                  for: 15m
                  labels: { severity: warning }
                  annotations:
                    summary: "Certificate {{ $labels.name }} is not ready"
        ```

        Save and close the file.

    1. Apply the manifest.

        ```console
        $ kubectl apply -f 50-monitoring.yaml
        ```

    ### Access Grafana and Prometheus

    A port forward opens Grafana and Prometheus on the workstation.

    1. Display the Grafana administrator password.

        ```console
        $ kubectl -n monitoring get secret grafana-admin -o jsonpath='{.data.admin-password}' | base64 -d; echo
        ```

    1. Forward local port `3000` to Grafana in the background.

        ```console
        $ kubectl -n monitoring port-forward svc/kube-prometheus-stack-grafana 3000:80 > /dev/null 2>&1 &
        ```

    1. Open `http://localhost:3000` in a web browser.

    1. Log in as `admin` with the password from the first step.

    1. Click **Dashboards** to list the installed dashboards.

        ![Grafana Dashboards page showing the ClickHouse folder with the Altinity ClickHouse Operator Dashboard, ClickHouse in Kubernetes Queries, ClickHouseKeeper Dashboard, Kafka Dashboard, and ZooKeeper Dashboard, followed by the Kubernetes dashboards from kube-prometheus-stack.](https://assets.vultrdevrel.com/docs-main-doc-assets-1/2696/96f3e361-dadf-4786-bd41-ba6b649618ef.png)

        The **ClickHouse** folder holds the operator dashboards for servers, queries, and Keeper. The Kafka and ZooKeeper dashboards stay empty.

    1. Open **Kubernetes / Compute Resources / Namespace (Pods)** and select a namespace to compare the CPU and memory use of its pods with their requests.

        ![Grafana Kubernetes Compute Resources Namespace (Pods) dashboard for the cert-manager namespace, showing CPU usage near 0.001 cores per pod, CPU usage between 1.65% and 10.7% of requests, and memory usage between 12 MiB and 32 MiB per pod.](https://assets.vultrdevrel.com/docs-main-doc-assets-1/2696/d68409a7-f8f9-4be0-ae5c-ef46a434b89e.png)

    1. Stop the Grafana port forward after you finish.

        ```console
        $ pkill -f 'port-forward svc/kube-prometheus-stack-grafana'
        ```

    1. Forward local port `9090` to Prometheus in the background.

        ```console
        $ kubectl -n monitoring port-forward svc/kube-prometheus-stack-prometheus 9090:9090 > /dev/null 2>&1 &
        ```

    1. Open `http://localhost:9090/targets` in a web browser. Every target is in the `UP` state.

    1. Stop the Prometheus port forward after you finish.

        ```console
        $ pkill -f 'port-forward svc/kube-prometheus-stack-prometheus'
        ```

    > [!NOTE]
    > Alerts appear only in the Prometheus and Alertmanager interfaces until you configure a receiver in the `alertmanager.config` section of `kube-prometheus-stack.values.yaml` and run the `helm upgrade` command again.

## Maintain the Cluster

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](#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.

    ```console
    $ kubectl -n clickhouse annotate svc clickhouse-analytics --overwrite service.beta.kubernetes.io/vultr-loadbalancer-firewall-rules="ALLOWED_IP/32,9440"
    ```

* **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](#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.

## Migrate from Amazon Redshift to ClickHouse

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.

### Schema Migration

Recreate each Redshift table as a `ReplicatedMergeTree` local table and a `Distributed` table, both with `ON CLUSTER 'main'`, as in [Verify the Deployment](#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:

* **Schemas:** Each Redshift schema becomes a ClickHouse database, so a table such as `sales.orders` keeps its name.
* **Numbers:** `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`.
* **Text and Boolean values:** `CHAR` and `VARCHAR` become `String`, or `LowCardinality(String)` for columns with few distinct values, such as status codes or country names. `BOOLEAN` becomes `Bool`.
* **Dates and times:** `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.
* **Semi-structured and binary data:** `SUPER` becomes `JSON`, and `VARBYTE` and `GEOMETRY` become `String`. `HLLSKETCH` has no equivalent, so compute distinct counts with `uniq`.
* **Null values:** A ClickHouse column stores a default value in place of `NULL` unless its type is wrapped in `Nullable`. Use `Nullable` only where `NULL` carries meaning.
* **Distribution:** `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.
* **Joins:** Shard both tables by the join key and join the `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.
* **Sort keys:** A compound `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.
* **Compression:** Remove the `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.
* **Keys and identity columns:** A ClickHouse `PRIMARY KEY` is a prefix of the sorting key, not a uniqueness rule. Generate `IDENTITY` values in the application or with `generateSnowflakeID()`.
* **Updates and upserts:** A table that receives `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.

### Data Migration

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](#schema-migration).

1. 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`.

    ```sql
    UNLOAD ('SELECT * FROM sales.orders')
    TO 's3://BUCKET/PREFIX/'
    IAM_ROLE 'ROLE_ARN'
    FORMAT AS PARQUET;
    ```

    Redshift writes one or more Parquet files per slice under the `PREFIX/` folder.

1. 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.

1. 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.

    ```console
    $ ch "INSERT INTO sales.orders SELECT * FROM s3('https://S3_HOSTNAME/BUCKET/PREFIX/*.parquet', 'S3_ACCESS_KEY', 'S3_SECRET_KEY', 'Parquet') SETTINGS distributed_foreground_insert = 1"
    ```

1. Count the loaded rows and compare the result with `SELECT COUNT(*) FROM sales.orders` in Redshift.

    ```console
    $ ch "SELECT count() FROM sales.orders"
    ```

Plan for the following behavior during the copy:

* **Consistency:** Each `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](#data-migration-strategy).
* **Redshift capacity:** `UNLOAD` competes with other queries. Export large tables outside peak hours or one month at a time.
* **Partition columns:** `UNLOAD` with `PARTITION BY` removes the partition columns from the files unless you add the `INCLUDE` option.
* **Unsupported types:** `UNLOAD` writes `GEOMETRY`, `VARBYTE`, and `HLLSKETCH` columns only to CSV, so export those tables in a separate CSV `UNLOAD`.
* **Insert size and cost:** Load from large files, and watch the part count in `system.parts`. AWS bills reads from outside AWS as data transfer out.
* **Validation:** Compare row counts and sums per month between the two systems.

### Query Migration

Joins, window functions, and common table expressions usually need only small changes. Check each query for the following differences:

* **Functions:** `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'`.
* **Integer division:** Redshift returns `2` for `5 / 2`, and ClickHouse returns `2.5`. Use `intDiv(5, 2)` where a query depends on integer results.
* **Outer joins:** ClickHouse fills the columns of unmatched rows with default values instead of `NULL`. Set `join_use_nulls = 1` in the settings profile of the application user to return `NULL`, as Redshift does.
* **Identifiers:** Redshift converts unquoted identifiers to lowercase, and ClickHouse names are case-sensitive. Use the exact names, usually lowercase, in every query.
* **Transactions:** The replicated tables in this article do not support multi-statement transactions, so a job that changes several tables in one Redshift transaction must be able to repeat a failed step without duplicating rows.
* **Stored procedures and prepared statements:** Move procedural logic into the application or a tool such as dbt, and replace `PREPARE` with typed query parameters, such as `{customer_id:UInt64}`.
* **Table maintenance:** Remove the `VACUUM` and `ANALYZE` jobs. ClickHouse merges data parts in the background.

### Application Migration

Each application, dashboard, and data pipeline needs a new driver and new connection settings:

* **Endpoint:** Replace the Redshift endpoint, such as `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`.
* **Driver:** Replace each Redshift driver and BI connector with its ClickHouse equivalent. Native-protocol clients connect to port `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.
* **TLS:** Replace the Amazon Redshift certificate bundle with the private CA certificate `clickhouse-ca.crt` from [Connect to ClickHouse over TLS](#connect-to-clickhouse-over-tls), and keep certificate verification enabled.
* **Credentials:** Replace temporary IAM credentials or the Redshift database password with a ClickHouse user and its password, created as described in [Access Control Migration](#access-control-migration). Keep the `admin` user for administration only.

### Access Control Migration

The `admin` user creates ClickHouse users, roles, and grants with SQL statements:

* **Users:** Each Redshift database user, and each IAM identity that connects with temporary credentials, becomes a ClickHouse user created with `CREATE USER ... IDENTIFIED WITH sha256_password`.
* **Groups and roles:** Redshift groups and roles become ClickHouse roles, created with `CREATE ROLE` and assigned with `GRANT role_name TO user_name`.
* **Privileges:** `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.
* **Row-level security and masking:** Redshift row-level security policies become row policies, created with `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.
* **Workload management:** WLM queues and query monitoring rules become settings profiles and quotas assigned to roles. `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.
* **Every server:** ClickHouse stores SQL users, roles, and grants on each server separately. Run every `CREATE USER`, `CREATE ROLE`, `CREATE ROW POLICY`, `CREATE SETTINGS PROFILE`, `CREATE QUOTA`, and `GRANT` statement with `ON CLUSTER 'main'`.

### Data Migration Strategy

For tables that keep receiving data during the migration:

* **Dual-write period:** Change each load job or pipeline to write every batch to both Redshift and ClickHouse, so rows that arrive during the copy reach the cluster. A pipeline that loads files with `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.
* **Backfill historical data:** Copy the rows that arrived before the dual writes started with the tools in [Data Migration](#data-migration), one month or partition at a time.
* **Query validation:** Run each dashboard and report query on both systems and compare the results before you move it.
* **Read cutover:** Move dashboards and applications to ClickHouse one at a time, and watch query latency and errors in the `system.query_log` table, or in the **Altinity ClickHouse Operator Dashboard** if you configured the optional monitoring.
* **Write cutover:** Stop the writes to Redshift after ClickHouse serves all queries without errors for a period that you agree on in advance. Keep the Redshift cluster, or a final manual snapshot of it, until the first ClickHouse backups of the migrated data complete.
* **Rollback:** Until the write cutover, move the queries back to Redshift. The dual writes keep Redshift current.

### Migration Considerations

The following items require attention during the migration:

* **Storage sizing:** Redshift Managed Storage grows on its own, while this cluster stores each replica on its own block storage volume. Both replicas of a shard hold a full copy of its data, so size the volumes for twice the compressed data and keep 20% of each volume free for merges.
* **Recovery point:** Redshift takes snapshots about every 8 hours, while this cluster backs up nightly. Run the backup CronJob more often for a shorter recovery point.
* **Availability:** This cluster runs in one region and survives the loss of one data node. For a regional outage, restore the backups into a cluster in another region.
* **Replication:** An insert reaches the second replica of a shard through asynchronous replication, so a read from that replica can miss the newest rows for a short time. Set `insert_quorum = 2` on inserts that must reach both replicas before they return.
* **Encryption at rest:** This article does not configure encryption at rest. ClickHouse supports encrypted disks.

## Troubleshoot the Deployment

The following table lists common problems, their causes, and their resolutions.

| Symptom | Cause | Resolution |
|---|---|---|
| A ClickHouse or Keeper pod stays `Pending` | A node lacks the `clickhouse-pool` label, or a volume is still being created | Run `kubectl -n clickhouse describe pod POD_NAME` and read the events. Repeat [Label the Nodes](#label-the-nodes) if a label is missing. |
| The `chi` or `chk` status is `Aborted` | The operator rejected the manifest or could not reconcile it | Run `kubectl -n clickhouse describe chi analytics` and view the operator log with `kubectl -n clickhouse logs -l app.kubernetes.io/name=altinity-clickhouse-operator --all-containers --tail=100`. |
| The load balancer `EXTERNAL-IP` stays `<pending>` | The cloud controller is still provisioning the load balancer, or it rejected an annotation | Run `kubectl -n clickhouse describe svc clickhouse-analytics` and read the events. |
| Connections to port `9440` time out, or the client reports `SOCKET_TIMEOUT` | The client address is not in the load balancer allowlist, or a VPN changed the public address of the workstation | Compare the address from `curl -4 -s https://ifconfig.me` with the `vultr-loadbalancer-firewall-rules` value, then update the allowlist as described in [Maintain the Cluster](#maintain-the-cluster). |
| The backup log shows `NoSuchBucket` | The bucket does not exist in the object storage service | Create the bucket and run a backup job again. |
| The backup job fails with `/scripts/backup.sh is empty or incomplete` | The `clickhouse-backup-script` ConfigMap was changed or truncated | Apply `40-backup.yaml` again. Edit the script only in that file. |
| A restore fails with `backupName is required` or `is not found on remote storage` | The backup name variable is empty or does not match a backup | Copy the exact names from `cb POD_NAME list remote`. |
| `clickhouse-backup` reports an `EC2 IMDS` error | The object storage keys are empty, so the S3 SDK looks for instance credentials | Create the `clickhouse-backup-s3` secret again with the keys of your object storage service, then delete the ClickHouse pods one at a time so they read the new keys. |
| `INSERT ... SELECT FROM s3(...)` fails with `Access Denied` | The access key cannot read the bucket, or the URL does not match the bucket's Region | Grant the key read access to the bucket and use the regional URL, such as `https://BUCKET.s3.REGION.amazonaws.com/PREFIX/*.parquet`. |
| A join on two `Distributed` tables fails with `Double-distributed IN/JOIN subqueries is denied` | Both sides of the join read `Distributed` tables | Join the local table of the right side, or use `GLOBAL JOIN`. |

## Conclusion

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](#migrate-from-amazon-redshift-to-clickhouse). For more information, visit the [ClickHouse documentation](https://clickhouse.com/docs) and the [Altinity Kubernetes Operator for ClickHouse documentation](https://docs.altinity.com/altinitykubernetesoperator/).
