Skip to content

client-v2 retries an insert with the same query id after NoHttpResponseException, causing QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING #3174

Open

Description

@billykern

Description

Client.insert reuses requestSettings.getQueryId() across every retry attempt. After NoHttpResponseException (retried by default via ClientFaultCause.NoHttpResponse) the first request may already have reached the server and still be executing. The second attempt is then rejected with Code: 216 QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING, which is not retryable, so a transient transport fault becomes a hard failure.

#1721 introduced the retry and noted that "not every request may be retried safely". This is that case.

Steps to reproduce

  1. client.insert(table, data, format, settings) with default retry settings through a proxy or load balancer.
  2. The proxy closes the keep-alive connection after forwarding the request, while the server is still executing the insert (async_insert=1, wait_for_async_insert=1 makes the window at least the busy timeout).
  3. The client gets NoHttpResponseException, logs Retrying., and resends with the same query id. The server answers 216.

Error Log or Exception StackTrace

WARN Retrying. (com.clickhouse.client.api.Client)
org.apache.hc.core5.http.NoHttpResponseException: <host>:8443 failed to respond
    at org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:333)
    ...
    at com.clickhouse.client.api.internal.HttpAPIClientHelper.executeRequest(HttpAPIClientHelper.java:453)
    at com.clickhouse.client.api.Client.lambda$insert$3(Client.java:1474)
    at com.clickhouse.client.api.Client.runAsyncOperation(Client.java:2012)
    at com.clickhouse.client.api.Client.insert(Client.java:1518)

com.clickhouse.client.api.ServerException: Code: 216. DB::Exception: Query with id = b266240e-d406-4874-ba3b-cd1b0bd969f8 is already running. (QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING) (version 26.4.1.2359 (official build))
    at com.clickhouse.client.api.internal.HttpAPIClientHelper.readError(HttpAPIClientHelper.java:403)
    at com.clickhouse.client.api.internal.HttpAPIClientHelper.executeRequest(HttpAPIClientHelper.java:467)
    at com.clickhouse.client.api.Client.lambda$insert$3(Client.java:1474)
    at com.clickhouse.client.api.Client.runAsyncOperation(Client.java:2012)
    at com.clickhouse.client.api.Client.insert(Client.java:1518)
    at com.clickhouse.client.api.Client.insert(Client.java:1408)

Expected Behaviour

A retry after a fault where the first request may have been delivered does not collide with its own earlier attempt. Either the retry uses a fresh query id, or the client does not retry once the request body has been sent.

Configuration

Client Configuration

Defaults: retry=3, retryOnFailures = [NoHttpResponse, ConnectTimeout, ConnectionRequestTimeout, ServerRetryable]. Caller sets queryId and insert_deduplication_token per insert (clickhouse-kafka-connect v1.6.0).

Environment

  • Cloud
  • Client version: client-v2 0.9.5 (insert loop unchanged on 0.9.6, 0.10.0 and main)
  • Language version: Java 21.0.10
  • OS: Linux

ClickHouse Server

  • ClickHouse Server version: 26.4.1 and 26.6.1
  • Non-default settings: async_insert=1, wait_for_async_insert=1, async_insert_busy_timeout_ms=200

Related: #1529 (same code, different cause). Downstream: ClickHouse/clickhouse-kafka-connect#847.

Activity

  1. chernser commented on Oct 14, 2026

    @chernser
    Contributor

    thank you for reporting this @billykern !

    I will look into it.

  2. modified the milestone: 0.12.0 on Oct 14, 2026
  3. billykern commented on Oct 15, 2026

    @billykern
    Author

    4. thank you for reporting this @billykern !
    I will look into it.

    Thank you @chernser 🙏

  4. added this to the 0.12.0 milestone on Nov 10, 2026
  5. added
    planned_work
    on Nov 18, 2026
  6. polyglotAI-bot commented on Nov 27, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — fix needed
    No open PR. The fix needs a maintainer decision: what the client does when it retries an insert that the server can already have received (the issue gives two options).

    • Category: Bug
    • Classification: impact: none · area: Connectivity (retries)
    • Status on main: Reproduced on main — the retry sends the same query id, the server answers 216, and the first attempt stores the row.
    • Breaking change: No API change; a fix changes the documented retry behavior (docs/features.md:37), which docs/ai-review.md lists as high-risk.
    • Duplicates / related: No others.

    Analysis: Client.java:1871 reads the query id once, before the retry loop, and every attempt sends the same settings (Client.java:1876); HttpAPIClientHelper.java:1185 retries a NoHttpResponseException by default, also when the server got the request. The POJO insert (Client.java:1627) and query (Client.java:2028) reuse the query id the same way. A query id is sent only when the caller sets one or a setQueryIdGenerator supplier (Client.java:1857).

    Reproduction: complete program and output

    Changed from the issue's steps: a proxy in the program forwards the first INSERT and then closes the connection with no response; async_insert_busy_timeout_ms=3000 keeps the first attempt running.

    import com.clickhouse.client.api.Client;
    import com.clickhouse.client.api.insert.InsertSettings;
    import com.clickhouse.data.ClickHouseFormat;
    
    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketTimeoutException;
    import java.net.URI;
    import java.nio.charset.StandardCharsets;
    import java.util.UUID;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.atomic.AtomicBoolean;
    
    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 AtomicBoolean dropped = new AtomicBoolean();
    
        public static void main(String[] args) throws Exception {
            URI server = URI.create(URL);
            ServerSocket proxy = new ServerSocket(0);
            Thread acceptor = new Thread(() -> accept(proxy, server.getHost(), server.getPort()));
            acceptor.setDaemon(true);
            acceptor.start();
    
            try (Client admin = client(URL)) {
                admin.execute("DROP TABLE IF EXISTS t3174").get().close();
                admin.execute("CREATE TABLE t3174 (id UInt32) ENGINE = MergeTree ORDER BY id").get().close();
            }
    
            // The proxy forwards the first INSERT, then closes the connection with no response (NoHttpResponseException).
            try (Client client = client("http://127.0.0.1:" + proxy.getLocalPort())) {
                InsertSettings settings = new InsertSettings()
                        .setQueryId(UUID.randomUUID().toString())
                        .serverSetting("async_insert", "1")
                        .serverSetting("wait_for_async_insert", "1")
                        .serverSetting("async_insert_use_adaptive_busy_timeout", "0")
                        .serverSetting("async_insert_busy_timeout_ms", "3000");
                InputStream data = new ByteArrayInputStream("1\n".getBytes(StandardCharsets.UTF_8));
                try {
                    client.insert("t3174", data, ClickHouseFormat.TSV, settings).get().close();
                    System.out.println("insert with a query id: OK");
                } catch (Exception e) {
                    Throwable c = e instanceof ExecutionException ? e.getCause() : e;
                    System.out.println("insert with a query id: " + c.getClass().getName() + ": " + c.getMessage());
                }
            }
    
            Thread.sleep(4000); // the first attempt finishes on the server
            try (Client admin = client(URL)) {
                System.out.println("rows in table: " + admin.queryAll("SELECT count() FROM t3174").get(0).getLong(1));
                admin.execute("DROP TABLE t3174").get().close();
            }
        }
    
        static Client client(String url) {
            return new Client.Builder().addEndpoint(url).setUsername("default").setPassword(PASSWORD).build();
        }
    
        static void accept(ServerSocket proxy, String host, int port) {
            try {
                while (true) {
                    Socket in = proxy.accept();
                    Socket out = new Socket(host, port);
                    AtomicBoolean drop = new AtomicBoolean();
                    new Thread(() -> toServer(in, out, drop)).start();
                    new Thread(() -> toClient(out, in, drop)).start();
                }
            } catch (Exception ignored) {
            }
        }
    
        static void toServer(Socket in, Socket out, AtomicBoolean drop) {
            byte[] buf = new byte[8192];
            try {
                in.setSoTimeout(1000);
                InputStream src = in.getInputStream();
                OutputStream dst = out.getOutputStream();
                while (true) {
                    int n;
                    try {
                        n = src.read(buf);
                    } catch (SocketTimeoutException idle) {
                        if (drop.get()) { // the request is sent: close the client side, keep the server side open
                            in.close();
                            return;
                        }
                        continue;
                    }
                    if (n < 0) {
                        return;
                    }
                    if (new String(buf, 0, n, StandardCharsets.ISO_8859_1).contains("INSERT") && dropped.compareAndSet(false, true)) {
                        drop.set(true);
                    }
                    dst.write(buf, 0, n);
                    dst.flush();
                }
            } catch (Exception ignored) {
            }
        }
    
        static void toClient(Socket out, Socket in, AtomicBoolean drop) {
            byte[] buf = new byte[8192];
            try {
                InputStream src = out.getInputStream();
                int n;
                while ((n = src.read(buf)) >= 0) {
                    if (!drop.get()) {
                        in.getOutputStream().write(buf, 0, n);
                        in.getOutputStream().flush();
                    }
                }
            } catch (Exception ignored) {
            }
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.2.4:

    WARN Client - Insert (stream) failed (attempt 1 of 4, queryId: 49ebe127-…), endpoint: http://127.0.0.1:32779/, cause: org.apache.hc.core5.http.NoHttpResponseException: 127.0.0.1:32779 failed to respond. Retrying.
    insert with a query id: com.clickhouse.client.api.ServerException: Code: 216. DB::Exception: Query with id = 49ebe127-0e21-497b-96e6-2b0071c8e46d is already running. (QUERY_WITH_SAME_ID_IS_ALREADY_RUNNING) …
    rows in table: 1
    

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

  7. added
    client
    connectivity
    on Nov 27, 2026
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

    bugclientconnectivityplanned_work

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions