0

Related Question: https://stackoverflow.com/questions/34852236/spring-boot-rest-api-request-timeout

If we are making a REST API call in Spring Boot, then we have two timeout properties to set as ConnectTimeout and ReadTimeout.

Actually these timeouts are coming from org.apache.http.client library.

The following is the code snippet from HttpComponentsClientHttpRequestFactory class of Spring http client.

    public void setConnectTimeout(int timeout) {
        Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value");
        this.requestConfig = this.requestConfigBuilder().setConnectTimeout(timeout).build();
    }

    public void setConnectionRequestTimeout(int connectionRequestTimeout) {
        this.requestConfig = this.requestConfigBuilder().setConnectionRequestTimeout(connectionRequestTimeout).build();
    }

    public void setReadTimeout(int timeout) {
        Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value");
        this.requestConfig = this.requestConfigBuilder().setSocketTimeout(timeout).build();
    }

The ReadTimeout is nothing but the SocketTimeout.

The meaning of these Timeout properties is as follows:
ConnectTimeout: the time to establish the connection with the remote host.
SocketTimeout: This is the time spent waiting for the data after the connection with the remote host has been established. In other words, it is the time between receiving two packets of data.

Suppose I have set the value of both the Timeouts as 3 seconds. So, ConnectTimeout occurs when establishing a connection takes longer than 3 seconds and ReadTimeout/SocketTimeout occurs when the client doesn't receive any data from the server(as part of API Request) for 3 seconds.

I was assuming that this ReadTimeout can be used to timeout an HTTP Request made to the third-party API if it takes longer than N seconds to respond. But it looks like the meaning is different it can take way beyond N seconds (or 3 seconds as in my case) if it serves data slowly but with breaks shorter than 3 seconds. Please confirm if this understanding is correct.

So, why isn't there a direct property in spring boot or Apache HTTP Client which times out a REST API request if it takes longer than N seconds? What might be the negative consequences if such type of timeout is provided? There may be some limitations also. I can think of one: If the target API is a resource modifying (CREATE/UPDATE) one and if we time out the request, then the consumer gets an exception even if the resource is modified by the third-party API. However, if it is a Query call, then there is no issues.

Is using libraries like Resilience4j and Netflix Hystrix the only solution? Is there any new addition for this in the latest Java/Spring Boot versions?

mukund
  • 2,866
  • 5
  • 31
  • 41

0 Answers0