Load balancing ensures queries are distributed evenly across ClickHouse nodes. With Spring Boot, you can easily configure and use it.
1. Cluster Setup in ClickHouse
Define replicas under a shard for balancing:
<remote_servers>
<my_cluster>
<shard>
<replica>
<host>node1</host>
<port>9000</port>
</replica>
<replica>
<host>node2</host>
<port>9000</port>
</replica>
</shard>
</my_cluster>
</remote_servers>
ClickHouse automatically balances queries among replicas.
2. Create a Distributed Table
CREATE TABLE logs_local (
id UInt32,
message String,
ts DateTime
) ENGINE = MergeTree()
ORDER BY id;
CREATE TABLE logs_dist AS logs_local
ENGINE = Distributed('my_cluster', 'default', 'logs_local', rand());
rand() ensures random replica selection for load balancing.
3. Use in Spring Boot
List<Map<String, Object>> logs = jdbcTemplate.queryForList(
"SELECT * FROM logs_dist WHERE ts > now() - INTERVAL 1 DAY"
);
Spring Boot queries the distributed table, and ClickHouse handles balancing.
4. Connection Pooling
Add HikariCP to manage connections efficiently:
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
This helps Spring Boot apps perform better under load.
5. Failover and Reliability
If one replica is down, ClickHouse routes queries to others automatically. Your Spring Boot app stays responsive.
image quote pre code