Saturday, July 01, 2023

revisit timeout settings after 9 years

After almost 9 year, this is part 2, or an update to Are you setting Connect Timeout correctly? I'm going to give the best practice of setting connect timeout and read timeout for org.springframework.boot.web.client.RestTemplateBuilder as of Spring Boot 2.7.13.

Let's say it takes up to 0.1 sec to setup connection and 1 sec to receive response, then it's easy to understand you'll get org.apache.http.conn.ConnectTimeoutException if

return restTemplateBuilder
.rootUri(rootUri)
.basicAuthentication(username, password)
.setConnectTimeout(ofMillis(10))
.setReadTimeout(ofMillis(1000))
.build();

and java.net.SocketTimeoutException: Read timed out if

return restTemplateBuilder
.rootUri(rootUri)
.basicAuthentication(username, password)
.setConnectTimeout(ofMillis(100))
.setReadTimeout(ofMillis(100))
.build();

You can either set both timeouts

return restTemplateBuilder
.rootUri(rootUri)
.basicAuthentication(username, password)
.setConnectTimeout(ofMillis(100))
.setReadTimeout(ofMillis(1000))
.build();

or omit connect timeout and only set read timeout

return restTemplateBuilder
.rootUri(rootUri)
.basicAuthentication(username, password)
//.setConnectTimeout(ofMillis(100))
.setReadTimeout(ofMillis(1000))
.build();

however by setting connect timeout only and omitting read timeout, you'll get java.net.SocketTimeoutException: Read timed out

return restTemplateBuilder
.rootUri(rootUri)
.basicAuthentication(username, password)
.setConnectTimeout(ofMillis(100))
//.setReadTimeout(ofMillis(1000))
.build();

Let me rephrase what I said 9 years ago, don't set both timeout to be the same, which shows you don't know how network communication works.


No comments:

Post a Comment