Video in progress

Why do you need a connection pool for HTTP calls between services, and how do you configure it?

Opening a new TCP (and TLS) connection for each request is expensive; a pool reuses connections. But the pool has a limit too: if it's small, requests queue up waiting for a connection. So the maximum connections, the per-host limit and the timeout for waiting for a connection from the pool are set explicitly.

📖 Answer

Inside a cluster, a new TCP connection takes a few milliseconds, and more with TLS. At 500 requests per second that's noticeable CPU and latency. With keep-alive, the pool reuses connections.

A RestClient with Apache HttpClient 5:

@Bean
RestClient inventoryClient(RestClient.Builder builder) {
    var pool = PoolingHttpClientConnectionManagerBuilder.create()
            .setMaxConnTotal(200)
            .setMaxConnPerRoute(50)
            .setDefaultConnectionConfig(ConnectionConfig.custom()
                    .setConnectTimeout(Timeout.ofMilliseconds(500))
                    .setSocketTimeout(Timeout.ofSeconds(2))
                    .build())
            .build();
    var http = HttpClients.custom()
            .setConnectionManager(pool)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(Timeout.ofMilliseconds(200))
                    .build())
            .build();
    return builder.baseUrl("http://inventory-service")
            .requestFactory(new HttpComponentsClientHttpRequestFactory(http))
            .build();
}

The most common problem is maxConnPerRoute. In HttpClient 5 its default is only 5. If the service has 200 Tomcat threads and all of them call inventory-service, 195 sit waiting for a connection. The downstream is fast, but your latency is up; in a thread dump you see the threads waiting to get a connection from the pool.

connectionRequestTimeout is the limit on waiting for a connection from the pool. Without it, when the pool runs out, threads hang for a long time.

Size the pool from the expected parallel calls: 400 requests per second × 50 ms average = ~20 parallel connections, with headroom 40-50. With the JDK HttpClient (JdkClientHttpRequestFactory) there are few pool settings, since over HTTP/2 it sends many requests over a single connection.

Export the pool metrics (busy and idle connections, waiters) through Micrometer; that's where the problem shows up first.