Skip to content

[R2DBC] Cancelled reactive queries leak HTTP connections and exhaust the connection pool #2976

Description

@tomaszzason

Description

Cancelling HTTP requests in a Spring WebFlux application while a ClickHouse R2DBC query is still running can leave the underlying HTTP response unclosed.

After enough cancelled requests, HTTP connections remain leased in the Apache HttpClient connection pool. Once the pool is exhausted, subsequent ClickHouse queries cannot acquire a connection and eventually fail with ConnectionRequestTimeoutException.

A complete minimal reproduction project is available here:

https://github.com/tomaszzason/clickhouse

The repository contains:

  • docker-compose.yml — starts a local ClickHouse server;
  • requests.sh — sends 1,000 HTTP requests and cancels them almost immediately;
  • single_request.http — sends one normal request;
  • stack_trace.log — thread dump captured after the application stops responding;
  • a minimal Spring Boot WebFlux controller using DatabaseClient and clickhouse-r2dbc.

Root cause

The R2DBC statement adapts ClickHouseRequest.execute() through a Reactor Mono backed by a CompletableFuture.

The problematic lifecycle is:

WebFlux request starts
→ ClickHouseStatement starts ClickHouseRequest.execute()
→ the HTTP client cancels the WebFlux request
→ the Reactor subscription is cancelled
→ the client-v1 operation continues on a ClickHouseWorker thread
→ ClickHouseStreamResponse is created after cancellation
→ ClickHouseResult is never created
→ nobody closes the late response
→ the Apache HTTP connection remains leased

Cancelling the CompletableFuture does not necessarily stop the blocking HTTP operation running in client-v1.

If the operation finishes after the Reactor subscriber has already cancelled, its ClickHouseResponse may no longer have an owner responsible for closing it.

There is also a second cleanup gap in ClickHouseResult. The response is currently closed on normal completion using:

.doOnComplete(response::close)

This does not cover cancellation or error signals.

As a result, responses may remain open when cancellation happens either:

  1. before ClickHouseResult is created; or
  2. while the result is being consumed.

Steps to reproduce

  1. Clone the reproduction repository:
git clone https://github.com/tomaszzason/clickhouse.git
cd clickhouse
  1. Start ClickHouse:
docker compose up -d
  1. Start the Spring Boot application from the repository.

  2. Verify that one normal request works by running the request from:

single_request.http
  1. Run the cancellation script:
./requests.sh

The script starts 1,000 HTTP requests and cancels them almost immediately.

  1. Wait for the script to finish.

  2. Run the request from single_request.http again.

  3. Observe that the application no longer responds normally.

  4. After the configured connection request timeout expires, the application reports ConnectionRequestTimeoutException.

  5. Inspect:

stack_trace.log

The thread dump shows ClickHouseWorker-* threads waiting while Apache HttpClient tries to acquire an endpoint from the exhausted connection pool.

Error Log or Exception StackTrace

org.apache.hc.core5.http.ConnectionRequestTimeoutException:
Timeout deadline: 180000 MILLISECONDS, actual: 180001 MILLISECONDS
    at org.apache.hc.client5.http.impl.classic.InternalExecRuntime.acquireEndpoint(InternalExecRuntime.java:122)
    at org.apache.hc.client5.http.impl.classic.ConnectExec.execute(ConnectExec.java:127)
    at org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)
    at org.apache.hc.client5.http.impl.classic.ProtocolExec.execute(ProtocolExec.java:192)
    at org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)
    at org.apache.hc.client5.http.impl.classic.HttpRequestRetryExec.execute(HttpRequestRetryExec.java:112)
    at org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)
    at org.apache.hc.client5.http.impl.classic.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.hc.client5.http.impl.classic.ExecChainElement.execute(ExecChainElement.java:51)
    at org.apache.hc.client5.http.impl.classic.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.hc.client5.http.impl.classic.CloseableHttpClient.execute(CloseableHttpClient.java:123)
    at com.clickhouse.client.http.ApacheHttpConnectionImpl.post(ApacheHttpConnectionImpl.java:301)
    at com.clickhouse.client.http.ClickHouseHttpClient.send(ClickHouseHttpClient.java:196)
    at com.clickhouse.client.AbstractClient.sendAsync(AbstractClient.java:165)
    at com.clickhouse.client.AbstractClient.lambda$execute$0(AbstractClient.java:280)
    at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1789)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614)
    at java.base/java.lang.Thread.run(Thread.java:1474)

