Video in progress
What's dangerous in this HTTP client configuration? What happens if the payment service hangs?
@Bean
RestClient paymentClient() {
return RestClient.builder()
.baseUrl("http://payment-service")
.requestFactory(new SimpleClientHttpRequestFactory())
.build();
}
No timeout is configured: SimpleClientHttpRequestFactory waits forever by default. If payment hangs, every request ties up a Tomcat thread forever, and order-service soon stops responding entirely.
📖 Answer
This code works fine in tests and on ordinary days. The problem shows up only on the day payment-service stops responding.
SimpleClientHttpRequestFactory runs on top of HttpURLConnection; its connect and read timeouts default to 0, meaning there's no wait limit. If the server doesn't respond after the connection is made, the thread hangs in read().
How it looks on prod: order-service CPU is low, there are no errors, but no endpoint responds. If you take a thread dump (jstack or /actuator/threaddump), you'll see all the http-nio-* threads sitting in a socket read (NioSocketImpl.read on Java 17+, SocketInputStream.read on older JDKs).
The fix:
@Bean
RestClient paymentClient(RestClient.Builder builder) {
var factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofSeconds(1));
factory.setReadTimeout(Duration.ofSeconds(2));
return builder.baseUrl("http://payment-service")
.requestFactory(factory)
.build();
}
There's a second mistake too: the static RestClient.builder() method isn't the builder Spring Boot configured, so tracing and metrics aren't wired in. It's better to inject the RestClient.Builder bean Boot provides.
Make it a habit to check the default timeout every time you work with a new HTTP client, connection pool or DB driver; in many libraries it's very large or unlimited.
Sign up to mark studied questions and save your progress.