Skip to content

[jdbc-v2, client-v2] MAX_NUM_OF_CONNECTIONS doesn't limit connection. #2379

Open

Description

@chernser

Description

There was an issue #1705
The problem still exists: #1705 (comment)

Hi @Paultagoras, I have taken some new tests - I tried to re-run both my old tests and the project @f1llon provided - with clickhouse-jdbc version 0.8.6 and using JDBC-v2 classes (for example DataSourceImpl instead of the old ClickHouseDataSource).
On one hand, I don't see anymore the Hikari CP issue I first submitted, so many thanks! But on the other hand, I still have some issues:

running @f1llon 's test project, I still have the old logs "route allocated: 1 of N; total allocated: 1 of N"
using the "default" connection pool and running my own tests of concurrent reading, property ClientConfigProperties.HTTP_MAX_OPEN_CONNECTIONS is ignored: when I run a netstat command on my PC, the number of connections opened toward ClickHouse can be well above the one I set with the ClientConfigProperties.HTTP_MAX_OPEN_CONNECTIONS property.

Is it enough to initialize my DataSourceImpl with
baseProperties.setProperty(ClientConfigProperties.HTTP_MAX_OPEN_CONNECTIONS.getKey(), "5");
and then use
datasource.getConnection()
to make this configuration effective or do I need to do anything else?

Still, thank you for your help!

Steps to reproduce

Error Log or Exception StackTrace

Expected Behaviour

Code Example

Configuration

Client Configuration

Environment

  • Cloud
  • Client version:
  • Language version:
  • OS:

ClickHouse Server

  • ClickHouse Server version:
  • ClickHouse Server non-default settings, if any:
  • CREATE TABLE statements for tables involved:
  • Sample data for all these tables, use clickhouse-obfuscator if necessary

Activity

  1. added
    client
    jdbc
    on May 21, 2025
  2. added
    connectivity
    on Jul 12, 2025
  3. added this to the 0.9.8 milestone on Feb 18, 2026
  4. modified the milestones: 0.9.8, 0.9.9 on Mar 16, 2026
  5. added this to the 0.9.9 milestone on Apr 15, 2026
  6. modified the milestones: 0.10.0, 0.11.0 on Jun 8, 2026
  7. modified the milestones: 0.11.0, 0.12.0 on Oct 1, 2026
  8. removed this from the 0.12.0 milestone on Oct 14, 2026
  9. polyglotAI-bot commented on Nov 28, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Close — no-op: works as intended
    max_open_connections limits the HTTP connections of each JDBC Connection, not of the whole DataSource. To limit the total, limit the number of JDBC connections, for example with the HikariCP maximumPoolSize.

    • Category: Incorrect usage
    • Classification: impact: none · area: Connectivity (connection pool)
    • Status on main: Not a bug — one client-v2 Client keeps the limit (peak 2 connections, 8 queries in 4 s); a DataSourceImpl with one getConnection() per thread opens one pool per connection (peak 8, 1 s).
    • Breaking change: No
    • Duplicates / related: No others

    Analysis: jdbc-v2 builds a new Client for each JDBC Connection (jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java:98-105), and each Client applies max_open_connections to its own pool (client-v2/src/main/java/com/clickhouse/client/api/internal/HttpAPIClientHelper.java:284). docs/integration-jdbc.md:156-159 documents these two layers of pooling, and makes the JDBC connection pool the task of the application.

    Reproduction: complete program and output
    import com.clickhouse.client.api.Client;
    import com.clickhouse.client.api.ClientConfigProperties;
    import com.clickhouse.client.api.query.GenericRecord;
    import com.clickhouse.jdbc.DataSourceImpl;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Properties;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.atomic.AtomicBoolean;
    import java.util.concurrent.atomic.AtomicLong;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        static final int LIMIT = 2;
        static final int THREADS = 8;
    
        // Open HTTP connections on the server, read with a separate client.
        static long httpConnections(Client monitor) {
            List<GenericRecord> rows = monitor.queryAll("SELECT value FROM system.metrics WHERE metric = 'HTTPConnection'");
            return rows.get(0).getLong(1);
        }
    
        // Runs THREADS tasks at the same time and prints the peak number of HTTP connections that they open.
        static void measure(String name, Client monitor, Callable<Object> task) throws Exception {
            long baseline = httpConnections(monitor);
            AtomicLong peak = new AtomicLong(baseline);
            AtomicBoolean done = new AtomicBoolean(false);
            Thread sampler = new Thread(() -> {
                while (!done.get()) {
                    peak.accumulateAndGet(httpConnections(monitor), Math::max);
                    try { Thread.sleep(50); } catch (InterruptedException e) { return; }
                }
            });
            sampler.start();
            ExecutorService pool = Executors.newFixedThreadPool(THREADS);
            List<Callable<Object>> tasks = new ArrayList<>();
            for (int i = 0; i < THREADS; i++) tasks.add(task);
            long start = System.nanoTime();
            String errors = "";
            for (Future<Object> f : pool.invokeAll(tasks)) {
                try { f.get(); } catch (Exception e) { errors = " | error: " + e.getCause(); }
            }
            long ms = (System.nanoTime() - start) / 1_000_000;
            done.set(true);
            sampler.join();
            pool.shutdown();
            System.out.println(name + ": max_open_connections=" + LIMIT + ", " + THREADS + " concurrent queries, peak extra HTTP connections="
                + (peak.get() - baseline) + ", elapsed=" + ms + " ms" + errors);
        }
    
        public static void main(String[] args) throws Exception {
            try (Client monitor = new Client.Builder().addEndpoint(URL).setUsername("default").setPassword(PASSWORD)
                    .setMaxConnections(1).build()) {
                // client-v2: one Client, shared by all threads
                try (Client client = new Client.Builder().addEndpoint(URL).setUsername("default").setPassword(PASSWORD)
                        .setMaxConnections(LIMIT).build()) {
                    measure("client-v2 one Client", monitor, () -> client.queryAll("SELECT sleep(1)"));
                }
                Thread.sleep(1000);
    
                // jdbc-v2: one DataSourceImpl, each thread calls getConnection(), as in the issue
                Properties props = new Properties();
                props.setProperty("user", "default");
                props.setProperty("password", PASSWORD);
                props.setProperty(ClientConfigProperties.HTTP_MAX_OPEN_CONNECTIONS.getKey(), String.valueOf(LIMIT));
                DataSourceImpl ds = new DataSourceImpl("jdbc:clickhouse:" + URL.replaceFirst("^https?:", "") + "/default", props);
                measure("jdbc-v2 DataSourceImpl.getConnection() per thread", monitor, () -> {
                    try (Connection conn = ds.getConnection(); Statement s = conn.createStatement();
                         ResultSet rs = s.executeQuery("SELECT sleep(1)")) {
                        rs.next();
                    }
                    return null;
                });
            }
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.4.11:

    client-v2 one Client: max_open_connections=2, 8 concurrent queries, peak extra HTTP connections=2, elapsed=4020 ms
    jdbc-v2 DataSourceImpl.getConnection() per thread: max_open_connections=2, 8 concurrent queries, peak extra HTTP connections=8, elapsed=1036 ms
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    clientconnectivityjdbcquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions