Connection Timeout HttpClient Apache

Motivatione

What is ConnectionTimeout and ConnectionRequestTimeout

  • I was debugging one api and found there is a request which is taking way too much time to complete, after analaysis found there are some Stored Procedure and some API's are made in this endpoint.
  • Later found there is one api call that is failing and throwing a exception.

so I am checking the timeout properties for the Apache Http Client

Example code

int timeout = 5;
RequestConfig config = RequestConfig.custom() 
                        .setConnectTimeout(timeout * 1000)
                        .setConnectionRequestTimeout(timeout * 1000)
                        .setSocketTimeout(timeout * 1000).build(); 

CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
  1. Connection Timeout : http.connection.timeout --> time taken to establish a connection with remote host
  2. Socket Timeout : http.socket.timeout : means we have established the connection and we are waiting for the data --> so this is time up to which we can wait after making a connection
  3. Connection Manager Timeout : time to wait for the a connection from the connecton manager pool

So, the first one, connectionRequestTimeout happens when you have a pool of connections and they are all busy, not allowing the connection manager to give you one connection to make the request.

connectTimeout happens when establishing the connection. For instance while doing the tcp handshake.

socketTimeout like the description says, is the timeout while waiting for data. Usually happens when your server is slow.

Code Sample

After configuring it, we can now use the client to perform HTTP requests:

HttpGet getMethod = new HttpGet("http://host:8080/path");
HttpResponse response = httpClient.execute(getMethod);
System.out.println(
  "HTTP Status of response: " + response.getStatusLine().getStatusCode());

With the previously defined client, the connection to the host will time out in 5 seconds. Also, if the connection is established but no data is received, the timeout will also be 5 additional seconds.

Note that the connection timeout will result in an org.apache.http.conn.ConnectTimeoutException being thrown, while socket timeout will result in a java.net.SocketTimeoutException.