The complete thread dump is available in the reproduction repository:

https://github.com/tomaszzason/clickhouse/blob/master/stack_trace.log

Expected Behaviour

Cancelling a WebFlux request must not permanently retain an HTTP connection.

If a ClickHouse request completes after the Reactor subscriber has already cancelled:

  • the late ClickHouseResponse must be closed;
  • the response stream must be closed or drained;
  • the Apache HTTP endpoint must be released;
  • the connection must return to the pool.

After running requests.sh, the request from single_request.http should still complete successfully without restarting the application.

Repeated request cancellation should not cause permanent connection pool exhaustion.

Code Example

The complete executable example is available at:

https://github.com/tomaszzason/clickhouse

The controller uses the standard reactive Spring R2DBC flow:

@GetMapping("/clickhouse/test")
public Mono<Integer> executeQuery() {
    return databaseClient.sql(QUERY)
            .map((row, metadata) ->
                    row.get("value", Integer.class))
            .one();
}

The cancellation scenario is generated by requests.sh, which follows this pattern:

for i in $(seq 1 1000); do
  curl \
    --silent \
    --max-time 0.001 \
    "http://localhost:8080/clickhouse/test" \
    >/dev/null 2>&1 &
done

wait

The full controller, configuration and runnable script should be taken from the reproduction repository rather than duplicated in this issue.

Suggested Fix

1. Handle responses that arrive after cancellation in ClickHouseStatement

ClickHouseStatement should retain responsibility for the request until the resulting response is either:

  • successfully transferred to ClickHouseResult; or
  • closed because the downstream subscription has already been cancelled.

Conceptually:

final CompletableFuture<ClickHouseResponse> future =
        request.execute();

future.whenComplete((response, throwable) -> {
    if (throwable != null) {
        propagateErrorIfSubscriberIsActive(throwable);
        return;
    }

    if (subscriberWasCancelled()) {
        response.close();
        return;
    }

    emitResponse(response);
});

The implementation must safely handle the race between:

subscriber cancellation
future completion
response emission
response ownership transfer

An abandoned response must be closed exactly once.

The response must not be closed after it has already been transferred to an active ClickHouseResult.

2. Close ClickHouseResult for all terminal Reactor signals

Current cleanup based on:

.doOnComplete(response::close)

only covers normal completion.

The response lifecycle should also cover cancellation and errors, for example:

.doFinally(signalType -> response.close())

or an equivalent explicit resource-management mechanism.

Both changes are needed because cancellation can happen before or after ClickHouseResult is created.

3. Add regression coverage

A regression test should repeatedly:

  1. start a request;
  2. cancel the Reactor subscription before the response is delivered;
  3. allow the underlying request to finish;
  4. verify that the late response is closed;
  5. verify that another query can still acquire an HTTP connection.

The test should also cover cancellation while ClickHouseResult is already consuming a streaming response.

Compatibility considerations

The proposed fix should not change the public R2DBC API.

Successful queries should behave exactly as before.

The user-visible change should only be that resources associated with cancelled or failed queries are released reliably.

Special care is required around cancellation races to avoid:

  • closing a response still owned by an active subscriber;
  • closing the same response more than once;
  • losing a late response without cleanup.

Configuration

Client Configuration

The complete configuration is included in:

https://github.com/tomaszzason/clickhouse

The reproduction uses:

clickhouse-r2dbc 0.9.8:http
Apache HttpClient 5.6.1
connection_request_timeout = 180000 ms

Environment

  • Cloud
  • Client version: clickhouse-r2dbc 0.9.8:http
  • Language version: Java 25
  • OS: Windows 11 for the Spring Boot application; Docker Desktop for ClickHouse

ClickHouse Server

  • ClickHouse Server version: See docker-compose.yml in the reproduction repository
  • ClickHouse Server non-default settings, if any: See the repository configuration
  • CREATE TABLE statements for tables involved: Not required
  • Sample data for all these tables: Not required

The reproduction uses ClickHouse system tables and does not require project-specific schemas or data.

Activity

  1. chernser commented on Jul 29, 2026

    @chernser
    Contributor

    @tomaszzason
    Thank you for reporting! Will look into it shortly.

  2. added
    connectivity
    on Jul 29, 2026
  3. added this to the 0.12.0 milestone on Jul 29, 2026
  4. removed this from the 0.12.0 milestone on Oct 14, 2026
  5. polyglotAI-bot commented on Nov 27, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — fix needed
    Review PR #3354. With its diff, the program below gets a connection again after both kinds of cancellation.

    • Category: Bug
    • Classification: impact: Stability · area: Connectivity (cancellation, connection pool)
    • Status on main: Reproduced on main — 2 cancelled queries take the 2 pool connections, and the next query waits; it fails after 180 s with ConnectionRequestTimeoutException, as in the issue.
    • Breaking change: No.
    • Duplicates / related: No others.

    Analysis: The issue's root causes are correct. ClickHouseStatement.java:139 wraps request::execute in Mono.fromFuture: a cancel cancels only the CompletableFuture, so the v1 request runs on and its response has no owner to close it. ClickHouseResult.java:36 closes the response only in doOnComplete, so a cancel while rows are read also leaves it open. Each open response keeps one pool connection (max_open_connections, default 10).

    Reproduction: complete program and output

    Changed from the issue's steps: no Spring application; the program calls R2DBC directly, with a pool of 2 connections (max_open_connections=2), compress=0 (#3107), and one case for each JVM run (java -cp <clickhouse-r2dbc classpath> Repro.java <case>).

    import io.r2dbc.spi.Connection;
    import io.r2dbc.spi.ConnectionFactories;
    import io.r2dbc.spi.ConnectionFactory;
    import reactor.core.Disposable;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;
    
    import java.time.Duration;
    import java.util.List;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
    
        // A pool of 2 HTTP connections, so that 2 leaked responses exhaust it.
        static Connection connect() {
            String url = "r2dbc:clickhouse:" + URL.replaceFirst("^https?:", "").replaceFirst("//", "//default:" + PASSWORD + "@")
                    + "/default?compress=0&max_open_connections=2";
            ConnectionFactory factory = ConnectionFactories.get(url);
            return Mono.from(factory.create()).block();
        }
    
        static Flux<Object> rows(Connection conn, String sql) {
            return Flux.from(conn.createStatement(sql).execute()).flatMap(r -> r.map((row, md) -> row.get(0)));
        }
    
        // After the loop: does a normal query still get an HTTP connection?
        static String probe(Connection conn) {
            try {
                List<Object> v = rows(conn, "SELECT 1").collectList().block(Duration.ofSeconds(5));
                return "ok " + v;
            } catch (Exception e) {
                return e.getClass().getSimpleName() + ": " + e.getMessage();
            }
        }
    
        // Run one case per JVM: java Repro.java <no-cancel|cancel-before-response|cancel-while-reading>
        public static void main(String[] args) throws Exception {
            String mode = args[0];
            Connection c = connect();
            for (int i = 0; i < 2; i++) { // 2 = max_open_connections
                if (mode.equals("no-cancel")) {             // contrast: each query read to the end
                    rows(c, "SELECT sleep(0.5)").collectList().block();
                } else if (mode.equals("cancel-before-response")) { // query takes 0.5 s, cancel after 50 ms
                    Disposable d = rows(c, "SELECT sleep(0.5)").subscribe();
                    Thread.sleep(50);
                    d.dispose();
                } else {                                    // cancel-while-reading: first row of 1M, then cancel
                    rows(c, "SELECT number FROM numbers(1000000)").next().block();
                }
            }
            Thread.sleep(1500); // let the cancelled requests finish
            System.out.println(mode + ": next query -> " + probe(c));
            System.exit(0); // a blocked worker thread waits 3 min for a pool connection
        }
    }
    

    Output on main (8480ca001), ClickHouse 26.11.2.4:

    no-cancel: next query -> ok [1]
    cancel-before-response: next query -> IllegalStateException: Timeout on blocking read for 5000000000 NANOSECONDS
    cancel-while-reading: next query -> IllegalStateException: Timeout on blocking read for 5000000000 NANOSECONDS
    

    Output with the diff of PR #3354 applied on main:

    no-cancel: next query -> ok [1]
    cancel-before-response: next query -> ok [1]
    cancel-while-reading: next query -> ok [1]
    

    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

    bugconnectivityr2dbc

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions