Skip to main content

ClickHouse Cluster Setup Guide (Scale Architecture §2)

Status: build-only, needs cluster verification

The cluster macros, config files and dbt changes are implemented and dbt parse passes with the single-node default unchanged. End-to-end cluster correctness (Distributed reads, cross-shard consolidation, the full test suite in cluster mode) has not been verified — a real multi-node ClickHouse + Keeper setup is required. This guide describes the expected setup procedure.

Files last changed 2026-06-18 (konsolidat 721b6f3); re-verified against the repository on 2026-11-05 (konsolidat 54d072a). Issue: grynn-in/konsolidat#53. Decision record: #57 ClickHouse cluster mode (stay single-node until a scale or HA trigger).

Overview​

Konsolidat shards the ClickHouse warehouse by data_area_id (the materialized legal-entity column; the canonical entity_id is renamed to data_area_id at the bronze source boundary) across a konsol_cluster cluster using Distributed + ReplicatedMergeTree. A given legal entity's rows colocate on one shard (cityHash64(data_area_id)), so per-entity GL history queries avoid cross-shard scatter for common single-entity reports.

ItemValue
Cluster namekonsol_cluster
Shard keycityHash64(data_area_id)
Local table engineReplicatedMergeTree (Keeper path /clickhouse/tables/{shard}/{database}/{table})
Query table engineDistributed(konsol_cluster, <db>, <local_table>, cityHash64(data_area_id))
CoordinatorClickHouse Keeper (co-located or standalone quorum)
Sharded databasesepm_bronze, epm_silver, epm_gold
Imageclickhouse/clickhouse-server:24.8-alpine (docker-compose.cluster.yml)

Single-node remains the default (cluster_enabled: false in dbt_project.yml); cluster mode is opt-in via:

dbt build --target cluster --vars '{"cluster_enabled": true}'

Architecture​

┌─────────────────────────────────────────────────────────────────┐
│ API / dbt tests │
│ ↓ SELECT from Distributed table │
├──────────────────┬──────────────────┬──────────────────────────┤
│ ch-shard1 │ ch-shard2 │ ch-shard3 │
│ ReplicatedMT │ ReplicatedMT │ ReplicatedMT │
│ _local tables │ _local tables │ _local tables │
│ (entities A-D) │ (entities E-K) │ (entities L-Z) │
├──────────────────┴──────────────────┴──────────────────────────┤
│ ClickHouse Keeper quorum (consensus / replication coordination) │
└─────────────────────────────────────────────────────────────────┘

Prerequisites​

  • 3 (or more) hosts / VMs with Docker and Docker Compose v2.
  • A private network between the hosts (all nodes reachable by hostname).
  • Shared CLICKHOUSE_PASSWORD secret.
  • dbt-clickhouse ≥ 1.6.0 (cluster config key support).

Step 1 — Per-node macros files​

Each ClickHouse node needs a macros.xml with its {shard} and {replica} values so ClickHouse can expand them in ReplicatedMergeTree Keeper paths. The repository ships one per shard: clickhouse/cluster/macros-shard1-replica1.xml, macros-shard2-replica1.xml, macros-shard3-replica1.xml; docker-compose.cluster.yml mounts the one matching SHARD_ID/REPLICA_ID. To add a replica, generate another:

shard=1; replica=2
cat > clickhouse/cluster/macros-shard${shard}-replica${replica}.xml <<EOF
<clickhouse>
<macros>
<shard>0${shard}</shard>
<replica>replica${replica}</replica>
<cluster>konsol_cluster</cluster>
</macros>
</clickhouse>
EOF

Step 2 — Update remote_servers.xml​

Edit clickhouse/cluster/remote_servers.xml and replace the placeholder hostnames (ch-shard1, ch-shard2, ch-shard3) with the real IPs or DNS names of your three nodes, or set CH_HOST_1..3 so the compose file's extra_hosts resolve them.

Step 3 — Start the cluster​

On each of the three nodes, set the node-specific environment and start:

# On node 1
export SHARD_ID=1
export REPLICA_ID=1
export CH_HOST_1=<ip-of-node1>
export CH_HOST_2=<ip-of-node2>
export CH_HOST_3=<ip-of-node3>
export CLICKHOUSE_PASSWORD=<shared-secret>

docker compose -f docker-compose.cluster.yml up -d

Repeat with SHARD_ID=2 on node 2 and SHARD_ID=3 on node 3. The compose file maps Keeper's server_id to SHARD_ID, which is unique only with one replica per shard; a second replica needs its own Keeper id (comment in docker-compose.cluster.yml).

Wait for all three healthchecks to pass:

docker compose -f docker-compose.cluster.yml ps

Step 4 — Initialise databases ON CLUSTER​

Run the init script through the cluster so all nodes create the databases:

for db in epm_raw epm_staging epm_bronze epm_silver epm_gold; do
docker compose -f docker-compose.cluster.yml exec clickhouse \
clickhouse-client -q "CREATE DATABASE IF NOT EXISTS $db ON CLUSTER konsol_cluster"
done

Also run the init script, which creates the konsol-owned reference and submission tables:

docker compose -f docker-compose.cluster.yml exec -T clickhouse \
clickhouse-client --multiquery < clickhouse/init-db.sql

init-db.sql creates single-node tables; on a cluster the konsol-owned epm_staging.* / epm_gold.* tables are not sharded (they are small reference tables) and must exist on every node konsol writes to. This is one of the open points below.

Step 5 — Set environment and run dbt in cluster mode​

export CLICKHOUSE_HOST=<ip-of-any-node>
export CLICKHOUSE_PORT=8443 # the cluster target defaults to 8443 with secure: true, verify: true
export CLICKHOUSE_USER=default
export CLICKHOUSE_PASSWORD=<shared-secret>
export DBT_TARGET=cluster

cd dbt_project

# Build all models with cluster engines + ON CLUSTER DDL
dbt build --target cluster --vars '{"cluster_enabled": true}'

Port note: dbt_project/profiles.yml's cluster target reads CLICKHOUSE_PORT with default 8443 and secure: true, but docker-compose.cluster.yml publishes only the plain ports 8123 (HTTP) and 9000 (native). Either terminate TLS in front of the nodes on 8443, or set CLICKHOUSE_PORT=8123 and change secure/verify in the target. This mismatch is in the repository as of 2026-11-05 and is listed as an open question.

This builds every opted-in model with ReplicatedMergeTree ON CLUSTER. Tables are named <model>_local by the convention established in the macros.

Step 6 — Create Distributed overlay tables​

After the _local ReplicatedMergeTree tables exist on all shards, create the unsuffixed Distributed tables that the API queries:

dbt run-operation create_distributed_tables \
--vars '{"cluster_enabled": true}'

This generates and executes DDL of the form:

CREATE TABLE IF NOT EXISTS epm_bronze.bronze_general_journal_account_entries
ON CLUSTER konsol_cluster
AS epm_bronze.bronze_general_journal_account_entries_local
ENGINE = Distributed(
'konsol_cluster',
'epm_bronze',
'bronze_general_journal_account_entries_local',
cityHash64(data_area_id)
);

drop_distributed_tables is the inverse operation (both in dbt_project/macros/cluster.sql).

Step 7 — Verify​

# Check shards are online
clickhouse-client -q "SELECT * FROM system.clusters WHERE cluster = 'konsol_cluster'"

# Confirm entity rows colocate (one row per data_area_id per shard)
clickhouse-client -q "
SELECT shardNum(), count() as row_count
FROM epm_gold.gold_trial_balance
WHERE data_area_id = 'USSI'
GROUP BY shardNum()
"
# Expected: exactly ONE shard returns a non-zero count.

# Distributed count matches single-node baseline
clickhouse-client -q "
SELECT count(distinct data_area_id) FROM epm_gold.gold_trial_balance
"

Run the full dbt test suite against the cluster:

dbt test --target cluster --vars '{"cluster_enabled": true}'

Needs a cluster: all 144 singular tests and 129 schema tests (the counts at konsolidat f728d59; scripts/check-docs-drift.sh prints the live numbers) must pass in cluster mode before this is considered production-ready.

Model opt-in​

Not all models need to be cluster-aware immediately. To opt a model in:

  1. Replace the hardcoded engine and add cluster in its config():
-- Before
{{
config(
engine='MergeTree()',
order_by='tuple()'
)
}}

-- After (cluster-aware)
{{
config(
engine=cluster_engine('MergeTree()'),
order_by='tuple()',
cluster=cluster_name()
)
}}
  1. The SELECT query body is never changed.

  2. When cluster_enabled=false (default), cluster_engine() returns the original string and cluster_name() returns none → compiled SQL is identical to before.

Models already opted in (11, measured 2026-11-05 with grep -l cluster_engine dbt_project/models):

  • bronze_general_journal_account_entries, bronze_general_journal_entries, bronze_trial_balance_submissions
  • gold_trial_balance, gold_trial_balance_by_partner, gold_tb_at_hierarchy_node, gold_budget_at_hierarchy_node, gold_variance_at_hierarchy_node, gold_reporting_hierarchy, gold_reporting_hierarchy_closure, gold_unassigned_hierarchy_members

The other 90 models, including gold_consolidated_trial_balance and the deal journals, still use plain MergeTree engines and would be created on the node dbt connects to only.

Configuration files​

FilePurpose
clickhouse/cluster/remote_servers.xmlCluster topology (shard hosts)
clickhouse/cluster/keeper.xmlClickHouse Keeper (raft + ZooKeeper-compatible)
clickhouse/cluster/macros-shard{1,2,3}-replica1.xmlPer-node {shard} / {replica} macros
docker-compose.cluster.ymlDocker Compose overlay for the 3-node cluster (SHARD_ID, REPLICA_ID, CH_HOST_1..3)
dbt_project/profiles.yml (cluster target)dbt cluster target with cluster: konsol_cluster
dbt_project/macros/cluster.sqlcluster_enabled, cluster_name, cluster_zk_path, cluster_sharding_key, cluster_engine, cluster_sharded_tables, create_distributed_tables, drop_distributed_tables

Open questions​

These items are not resolved and require cluster-level testing before GA:

Hot-shard risk​

cityHash64(data_area_id) distributes entities evenly by hash, but a single very large entity (e.g. one entity with 10 years of daily GL history) may concentrate row volume on one shard.

Options to evaluate on a real cluster:

  • Composite shard key: cityHash64(concat(data_area_id, toString(fiscal_year))) — fans out one entity across shards by year; breaks per-entity colocality for some queries.
  • Oversized-entity detection: monitor system.parts per shard; flag entities where sum(rows) on a single shard exceeds 3× the mean.
  • Per-entity manual routing: route known large entities to dedicated shards via custom sharding_key expressions or separate databases.

Rebalancing​

When a new legal entity is onboarded after initial sharding, cityHash64 routes it deterministically — no explicit rebalancing is needed. However, if an existing entity grows disproportionately, resharding requires:

  1. Creating a new cluster topology.
  2. Copying data using INSERT INTO new_table SELECT * FROM old_table.
  3. Swapping Distributed table definitions.

This is operationally expensive. Decide on acceptable skew tolerance before GA. A max_rows_to_read limit per shard query can mitigate hot-shard query timeouts in the interim.

Cross-shard aggregation correctness​

Gold models that aggregate across entities (gold_trial_balance, gold_consolidated_trial_balance, IC eliminations, NCI movement) perform cross-shard reads through the Distributed engine. ClickHouse pushes aggregation to each shard first then combines results at the coordinator.

Points to verify on a real cluster:

  • GLOBAL IN / GLOBAL JOIN for cross-shard subqueries (ClickHouse does not automatically promote IN to GLOBAL IN for Distributed reads).
  • sum() / count() aggregations across shards are additive — verify totals match the single-node baseline.
  • asof left join in gold_consolidated_trial_balance and temporal ownership joins may behave differently under Distributed read semantics.
  • The konsol-owned reference tables (epm_staging.*, epm_gold.consolidation_groups, …) are written by konsol to one host; they must be visible to every shard's queries.

TLS port​

profiles.yml defaults the cluster target to 8443 secure; the compose overlay publishes 8123 and 9000 only (see Step 5).